Skip to content

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(platform): device code OAuth flow + Stripe Link wallet blocks (#14062)

Nicholas Tindled286d4917dc7
diff --git a/.secrets.baseline b/.secrets.baseline
index 4f75d0f2e1..1c4ecd9fc7 100644
--- a/.secrets.baseline
+++ b/.secrets.baseline
@@ -498,14 +498,14 @@
"filename": "autogpt_platform/frontend/src/components/contextual/CredentialsInput/helpers.ts",
"hashed_secret": "47acd2028cf81b5da88ddeedb2aea4eca4b71fbd",
"is_verified": false,
- "line_number": 102
+ "line_number": 116
},
{
"type": "Secret Keyword",
"filename": "autogpt_platform/frontend/src/components/contextual/CredentialsInput/helpers.ts",
"hashed_secret": "8be3c943b1609fffbfc51aad666d0a04adf83c9d",
"is_verified": false,
- "line_number": 103
+ "line_number": 117
}
],
"autogpt_platform/frontend/src/lib/autogpt-server-api/utils.ts": [
@@ -578,5 +578,5 @@
}
]
},
- "generated_at": "2026-08-11T17:17:27Z"
+ "generated_at": "2026-08-18T14:15:25Z"
}
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.py
index df7d4ff77b..199911b3db 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py
@@ -67,8 +67,13 @@ from backend.integrations.managed_providers.ayrshare import AyrshareManagedProvi
from backend.integrations.managed_providers.ayrshare import (
settings_available as ayrshare_settings_available,
)
-from backend.integrations.oauth import CREDENTIALS_BY_PROVIDER, HANDLERS_BY_NAME
-from backend.integrations.providers import ProviderName
+from backend.integrations.oauth import (
+ CREDENTIALS_BY_PROVIDER,
+ DEVICE_HANDLERS_BY_NAME,
+ HANDLERS_BY_NAME,
+)
+from backend.integrations.oauth.device_base import BaseDeviceAuthHandler
+from backend.integrations.providers import ProviderName, provider_key
from backend.integrations.webhooks import get_webhook_manager
from backend.util.exceptions import (
ExpertRunPausedError,
@@ -100,6 +105,13 @@ if TYPE_CHECKING:
from backend.integrations.oauth import BaseOAuthHandler
logger = logging.getLogger(__name__)
+
+# Long enough to stop a loop, short enough that a user who cancels and retries
+# is not left waiting.
+_INITIATE_COOLDOWN_SECONDS = 3
+# The throttle protects an upstream client id; it must never be the reason a
+# request hangs.
+_THROTTLE_TIMEOUT_SECONDS = 1.0
settings = Settings()
router = APIRouter()
router.include_router(codex_router, prefix="/codex")
@@ -371,6 +383,338 @@ async def callback(
return to_meta_response(credentials)
+# ================================================================== #
+# Device Code Grant endpoints (RFC 8628)
+# ================================================================== #
+
+
+class DeviceAuthInitiateResponse(BaseModel):
+ # Deliberately no `device_code`: it is the secret used to poll for tokens.
+ # The browser never needs it — /device-auth/poll takes only `state_token`
+ # and reads the device code back out of server-side state.
+ state_token: str
+ user_code: str
+ verification_url: str
+ verification_url_complete: str | None = None
+ expires_in: int
+ interval: int
+
+
+class DeviceAuthPollRequest(BaseModel):
+ state_token: str
+
+
+class DeviceAuthPollResponse(BaseModel):
+ # Literal, not `str`: this is what reaches the generated OpenAPI schema and
+ # the frontend types, and the poll loop branches on exactly these values.
+ status: Literal["pending", "slow_down", "approved", "denied", "expired"]
+ credentials: CredentialsMetaResponse | None = None
+
+
+async def _throttle_upstream(
+ user_id: str, provider: ProviderName, seconds: int, scope: str, flow: str = ""
+) -> bool:
+ """Rate-limit outbound device-auth calls per user and provider.
+
+ Every initiate/poll drives a request to the provider under one hardcoded
+ public client ID shared by the whole platform, so a single account looping
+ an endpoint can get that client throttled for everyone. RFC 8628 already
+ defines the minimum gap between polls; this holds callers to it
+ server-side instead of trusting the client to.
+
+ Returns True when the caller is going too fast. Fails open, and fails open
+ *fast*: an unreachable Redis must not turn a throttle check into a hung
+ request, so the whole check is bounded.
+ """
+
+ async def _claim() -> bool:
+ from backend.data.redis_client import get_redis_async
+
+ redis = await get_redis_async()
+ # Namespaced per endpoint, and for polls per flow. Sharing one key
+ # across endpoints deadlocked the pair: a live poll loop re-claims its
+ # key every `interval` seconds with the same TTL, so it never expires
+ # and `initiate` could never claim it. Keying polls per user rather
+ # than per flow had the same shape one level down — a second
+ # concurrent flow lost every window and spun "waiting for approval"
+ # past the point the user approved. RFC 8628's interval is an
+ # obligation per device code, so that is what a poll is held to.
+ # `initiate` has no flow yet and stays per user, which is the point:
+ # it is what stops a loop minting device codes.
+ key = f"device-auth-throttle:{scope}:{user_id}:{provider_key(provider)}"
+ if flow:
+ key = f"{key}:{flow}"
+ # SET NX EX: the first caller in the window claims the key.
+ claimed = await redis.set(key, "1", ex=max(seconds, 1), nx=True)
+ return not claimed
+
+ try:
+ return await asyncio.wait_for(_claim(), timeout=_THROTTLE_TIMEOUT_SECONDS)
+ except Exception as e:
+ logger.warning(f"Device auth throttle unavailable, allowing through: {e}")
+ return False
+
+
+async def _credential_for_grant(
+ user_id: str, provider: ProviderName, credential_id: str | None
+) -> Any | None:
+ """The credential this grant produced, or None if it is not stored yet.
+
+ Used by the poll that loses the consume race. It must be *this* grant's
+ credential, not merely the provider's newest: `get_creds_by_provider`
+ filters by provider with no ordering contract, and a merged re-auth keeps
+ its original position — so a user with two Link wallets could have the
+ losing poll report the wrong one, which the connect modal then auto-wires
+ into the node. An agent authorized against an account the user did not
+ pick is a worse outcome than reporting nothing.
+
+ Only a re-auth carries a credential id. A first-time grant has none, so
+ there is nothing to match on and the caller is told to keep polling.
+ """
+ if not credential_id:
+ return None
+ try:
+ return await creds_manager.store.get_creds_by_id(user_id, credential_id)
+ except Exception as e:
+ logger.warning(f"Could not read stored credential for {provider}: {e}")
+ return None
+
+
+def _get_device_auth_handler(provider: ProviderName) -> BaseDeviceAuthHandler:
+ key = provider_key(provider)
+ if key not in DEVICE_HANDLERS_BY_NAME:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"No device-auth handler for provider '{key}'",
+ )
+ handler_class = DEVICE_HANDLERS_BY_NAME[key]
+ return handler_class()
+
+
+ "/{provider}/device-auth/initiate",
+ summary="Initiate device code OAuth flow",
+)
+async def device_auth_initiate(
+ provider: Annotated[
+ ProviderName,
+ Path(title="The provider to initiate device auth for"),
+ ],
+ user_id: Annotated[str, Security(get_user_id)],
+ scopes: Annotated[
+ str, Query(title="Comma-separated list of authorization scopes")
+ ] = "",
+) -> DeviceAuthInitiateResponse:
+ handler = _get_device_auth_handler(provider)
+
+ # Cheapest endpoint to abuse: it takes no state token, and each call mints
+ # a device code upstream.
+ if await _throttle_upstream(
+ user_id, provider, _INITIATE_COOLDOWN_SECONDS, scope="initiate"
+ ):
+ raise HTTPException(
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
+ detail="A device authorization was just started. Please wait a moment.",
+ )
+
+ requested_scopes = scopes.split(",") if scopes else []
+ requested_scopes = handler.handle_default_scopes(requested_scopes)
+
+ try:
+ initiation = await handler.initiate_device_auth(requested_scopes)
+ except Exception as e:
+ # The message carries the upstream response body verbatim; keep it in
+ # the logs rather than handing it to the caller.
+ logger.error(f"Device auth initiation failed for {provider}: {e}")
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail="Failed to initiate device auth with the provider.",
+ )
+
+ # Outlive the provider's device code by a minute. If the state token
+ # expired first the poll loop would die with "Invalid or expired state
+ # token" while the user could still legitimately approve; the extra grace
+ # also lets the final poll consume the token and report `expired` properly.
+ try:
+ state_token, _ = await creds_manager.store.store_state_token(
+ user_id=user_id,
+ provider=provider_key(provider),
+ scopes=requested_scopes,
+ expires_in_seconds=initiation.expires_in + 60,
+ state_metadata={
+ "flow_type": "device_code",
+ "device_code": initiation.device_code,
+ "interval": initiation.interval,
+ "user_code": initiation.user_code,
+ },
+ )
+ except Exception as e:
+ # The upstream device code is already issued at this point; it simply
+ # goes unused and expires on its own. Surfacing the storage error --
+ # a raw Prisma failure when the user row is missing -- would leak
+ # internals for something the caller can only retry.
+ logger.error(f"Failed to persist device auth state for {provider}: {e}")
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail="Failed to start device authorization. Please try again.",
+ )
+
+ return DeviceAuthInitiateResponse(
+ state_token=state_token,
+ user_code=initiation.user_code,
+ verification_url=initiation.verification_url,
+ verification_url_complete=initiation.verification_url_complete,
+ expires_in=initiation.expires_in,
+ interval=initiation.interval,
+ )
+
+
+ "/{provider}/device-auth/poll",
+ summary="Poll device code OAuth flow for completion",
+)
+async def device_auth_poll(
+ provider: Annotated[
+ ProviderName,
+ Path(title="The provider to poll device auth for"),
+ ],
+ body: DeviceAuthPollRequest,
+ user_id: Annotated[str, Security(get_user_id)],
+) -> DeviceAuthPollResponse:
+ handler = _get_device_auth_handler(provider)
+
+ # Non-consuming read — state survives across many polls
+ try:
+ valid_state = await creds_manager.store.peek_state_token(
+ user_id, body.state_token, provider
+ )
+ except Exception as e:
+ # A caller with no backend User row raises a Prisma RecordNotFound
+ # here. That is the same "invalid token" outcome as far as the poll
+ # loop is concerned, and returning it as a 400 keeps the raw DB text
+ # out of the response — matching what `initiate` already does.
+ logger.error(f"Device auth poll state lookup failed for {provider}: {e}")
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Invalid or expired state token",
+ )
+ if not valid_state:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Invalid or expired state token",
+ )
+
+ interval = int(valid_state.state_metadata.get("interval") or 5)
+ if await _throttle_upstream(
+ user_id, provider, interval, scope="poll", flow=body.state_token
+ ):
+ # Polling faster than the provider asked for. Say so in its own
+ # vocabulary rather than spending an upstream call to be told.
+ return DeviceAuthPollResponse(status="slow_down")
+
+ device_code = valid_state.state_metadata.get("device_code")
+ if not device_code:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="State token is not for a device code flow",
+ )
+
+ try:
+ result = await handler.poll_for_tokens(device_code)
+ except Exception as e:
+ # As above: `poll_for_tokens` embeds the raw upstream body in its
+ # error, so log it and return something generic.
+ logger.error(f"Device auth poll failed for {provider}: {e}")
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail="Device auth poll failed against the provider.",
+ )
+
+ if result.status in ("pending", "slow_down"):
+ return DeviceAuthPollResponse(status=result.status)
+
+ # Terminal state — consume the token so it can't be reused. The consume is
+ # the serialization point: `peek` is deliberately non-consuming, so two
+ # concurrent polls can both reach here after an approval. Only the caller
+ # that actually consumes the token may store credentials; the loser would
+ # otherwise create a duplicate for the same authorization.
+ consumed = await creds_manager.store.consume_state_token(
+ user_id, body.state_token, provider
+ )
+ if consumed is None:
+ logger.debug(
+ "Device auth poll for user %s lost the race to consume the state "
+ "token; another poll already handled this terminal state",
+ user_id,
+ )
+ if result.status != "approved":
+ return DeviceAuthPollResponse(status=result.status)
+
+ # The winner stored a credential for this grant; report *that* rather
+ # than "approved" with nothing attached. A client branching on the
+ # status alone would otherwise show success, wire up nothing, and be
+ # unable to retry — the state token is gone by now.
+ stored = await _credential_for_grant(
+ user_id, provider, valid_state.credential_id
+ )
+ if stored is None:
+ # Either the winner has not finished storing, or this is a
+ # first-time grant with no id to match on. Report the approval
+ # without a credential and let the client pick it up from the
+ # refreshed credential list — `pending` would send it back to a
+ # state token the winner has already consumed, and the next poll
+ # would 400.
+ return DeviceAuthPollResponse(status="approved")
+ return DeviceAuthPollResponse(
+ status="approved", credentials=to_meta_response(stored)
+ )
+
+ if result.status == "approved" and result.credentials:
+ credentials = result.credentials
+
+ if len(credentials.scopes) == 1 and " " in credentials.scopes[0]:
+ credentials.scopes = credentials.scopes[0].split(" ")
+
+ try:
+ credentials = await _merge_or_create_credential(
+ user_id, provider, credentials, valid_state.credential_id
+ )
+ except Exception:
+ # The grant is live at the provider and we could not store it, so
+ # there is no local credential to revoke it with and nothing to
+ # tell the user it exists. Restoring the state token does not help:
+ # RFC 8628 device codes are single-use, so the next poll would only
+ # ever get `expired_token`. Hand the authorization back instead.
+ try:
+ await handler.revoke_tokens(result.credentials)
+ logger.warning(
+ "Revoked an unstorable device-auth grant for user %s and "
+ "provider %s rather than leaving it live at the provider",
+ user_id,
+ provider,
+ )
+ except Exception as revoke_error:
+ logger.error(
+ "Could not revoke an unstorable device-auth grant for user "
+ "%s and provider %s; it remains live upstream: %s",
+ user_id,
+ provider,
+ revoke_error,
+ )
+ raise
+
+ logger.debug(
+ f"Device auth approved for user {user_id} and provider {provider.value}"
+ )
+ return DeviceAuthPollResponse(
+ status="approved",
+ credentials=to_meta_response(credentials),
+ )
+
+ # denied / expired
+ return DeviceAuthPollResponse(status=result.status)
+
+
# Bound the first-time sweep so a slow upstream (e.g. Ayrshare) can't hang
# the credential-list endpoint. On timeout we still kick off a fire-and-
# forget sweep so provisioning eventually completes; the user just won't
@@ -670,6 +1014,15 @@ async def delete_credentials(
if provider_matches(provider.value, ProviderName.MCP.value):
# MCP uses dynamic per-server OAuth — create handler from metadata
handler = create_mcp_oauth_handler(creds)
+ elif (
+ device_handler := DEVICE_HANDLERS_BY_NAME.get(provider_key(provider))
+ ) is not None:
+ # A device-code grant stores an OAuth2Credentials, so it reaches
+ # this branch too — but its handler lives in the other registry.
+ # Looking only in HANDLERS_BY_NAME raised "does not support OAuth"
+ # *after* the local delete had already run, leaving a live token
+ # at the provider with nothing left to revoke it with.
+ handler = device_handler()
else:
handler = _get_provider_oauth_handler(request, provider)
tokens_revoked = await handler.revoke_tokens(creds)
@@ -1323,18 +1676,16 @@ def _get_provider_oauth_handler(
logger.warning(f"Failed to load blocks: {e}")
# Convert provider_name to string for lookup
- provider_key = (
- provider_name.value if hasattr(provider_name, "value") else str(provider_name)
- )
+ key = provider_key(provider_name)
- if provider_key not in HANDLERS_BY_NAME:
+ if key not in HANDLERS_BY_NAME:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Provider '{provider_key}' does not support OAuth",
+ detail=f"Provider '{key}' does not support OAuth",
)
# Check if this provider has custom OAuth credentials
- oauth_credentials = CREDENTIALS_BY_PROVIDER.get(provider_key)
+ oauth_credentials = CREDENTIALS_BY_PROVIDER.get(key)
if oauth_credentials and not oauth_credentials.use_secrets:
# SDK provider with custom env vars
@@ -1369,7 +1720,7 @@ def _get_provider_oauth_handler(
},
)
- handler_class = HANDLERS_BY_NAME[provider_key]
+ handler_class = HANDLERS_BY_NAME[key]
frontend_base_url = settings.config.frontend_base_url
if not frontend_base_url:
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router_test.py b/autogpt_platform/backend/backend/api/features/integrations/router_test.py
index 3ecaeffeb6..2db2d8d9dd 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router_test.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router_test.py
@@ -34,6 +34,9 @@ async def _not_found_handler(
client = fastapi.testclient.TestClient(app)
TEST_USER_ID = "test-user-id"
+# The id the mock_jwt_user fixture authenticates as, i.e. what the endpoints
+# must scope every store operation to.
+JWT_USER_ID = "3e53486c-cf57-477e-ba2a-cb02dc828e1a"
def _make_webhook(
@@ -851,3 +854,580 @@ class TestWebhookPingOwnership:
assert resp.status_code == 200
assert resp.json() is True
webhook_manager.trigger_ping.assert_awaited_once()
+
+
+class TestDeviceAuthEndpoints:
+ """POST /{provider}/device-auth/{initiate,poll}.
+
+ The concurrency contract here is load-bearing: `peek` must survive many
+ polls while `consume` must admit exactly one terminal handler, or an
+ approval produces duplicate credentials.
+ """
+
+ PROVIDER = "stripe_link"
+
+ @staticmethod
+ def _initiation():
+ from backend.integrations.oauth.device_base import DeviceAuthInitiation
+
+ return DeviceAuthInitiation(
+ device_code="dev-code-secret",
+ user_code="GLOW-RELISH",
+ verification_url="https://login.link.com/device",
+ verification_url_complete="https://login.link.com/device?code=GLOW-RELISH",
+ expires_in=600,
+ interval=5,
+ )
+
+ @staticmethod
+ def _state(metadata: dict | None = None):
+ from backend.data.model import OAuthState
+
+ return OAuthState(
+ token="state-token",
+ provider="stripe_link",
+ expires_at=9999999999,
+ scopes=["userinfo:read"],
+ state_metadata=(
+ metadata
+ if metadata is not None
+ else {"flow_type": "device_code", "device_code": "dev-code-secret"}
+ ),
+ )
+
+ def _patched(self, handler, mock_mgr):
+ return (
+ patch.object(router, "dependencies", []),
+ patch(
+ "backend.api.features.integrations.router._get_device_auth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager", mock_mgr),
+ # Off by default. Every test in this class drives the same user and
+ # provider within the same second, so with a live Redis the
+ # throttle would answer for whichever endpoint ran second. It has
+ # its own tests below.
+ patch(
+ "backend.api.features.integrations.router._throttle_upstream",
+ new=AsyncMock(return_value=False),
+ ),
+ )
+
+ def test_initiate_does_not_return_the_device_code(self):
+ """The device code is the bearer secret of the flow.
+
+ It is stored encrypted server-side and the browser never needs it, so
+ it must not appear anywhere in the response.
+ """
+ handler = MagicMock()
+ handler.handle_default_scopes.return_value = ["userinfo:read"]
+ handler.initiate_device_auth = AsyncMock(return_value=self._initiation())
+
+ mock_mgr = MagicMock()
+ mock_mgr.store.store_state_token = AsyncMock(
+ return_value=("state-token", "verifier")
+ )
+
+ p1, p2, p3, p4 = self._patched(handler, mock_mgr)
+ with p1, p2, p3, p4:
+ response = client.post(
+ f"/{self.PROVIDER}/device-auth/initiate?scopes=userinfo:read"
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["user_code"] == "GLOW-RELISH"
+ assert body["state_token"] == "state-token"
+ assert "device_code" not in body
+ assert "dev-code-secret" not in response.text
+
+ def test_initiate_outlives_the_provider_code(self):
+ """State must expire after the device code, not before.
+
+ Otherwise the poll loop dies with "invalid state token" while the user
+ can still legitimately approve on their phone.
+ """
+ handler = MagicMock()
+ handler.handle_default_scopes.return_value = ["userinfo:read"]
+ handler.initiate_device_auth = AsyncMock(return_value=self._initiation())
+
+ mock_mgr = MagicMock()
+ mock_mgr.store.store_state_token = AsyncMock(
+ return_value=("state-token", "verifier")
+ )
+
+ p1, p2, p3, p4 = self._patched(handler, mock_mgr)
+ with p1, p2, p3, p4:
+ client.post(f"/{self.PROVIDER}/device-auth/initiate")
+
+ kwargs = mock_mgr.store.store_state_token.await_args.kwargs
+ assert kwargs["expires_in_seconds"] > 600
+ assert kwargs["state_metadata"]["device_code"] == "dev-code-secret"
+
+ def test_initiate_does_not_leak_upstream_error_text(self):
+ handler = MagicMock()
+ handler.handle_default_scopes.return_value = []
+ handler.initiate_device_auth = AsyncMock(
+ side_effect=RuntimeError("401 {'secret_hint': 'client_id lwlpk_xyz'}")
+ )
+
+ p1, p2, p3, p4 = self._patched(handler, MagicMock())
+ with p1, p2, p3, p4:
+ response = client.post(f"/{self.PROVIDER}/device-auth/initiate")
+
+ assert response.status_code == 502
+ assert "lwlpk_xyz" not in response.text
+
+ def test_poll_rejects_an_unknown_state_token(self):
+ handler = MagicMock()
+ mock_mgr = MagicMock()
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=None)
+
+ p1, p2, p3, p4 = self._patched(handler, mock_mgr)
+ with p1, p2, p3, p4:
+ response = client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "not-a-real-token"},
+ )
+
+ assert response.status_code == 400
+
+ def test_poll_rejects_a_non_device_flow_state_token(self):
+ """A plain OAuth state token has no device code and must not be usable."""
+ handler = MagicMock()
+ mock_mgr = MagicMock()
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=self._state({}))
+
+ p1, p2, p3, p4 = self._patched(handler, mock_mgr)
+ with p1, p2, p3, p4:
+ response = client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "state-token"},
+ )
+
+ assert response.status_code == 400
+
+ def test_pending_poll_does_not_consume_the_state_token(self):
+ """`peek` is non-consuming so the loop can poll for the full 10 minutes."""
+ from backend.integrations.oauth.device_base import DeviceAuthPollResult
+
+ handler = MagicMock()
+ handler.poll_for_tokens = AsyncMock(
+ return_value=DeviceAuthPollResult(status="pending")
+ )
+
+ mock_mgr = MagicMock()
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=self._state())
+ mock_mgr.store.consume_state_token = AsyncMock()
+
+ p1, p2, p3, p4 = self._patched(handler, mock_mgr)
+ with p1, p2, p3, p4:
+ for _ in range(3):
+ response = client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "state-token"},
+ )
+ assert response.status_code == 200
+ assert response.json()["status"] == "pending"
+
+ mock_mgr.store.consume_state_token.assert_not_awaited()
+
+ def test_poll_race_loser_does_not_create_a_second_credential(self):
+ """Two polls can both see an approval; only the one that consumes wins.
+
+ `consume_state_token` returning None means another poll already handled
+ this terminal state -- storing credentials anyway would duplicate them
+ for a single authorization.
+ """
+ from backend.data.model import OAuth2Credentials
+ from backend.integrations.oauth.device_base import DeviceAuthPollResult
+
+ handler = MagicMock()
+ handler.handle_default_scopes.side_effect = lambda scopes: scopes
+ handler.poll_for_tokens = AsyncMock(
+ return_value=DeviceAuthPollResult(
+ status="approved",
+ credentials=OAuth2Credentials(
+ provider="stripe_link",
+ access_token=SecretStr("at"),
+ refresh_token=SecretStr("rt"),
+ scopes=["userinfo:read"],
+ title="Stripe Link",
+ ),
+ )
+ )
+
+ mock_mgr = MagicMock()
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=self._state())
+ mock_mgr.store.consume_state_token = AsyncMock(return_value=None)
+
+ with (
+ patch.object(router, "dependencies", []),
+ patch(
+ "backend.api.features.integrations.router._get_device_auth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager", mock_mgr),
+ patch(
+ "backend.api.features.integrations.router._throttle_upstream",
+ new=AsyncMock(return_value=False),
+ ),
+ patch(
+ "backend.api.features.integrations.router._merge_or_create_credential",
+ new=AsyncMock(),
+ ) as mock_merge,
+ ):
+ response = client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "state-token"},
+ )
+
+ assert response.status_code == 200
+ # The winner handled this grant, so the loser must not store a second
+ # credential. It reports the approval without one — a first-time grant
+ # has no credential id to look the stored one up by, and answering
+ # `pending` would send the client back to a state token the winner has
+ # already consumed, where the next poll 400s.
+ assert response.json()["status"] == "approved"
+ assert response.json()["credentials"] is None
+ mock_merge.assert_not_awaited()
+
+ def test_poll_does_not_leak_upstream_error_text(self):
+ handler = MagicMock()
+ handler.poll_for_tokens = AsyncMock(
+ side_effect=RuntimeError("500 {'trace': 'internal-host-1.link.com'}")
+ )
+
+ mock_mgr = MagicMock()
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=self._state())
+
+ p1, p2, p3, p4 = self._patched(handler, mock_mgr)
+ with p1, p2, p3, p4:
+ response = client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "state-token"},
+ )
+
+ assert response.status_code == 502
+ assert "internal-host-1" not in response.text
+
+ def test_poll_stores_the_credential_on_the_winning_approval(self):
+ """The primary success path: consume wins, credential is stored.
+
+ Every other approved-status test here makes `consume_state_token`
+ return None to exercise the race loser, so the path that actually
+ stores a credential -- and the scope un-flatten below it -- had no
+ coverage at all.
+ """
+ from backend.data.model import OAuth2Credentials
+ from backend.integrations.oauth.device_base import DeviceAuthPollResult
+
+ stored = OAuth2Credentials(
+ provider="stripe_link",
+ access_token=SecretStr("tok-access-do-not-leak"),
+ refresh_token=SecretStr("tok-refresh-do-not-leak"),
+ # Link returns RFC 6749 space-delimited scopes; the router
+ # un-flattens them so scope checks compare like with like.
+ scopes=["userinfo:read payment_methods.agentic"],
+ title="Stripe Link",
+ )
+ handler = MagicMock()
+ handler.handle_default_scopes.side_effect = lambda scopes: scopes
+ handler.poll_for_tokens = AsyncMock(
+ return_value=DeviceAuthPollResult(status="approved", credentials=stored)
+ )
+
+ mock_mgr = MagicMock()
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=self._state())
+ mock_mgr.store.consume_state_token = AsyncMock(return_value=self._state())
+
+ with (
+ patch.object(router, "dependencies", []),
+ patch(
+ "backend.api.features.integrations.router._get_device_auth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager", mock_mgr),
+ patch(
+ "backend.api.features.integrations.router._throttle_upstream",
+ new=AsyncMock(return_value=False),
+ ),
+ patch(
+ "backend.api.features.integrations.router._merge_or_create_credential",
+ new=AsyncMock(side_effect=lambda *a, **kw: a[2]),
+ ) as mock_merge,
+ ):
+ response = client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "state-token"},
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["status"] == "approved"
+ assert body["credentials"] is not None
+ mock_merge.assert_awaited()
+ # The space-delimited scope string is split before storage.
+ assert stored.scopes == ["userinfo:read", "payment_methods.agentic"]
+ # And no secret rides along in the response.
+ assert "do-not-leak" not in response.text
+
+ def test_poll_maps_a_missing_user_row_to_an_invalid_token(self):
+ """A caller with no backend User row raises a Prisma RecordNotFound in
+ `peek_state_token`. That used to surface as a 500 carrying raw DB text,
+ inconsistent with `initiate`, which already returns a clean message."""
+ handler = MagicMock()
+ mock_mgr = MagicMock()
+ mock_mgr.store.peek_state_token = AsyncMock(
+ side_effect=RuntimeError(
+ "An operation failed because it depends on one or more records "
+ "that were required but not found. Expected a record, found none."
+ )
+ )
+
+ p1, p2, p3, p4 = self._patched(handler, mock_mgr)
+ with p1, p2, p3, p4:
+ response = client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "state-token"},
+ )
+
+ assert response.status_code == 400
+ assert "Expected a record" not in response.text
+
+ def test_every_state_operation_is_scoped_to_the_authenticated_user(self):
+ """User scoping is the whole authorization control on these endpoints.
+
+ Every other test here hands `creds_manager` a bare MagicMock and never
+ checks which user id reached the store, so a regression that passed a
+ constant — or dropped the argument — would leave the suite green.
+ """
+ from backend.integrations.oauth.device_base import DeviceAuthPollResult
+
+ handler = MagicMock()
+ handler.handle_default_scopes.return_value = ["userinfo:read"]
+ handler.initiate_device_auth = AsyncMock(return_value=self._initiation())
+ handler.poll_for_tokens = AsyncMock(
+ return_value=DeviceAuthPollResult(status="pending")
+ )
+
+ mock_mgr = MagicMock()
+ mock_mgr.store.store_state_token = AsyncMock(return_value=("tok", "v"))
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=self._state())
+
+ p1, p2, p3, p4 = self._patched(handler, mock_mgr)
+ with p1, p2, p3, p4:
+ client.post(f"/{self.PROVIDER}/device-auth/initiate")
+ client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "state-token"},
+ )
+
+ authenticated = mock_mgr.store.store_state_token.await_args.kwargs["user_id"]
+ assert authenticated == JWT_USER_ID
+ # peek is positional: (user_id, token, provider)
+ assert mock_mgr.store.peek_state_token.await_args.args[0] == JWT_USER_ID
+
+ def test_one_user_cannot_poll_another_users_state_token(self):
+ """The store scopes by user, so a token belonging to someone else reads
+ as absent rather than as someone else's flow."""
+ handler = MagicMock()
+ mock_mgr = MagicMock()
+ # What the store returns for a token that is not this user's.
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=None)
+
+ p1, p2, p3, p4 = self._patched(handler, mock_mgr)
+ with p1, p2, p3, p4:
+ response = client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "another-users-token"},
+ )
+
+ assert response.status_code == 400
+ assert mock_mgr.store.peek_state_token.await_args.args[0] == JWT_USER_ID
+ # And the provider is never contacted for a token we could not place.
+ handler.poll_for_tokens.assert_not_called()
+
+ def test_the_throttle_holds_callers_to_the_provider_interval(self):
+ """Every call drives the provider under one public client id shared by
+ the whole platform, so a single looping account can get Stripe Link
+ connect throttled for everyone. Covered here rather than in the other
+ tests, which switch it off so they can drive the same user twice."""
+ from backend.integrations.oauth.device_base import DeviceAuthPollResult
+
+ handler = MagicMock()
+ handler.poll_for_tokens = AsyncMock(
+ return_value=DeviceAuthPollResult(status="pending")
+ )
+ mock_mgr = MagicMock()
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=self._state())
+
+ with (
+ patch.object(router, "dependencies", []),
+ patch(
+ "backend.api.features.integrations.router._get_device_auth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager", mock_mgr),
+ patch(
+ "backend.api.features.integrations.router._throttle_upstream",
+ new=AsyncMock(return_value=True),
+ ),
+ ):
+ poll = client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "state-token"},
+ )
+ initiate = client.post(f"/{self.PROVIDER}/device-auth/initiate")
+
+ # RFC 8628's own vocabulary, and the provider is never contacted.
+ assert poll.status_code == 200
+ assert poll.json()["status"] == "slow_down"
+ handler.poll_for_tokens.assert_not_called()
+
+ assert initiate.status_code == 429
+
+ async def test_the_throttle_fails_open_when_redis_is_unreachable(self):
+ """It protects an upstream client id; it must never be the reason a
+ request fails or hangs."""
+ import backend.api.features.integrations.router as router_module
+
+ with patch(
+ "backend.data.redis_client.get_redis_async",
+ new=AsyncMock(side_effect=ConnectionError("redis down")),
+ ):
+ throttled = await router_module._throttle_upstream(
+ TEST_USER_ID, ProviderName.STRIPE_LINK, 5, scope="poll", flow="f"
+ )
+
+ assert throttled is False
+
+ async def test_initiate_and_poll_do_not_share_a_throttle_key(self):
+ """A live poll loop must not lock out starting a new flow.
+
+ Both endpoints claimed one key, and poll re-claims its key every
+ `interval` seconds with the same TTL — so the key never expired and
+ initiate returned 429 for as long as any flow was open. Leaving a
+ dialog open while approving on a phone is the intended behaviour, and
+ it blocked every other surface, including cancel-and-retry.
+ """
+ import backend.api.features.integrations.router as router_module
+
+ claimed: dict[str, int] = {}
+
+ class _Redis:
+ async def set(self, key, value, ex=None, nx=False):
+ if nx and key in claimed:
+ return None
+ claimed[key] = ex
+ return True
+
+ with patch(
+ "backend.data.redis_client.get_redis_async",
+ new=AsyncMock(return_value=_Redis()),
+ ):
+ first_poll = await router_module._throttle_upstream(
+ TEST_USER_ID, ProviderName.STRIPE_LINK, 5, scope="poll", flow="flow-a"
+ )
+ # A poll loop is live; starting a flow must still be allowed.
+ initiate = await router_module._throttle_upstream(
+ TEST_USER_ID, ProviderName.STRIPE_LINK, 3, scope="initiate"
+ )
+ # And each scope still throttles itself.
+ second_poll = await router_module._throttle_upstream(
+ TEST_USER_ID, ProviderName.STRIPE_LINK, 5, scope="poll", flow="flow-a"
+ )
+ # A *different* flow must not be starved by the first one's window.
+ other_flow = await router_module._throttle_upstream(
+ TEST_USER_ID, ProviderName.STRIPE_LINK, 5, scope="poll", flow="flow-b"
+ )
+
+ assert first_poll is False
+ assert initiate is False, "an active poll loop blocked initiate"
+ assert second_poll is True
+ assert other_flow is False, "a second concurrent flow was starved"
+ assert len(claimed) == 3, claimed
+
+ async def test_an_unstorable_grant_is_revoked_not_left_live(self):
+ """The device code is spent by the time the store runs, so the state
+ token cannot be replayed to retry. Handing the authorization back is
+ the only way to avoid a live grant with no local record of it."""
+ from backend.data.model import OAuth2Credentials
+ from backend.integrations.oauth.device_base import DeviceAuthPollResult
+
+ issued = OAuth2Credentials(
+ provider="stripe_link",
+ access_token=SecretStr("at"),
+ refresh_token=SecretStr("rt"),
+ scopes=["userinfo:read"],
+ title="Stripe Link",
+ )
+ handler = MagicMock()
+ handler.handle_default_scopes.side_effect = lambda scopes: scopes
+ handler.poll_for_tokens = AsyncMock(
+ return_value=DeviceAuthPollResult(status="approved", credentials=issued)
+ )
+ handler.revoke_tokens = AsyncMock(return_value=True)
+
+ mock_mgr = MagicMock()
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=self._state())
+ mock_mgr.store.consume_state_token = AsyncMock(return_value=self._state())
+
+ with (
+ patch.object(router, "dependencies", []),
+ patch(
+ "backend.api.features.integrations.router._get_device_auth_handler",
+ return_value=handler,
+ ),
+ patch("backend.api.features.integrations.router.creds_manager", mock_mgr),
+ patch(
+ "backend.api.features.integrations.router._throttle_upstream",
+ new=AsyncMock(return_value=False),
+ ),
+ patch(
+ "backend.api.features.integrations.router._merge_or_create_credential",
+ new=AsyncMock(side_effect=RuntimeError("db down")),
+ ),
+ ):
+ with pytest.raises(Exception):
+ client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "state-token"},
+ )
+
+ handler.revoke_tokens.assert_awaited_once_with(issued)
+
+ def test_the_race_loser_reports_this_grants_credential_not_the_newest(self):
+ """`get_creds_by_provider` has no ordering contract, and a merged
+ re-auth keeps its position — so picking the last entry could hand the
+ connect modal a different wallet than the user approved."""
+ from backend.integrations.oauth.device_base import DeviceAuthPollResult
+
+ handler = MagicMock()
+ handler.poll_for_tokens = AsyncMock(
+ return_value=DeviceAuthPollResult(status="approved")
+ )
+
+ state = self._state()
+ state.credential_id = "the-right-wallet"
+
+ mock_mgr = MagicMock()
+ mock_mgr.store.peek_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.consume_state_token = AsyncMock(return_value=None)
+ mock_mgr.store.get_creds_by_id = AsyncMock(
+ return_value=_make_oauth2_cred("the-right-wallet", "stripe_link")
+ )
+
+ p1, p2, p3, p4 = self._patched(handler, mock_mgr)
+ with p1, p2, p3, p4:
+ response = client.post(
+ f"/{self.PROVIDER}/device-auth/poll",
+ json={"state_token": "state-token"},
+ )
+
+ assert response.status_code == 200
+ mock_mgr.store.get_creds_by_id.assert_awaited_once_with(
+ JWT_USER_ID, "the-right-wallet"
+ )
+ # And never the "newest for this provider" shortcut.
+ mock_mgr.store.get_creds_by_provider.assert_not_called()
diff --git a/autogpt_platform/backend/backend/blocks/_static_provider_configs.py b/autogpt_platform/backend/backend/blocks/_static_provider_configs.py
index 1443caa415..a733298448 100644
--- a/autogpt_platform/backend/backend/blocks/_static_provider_configs.py
+++ b/autogpt_platform/backend/backend/blocks/_static_provider_configs.py
@@ -44,6 +44,7 @@ _STATIC_PROVIDER_CONFIGS: dict[str, tuple[str, tuple[CredentialsType, ...]]] = {
"revid": ("AI-generated short-form video", ("api_key",)),
"screenshotone": ("Automated website screenshots", ("api_key",)),
"smtp": ("Send email via SMTP", ("user_password",)),
+ "stripe_link": ("Stripe Link wallet for agent payments", ("device_code",)),
"unreal_speech": ("Low-cost text-to-speech", ("api_key",)),
"webshare_proxy": ("Rotating proxies for scraping", ("api_key",)),
}
diff --git a/autogpt_platform/backend/backend/blocks/_utils.py b/autogpt_platform/backend/backend/blocks/_utils.py
index bec033bd2c..e3b421b55f 100644
--- a/autogpt_platform/backend/backend/blocks/_utils.py
+++ b/autogpt_platform/backend/backend/blocks/_utils.py
@@ -78,12 +78,21 @@ def is_block_auth_configured(
)
return False
- # Check the provider's supported auth types
- if field_info.supported_types != provider.supported_auth_types:
+ # Check the provider's supported auth types.
+ # A block may accept more types than the provider advertises --
+ # a device-code grant is acquired as `device_code` but stored as
+ # an ordinary `oauth2` credential, so such blocks list both. What
+ # is always a bug is the provider offering a method the block will
+ # not accept: the user connects successfully and the credential
+ # then fails to match the input.
+ if unaccepted := set(provider.supported_auth_types) - set(
+ field_info.supported_types
+ ):
logger.warning(
f"Block {block_cls.__name__} credential input '{field_name}' "
- f"has mismatched supported auth types (field <> Provider): "
- f"{field_info.supported_types} != {provider.supported_auth_types}"
+ f"rejects auth types the provider offers: {sorted(unaccepted)} "
+ f"(field={sorted(field_info.supported_types)}, "
+ f"provider={sorted(provider.supported_auth_types)})"
)
if not (supported_auth_types := provider.supported_auth_types):
diff --git a/autogpt_platform/backend/backend/blocks/allquiet/_webhook.py b/autogpt_platform/backend/backend/blocks/allquiet/_webhook.py
index 3d4e8a6d7f..af8f9e95e2 100644
--- a/autogpt_platform/backend/backend/blocks/allquiet/_webhook.py
+++ b/autogpt_platform/backend/backend/blocks/allquiet/_webhook.py
@@ -15,6 +15,7 @@ import base64
import hashlib
import hmac
import logging
+import re
from datetime import datetime, timedelta, timezone
from typing import Optional
@@ -38,6 +39,9 @@ SIGNATURE_HEADER_PAIRS = (
# always checked.
MAX_TIMESTAMP_SKEW = timedelta(minutes=5)
+# Epoch seconds or milliseconds, optionally signed or fractional.
+_EPOCH_ONLY = re.compile(r"[+-]?\d+(?:\.\d+)?")
+
_OPTIONAL_SECRET = TypeAdapter(Optional[SecretStr])
_JSON_OBJECT = TypeAdapter(dict)
@@ -220,12 +224,20 @@ def _parse_timestamp(timestamp: str) -> Optional[datetime]:
if not candidate:
return None
- try:
- parsed = datetime.fromisoformat(candidate.replace("Z", "+00:00"))
- except ValueError:
- pass
- else:
- return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
+ # An all-digit value is an epoch, and must not be offered to
+ # `fromisoformat` first. Python 3.11+ accepts ISO 8601 *basic* format, so a
+ # 13-digit millisecond value whose leading digits happen to spell a valid
+ # YYYYMMDD parses as a date centuries in the past — 1787121651526 becomes
+ # 1787-12-16 — which then fails the replay-window check. Whether a given
+ # millisecond value does that depends on the wall clock, so the symptom is
+ # an intermittent 403 on valid deliveries.
+ if not _EPOCH_ONLY.fullmatch(candidate):
+ try:
+ parsed = datetime.fromisoformat(candidate.replace("Z", "+00:00"))
+ except ValueError:
+ pass
+ else:
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
try:
epoch = float(candidate)
diff --git a/autogpt_platform/backend/backend/blocks/allquiet/_webhook_test.py b/autogpt_platform/backend/backend/blocks/allquiet/_webhook_test.py
index 010544c811..9d1a274104 100644
--- a/autogpt_platform/backend/backend/blocks/allquiet/_webhook_test.py
+++ b/autogpt_platform/backend/backend/blocks/allquiet/_webhook_test.py
@@ -6,7 +6,7 @@ import hmac
import json
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
-from typing import Any
+from typing import Any, Callable
import pytest
from fastapi import HTTPException
@@ -262,23 +262,52 @@ class TestTimestampFormats:
"""All Quiet's two header pairs don't share a timestamp format."""
@pytest.mark.parametrize(
- "stamp",
+ "format_stamp",
[
- datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
- datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"),
- datetime.now(timezone.utc).isoformat(),
- str(int(datetime.now(timezone.utc).timestamp())),
- str(int(datetime.now(timezone.utc).timestamp() * 1000)),
+ lambda now: now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
+ lambda now: now.strftime("%Y-%m-%dT%H:%M:%S.000Z"),
+ lambda now: now.isoformat(),
+ lambda now: str(int(now.timestamp())),
+ lambda now: str(int(now.timestamp() * 1000)),
],
ids=["aq-millis", "aws-iso", "iso-offset", "epoch-seconds", "epoch-millis"],
)
- async def test_accepts_each_format_all_quiet_may_send(self, stamp: str):
+ async def test_accepts_each_format_all_quiet_may_send(
+ self, format_stamp: Callable[[datetime], str]
+ ):
+ # Stamped here rather than in the parametrize list. Decorator arguments
+ # are evaluated at import time, so on any suite that takes longer than
+ # MAX_TIMESTAMP_SKEW to reach this test the stamp is already stale and
+ # the replay check rejects it -- a failure that depends on how long the
+ # rest of the suite took, not on this code.
+ stamp = format_stamp(datetime.now(timezone.utc))
request = _request(
{"x-aq-signature": _sign(BODY, stamp), "x-aq-timestamp": stamp}
)
await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)
+ @pytest.mark.parametrize(
+ "millis",
+ [
+ # Leading digits spell a valid YYYYMMDD (1787-12-16), so
+ # `fromisoformat` claims it on Python 3.11+ and returns a date
+ # centuries in the past, which then fails the replay window.
+ "1787121651526",
+ # Leading digits are not a valid date (month 20), so this one
+ # always fell through to the epoch branch and passed — which is why
+ # the failure came and went with the wall clock.
+ "1787207590123",
+ ],
+ )
+ def test_epoch_millis_are_never_read_as_a_basic_format_date(self, millis: str):
+ from backend.blocks.allquiet._webhook import _parse_timestamp
+
+ parsed = _parse_timestamp(millis)
+
+ assert parsed is not None
+ assert parsed.year >= 2020, f"{millis} parsed as {parsed}"
+
async def test_fails_closed_on_an_unrecognized_format(self):
# Previously this was waved through, which left the replay window
# permanently open for any sender using an unusual timestamp format.
diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/__init__.py b/autogpt_platform/backend/backend/blocks/stripe_link/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/_auth.py b/autogpt_platform/backend/backend/blocks/stripe_link/_auth.py
new file mode 100644
index 0000000000..61cc21a077
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/stripe_link/_auth.py
@@ -0,0 +1,111 @@
+"""
+Stripe Link CLI — Credential definitions for AutoGPT blocks.
+
+Link CLI uses OAuth 2.0 Device Code Grant (RFC 8628), which produces standard
+access_token + refresh_token pairs stored as OAuth2Credentials. The device-code
+acquisition flow is handled by ``StripeLinkDeviceAuthHandler`` in
+``backend/integrations/oauth/stripe_link.py``.
+"""
+
+from typing import Any, Literal
+
+import httpx
+from pydantic import SecretStr
+
+from backend.data.model import CredentialsField, CredentialsMetaInput, OAuth2Credentials
+
+# Owned by the integrations layer; re-exported so blocks import from their own
+# package. Every other arrow in this codebase runs blocks -> integrations, and
+# the oauth package builds its registries at import, so importing integrations
+# from here would drag every block in eagerly.
+from backend.integrations.oauth.stripe_link import ( # noqa: E402
+ LINK_API_BASE_URL,
+ LINK_HTTP_TIMEOUT,
+)
+from backend.integrations.providers import ProviderName
+
+LINK_DEFAULT_SCOPES = ["userinfo:read", "payment_methods.agentic"]
+
+StripeLinkCredentials = OAuth2Credentials
+
+# `credentials_types` carries two different things at once: the *shape* of the
+# stored credential and the *method* used to acquire it. For every other
+# provider those coincide, but a device-code grant yields an ordinary OAuth2
+# token pair — so the block has to accept `oauth2` (or saved credentials stop
+# matching) while still advertising `device_code` so connect UIs offer the
+# device flow instead of an authorization-code redirect the provider has no
+# client secret for.
+StripeLinkCredentialsInput = CredentialsMetaInput[
+ Literal[ProviderName.STRIPE_LINK], # type: ignore[index]
+ Literal["oauth2", "device_code"],
+]
+
+
+def StripeLinkCredentialsField() -> StripeLinkCredentialsInput:
+ """
+ Creates a Stripe Link credentials input on a block.
+
+ All Link blocks require the same `payment_methods.agentic` scope.
+ """
+ return CredentialsField(
+ required_scopes=set(LINK_DEFAULT_SCOPES),
+ description=(
+ "Connect your Stripe Link account to enable the agent to request "
+ "secure, one-time-use payment credentials from your Link wallet. "
+ "You'll approve each spend request via the Link app."
+ ),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Test credentials for block testing
+# ---------------------------------------------------------------------------
+TEST_CREDENTIALS = OAuth2Credentials(
+ id="01234567-89ab-cdef-0123-456789abcdef",
+ provider="stripe_link",
+ access_token=SecretStr("mock-link-access-token"),
+ refresh_token=SecretStr("mock-link-refresh-token"),
+ access_token_expires_at=None,
+ scopes=LINK_DEFAULT_SCOPES,
+ title="Mock Stripe Link credentials",
+ username="[email protected]",
+)
+
+TEST_CREDENTIALS_INPUT = {
+ "provider": TEST_CREDENTIALS.provider,
+ "id": TEST_CREDENTIALS.id,
+ "type": TEST_CREDENTIALS.type,
+ "title": TEST_CREDENTIALS.title,
+}
+
+
+async def link_api_request(
+ credentials: StripeLinkCredentials,
+ method: str,
+ path: str,
+ body: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """
+ Make an authenticated request to the Link API.
+
+ Uses the access_token from OAuth2Credentials as a Bearer token.
+
+ Refresh is deliberately not handled here: `IntegrationCredentialsManager`
+ already refreshes on acquire (`_refresh_locked`), under a per-credential
+ lock, and persists the rotated tokens. Refreshing inside the block would
+ bypass both and let concurrent nodes stampede the token endpoint.
+ """
+ headers = {
+ "Authorization": f"Bearer {credentials.access_token.get_secret_value()}",
+ "Content-Type": "application/json",
+ }
+
+ async with httpx.AsyncClient(timeout=LINK_HTTP_TIMEOUT) as client:
+ response = await client.request(
+ method=method,
+ url=f"{LINK_API_BASE_URL}{path}",
+ headers=headers,
+ json=body,
+ )
+ response.raise_for_status()
+ return response.json()
diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/profile.py b/autogpt_platform/backend/backend/blocks/stripe_link/profile.py
new file mode 100644
index 0000000000..6fd2c74088
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/stripe_link/profile.py
@@ -0,0 +1,177 @@
+"""
+Stripe Link — wallet profile blocks.
+
+Read-only lookups an agent needs to actually complete a purchase: who the
+user is, and where to ship. Both are separate from the spend-request flow.
+"""
+
+from typing import Any
+
+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,
+ link_api_request,
+)
+from backend.data.model import SchemaField
+
+
+class StripeLinkGetUserInfoBlock(Block):
+ """Read the Link account holder's name and contact details."""
+
+ # Exposed as a class attribute so `test_mock` can patch it; the harness
+ # only replaces names it can find on the block instance.
+ _link_api_request = staticmethod(link_api_request)
+
+ class Input(BlockSchemaInput):
+ credentials: StripeLinkCredentialsInput = StripeLinkCredentialsField()
+
+ class Output(BlockSchemaOutput):
+ name: str = SchemaField(description="Full name on the Link account")
+ first_name: str = SchemaField(description="Given name", default="")
+ last_name: str = SchemaField(description="Family name", default="")
+ email: str = SchemaField(description="Email on the Link account", default="")
+ phone: str = SchemaField(
+ description="Phone number in E.164 format, e.g. +15551234567", default=""
+ )
+ error: str = SchemaField(
+ description="Error message if the request failed", default=""
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="780daefe-be88-457d-af4b-c8c931daaad0",
+ description=(
+ "Get the Link account holder's name, email and phone. Use it "
+ "to fill in a checkout that asks who the buyer is. Pairs with "
+ "Get Shipping Address for anything physical."
+ ),
+ categories={BlockCategory.DATA},
+ input_schema=self.Input,
+ output_schema=self.Output,
+ test_input={"credentials": TEST_CREDENTIALS_INPUT},
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("name", "Ada Lovelace"),
+ ("first_name", "Ada"),
+ ("last_name", "Lovelace"),
+ ("email", "[email protected]"),
+ ("phone", "+15551234567"),
+ ],
+ test_mock={
+ "_link_api_request": lambda *args, **kwargs: {
+ "name": "Ada Lovelace",
+ "first_name": "Ada",
+ "last_name": "Lovelace",
+ "email": "[email protected]",
+ "phone": "+15551234567",
+ }
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: StripeLinkCredentials,
+ **kwargs: Any,
+ ) -> BlockOutput:
+ try:
+ info = await self._link_api_request(credentials, "GET", "/userinfo")
+ yield "name", info.get("name", "")
+ yield "first_name", info.get("first_name", "")
+ yield "last_name", info.get("last_name", "")
+ yield "email", info.get("email", "")
+ yield "phone", info.get("phone", "")
+ except Exception as e:
+ yield "error", str(e)
+
+
+class StripeLinkGetShippingAddressBlock(Block):
+ """Read the shipping addresses saved on the Link account."""
+
+ _link_api_request = staticmethod(link_api_request)
+
+ class Input(BlockSchemaInput):
+ credentials: StripeLinkCredentialsInput = StripeLinkCredentialsField()
+
+ class Output(BlockSchemaOutput):
+ addresses: list[dict[str, Any]] = SchemaField(
+ description="Every shipping address on the account, each with an "
+ "`id`, `is_default` and an `address` object"
+ )
+ default_address: dict[str, Any] = SchemaField(
+ description="The address object marked default, or the first one "
+ "if none is. Empty when the account has no addresses."
+ )
+ error: str = SchemaField(
+ description="Error message if the request failed", default=""
+ )
+
+ def __init__(self):
+ example = {
+ "id": "csmrsa_test",
+ "is_default": True,
+ "address": {
+ "line_1": "1 Infinite Loop",
+ "locality": "Cupertino",
+ "administrative_area": "CA",
+ "postal_code": "95014",
+ "country_code": "US",
+ },
+ }
+ super().__init__(
+ id="4ace99c4-5b0d-4f2d-a371-397c65acfcd2",
+ description=(
+ "Get the delivery addresses saved on the user's Link wallet, "
+ "with the default one resolved for you. Use it for any "
+ "purchase that ships something."
+ ),
+ categories={BlockCategory.DATA},
+ input_schema=self.Input,
+ output_schema=self.Output,
+ test_input={"credentials": TEST_CREDENTIALS_INPUT},
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("addresses", [example]),
+ ("default_address", example["address"]),
+ ],
+ test_mock={
+ "_link_api_request": lambda *args, **kwargs: {
+ "shipping_addresses": [example]
+ }
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: StripeLinkCredentials,
+ **kwargs: Any,
+ ) -> BlockOutput:
+ try:
+ response = await self._link_api_request(
+ credentials, "GET", "/shipping_addresses"
+ )
+ addresses = response.get("shipping_addresses", [])
+ yield "addresses", addresses
+
+ # Prefer the one the user marked default; fall back to the first so
+ # a single-address account still yields something usable.
+ default = next(
+ (a for a in addresses if a.get("is_default")),
+ addresses[0] if addresses else None,
+ )
+ yield "default_address", (default or {}).get("address", {})
+ except Exception as e:
+ yield "error", str(e)
diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.py b/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.py
new file mode 100644
index 0000000000..d661a677ba
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/stripe_link/spend_request.py
@@ -0,0 +1,578 @@
+"""
+Stripe Link — Spend Request blocks.
+
+These blocks interact with the Link API (api.link.com) to create, retrieve,
+and approve spend requests. A spend request provisions a one-time-use virtual
+card or shared payment token from the user's Link wallet.
+"""
+
+import logging
+import re
+from typing import Any
+
+from pydantic import field_validator
+
+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,
+ link_api_request,
+)
+from backend.data.model import SchemaField
+from backend.util.settings import BehaveAs, Settings
+
+logger = logging.getLogger(__name__)
+settings = Settings()
+
+
+# Raw virtual-card numbers cannot be handed out on the hosted platform: block
+# outputs are persisted with the execution and surface into AutoPilot
+# transcripts, so a PAN there is cardholder data at rest and a stored CVC is
+# prohibited outright. Rather than returning a crippled card block, the card
+# flow is absent from Cloud entirely — you cannot create a spend request you
+# would have no way to redeem. Self-hosted installs get the full flow: the
+# operator is the cardholder, holding their own card in their own database.
+#
+# The Shared Payment Token flow is unaffected and runs on both. An SPT is a
+# token rather than a PAN, and the MPP blocks consume it in-process without
+# ever emitting it.
+def card_flow_disabled() -> bool:
+ """Whether this deployment withholds the virtual-card blocks.
+
+ A function so the predicate itself is testable: the blocks read the
+ constant below at class-definition time, so a test that patches the
+ constant proves only that the wiring works, not that it is derived from
+ the right thing.
+ """
+ return settings.config.behave_as == BehaveAs.CLOUD
+
+
+CARD_FLOW_DISABLED = card_flow_disabled()
+
+# Link's own id shape. Validated rather than only escaped: the status block is
+# the one spend-request read reachable on Cloud, and an id like
+# `lsrq_x?include=card` would make it ask Link for card material — the
+# guarantee that it cannot pull card data otherwise holds only for well-formed
+# input.
+_SPEND_REQUEST_ID = re.compile(r"^lsrq_[A-Za-z0-9_-]+$")
+
+
+def _validate_spend_request_id(value: str) -> str:
+ if not _SPEND_REQUEST_ID.match(value):
+ raise ValueError(
+ "spend_request_id must look like 'lsrq_...' — anything else could "
+ "steer the authenticated call at a different Link endpoint"
+ )
+ return value
+
+
+# What a payment method may contribute to a block output. Listing payment
+# methods is not behind CARD_FLOW_DISABLED, so it runs on Cloud — projecting
+# explicitly makes "no cardholder data at rest on Cloud" a property of this
+# repo rather than of whatever Link happens to add to `payment_details` next.
+_PAYMENT_METHOD_FIELDS = ("id", "type", "name", "is_default")
+_CARD_DETAIL_FIELDS = ("brand", "last4", "exp_month", "exp_year")
+
+
+def _project_payment_method(pm: dict[str, Any]) -> dict[str, Any]:
+ """Keep only the fields a graph needs to choose a payment method."""
+ projected: dict[str, Any] = {k: pm[k] for k in _PAYMENT_METHOD_FIELDS if k in pm}
+ details = pm.get("card_details")
+ if isinstance(details, dict):
+ projected["card_details"] = {
+ k: details[k] for k in _CARD_DETAIL_FIELDS if k in details
+ }
+ return projected
+
+
+# ---------------------------------------------------------------------------
+# Shared helpers
+# ---------------------------------------------------------------------------
+
+
+# ---------------------------------------------------------------------------
+# Block: List Payment Methods
+# ---------------------------------------------------------------------------
+class StripeLinkListPaymentMethodsBlock(Block):
+ """List payment methods (cards and bank accounts) from the user's Link wallet."""
+
+ # Exposed as a class attribute so `test_mock` can patch it; the harness
+ # only replaces names it can find on the block instance.
+ _link_api_request = staticmethod(link_api_request)
+
+ class Input(BlockSchemaInput):
+ credentials: StripeLinkCredentialsInput = StripeLinkCredentialsField()
+
+ class Output(BlockSchemaOutput):
+ payment_methods: list[dict[str, Any]] = SchemaField(
+ description="List of payment methods in the Link wallet"
+ )
+ error: str = SchemaField(
+ description="Error message if the request failed",
+ default="",
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="6eacc954-2218-4dc7-a485-5bf21549ecbe",
+ description="List payment methods from a Stripe Link wallet",
+ categories={BlockCategory.DATA},
+ input_schema=self.Input,
+ output_schema=self.Output,
+ test_input={
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ (
+ "payment_methods",
+ [
+ {
+ "id": "csmrpd_test",
+ "type": "CARD",
+ "name": "Test Debit Card",
+ "is_default": False,
+ "card_details": {
+ "brand": "visa",
+ "last4": "4242",
+ "exp_month": 12,
+ "exp_year": 2030,
+ },
+ }
+ ],
+ )
+ ],
+ test_mock={
+ "_link_api_request": lambda *args, **kwargs: {
+ "payment_details": [
+ {
+ "id": "csmrpd_test",
+ "type": "CARD",
+ "name": "Test Debit Card",
+ "is_default": False,
+ "card_details": {
+ "brand": "visa",
+ "last4": "4242",
+ "exp_month": 12,
+ "exp_year": 2030,
+ },
+ }
+ ]
+ }
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: StripeLinkCredentials,
+ **kwargs: Any,
+ ) -> BlockOutput:
+ try:
+ # `/payment-details`, not `/payment_methods` — the latter 404s. The
+ # list is nested under `payment_details`, matching @stripe/link-cli's
+ # SDK (packages/sdk/src/resources/payment-methods.ts).
+ response = await self._link_api_request(
+ credentials, "GET", "/payment-details"
+ )
+ yield "payment_methods", [
+ _project_payment_method(pm)
+ for pm in response.get("payment_details", [])
+ if isinstance(pm, dict)
+ ]
+ except Exception as e:
+ yield "error", str(e)
+
+
+# ---------------------------------------------------------------------------
+# Block: Create Spend Request
+# ---------------------------------------------------------------------------
+class StripeLinkCreateCardSpendRequestBlock(Block):
+ """
+ Create a spend request for a one-time-use virtual card.
+
+ The user approves the request in the Link app, after which
+ `StripeLinkRetrieveCardBlock` returns the card details. Poll for that
+ approval with `StripeLinkGetSpendRequestStatusBlock`.
+
+ Self-hosted only — see CARD_FLOW_DISABLED.
+ """
+
+ # Exposed as a class attribute so `test_mock` can patch it; the harness
+ # only replaces names it can find on the block instance.
+ _link_api_request = staticmethod(link_api_request)
+
+ class Input(BlockSchemaInput):
+ credentials: StripeLinkCredentialsInput = StripeLinkCredentialsField()
+ payment_method_id: str = SchemaField(
+ description="ID of the payment method to use (from list payment methods)"
+ )
+ merchant_name: str = SchemaField(
+ description="Name of the merchant for this purchase"
+ )
+ merchant_url: str = SchemaField(description="URL of the merchant website")
+ context: str = SchemaField(
+ description=(
+ "Description of the purchase context (min 100 characters). "
+ "Shown to the user when they approve the request."
+ ),
+ # Enforced, not just documented: this is the text the user reads
+ # when deciding whether to approve a charge.
+ min_length=100,
+ )
+ amount: int = SchemaField(
+ description=(
+ "Amount in the currency's smallest unit — cents for USD, but "
+ "whole units for zero-decimal currencies like JPY (max 50000)"
+ ),
+ ge=1,
+ le=50000,
+ )
+ currency: str = SchemaField(
+ description="3-letter ISO currency code", default="usd"
+ )
+ request_approval: bool = SchemaField(
+ description=(
+ "If true, immediately sends a push notification to the user "
+ "for approval. Otherwise, call request-approval separately."
+ ),
+ default=True,
+ )
+ test_mode: bool = SchemaField(
+ description="Use test mode (fake card 4242424242424242)",
+ default=False,
+ )
+
+ class Output(BlockSchemaOutput):
+ spend_request_id: str = SchemaField(
+ description="ID of the created spend request"
+ )
+ status: str = SchemaField(
+ description="Status: created, pending_approval, approved, denied, etc."
+ )
+ approval_url: str = SchemaField(
+ description="URL the user can visit to approve (if not using push)",
+ default="",
+ )
+ error: str = SchemaField(
+ description="Error message if the request failed",
+ default="",
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="932c3c12-1e80-4392-8fb3-37824eb8a427",
+ description=(
+ "Create a Stripe Link spend request for a one-time virtual "
+ "card. Self-hosted only; on AutoGPT Cloud use the Shared "
+ "Payment Token flow with the MPP blocks instead."
+ ),
+ categories={BlockCategory.DATA},
+ disabled=CARD_FLOW_DISABLED,
+ input_schema=self.Input,
+ output_schema=self.Output,
+ test_input={
+ "credentials": TEST_CREDENTIALS_INPUT,
+ "payment_method_id": "csmrpd_test",
+ "merchant_name": "Test Store",
+ "merchant_url": "https://example.com",
+ "context": "x" * 100,
+ "amount": 1000,
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("spend_request_id", "lsrq_test123"),
+ ("status", "pending_approval"),
+ ],
+ test_mock={
+ "_link_api_request": lambda *args, **kwargs: {
+ "id": "lsrq_test123",
+ "status": "pending_approval",
+ "approval_url": "",
+ }
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: StripeLinkCredentials,
+ **kwargs: Any,
+ ) -> BlockOutput:
+ try:
+ result = await self._link_api_request(
+ credentials,
+ "POST",
+ "/spend_requests",
+ body={
+ "payment_details": input_data.payment_method_id,
+ "merchant_name": input_data.merchant_name,
+ "merchant_url": input_data.merchant_url,
+ "context": input_data.context,
+ "amount": input_data.amount,
+ "currency": input_data.currency,
+ "request_approval": input_data.request_approval,
+ "test": input_data.test_mode,
+ },
+ )
+ # Note: do NOT also call POST /spend_requests/{id}/request_approval
+ # here. `request_approval` in the body already moves the request to
+ # pending_approval, and the dedicated endpoint then 409s. That
+ # endpoint is for requesting approval on a request created without
+ # it — verified against the live API.
+ yield "spend_request_id", result["id"]
+ yield "status", result["status"]
+ if result.get("approval_url"):
+ yield "approval_url", result["approval_url"]
+ except Exception as e:
+ yield "error", str(e)
+
+
+# ---------------------------------------------------------------------------
+# Block: Get Spend Request Status
+# ---------------------------------------------------------------------------
+class StripeLinkGetSpendRequestStatusBlock(Block):
+ """
+ Poll a spend request until the user approves it.
+
+ Every flow needs this step — a freshly created request is
+ `pending_approval` until the user acts in the Link app, and both the card
+ and MPP paths must wait for `approved` before they can do anything. It
+ carries no payment credential, so it runs on every deployment.
+ """
+
+ # Exposed as a class attribute so `test_mock` can patch it; the harness
+ # only replaces names it can find on the block instance.
+ _link_api_request = staticmethod(link_api_request)
+
+ class Input(BlockSchemaInput):
+ credentials: StripeLinkCredentialsInput = StripeLinkCredentialsField()
+ spend_request_id: str = SchemaField(
+ description="ID of the spend request to check (e.g., lsrq_...)"
+ )
+
+ _check_id = field_validator("spend_request_id")(_validate_spend_request_id)
+
+ class Output(BlockSchemaOutput):
+ status: str = SchemaField(
+ description=(
+ "Current status: pending_approval, approved, denied, expired. "
+ "Wait for `approved` before spending the credential."
+ )
+ )
+ error: str = SchemaField(
+ description="Error message if the request failed",
+ default="",
+ )
+
+ def __init__(self):
+ super().__init__(
+ 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."
+ ),
+ categories={BlockCategory.DATA},
+ input_schema=self.Input,
+ output_schema=self.Output,
+ test_input={
+ "credentials": TEST_CREDENTIALS_INPUT,
+ "spend_request_id": "lsrq_test123",
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[("status", "approved")],
+ test_mock={
+ "_link_api_request": lambda *args, **kwargs: {"status": "approved"}
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: StripeLinkCredentials,
+ **kwargs: Any,
+ ) -> BlockOutput:
+ try:
+ result = await self._link_api_request(
+ credentials,
+ "GET",
+ f"/spend_requests/{input_data.spend_request_id}",
+ )
+ yield "status", result["status"]
+ except Exception as e:
+ yield "error", str(e)
+
+
+# ---------------------------------------------------------------------------
+# Block: Retrieve Card
+# ---------------------------------------------------------------------------
+class StripeLinkRetrieveCardBlock(Block):
+ """
+ Return the virtual card for an approved spend request.
+
+ Single-use, capped at the approved amount, and expiring at `valid_until`.
+ There is no opt-in flag: emitting the card is the entire purpose of this
+ block, so its availability is the control. Self-hosted only — see
+ CARD_FLOW_DISABLED.
+
+ The card number and CVC are written to the execution record in clear text
+ and are readable through the execution-results API. Nothing redacts them.
+ Do not enable this block in an environment where PCI compliance matters.
+ """
+
+ # Exposed as a class attribute so `test_mock` can patch it; the harness
+ # only replaces names it can find on the block instance.
+ _link_api_request = staticmethod(link_api_request)
+
+ class Input(BlockSchemaInput):
+ credentials: StripeLinkCredentialsInput = StripeLinkCredentialsField()
+ spend_request_id: str = SchemaField(
+ description="ID of an approved spend request (e.g., lsrq_...)"
+ )
+
+ _check_id = field_validator("spend_request_id")(_validate_spend_request_id)
+
+ # if you use this block note the card number will be logged. Do not use
+ # this in environments where PCI compliance matters.
+ #
+ # Deliberately no `secret=True` on the card fields: that flag reaches only
+ # `json_schema_extra`, whose sole consumer strips `input_default` on graph
+ # export, so it does nothing for outputs. Marking them would advertise a
+ # redaction that does not exist.
+ class Output(BlockSchemaOutput):
+ status: str = SchemaField(description="Current status of the spend request")
+ card_number: str = SchemaField(
+ description=(
+ "Virtual card number. Single-use, capped at the approved "
+ "amount, and expires at `valid_until`. Stored in clear text "
+ "with the execution record and readable through the "
+ "execution-results API — do not enable this block where PCI "
+ "compliance matters."
+ ),
+ default="",
+ )
+ card_cvc: str = SchemaField(
+ description=(
+ "Virtual card CVC. Stored in clear text with the execution "
+ "record, same as `card_number`. Retaining a CVC after "
+ "authorization is prohibited under PCI DSS 3.2."
+ ),
+ default="",
+ )
+ card_exp_month: int = SchemaField(
+ description="Card expiry month",
+ default=0,
+ )
+ card_exp_year: int = SchemaField(
+ description="Card expiry year",
+ default=0,
+ )
+ card_brand: str = SchemaField(
+ description="Card brand (visa, mastercard, etc.)",
+ default="",
+ )
+ valid_until: str = SchemaField(
+ description="ISO timestamp when the virtual card expires",
+ default="",
+ )
+ error: str = SchemaField(
+ description="Error message if the request failed",
+ default="",
+ )
+
+ def __init__(self):
+ 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."
+ ),
+ categories={BlockCategory.DATA},
+ disabled=CARD_FLOW_DISABLED,
+ input_schema=self.Input,
+ output_schema=self.Output,
+ test_input={
+ "credentials": TEST_CREDENTIALS_INPUT,
+ "spend_request_id": "lsrq_test123",
+ },
+ test_credentials=TEST_CREDENTIALS,
+ test_output=[
+ ("status", "approved"),
+ ("card_number", "4242424242424242"),
+ ("card_cvc", "123"),
+ ("card_exp_month", 12),
+ ("card_exp_year", 2030),
+ ("card_brand", "visa"),
+ ("valid_until", "2025-12-31T23:59:59Z"),
+ ],
+ test_mock={
+ "_link_api_request": lambda *args, **kwargs: {
+ "status": "approved",
+ "card": {
+ "number": "4242424242424242",
+ "cvc": "123",
+ "exp_month": 12,
+ "exp_year": 2030,
+ "brand": "visa",
+ "valid_until": "2025-12-31T23:59:59Z",
+ },
+ }
+ },
+ )
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: StripeLinkCredentials,
+ **kwargs: Any,
+ ) -> BlockOutput:
+ try:
+ result = await self._link_api_request(
+ credentials,
+ "GET",
+ f"/spend_requests/{input_data.spend_request_id}?include=card",
+ )
+
+ status = result["status"]
+ yield "status", status
+
+ # Only for a spend the user actually approved. If a denied or
+ # expired request ever came back with card material attached,
+ # emitting it would put a PAN and CVC in the execution record for
+ # a charge that was refused.
+ if status != "approved":
+ # Terminal and unusable. Without this the graph stalls: nothing
+ # fires downstream and the agent stops mid-checkout with no
+ # message about why.
+ yield "error", (
+ f"Spend request is {status}, so no card was issued. "
+ "Create a new spend request if the user still wants to pay."
+ )
+ return
+
+ card = result.get("card")
+ if card:
+ yield "card_number", card.get("number", "")
+ yield "card_cvc", card.get("cvc", "")
+ yield "card_exp_month", card.get("exp_month", 0)
+ yield "card_exp_year", card.get("exp_year", 0)
+ yield "card_brand", card.get("brand", "")
+ yield "valid_until", card.get("valid_until", "")
+ except Exception as e:
+ yield "error", str(e)
diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/spend_request_test.py b/autogpt_platform/backend/backend/blocks/stripe_link/spend_request_test.py
new file mode 100644
index 0000000000..5cd1c6b357
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/stripe_link/spend_request_test.py
@@ -0,0 +1,197 @@
+"""Deployment gating for the Stripe Link spend-request blocks.
+
+The virtual-card flow is self-hosted only: block outputs are persisted with
+the execution and surface into AutoPilot transcripts, so a PAN there is
+cardholder data at rest and a stored CVC is prohibited outright. The blocks
+are split along that line — card create/retrieve are gated, while the pieces
+the Shared Payment Token flow needs stay available everywhere.
+"""
+
+import pytest
+from pydantic import ValidationError
+
+from backend.blocks.stripe_link import spend_request as sr
+from backend.blocks.stripe_link._auth import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT
+
+CARD_BLOCKS = (
+ sr.StripeLinkCreateCardSpendRequestBlock,
+ sr.StripeLinkRetrieveCardBlock,
+)
+ALWAYS_AVAILABLE_BLOCKS = (
+ sr.StripeLinkListPaymentMethodsBlock,
+ sr.StripeLinkGetSpendRequestStatusBlock,
+)
+
+
+def test_card_blocks_are_unavailable_on_cloud(monkeypatch):
+ monkeypatch.setattr(sr, "CARD_FLOW_DISABLED", True)
+
+ for block_cls in CARD_BLOCKS:
+ assert block_cls().disabled is True, block_cls.__name__
+
+
+def test_card_blocks_are_available_when_self_hosted(monkeypatch):
+ monkeypatch.setattr(sr, "CARD_FLOW_DISABLED", False)
+
+ for block_cls in CARD_BLOCKS:
+ assert block_cls().disabled is False, block_cls.__name__
+
+
+def test_the_spt_flow_survives_on_cloud(monkeypatch):
+ """Gating the card flow must not take the token flow with it.
+
+ Creating a spend request is pointless unless something can wait for the
+ user to approve it, so the status poll has to remain available even where
+ no card may be issued.
+ """
+ monkeypatch.setattr(sr, "CARD_FLOW_DISABLED", True)
+
+ for block_cls in ALWAYS_AVAILABLE_BLOCKS:
+ assert block_cls().disabled is False, block_cls.__name__
+
+
+async def test_the_status_block_cannot_pull_card_data():
+ """It is the one spend-request block reachable on Cloud, so it must have
+ no way to ask Link for a card in the first place."""
+ seen: dict = {}
+ block = sr.StripeLinkGetSpendRequestStatusBlock()
+
+ async def _fake(credentials, method, path, body=None):
+ seen["path"] = path
+ return {"status": "approved", "card": {"number": "4242424242424242"}}
+
+ object.__setattr__(block, "_link_api_request", _fake)
+ inp = block.Input.model_validate(
+ {"credentials": TEST_CREDENTIALS_INPUT, "spend_request_id": "lsrq_test"}
+ )
+
+ outputs = {n: v async for n, v in block.run(inp, credentials=TEST_CREDENTIALS)}
+
+ assert "include" not in seen["path"]
+ assert outputs["status"] == "approved"
+ # Even when Link volunteers a card, this block has no output for it.
+ assert "card_number" not in outputs
+
+
+async def test_the_card_block_asks_for_the_card_without_an_opt_in():
+ """Availability is the control now, so there is no include_card flag to
+ forget to set."""
+ seen: dict = {}
+ block = sr.StripeLinkRetrieveCardBlock()
+
+ async def _fake(credentials, method, path, body=None):
+ seen["path"] = path
+ return {
+ "status": "approved",
+ "card": {"number": "4242424242424242", "cvc": "123"},
+ }
+
+ object.__setattr__(block, "_link_api_request", _fake)
+ inp = block.Input.model_validate(
+ {"credentials": TEST_CREDENTIALS_INPUT, "spend_request_id": "lsrq_test"}
+ )
+
+ outputs = {n: v async for n, v in block.run(inp, credentials=TEST_CREDENTIALS)}
+
+ assert "include=card" in seen["path"]
+ assert outputs["card_number"] == "4242424242424242"
+ assert outputs["card_cvc"] == "123"
+
+
+def test_the_card_gate_predicate_itself_tracks_behave_as(monkeypatch):
+ """The other gate tests patch CARD_FLOW_DISABLED, so none of them pin the
+ predicate. Invert it — or point it at a setting Cloud does not set — and
+ they would all still pass while the card blocks went live on Cloud."""
+ from backend.util.settings import BehaveAs
+
+ monkeypatch.setattr(sr.settings.config, "behave_as", BehaveAs.CLOUD)
+ assert sr.card_flow_disabled() is True
+
+ monkeypatch.setattr(sr.settings.config, "behave_as", BehaveAs.LOCAL)
+ assert sr.card_flow_disabled() is False
+
+ # And the constant the blocks are wired to comes from that predicate.
+ assert sr.CARD_FLOW_DISABLED == sr.card_flow_disabled()
+
+
+async def test_listed_payment_methods_are_projected_to_known_fields():
+ """This block runs on Cloud, so what it emits cannot depend on Link's
+ response shape — a field added upstream would otherwise land in a
+ persisted execution record without anyone touching this repo."""
+ block = sr.StripeLinkListPaymentMethodsBlock()
+
+ async def _fake(credentials, method, path, body=None):
+ return {
+ "payment_details": [
+ {
+ "id": "csmrpd_1",
+ "type": "CARD",
+ "name": "Debit",
+ "is_default": True,
+ "card_details": {
+ "brand": "visa",
+ "last4": "4242",
+ "number": "4242424242424242",
+ "cvc": "123",
+ },
+ "some_future_field": "should not be emitted",
+ }
+ ]
+ }
+
+ object.__setattr__(block, "_link_api_request", _fake)
+ inp = block.Input.model_validate({"credentials": TEST_CREDENTIALS_INPUT})
+ outputs = {n: v async for n, v in block.run(inp, credentials=TEST_CREDENTIALS)}
+
+ [pm] = outputs["payment_methods"]
+ assert pm == {
+ "id": "csmrpd_1",
+ "type": "CARD",
+ "name": "Debit",
+ "is_default": True,
+ "card_details": {"brand": "visa", "last4": "4242"},
+ }
+ assert "number" not in pm["card_details"]
+ assert "some_future_field" not in pm
+
+
+async def test_a_denied_request_emits_no_card_and_says_so():
+ """Inverting the status guard left the suite green: nothing asserted the
+ negative. A refused spend must not put a PAN in the execution record, and
+ must not stall the graph silently either."""
+ block = sr.StripeLinkRetrieveCardBlock()
+
+ async def _fake(credentials, method, path, body=None):
+ return {
+ "status": "denied",
+ "card": {"number": "4242424242424242", "cvc": "123"},
+ }
+
+ object.__setattr__(block, "_link_api_request", _fake)
+ inp = block.Input.model_validate(
+ {"credentials": TEST_CREDENTIALS_INPUT, "spend_request_id": "lsrq_test"}
+ )
+ outputs = {n: v async for n, v in block.run(inp, credentials=TEST_CREDENTIALS)}
+
+ assert outputs["status"] == "denied"
+ assert "card_number" not in outputs
+ assert "card_cvc" not in outputs
+ # Downstream nodes need something to fire on, or the agent stops
+ # mid-checkout with no message.
+ assert "error" in outputs
+
+
+async def test_a_malformed_spend_request_id_is_rejected():
+ """The status block is the one spend-request read reachable on Cloud, and
+ `lsrq_x?include=card` would make it ask Link for card material."""
+ block = sr.StripeLinkGetSpendRequestStatusBlock()
+ for bad in ("lsrq_x?include=card", "../../other", "lsrq_a/b", "nope"):
+ with pytest.raises(ValidationError):
+ block.Input.model_validate(
+ {"credentials": TEST_CREDENTIALS_INPUT, "spend_request_id": bad}
+ )
diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.py
index 5c0cd5873c..b5edd3b0c4 100644
--- a/autogpt_platform/backend/backend/data/model.py
+++ b/autogpt_platform/backend/backend/data/model.py
@@ -459,7 +459,9 @@ Credentials = Annotated[
CREDENTIALS_ADAPTER: TypeAdapter[Credentials] = TypeAdapter(Credentials)
-CredentialsType = Literal["api_key", "oauth2", "user_password", "host_scoped"]
+CredentialsType = Literal[
+ "api_key", "oauth2", "user_password", "host_scoped", "device_code"
+]
class OAuthState(BaseModel):
diff --git a/autogpt_platform/backend/backend/integrations/credentials_store.py b/autogpt_platform/backend/backend/integrations/credentials_store.py
index 465fbcffd9..64e99a9253 100644
--- a/autogpt_platform/backend/backend/integrations/credentials_store.py
+++ b/autogpt_platform/backend/backend/integrations/credentials_store.py
@@ -640,6 +640,70 @@ class IntegrationCredentialsStore:
return None
+ async def peek_state_token(
+ self, user_id: str, token: str, provider: str
+ ) -> Optional[OAuthState]:
+ """Validate a state token WITHOUT consuming it.
+
+ Used by the device-auth polling loop: the state must survive many
+ poll attempts and is only consumed once auth reaches a terminal
+ state (approved / denied / expired).
+
+ Deliberately lock-free. A poll loop calls this every ~5s for up to ten
+ minutes, and taking the per-user write lock on a pure read serialized
+ the user's other credential operations behind ~120 acquisitions per
+ flow. Racing a concurrent `consume` can only mean seeing the state or
+ not seeing it, which are both valid poll outcomes; single-use
+ consumption is still enforced under the lock in `consume_state_token`.
+ """
+ user_integrations = await self._get_user_integrations(user_id)
+
+ now = datetime.now(timezone.utc)
+ return next(
+ (
+ state
+ for state in user_integrations.oauth_states
+ if secrets.compare_digest(state.token, token)
+ and provider_matches(state.provider, provider)
+ and state.expires_at > now.timestamp()
+ ),
+ None,
+ )
+
+ async def consume_state_token(
+ self, user_id: str, token: str, provider: str
+ ) -> Optional[OAuthState]:
+ """Validate and remove a state token (one-time consumption).
+
+ Used when the device-auth flow reaches a terminal state so the
+ token cannot be reused.
+ """
+ async with await self.locked_user_integrations(user_id):
+ user_integrations = await self._get_user_integrations(user_id)
+ oauth_states = user_integrations.oauth_states
+
+ now = datetime.now(timezone.utc)
+ valid_state = next(
+ (
+ state
+ for state in oauth_states
+ if secrets.compare_digest(state.token, token)
+ and provider_matches(state.provider, provider)
+ and state.expires_at > now.timestamp()
+ ),
+ None,
+ )
+
+ if valid_state:
+ oauth_states.remove(valid_state)
+ user_integrations.oauth_states = oauth_states
+ await self.db_manager.update_user_integrations(
+ user_id, user_integrations
+ )
+ return valid_state
+
+ return None
+
# =================== GET/SET HELPERS =================== #
@asynccontextmanager
diff --git a/autogpt_platform/backend/backend/integrations/credentials_store_state_token_test.py b/autogpt_platform/backend/backend/integrations/credentials_store_state_token_test.py
new file mode 100644
index 0000000000..ce51c76e5a
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/credentials_store_state_token_test.py
@@ -0,0 +1,111 @@
+"""State-token lifecycle for the device-code flow.
+
+`peek` and `consume` exist as a pair specifically so a poll loop can read the
+same token many times while exactly one caller may retire it. Both halves are
+pinned here: without the non-consuming read the second poll 400s, and without
+single-use consumption an approval stores duplicate credentials.
+"""
+
+from datetime import datetime, timedelta, timezone
+from unittest.mock import AsyncMock, MagicMock, PropertyMock
+
+import pytest
+
+from backend.data.model import OAuthState, UserIntegrations
+from backend.integrations.credentials_store import IntegrationCredentialsStore
+
+
+class _NoopLockContext:
+ async def __aenter__(self) -> None:
+ return None
+
+ async def __aexit__(self, _exc_type, _exc, _traceback) -> None:
+ return None
+
+
+def _state(
+ token: str = "tok",
+ provider: str = "stripe_link",
+ expires_in: int = 600,
+) -> OAuthState:
+ return OAuthState(
+ token=token,
+ provider=provider,
+ expires_at=int(
+ (datetime.now(timezone.utc) + timedelta(seconds=expires_in)).timestamp()
+ ),
+ scopes=["userinfo:read"],
+ state_metadata={"flow_type": "device_code", "device_code": "dev-code"},
+ )
+
+
+def _store_with(mocker, states: list[OAuthState]):
+ store = IntegrationCredentialsStore()
+ integrations = UserIntegrations(oauth_states=states)
+ mocker.patch.object(
+ store, "locked_user_integrations", AsyncMock(return_value=_NoopLockContext())
+ )
+ mocker.patch.object(
+ store, "_get_user_integrations", AsyncMock(return_value=integrations)
+ )
+ # `db_manager` is a property returning the real DatabaseManager client; left
+ # unpatched, `consume_state_token` makes an RPC whose socket read never
+ # returns and the test hangs rather than fails.
+ db_manager = MagicMock()
+ db_manager.update_user_integrations = AsyncMock()
+ mocker.patch.object(
+ IntegrationCredentialsStore,
+ "db_manager",
+ new_callable=PropertyMock,
+ return_value=db_manager,
+ )
+ return store, integrations
+
+
+async def test_peek_returns_the_state_without_removing_it(mocker):
+ store, integrations = _store_with(mocker, [_state()])
+
+ for _ in range(3):
+ found = await store.peek_state_token("user-a", "tok", "stripe_link")
+ assert found is not None
+ assert found.state_metadata["device_code"] == "dev-code"
+
+ assert len(integrations.oauth_states) == 1
+
+
+async def test_consume_removes_the_state_and_only_succeeds_once(mocker):
+ store, integrations = _store_with(mocker, [_state()])
+
+ first = await store.consume_state_token("user-a", "tok", "stripe_link")
+ assert first is not None
+ assert integrations.oauth_states == []
+
+ # The race loser: same token, already retired.
+ second = await store.consume_state_token("user-a", "tok", "stripe_link")
+ assert second is None
+
+
+async def test_peek_rejects_a_token_from_another_provider(mocker):
+ store, _ = _store_with(mocker, [_state(provider="github")])
+
+ assert await store.peek_state_token("user-a", "tok", "stripe_link") is None
+
+
+async def test_peek_and_consume_reject_an_expired_token(mocker):
+ store, integrations = _store_with(mocker, [_state(expires_in=-1)])
+
+ assert await store.peek_state_token("user-a", "tok", "stripe_link") is None
+ assert await store.consume_state_token("user-a", "tok", "stripe_link") is None
+ # An expired token is rejected, not silently swept.
+ assert len(integrations.oauth_states) == 1
+
+
+async def test_peek_rejects_an_unknown_token(mocker):
+ store, _ = _store_with(mocker, [_state()])
+
+ assert await store.peek_state_token("user-a", "wrong", "stripe_link") is None
diff --git a/autogpt_platform/backend/backend/integrations/creds_manager.py b/autogpt_platform/backend/backend/integrations/creds_manager.py
index 21d0a3d11f..ff3a9f674d 100644
--- a/autogpt_platform/backend/backend/integrations/creds_manager.py
+++ b/autogpt_platform/backend/backend/integrations/creds_manager.py
@@ -15,13 +15,18 @@ from backend.integrations.credentials_store import (
IntegrationCredentialsStore,
provider_matches,
)
-from backend.integrations.oauth import CREDENTIALS_BY_PROVIDER, HANDLERS_BY_NAME
+from backend.integrations.oauth import (
+ CREDENTIALS_BY_PROVIDER,
+ DEVICE_HANDLERS_BY_NAME,
+ HANDLERS_BY_NAME,
+)
from backend.integrations.providers import ProviderName
from backend.util.exceptions import MissingConfigError
from backend.util.settings import Settings
if TYPE_CHECKING:
- from backend.integrations.oauth import BaseOAuthHandler
+ from backend.integrations.oauth.base import BaseOAuthHandler
+ from backend.integrations.oauth.device_base import BaseDeviceAuthHandler
logger = logging.getLogger(__name__)
settings = Settings()
@@ -221,23 +226,50 @@ class IntegrationCredentialsManager:
# integration_creds module which runs across multiple threads with separate
# event loops; acquiring a Redis lock whose asyncio.Lock() was created on
# a different loop raises "Future attached to a different loop".
- if lock:
- return await self._refresh_locked(user_id, credentials)
- return await self._refresh_unlocked(user_id, credentials)
+ # Resolve once: `_refresh_locked` needs the handler anyway, and
+ # building it twice per refresh just to read a class flag is wasteful.
+ # A construction failure is left to the refresh path to raise, rather
+ # than being turned into "take the lock" — `lock=False` exists because
+ # the copilot runs across threads with separate event loops, where
+ # entering a Redis lock raises "Future attached to a different loop".
+ handler = await self._get_oauth_handler(credentials)
+ if lock or getattr(handler, "ROTATES_REFRESH_TOKEN", False):
+ # A provider that rotates its refresh token cannot take the
+ # unlocked path: "last writer wins" is safe when the refresh token
+ # is static, but two workers replaying the same rotated token can
+ # have the grant revoked by a provider that treats reuse as
+ # compromise, and the loser can persist a token already
+ # invalidated upstream.
+ return await self._refresh_locked(user_id, credentials, handler=handler)
+ return await self._refresh_unlocked(user_id, credentials, handler=handler)
async def _get_oauth_handler(
self, credentials: OAuth2Credentials
- ) -> "BaseOAuthHandler":
+ ) -> "BaseOAuthHandler | BaseDeviceAuthHandler":
"""Resolve the appropriate OAuth handler for the given credentials."""
if provider_matches(credentials.provider, ProviderName.MCP.value):
return create_mcp_oauth_handler(credentials)
+
+ # Try device handlers first (they don't need client_id/secret lookup)
+ # `provider` is typed `str` but carries a ProviderName at runtime; prefer the
+ # enum value so the registry lookup matches either form.
+ provider_key = getattr(credentials.provider, "value", None) or str(
+ credentials.provider
+ )
+ if provider_key in DEVICE_HANDLERS_BY_NAME:
+ handler_class = DEVICE_HANDLERS_BY_NAME[provider_key]
+ return handler_class()
+
return await _get_provider_oauth_handler(credentials.provider)
async def _refresh_locked(
- self, user_id: str, credentials: OAuth2Credentials
+ self,
+ user_id: str,
+ credentials: OAuth2Credentials,
+ handler: "BaseOAuthHandler | BaseDeviceAuthHandler | None" = None,
) -> OAuth2Credentials:
async with self._locked(user_id, credentials.id, "refresh"):
- oauth_handler = await self._get_oauth_handler(credentials)
+ oauth_handler = handler or await self._get_oauth_handler(credentials)
if oauth_handler.needs_refresh(credentials):
logger.debug(
"Refreshing '%s' credentials #%s",
@@ -263,16 +295,20 @@ class IntegrationCredentialsManager:
return credentials
async def _refresh_unlocked(
- self, user_id: str, credentials: OAuth2Credentials
+ self,
+ user_id: str,
+ credentials: OAuth2Credentials,
+ handler: "BaseOAuthHandler | BaseDeviceAuthHandler | None" = None,
) -> OAuth2Credentials:
"""Best-effort token refresh without any Redis locking.
Safe for use from multi-threaded contexts (e.g. copilot workers) where
each thread has its own event loop and sharing Redis-backed asyncio locks
is not possible. Concurrent refreshes are tolerated: the last writer
- wins, and stale tokens are overwritten.
+ wins, and stale tokens are overwritten — which holds only for a static
+ refresh token, so a rotating provider never reaches this path.
"""
- oauth_handler = await self._get_oauth_handler(credentials)
+ oauth_handler = handler or await self._get_oauth_handler(credentials)
if oauth_handler.needs_refresh(credentials):
logger.debug(
"Refreshing '%s' credentials #%s (lock-free)",
diff --git a/autogpt_platform/backend/backend/integrations/oauth/__init__.py b/autogpt_platform/backend/backend/integrations/oauth/__init__.py
index 1ea7a23ee7..1b66585d62 100644
--- a/autogpt_platform/backend/backend/integrations/oauth/__init__.py
+++ b/autogpt_platform/backend/backend/integrations/oauth/__init__.py
@@ -3,12 +3,15 @@ from typing import TYPE_CHECKING, Optional
from pydantic import BaseModel
from backend.integrations.oauth.todoist import TodoistOAuthHandler
+from backend.integrations.providers import provider_key
+from .device_base import BaseDeviceAuthHandler
from .discord import DiscordOAuthHandler
from .github import GitHubOAuthHandler
from .google import GoogleOAuthHandler
from .notion import NotionOAuthHandler
from .reddit import RedditOAuthHandler
+from .stripe_link import StripeLinkDeviceAuthHandler
from .twitter import TwitterOAuthHandler
if TYPE_CHECKING:
@@ -28,11 +31,9 @@ _ORIGINAL_HANDLERS = [
# Start with original handlers
_handlers_dict = {
- (
- handler.PROVIDER_NAME.value
- if hasattr(handler.PROVIDER_NAME, "value")
- else str(handler.PROVIDER_NAME)
- ): handler
+ # PROVIDER_NAME is typed `ProviderName | str`; prefer the enum value so the
+ # registry key matches either form.
+ provider_key(handler.PROVIDER_NAME): handler
for handler in _ORIGINAL_HANDLERS
}
@@ -227,4 +228,27 @@ HANDLERS_BY_NAME: dict[str, type["BaseOAuthHandler"]] = SDKAwareHandlersDict()
CREDENTIALS_BY_PROVIDER: dict[str, SDKAwareCredentials] = SDKAwareCredentialsDict()
# --8<-- [end:HANDLERS_BY_NAMEExample]
-__all__ = ["HANDLERS_BY_NAME"]
+# ------------------------------------------------------------------ #
+# Device Code Grant handlers (RFC 8628)
+# ------------------------------------------------------------------ #
+_ORIGINAL_DEVICE_HANDLERS: list[type[BaseDeviceAuthHandler]] = [
+ StripeLinkDeviceAuthHandler,
+]
+
+_device_handlers_dict: dict[str, type[BaseDeviceAuthHandler]] = {
+ # PROVIDER_NAME is typed `ProviderName | str`; prefer the enum value so the
+ # registry key matches either form.
+ provider_key(handler.PROVIDER_NAME): handler
+ for handler in _ORIGINAL_DEVICE_HANDLERS
+}
+
+
+# A plain dict: the registry is static, unlike the SDK-aware OAuth one, and a
+# wrapper overriding only __getitem__/get/__contains__ left len(), iteration,
+# truthiness and ** unpacking reporting it as empty.
+DEVICE_HANDLERS_BY_NAME: dict[str, type[BaseDeviceAuthHandler]] = _device_handlers_dict
+
+__all__ = [
+ "HANDLERS_BY_NAME",
+ "DEVICE_HANDLERS_BY_NAME",
+]
diff --git a/autogpt_platform/backend/backend/integrations/oauth/device_base.py b/autogpt_platform/backend/backend/integrations/oauth/device_base.py
new file mode 100644
index 0000000000..d59431efa3
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/oauth/device_base.py
@@ -0,0 +1,123 @@
+"""
+Base handler for OAuth 2.0 Device Code Grant (RFC 8628).
+
+Providers that use the device authorization flow (CLI tools, IoT devices,
+smart TVs, etc.) implement this handler instead of ``BaseOAuthHandler``.
+
+The resulting credentials are standard ``OAuth2Credentials`` — the device
+code flow is only an *acquisition method*, not a different credential shape.
+"""
+
+import logging
+import time
+from abc import ABC, abstractmethod
+from typing import ClassVar, Literal, Optional
+
+from pydantic import BaseModel
+
+from backend.data.model import OAuth2Credentials
+from backend.integrations.providers import ProviderName
+
+logger = logging.getLogger(__name__)
+
+
+class DeviceAuthInitiation(BaseModel):
+ """Returned when initiating the device code flow."""
+
+ device_code: str
+ user_code: str
+ verification_url: str
+ verification_url_complete: Optional[str] = None
+ expires_in: int
+ interval: int # recommended seconds between polls
+
+
+class DeviceAuthPollResult(BaseModel):
+ """Returned from each poll attempt during the device code flow."""
+
+ status: Literal["pending", "slow_down", "approved", "denied", "expired"]
+ credentials: Optional[OAuth2Credentials] = None
+ next_poll_interval: Optional[int] = None
+
+
+class BaseDeviceAuthHandler(ABC):
+ """Base for RFC 8628 device-code handlers.
+
+ ``ROTATES_REFRESH_TOKEN`` tells the credentials manager it must serialize
+ refreshes for this provider: replaying a rotated refresh token can be
+ treated as compromise and revoke the whole grant.
+ """
+
+ ROTATES_REFRESH_TOKEN: ClassVar[bool] = False
+ """
+ Abstract handler for OAuth 2.0 Device Code Grant flows.
+
+ Subclasses implement provider-specific HTTP calls; the token lifecycle
+ helpers (refresh, needs_refresh, get_access_token) mirror
+ ``BaseOAuthHandler`` so the credential manager can dispatch refresh
+ calls uniformly.
+ """
+
+ PROVIDER_NAME: ClassVar[ProviderName | str]
+ DEFAULT_SCOPES: ClassVar[list[str]] = []
+
+ @abstractmethod
+ async def initiate_device_auth(self, scopes: list[str]) -> DeviceAuthInitiation:
+ """Start the device code flow. Returns URLs/codes for the user."""
+ ...
+
+ @abstractmethod
+ async def poll_for_tokens(self, device_code: str) -> DeviceAuthPollResult:
+ """
+ Poll the auth server for token completion.
+
+ Returns a result with status ``"pending"`` or ``"slow_down"`` while
+ waiting, ``"approved"`` with credentials on success, or
+ ``"denied"``/``"expired"`` on terminal failure.
+ """
+ ...
+
+ @abstractmethod
+ async def _refresh_tokens(
+ self, credentials: OAuth2Credentials
+ ) -> OAuth2Credentials:
+ """Implements the token refresh mechanism."""
+ ...
+
+ @abstractmethod
+ async def revoke_tokens(self, credentials: OAuth2Credentials) -> bool:
+ """Revokes the given token at the provider.
+ Returns False if the provider does not support revocation."""
+ ...
+
+ # ------------------------------------------------------------------ #
+ # Non-abstract helpers — same interface as BaseOAuthHandler
+ # ------------------------------------------------------------------ #
+
+ async def refresh_tokens(self, credentials: OAuth2Credentials) -> OAuth2Credentials:
+ if credentials.provider != self.PROVIDER_NAME:
+ raise ValueError(
+ f"{self.__class__.__name__} cannot refresh tokens "
+ f"for provider '{credentials.provider}'"
+ )
+ return await self._refresh_tokens(credentials)
+
+ async def get_access_token(self, credentials: OAuth2Credentials) -> str:
+ """Returns a valid access token, refreshing it first if needed."""
+ if self.needs_refresh(credentials):
+ credentials = await self.refresh_tokens(credentials)
+ return credentials.access_token.get_secret_value()
+
+ def needs_refresh(self, credentials: OAuth2Credentials) -> bool:
+ """Indicates whether the given tokens need to be refreshed."""
+ return (
+ credentials.access_token_expires_at is not None
+ and credentials.access_token_expires_at < int(time.time()) + 300
+ )
+
+ def handle_default_scopes(self, scopes: list[str]) -> list[str]:
+ """Uses default scopes when none are provided."""
+ if not scopes:
+ logger.debug("Using default scopes for provider %s", self.PROVIDER_NAME)
+ scopes = self.DEFAULT_SCOPES
+ return scopes
diff --git a/autogpt_platform/backend/backend/integrations/oauth/device_base_test.py b/autogpt_platform/backend/backend/integrations/oauth/device_base_test.py
new file mode 100644
index 0000000000..5d9f03443c
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/oauth/device_base_test.py
@@ -0,0 +1,102 @@
+"""Tests for the RFC 8628 device-auth base handler.
+
+These cover the shared token-lifecycle helpers, which every device-code
+provider inherits — the parts most likely to be relied on silently.
+"""
+
+import time
+from typing import ClassVar
+
+import pytest
+from pydantic import SecretStr
+
+from backend.data.model import OAuth2Credentials
+from backend.integrations.oauth.device_base import (
+ BaseDeviceAuthHandler,
+ DeviceAuthInitiation,
+ DeviceAuthPollResult,
+)
+
+
+class _StubHandler(BaseDeviceAuthHandler):
+ PROVIDER_NAME: ClassVar[str] = "stub_provider"
+ DEFAULT_SCOPES: ClassVar[list[str]] = ["default:one", "default:two"]
+
+ def __init__(self) -> None:
+ self.refresh_calls = 0
+
+ async def initiate_device_auth(self, scopes: list[str]) -> DeviceAuthInitiation:
+ raise NotImplementedError
+
+ async def poll_for_tokens(self, device_code: str) -> DeviceAuthPollResult:
+ raise NotImplementedError
+
+ async def _refresh_tokens(
+ self, credentials: OAuth2Credentials
+ ) -> OAuth2Credentials:
+ self.refresh_calls += 1
+ credentials.access_token = SecretStr("refreshed-token")
+ credentials.access_token_expires_at = int(time.time()) + 3600
+ return credentials
+
+ async def revoke_tokens(self, credentials: OAuth2Credentials) -> bool:
+ return True
+
+
+def make_credentials(
+ expires_at: int | None, provider: str = "stub_provider"
+) -> OAuth2Credentials:
+ return OAuth2Credentials(
+ provider=provider,
+ access_token=SecretStr("current-token"),
+ refresh_token=SecretStr("refresh-token"),
+ access_token_expires_at=expires_at,
+ scopes=["default:one"],
+ title="Stub credentials",
+ )
+
+
+def test_needs_refresh_is_false_well_before_expiry():
+ handler = _StubHandler()
+ assert handler.needs_refresh(make_credentials(int(time.time()) + 3600)) is False
+
+
+def test_needs_refresh_is_true_inside_the_skew_window():
+ """Refresh early: a token expiring mid-request is as bad as an expired one."""
+ handler = _StubHandler()
+ assert handler.needs_refresh(make_credentials(int(time.time()) + 60)) is True
+
+
+def test_needs_refresh_is_false_without_an_expiry():
+ """A credential with no known expiry must not be refreshed on every call."""
+ handler = _StubHandler()
+ assert handler.needs_refresh(make_credentials(None)) is False
+
+
+async def test_refresh_tokens_rejects_a_foreign_provider():
+ """A handler must never mint tokens for a provider it doesn't own."""
+ handler = _StubHandler()
+ foreign = make_credentials(int(time.time()) + 60, provider="someone_else")
+ with pytest.raises(ValueError, match="cannot refresh tokens"):
+ await handler.refresh_tokens(foreign)
+ assert handler.refresh_calls == 0
+
+
+async def test_get_access_token_refreshes_only_when_needed():
+ handler = _StubHandler()
+
+ fresh = await handler.get_access_token(make_credentials(int(time.time()) + 3600))
+ assert fresh == "current-token"
+ assert handler.refresh_calls == 0
+
+ stale = await handler.get_access_token(make_credentials(int(time.time()) + 60))
+ assert stale == "refreshed-token"
+ assert handler.refresh_calls == 1
+
+
+def test_handle_default_scopes_fills_in_only_when_empty():
+ handler = _StubHandler()
+ assert handler.handle_default_scopes([]) == ["default:one", "default:two"]
+ assert handler.handle_default_scopes(["explicit"]) == ["explicit"]
diff --git a/autogpt_platform/backend/backend/integrations/oauth/stripe_link.py b/autogpt_platform/backend/backend/integrations/oauth/stripe_link.py
new file mode 100644
index 0000000000..16fb2ebe2c
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/oauth/stripe_link.py
@@ -0,0 +1,240 @@
+"""
+Stripe Link — OAuth 2.0 Device Code Grant handler.
+
+Implements the device code flow for Stripe Link (login.link.com).
+Uses a public client ID (no client_secret).
+"""
+
+import logging
+import time
+from typing import ClassVar
+from urllib.parse import urlparse
+
+import httpx
+from pydantic import SecretStr
+
+from backend.data.model import OAuth2Credentials
+from backend.integrations.oauth.device_base import (
+ BaseDeviceAuthHandler,
+ DeviceAuthInitiation,
+ DeviceAuthPollResult,
+)
+from backend.integrations.providers import ProviderName
+from backend.util.settings import Config
+
+logger = logging.getLogger(__name__)
+app_config = Config()
+
+LINK_AUTH_BASE_URL = "https://login.link.com"
+LINK_API_BASE_URL = "https://api.link.com"
+
+# Every Link call is awaited inline by a block or an API handler, so an
+# upstream that accepts the connection and then stalls would hold a worker for
+# as long as it likes. Bound them all.
+LINK_HTTP_TIMEOUT = 15.0
+LINK_CLIENT_ID = "lwlpk_U7Qy7ThG69STZk"
+LINK_CLIENT_NAME = "AutoGPT"
+
+
+class StripeLinkDeviceAuthHandler(BaseDeviceAuthHandler):
+ """Device code handler for Stripe Link."""
+
+ PROVIDER_NAME: ClassVar[ProviderName | str] = ProviderName.STRIPE_LINK
+ DEFAULT_SCOPES: ClassVar[list[str]] = [
+ "userinfo:read",
+ "payment_methods.agentic",
+ ]
+ # Requested as RFC 9396 authorization details, not scopes — Link gates its
+ # read endpoints on these rather than on the scope string.
+ SOURCE_ACTIONS: ClassVar[list[str]] = [
+ "read_balances",
+ "read_external_transactions",
+ "read_link_transactions",
+ "read_source_details",
+ ]
+
+ async def initiate_device_auth(self, scopes: list[str]) -> DeviceAuthInitiation:
+ effective_scopes = self.handle_default_scopes(scopes)
+
+ # Shown in the user's Link app under connected apps, and on the consent
+ # screen. The CLI uses `<client> on <hostname>`, but our hostname is a
+ # container ID the user has never seen — the platform they are actually
+ # connecting to is the useful half.
+ platform_host = urlparse(app_config.platform_base_url or "").netloc
+ connection_label = (
+ f"{LINK_CLIENT_NAME} on {platform_host}"
+ if platform_host
+ else LINK_CLIENT_NAME
+ )
+
+ # RFC 9396 rich authorization details. Link gates its read endpoints
+ # (/balances, /transactions, /sources) on these source actions being
+ # part of the grant — without them those return 403 feature_unavailable
+ # even though the scopes look sufficient. One `source` detail carries
+ # every action, matching the CLI's buildAuthorizationDetails.
+ form = {
+ "client_id": LINK_CLIENT_ID,
+ "scope": " ".join(effective_scopes),
+ "connection_label": connection_label,
+ "client_hint": LINK_CLIENT_NAME,
+ "authorization_details[][type]": "source",
+ "authorization_details[][actions][]": self.SOURCE_ACTIONS,
+ }
+
+ async with httpx.AsyncClient(timeout=LINK_HTTP_TIMEOUT) as client:
+ response = await client.post(
+ f"{LINK_AUTH_BASE_URL}/device/code",
+ data=form,
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ response.raise_for_status()
+ data = response.json()
+
+ return DeviceAuthInitiation(
+ device_code=data["device_code"],
+ user_code=data["user_code"],
+ verification_url=data["verification_uri"],
+ verification_url_complete=data.get("verification_uri_complete"),
+ expires_in=data["expires_in"],
+ interval=data.get("interval", 5),
+ )
+
+ async def poll_for_tokens(self, device_code: str) -> DeviceAuthPollResult:
+ async with httpx.AsyncClient(timeout=LINK_HTTP_TIMEOUT) as client:
+ response = await client.post(
+ f"{LINK_AUTH_BASE_URL}/device/token",
+ data={
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
+ "device_code": device_code,
+ "client_id": LINK_CLIENT_ID,
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+
+ if response.status_code == 200:
+ data = response.json()
+ # Record what was actually granted, not what was asked for. The
+ # two can differ, and storing the request means a later scope
+ # check passes on scopes the token may not carry. Link returns a
+ # space-delimited `scope` string per RFC 6749; fall back to the
+ # requested set only when it is absent.
+ granted = str(data.get("scope") or "").split()
+ credentials = OAuth2Credentials(
+ provider=self.PROVIDER_NAME,
+ access_token=SecretStr(data["access_token"]),
+ refresh_token=SecretStr(data["refresh_token"]),
+ access_token_expires_at=int(time.time()) + data["expires_in"],
+ # No `or DEFAULT_SCOPES` fallback: recording the *requested*
+ # scopes as granted is exactly what this must not do. A
+ # credential that claims a scope its token lacks passes the
+ # up-front coverage check and then 403s at run time, and an
+ # inflated list can win `_merge_or_create_credential`'s
+ # superset check and overwrite a wider credential.
+ scopes=granted,
+ title="Stripe Link",
+ # Lets `_merge_or_create_credential` recognise a re-auth of the
+ # same wallet instead of stacking a second credential for it.
+ username=await self._fetch_username(data["access_token"]),
+ )
+ return DeviceAuthPollResult(status="approved", credentials=credentials)
+
+ if response.status_code == 400:
+ error = response.json()
+ error_code = error.get("error", "")
+
+ if error_code == "authorization_pending":
+ return DeviceAuthPollResult(status="pending")
+
+ if error_code == "slow_down":
+ return DeviceAuthPollResult(
+ status="slow_down",
+ next_poll_interval=10,
+ )
+
+ if error_code == "expired_token":
+ return DeviceAuthPollResult(status="expired")
+
+ if error_code == "access_denied":
+ return DeviceAuthPollResult(status="denied")
+
+ raise RuntimeError(
+ f"Unexpected response from Link auth: "
+ f"{response.status_code} {response.text}"
+ )
+
+ async def _fetch_username(self, access_token: str) -> str | None:
+ """Best-effort wallet identity, used only to de-duplicate credentials.
+
+ A failure here must not fail an otherwise-successful authorization:
+ the grant is already complete by this point, and the caller would be
+ left with an approved device code and no credential.
+ """
+ try:
+ async with httpx.AsyncClient(timeout=LINK_HTTP_TIMEOUT) as client:
+ response = await client.get(
+ f"{LINK_API_BASE_URL}/userinfo",
+ headers={"Authorization": f"Bearer {access_token}"},
+ )
+ if response.status_code != 200:
+ return None
+ info = response.json()
+ return info.get("email") or info.get("phone") or None
+ except Exception as e:
+ logger.warning(f"Could not read Link userinfo for credential title: {e}")
+ return None
+
+ # Link *rotates* the refresh token, unlike every other handler here. The
+ # credentials manager documents concurrent refreshes as tolerable because
+ # "the last writer wins and stale tokens are overwritten" — true only for a
+ # static refresh token. Two workers replaying the same rotated token can
+ # have the whole grant revoked by a provider that treats reuse as
+ # compromise, so refreshes for this provider must be serialized.
+ ROTATES_REFRESH_TOKEN: ClassVar[bool] = True
+
+ async def _refresh_tokens(
+ self, credentials: OAuth2Credentials
+ ) -> OAuth2Credentials:
+ if not credentials.refresh_token:
+ raise RuntimeError("No refresh token available")
+
+ async with httpx.AsyncClient(timeout=LINK_HTTP_TIMEOUT) as client:
+ response = await client.post(
+ f"{LINK_AUTH_BASE_URL}/device/token",
+ data={
+ "grant_type": "refresh_token",
+ "refresh_token": credentials.refresh_token.get_secret_value(),
+ "client_id": LINK_CLIENT_ID,
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ response.raise_for_status()
+ data = response.json()
+
+ credentials.access_token = SecretStr(data["access_token"])
+ # RFC 6749 §6 makes `refresh_token` optional on refresh; a provider that
+ # does not rotate simply omits it. Indexing it unguarded would raise
+ # inside `_refresh_locked`, leaving the credential un-updated and every
+ # later run failing the same way with nothing pointing at the cause.
+ if data.get("refresh_token"):
+ credentials.refresh_token = SecretStr(data["refresh_token"])
+ if data.get("expires_in") is not None:
+ credentials.access_token_expires_at = int(time.time()) + int(
+ data["expires_in"]
+ )
+ return credentials
+
+ async def revoke_tokens(self, credentials: OAuth2Credentials) -> bool:
+ if not credentials.refresh_token:
+ return False
+
+ async with httpx.AsyncClient(timeout=LINK_HTTP_TIMEOUT) as client:
+ response = await client.post(
+ f"{LINK_AUTH_BASE_URL}/device/revoke",
+ data={
+ "client_id": LINK_CLIENT_ID,
+ "token": credentials.refresh_token.get_secret_value(),
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+
+ return response.status_code == 200
diff --git a/autogpt_platform/backend/backend/integrations/oauth/stripe_link_test.py b/autogpt_platform/backend/backend/integrations/oauth/stripe_link_test.py
new file mode 100644
index 0000000000..6d0eb1cea0
--- /dev/null
+++ b/autogpt_platform/backend/backend/integrations/oauth/stripe_link_test.py
@@ -0,0 +1,202 @@
+"""Tests for the Stripe Link device-code handler.
+
+The polling branch is the important one: RFC 8628 signals `pending`,
+`slow_down`, `expired_token` and `access_denied` all as HTTP 400, so
+misreading the body silently turns a normal wait into a hard failure.
+"""
+
+import time
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from pydantic import SecretStr
+
+from backend.data.model import OAuth2Credentials
+from backend.integrations.oauth.stripe_link import StripeLinkDeviceAuthHandler
+
+
+def mock_http(status_code: int, payload: dict, text: str = ""):
+ """Patch the module's httpx client to return one canned response."""
+ response = MagicMock()
+ response.status_code = status_code
+ response.json = MagicMock(return_value=payload)
+ response.text = text
+ response.raise_for_status = MagicMock()
+
+ client = MagicMock()
+ client.post = AsyncMock(return_value=response)
+ ctx = MagicMock()
+ ctx.__aenter__ = AsyncMock(return_value=client)
+ ctx.__aexit__ = AsyncMock(return_value=False)
+ return (
+ patch(
+ "backend.integrations.oauth.stripe_link.httpx.AsyncClient",
+ return_value=ctx,
+ ),
+ client,
+ )
+
+
+def credentials(refresh_token: str | None = "old-refresh") -> OAuth2Credentials:
+ return OAuth2Credentials(
+ provider="stripe_link",
+ access_token=SecretStr("old-access"),
+ refresh_token=SecretStr(refresh_token) if refresh_token else None,
+ access_token_expires_at=int(time.time()) + 60,
+ scopes=["userinfo:read", "payment_methods.agentic"],
+ title="Stripe Link",
+ )
+
+
+async def test_initiate_maps_the_device_code_response():
+ patcher, client = mock_http(
+ 200,
+ {
+ "device_code": "lwldevice_abc",
+ "user_code": "glow-relish-chaste-soft",
+ "verification_uri": "https://app.link.com/device/setup",
+ "verification_uri_complete": "https://app.link.com/device/setup?code=glow",
+ "expires_in": 600,
+ "interval": 5,
+ },
+ )
+ with patcher:
+ result = await StripeLinkDeviceAuthHandler().initiate_device_auth([])
+
+ assert result.device_code == "lwldevice_abc"
+ assert result.user_code == "glow-relish-chaste-soft"
+ assert result.verification_url == "https://app.link.com/device/setup"
+ assert result.expires_in == 600 and result.interval == 5
+
+ sent = client.post.call_args.kwargs["data"]
+ # Defaults must be applied, since an empty scope list would be rejected
+ assert sent["scope"] == "userinfo:read payment_methods.agentic"
+ assert sent["client_id"].startswith("lwlpk_")
+
+
+async def test_initiate_defaults_the_poll_interval_when_absent():
+ """`interval` is optional in RFC 8628; polling must not crash without it."""
+ patcher, _ = mock_http(
+ 200,
+ {
+ "device_code": "d",
+ "user_code": "u",
+ "verification_uri": "https://app.link.com/device/setup",
+ "expires_in": 600,
+ },
+ )
+ with patcher:
+ result = await StripeLinkDeviceAuthHandler().initiate_device_auth([])
+ assert result.interval == 5
+ assert result.verification_url_complete is None
+
+
+async def test_poll_returns_credentials_once_approved():
+ patcher, _ = mock_http(
+ 200,
+ {
+ "access_token": "new-access",
+ "refresh_token": "new-refresh",
+ "expires_in": 3600,
+ },
+ )
+ with patcher:
+ result = await StripeLinkDeviceAuthHandler().poll_for_tokens("dc")
+
+ assert result.status == "approved"
+ assert result.credentials is not None
+ assert result.credentials.access_token.get_secret_value() == "new-access"
+ assert result.credentials.provider == "stripe_link"
+ assert result.credentials.access_token_expires_at is not None
+
+
+ "error_code, expected",
+ [
+ ("authorization_pending", "pending"),
+ ("slow_down", "slow_down"),
+ ("expired_token", "expired"),
+ ("access_denied", "denied"),
+ ],
+)
+async def test_poll_maps_each_rfc8628_error_code(error_code, expected):
+ """All four arrive as HTTP 400 and must not be conflated."""
+ patcher, _ = mock_http(400, {"error": error_code})
+ with patcher:
+ result = await StripeLinkDeviceAuthHandler().poll_for_tokens("dc")
+ assert result.status == expected
+ assert result.credentials is None
+
+
+async def test_poll_slow_down_backs_off():
+ patcher, _ = mock_http(400, {"error": "slow_down"})
+ with patcher:
+ result = await StripeLinkDeviceAuthHandler().poll_for_tokens("dc")
+ assert result.next_poll_interval == 10
+
+
+async def test_poll_raises_on_an_unrecognised_response():
+ """An unknown failure must be loud, not silently treated as pending."""
+ patcher, _ = mock_http(500, {}, text="upstream exploded")
+ with patcher, pytest.raises(RuntimeError, match="Unexpected response"):
+ await StripeLinkDeviceAuthHandler().poll_for_tokens("dc")
+
+
+async def test_refresh_replaces_both_tokens():
+ """Link rotates the refresh token, so keeping the old one locks the user out."""
+ patcher, _ = mock_http(
+ 200,
+ {
+ "access_token": "rotated-access",
+ "refresh_token": "rotated-refresh",
+ "expires_in": 3600,
+ },
+ )
+ creds = credentials()
+ with patcher:
+ updated = await StripeLinkDeviceAuthHandler()._refresh_tokens(creds)
+
+ assert updated.access_token.get_secret_value() == "rotated-access"
+ assert updated.refresh_token is not None
+ assert updated.refresh_token.get_secret_value() == "rotated-refresh"
+ assert updated.access_token_expires_at > int(time.time())
+
+
+async def test_refresh_without_a_refresh_token_is_an_error():
+ with pytest.raises(RuntimeError, match="No refresh token"):
+ await StripeLinkDeviceAuthHandler()._refresh_tokens(credentials(None))
+
+
+async def test_revoke_reports_success_and_failure():
+ patcher, _ = mock_http(200, {})
+ with patcher:
+ assert await StripeLinkDeviceAuthHandler().revoke_tokens(credentials()) is True
+
+ patcher, _ = mock_http(400, {})
+ with patcher:
+ assert await StripeLinkDeviceAuthHandler().revoke_tokens(credentials()) is False
+
+
+async def test_revoke_without_a_refresh_token_is_a_noop():
+ assert await StripeLinkDeviceAuthHandler().revoke_tokens(credentials(None)) is False
+
+
+async def test_credentials_manager_resolves_the_device_handler():
+ """The device registry is the seam between the handler and the platform:
+ if this lookup misses, refresh silently falls through to the OAuth path
+ and fails for every device-code provider."""
+ from backend.integrations.creds_manager import IntegrationCredentialsManager
+
+ handler = await IntegrationCredentialsManager()._get_oauth_handler(credentials())
+ assert isinstance(handler, StripeLinkDeviceAuthHandler)
diff --git a/autogpt_platform/backend/backend/integrations/providers.py b/autogpt_platform/backend/backend/integrations/providers.py
index 34c154f5a8..bd9f701f88 100644
--- a/autogpt_platform/backend/backend/integrations/providers.py
+++ b/autogpt_platform/backend/backend/integrations/providers.py
@@ -51,6 +51,7 @@ class ProviderName(str, Enum):
SMARTLEAD = "smartlead"
SMTP = "smtp"
STRIPE = "stripe"
+ STRIPE_LINK = "stripe_link"
TELEGRAM = "telegram"
TWITTER = "twitter"
TODOIST = "todoist"
@@ -112,3 +113,15 @@ class ProviderName(str, Enum):
)
# --8<-- [end:ProviderName]
+
+
+def provider_key(provider: "ProviderName | str") -> str:
+ """Normalize a provider to its plain string key.
+
+ Providers reach the registries as either a ``ProviderName`` member or a
+ bare string (SDK-registered providers, values loaded from the database).
+ ``str(ProviderName.X)`` returns ``"ProviderName.X"`` on Python 3.13, so the
+ enum value has to be preferred explicitly — which had been open-coded with
+ ``hasattr``/``getattr`` at every call site.
+ """
+ return getattr(provider, "value", None) or str(provider)
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsx
index 2cbc557bda..d759414792 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/ConnectToolsPanel.tsx
@@ -101,6 +101,10 @@ export function ConnectToolsPanel({ onBack, onNext }: Props) {
onSelectMethod={setSelectedMethod}
apiKeyForm={apiKeyForm}
onApiKeySubmit={handleApiKeySubmit}
+ // Without this, approving on the phone drops the user back on
+ // the initial "Connect <provider>" screen, which reads as a
+ // failure. OAuth and API key both return to the list.
+ onDeviceAuthSuccess={handleBackToList}
/>
</motion.div>
) : (
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/__tests__/connect-method-order.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/__tests__/connect-method-order.test.ts
new file mode 100644
index 0000000000..5fc5554fbe
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/OnboardingWelcomeDialog/__tests__/connect-method-order.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+
+import { ProviderMetadataSupportedAuthTypesItem as AuthType } from "@/app/api/__generated__/models/providerMetadataSupportedAuthTypesItem";
+import { METHOD_ORDER } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView";
+
+describe("METHOD_ORDER", () => {
+ // The dialog renders `METHOD_ORDER.filter(...)`, so a method missing here is
+ // not merely mis-ordered — it disappears. `device_code` was added to
+ // METHOD_COPY but not to this list, so a device-auth provider rendered an
+ // empty method list with no way to connect.
+ it("covers every auth type a provider can advertise", () => {
+ const missing = Object.values(AuthType).filter(
+ (type) => !METHOD_ORDER.includes(type),
+ );
+
+ expect(missing).toEqual([]);
+ });
+
+ it("offers OAuth and device auth ahead of the manual methods", () => {
+ expect(METHOD_ORDER.indexOf(AuthType.device_code)).toBeLessThan(
+ METHOD_ORDER.indexOf(AuthType.api_key),
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/AgentInputsReadOnly/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/AgentInputsReadOnly/helpers.ts
index 95069b1d30..49a0b271b9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/AgentInputsReadOnly/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/AgentInputsReadOnly/helpers.ts
@@ -7,6 +7,7 @@ export function getCredentialTypeDisplayName(type: string): string {
[CredentialsMetaResponseType.oauth2]: "OAuth2",
[CredentialsMetaResponseType.user_password]: "Username/Password",
[CredentialsMetaResponseType.host_scoped]: "Host-Scoped",
+ [CredentialsMetaResponseType.device_code]: "Device Auth",
};
return typeDisplayMap[type as CredentialsMetaResponseType] || type;
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/components/ModalRunSection/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/components/ModalRunSection/helpers.ts
index eedd6c788c..19f8b37379 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/components/ModalRunSection/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/components/ModalRunSection/helpers.ts
@@ -6,6 +6,7 @@ export function getCredentialTypeDisplayName(type: string): string {
[CredentialsMetaResponseType.oauth2]: "OAuth2",
[CredentialsMetaResponseType.user_password]: "Username/Password",
[CredentialsMetaResponseType.host_scoped]: "Host-Scoped",
+ [CredentialsMetaResponseType.device_code]: "Device Auth",
};
return typeDisplayMap[type as CredentialsMetaResponseType] || type;
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/integrations/page.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/integrations/page.tsx
index b6566145b6..8ed2c028d9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/integrations/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/integrations/page.tsx
@@ -155,6 +155,7 @@ export default function UserIntegrationsPage() {
api_key: IconKey,
user_password: IconKey,
host_scoped: IconKey,
+ device_code: IconUser,
}[credentials.type],
})),
)
@@ -192,6 +193,7 @@ export default function UserIntegrationsPage() {
api_key: "API key",
user_password: "Username & password",
host_scoped: "Host-scoped credentials",
+ device_code: "Device auth credentials",
}[cred.type]
}{" "}
- <code>{cred.id}</code>
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 906f621e90..215543fd59 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -7885,6 +7885,110 @@
}
}
},
+ "/api/integrations/{provider}/device-auth/initiate": {
+ "post": {
+ "tags": ["v1", "integrations"],
+ "summary": "Initiate device code OAuth flow",
+ "operationId": "postV1Initiate device code oauth flow",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "provider",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "title": "The provider to initiate device auth for",
+ "description": "Provider name for integrations. Can be any string value, including custom provider names."
+ }
+ },
+ {
+ "name": "scopes",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "title": "Comma-separated list of authorization scopes",
+ "default": ""
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/DeviceAuthInitiateResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/integrations/{provider}/device-auth/poll": {
+ "post": {
+ "tags": ["v1", "integrations"],
+ "summary": "Poll device code OAuth flow for completion",
+ "operationId": "postV1Poll device code oauth flow for completion",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "provider",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "title": "The provider to poll device auth for",
+ "description": "Provider name for integrations. Can be any string value, including custom provider names."
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/DeviceAuthPollRequest" }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/DeviceAuthPollResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/integrations/{provider}/login": {
"get": {
"tags": ["v1", "integrations"],
@@ -17705,7 +17809,13 @@
},
"type": {
"type": "string",
- "enum": ["api_key", "oauth2", "user_password", "host_scoped"],
+ "enum": [
+ "api_key",
+ "oauth2",
+ "user_password",
+ "host_scoped",
+ "device_code"
+ ],
"title": "Type"
}
},
@@ -17721,7 +17831,13 @@
"provider": { "type": "string", "title": "Provider" },
"type": {
"type": "string",
- "enum": ["api_key", "oauth2", "user_password", "host_scoped"],
+ "enum": [
+ "api_key",
+ "oauth2",
+ "user_password",
+ "host_scoped",
+ "device_code"
+ ],
"title": "Type"
},
"title": {
@@ -17903,6 +18019,54 @@
"title": "DemotionSummary",
"description": "One line per demoted RELATES_TO edge."
},
+ "DeviceAuthInitiateResponse": {
+ "properties": {
+ "state_token": { "type": "string", "title": "State Token" },
+ "user_code": { "type": "string", "title": "User Code" },
+ "verification_url": { "type": "string", "title": "Verification Url" },
+ "verification_url_complete": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Verification Url Complete"
+ },
+ "expires_in": { "type": "integer", "title": "Expires In" },
+ "interval": { "type": "integer", "title": "Interval" }
+ },
+ "type": "object",
+ "required": [
+ "state_token",
+ "user_code",
+ "verification_url",
+ "expires_in",
+ "interval"
+ ],
+ "title": "DeviceAuthInitiateResponse"
+ },
+ "DeviceAuthPollRequest": {
+ "properties": {
+ "state_token": { "type": "string", "title": "State Token" }
+ },
+ "type": "object",
+ "required": ["state_token"],
+ "title": "DeviceAuthPollRequest"
+ },
+ "DeviceAuthPollResponse": {
+ "properties": {
+ "status": {
+ "type": "string",
+ "enum": ["pending", "slow_down", "approved", "denied", "expired"],
+ "title": "Status"
+ },
+ "credentials": {
+ "anyOf": [
+ { "$ref": "#/components/schemas/CredentialsMetaResponse" },
+ { "type": "null" }
+ ]
+ }
+ },
+ "type": "object",
+ "required": ["status"],
+ "title": "DeviceAuthPollResponse"
+ },
"DiscoverToolsRequest": {
"properties": {
"server_url": {
@@ -23722,7 +23886,13 @@
"supported_auth_types": {
"items": {
"type": "string",
- "enum": ["api_key", "oauth2", "user_password", "host_scoped"]
+ "enum": [
+ "api_key",
+ "oauth2",
+ "user_password",
+ "host_scoped",
+ "device_code"
+ ]
},
"type": "array",
"title": "Supported Auth Types",
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsx
index 44a0d086da..b2303ad984 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/CredentialsInput.tsx
@@ -14,6 +14,7 @@ import { ConnectCredentialDialog } from "./components/ConnectCredentialDialog/Co
import { CredentialsFlatView } from "./components/CredentialsFlatView/CredentialsFlatView";
import { CredentialTypeSelector } from "./components/CredentialTypeSelector/CredentialTypeSelector";
import { DeleteConfirmationModal } from "./components/DeleteConfirmationModal/DeleteConfirmationModal";
+import { DeviceAuthCredentialsModal } from "./components/DeviceAuthCredentialsModal/DeviceAuthCredentialsModal";
import { HostScopedCredentialsModal } from "./components/HotScopedCredentialsModal/HotScopedCredentialsModal";
import { OAuthFlowWaitingModal } from "./components/OAuthWaitingModal/OAuthWaitingModal";
import { PasswordCredentialsModal } from "./components/PasswordCredentialsModal/PasswordCredentialsModal";
@@ -78,6 +79,7 @@ export function CredentialsInput({
providerName,
supportsApiKey,
supportsOAuth2,
+ supportsDeviceCode,
supportsUserPassword,
supportsHostScoped,
hasMultipleCredentialTypes,
@@ -88,6 +90,7 @@ export function CredentialsInput({
isAPICredentialsModalOpen,
isUserPasswordCredentialsModalOpen,
isHostScopedCredentialsModalOpen,
+ isDeviceAuthModalOpen,
isCredentialTypeSelectorOpen,
isOAuth2FlowInProgress,
oAuthPopupBlocked,
@@ -96,6 +99,7 @@ export function CredentialsInput({
setAPICredentialsModalOpen,
setUserPasswordCredentialsModalOpen,
setHostScopedCredentialsModalOpen,
+ setDeviceAuthModalOpen,
setCredentialTypeSelectorOpen,
handleActionButtonClick,
handleCredentialSelect,
@@ -193,6 +197,18 @@ export function CredentialsInput({
popupBlocked={oAuthPopupBlocked}
/>
)}
+ {supportsDeviceCode && (
+ <DeviceAuthCredentialsModal
+ open={isDeviceAuthModalOpen}
+ onClose={() => setDeviceAuthModalOpen(false)}
+ provider={provider}
+ providerName={providerName}
+ onCredentialsCreate={(creds) => {
+ onSelectCredential(creds);
+ setDeviceAuthModalOpen(false);
+ }}
+ />
+ )}
{supportsUserPassword && (
<PasswordCredentialsModal
schema={schema}
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx
index aa4195dc85..bf7b5bd4d3 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/CredentialsInput.test.tsx
@@ -476,3 +476,48 @@ describe("CredentialsInput – OAuth flow", () => {
expect(abortB).toHaveBeenCalled();
});
});
+
+describe("CredentialsInput – device auth", () => {
+ const deviceSchema = {
+ credentials_provider: ["stripe_link"],
+ // Both: a device-code grant yields an oauth2-shaped credential, so the
+ // block accepts oauth2 while device_code is how it is obtained.
+ credentials_types: ["oauth2", "device_code"],
+ credentials_scopes: ["userinfo:read"],
+ } as unknown as BlockIOCredentialsSubSchema;
+
+ function renderDeviceInput() {
+ mockUseCredentials.mockReturnValue(
+ makeCredentialsReturn({
+ provider: "stripe_link",
+ providerName: "Stripe Link",
+ schema: deviceSchema,
+ savedCredentials: [],
+ supportsOAuth2: false,
+ supportsDeviceCode: true,
+ } as any),
+ );
+ return render(
+ <CredentialsInput
+ schema={deviceSchema}
+ selectedCredentials={undefined}
+ onSelectCredentials={vi.fn()}
+ />,
+ );
+ }
+
+ // The regression: this path had no device_code branch, so "Add account"
+ // fell through to OAuth and the backend answered "Provider 'stripe_link'
+ // does not support OAuth" — the blocks were unconnectable from the builder.
+ it("opens the device auth flow instead of an OAuth popup", async () => {
+ renderDeviceInput();
+
+ fireEvent.click(screen.getByText("Add account"));
+
+ await waitFor(() => {
+ expect(screen.getByText(/device authorization/i)).toBeTruthy();
+ });
+ expect(mockOpenOAuthPopup).not.toHaveBeenCalled();
+ expect(mockPreOpenOAuthPopup).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts
index fdef637346..406b00e6d8 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/__tests__/helpers.test.ts
@@ -72,6 +72,14 @@ describe("getSupportedTypes", () => {
"host_scoped",
]);
});
+
+ // A device-code provider shipped with no branch here, so its blocks offered
+ // no connect method at all and "Add account" fell through to OAuth.
+ it("returns device_code when supportsDeviceCode is true", () => {
+ expect(getSupportedTypes(false, false, false, false, true)).toEqual([
+ "device_code",
+ ]);
+ });
});
describe("getCredentialTypeLabel", () => {
@@ -471,6 +479,19 @@ describe("resolveActionTarget", () => {
expect(resolveActionTarget(false, true, false, false, false)).toBe("oauth");
});
+ it("returns device_code when only device auth is supported", () => {
+ expect(resolveActionTarget(false, false, false, false, false, true)).toBe(
+ "device_code",
+ );
+ });
+
+ // Device auth is only reachable if it also counts toward the multi-type
+ // check — otherwise a provider offering device auth plus an API key would
+ // silently skip the selector and open the API-key modal.
+ it("counts device auth toward the multi-type selector", () => {
+ expect(countSupportedTypes(false, true, false, false, true)).toBe(2);
+ });
+
it("returns api_key when only API key is supported", () => {
expect(resolveActionTarget(false, false, true, false, false)).toBe(
"api_key",
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsx
index 2b28b23f86..e37b83cc88 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/ConnectCredentialDialog.tsx
@@ -7,6 +7,7 @@ import {
type AuthMethod,
type ConnectableProvider,
} from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/helpers";
+import { getConnectableCredentialTypes } from "@/hooks/useCredentials";
import { Dialog } from "@/components/molecules/Dialog/Dialog";
import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api/types";
import { useConnectCredentialDialog } from "./useConnectCredentialDialog";
@@ -55,9 +56,9 @@ export function ConnectCredentialDialog({
id: provider,
name: displayName,
description: null,
- supportedAuthTypes: (schema.credentials_types ?? []).filter(
- (t): t is AuthMethod => KNOWN_AUTH_METHODS.has(t as AuthMethod),
- ),
+ supportedAuthTypes: getConnectableCredentialTypes(
+ schema.credentials_types ?? [],
+ ).filter((t): t is AuthMethod => KNOWN_AUTH_METHODS.has(t as AuthMethod)),
};
return (
@@ -78,6 +79,7 @@ export function ConnectCredentialDialog({
onSelectMethod={setSelectedMethod}
apiKeyForm={apiKeyForm}
onApiKeySubmit={handleApiKeySubmit}
+ onDeviceAuthSuccess={handleClose}
/>
<div className="flex items-center justify-end gap-3">
<Button variant="secondary" size="small" onClick={handleClose}>
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsx
index ea2f094abf..c6ef2fc98d 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/ConnectCredentialDialog/__tests__/ConnectCredentialDialog.test.tsx
@@ -25,10 +25,12 @@ vi.mock(
provider,
selectedMethod,
onSelectMethod,
+ onDeviceAuthSuccess,
}: {
provider: { id: string; name: string; supportedAuthTypes: string[] };
selectedMethod: string | null;
onSelectMethod: (method: string) => void;
+ onDeviceAuthSuccess: () => void;
}) => (
<div data-testid="connect-method-view">
<span>Connect AutoGPT to {provider.name}</span>
@@ -41,6 +43,9 @@ vi.mock(
{`select-${method}`}
</button>
))}
+ {provider.supportedAuthTypes.includes("device_code") && (
+ <button onClick={onDeviceAuthSuccess}>complete-device_code</button>
+ )}
</div>
),
}),
@@ -159,6 +164,25 @@ describe("ConnectCredentialDialog", () => {
);
});
+ it("offers device auth instead of the stored OAuth credential shape", () => {
+ const apiKey = makeApiKeyReturn();
+ mockUseApiKeyConnectForm.mockReturnValue(apiKey);
+ const { onClose } = renderDialog({
+ schema: {
+ credentials_provider: ["stripe_link"],
+ credentials_types: ["oauth2", "device_code"],
+ } as BlockIOCredentialsSubSchema,
+ });
+
+ expect(screen.getByTestId("auth-methods").textContent).toBe("device_code");
+ expect(screen.queryByText("select-oauth2")).toBeNull();
+
+ fireEvent.click(screen.getByText("complete-device_code"));
+
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(apiKey.form.reset).toHaveBeenCalledOnce();
+ });
+
it("disables Continue until a method is selected", () => {
renderDialog();
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/DeviceAuthCredentialsModal/DeviceAuthCredentialsModal.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/DeviceAuthCredentialsModal/DeviceAuthCredentialsModal.tsx
new file mode 100644
index 0000000000..bd7206d5be
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/DeviceAuthCredentialsModal/DeviceAuthCredentialsModal.tsx
@@ -0,0 +1,63 @@
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
+import { DeviceAuthConnectButton } from "@/components/contextual/DeviceAuth/DeviceAuthConnectButton";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { CredentialsMetaInput } from "@/lib/autogpt-server-api/types";
+
+type Props = {
+ open: boolean;
+ onClose: () => void;
+ provider: string;
+ providerName: string;
+ onCredentialsCreate: (creds: CredentialsMetaInput) => void;
+};
+
+/**
+ * Builder-side host for the device-code flow.
+ *
+ * The integrations panel shows the same flow as a tab; here it is a modal
+ * opened from "Add account", because that is where a block's credentials
+ * input lives. Without this the input fell through to the OAuth branch and
+ * the backend rejected it — the provider is device-code only.
+ */
+export function DeviceAuthCredentialsModal({
+ open,
+ onClose,
+ provider,
+ providerName,
+ onCredentialsCreate,
+}: Props) {
+ return (
+ <Dialog
+ title={`Connect ${providerName}`}
+ controlled={{
+ isOpen: open,
+ set: (isOpen) => {
+ if (!isOpen) onClose();
+ },
+ }}
+ onClose={onClose}
+ styling={{ maxWidth: "25rem" }}
+ >
+ <Dialog.Content>
+ <DeviceAuthConnectButton
+ provider={provider}
+ providerName={providerName}
+ onSuccess={(credentials?: CredentialsMetaResponse) => {
+ // The poll hands back the credential it just stored, so the node
+ // can be wired up immediately instead of leaving the user to pick
+ // it out of the list by hand.
+ if (credentials) {
+ onCredentialsCreate({
+ id: credentials.id,
+ type: credentials.type,
+ provider: credentials.provider,
+ title: credentials.title ?? undefined,
+ });
+ }
+ onClose();
+ }}
+ />
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/DeviceAuthCredentialsModal/__tests__/DeviceAuthCredentialsModal.test.tsx b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/DeviceAuthCredentialsModal/__tests__/DeviceAuthCredentialsModal.test.tsx
new file mode 100644
index 0000000000..8d6bcb6b88
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/components/DeviceAuthCredentialsModal/__tests__/DeviceAuthCredentialsModal.test.tsx
@@ -0,0 +1,85 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { DeviceAuthCredentialsModal } from "../DeviceAuthCredentialsModal";
+
+const connectProps = vi.hoisted(() => ({ current: null as any }));
+
+vi.mock("@/components/contextual/DeviceAuth/DeviceAuthConnectButton", () => ({
+ DeviceAuthConnectButton: (props: any) => {
+ connectProps.current = props;
+ return <div data-testid="device-auth-connect">{props.providerName}</div>;
+ },
+}));
+
+afterEach(() => {
+ cleanup();
+ connectProps.current = null;
+});
+
+function renderModal(overrides: Record<string, unknown> = {}) {
+ const props = {
+ open: true,
+ onClose: vi.fn(),
+ provider: "stripe_link",
+ providerName: "Stripe Link",
+ onCredentialsCreate: vi.fn(),
+ ...overrides,
+ };
+ render(<DeviceAuthCredentialsModal {...(props as any)} />);
+ return props;
+}
+
+describe("DeviceAuthCredentialsModal", () => {
+ it("hosts the device auth flow for the block's provider", () => {
+ renderModal();
+
+ expect(screen.getByTestId("device-auth-connect")).toBeTruthy();
+ expect(connectProps.current.provider).toBe("stripe_link");
+ });
+
+ // The whole point of routing device_code here: the node has to end up wired
+ // to the credential the user just approved on their phone.
+ it("selects the credential the poll returned", () => {
+ const props = renderModal();
+
+ connectProps.current.onSuccess({
+ id: "cred-99",
+ type: "oauth2",
+ provider: "stripe_link",
+ title: "Stripe Link",
+ });
+
+ expect(props.onCredentialsCreate).toHaveBeenCalledWith({
+ id: "cred-99",
+ type: "oauth2",
+ provider: "stripe_link",
+ title: "Stripe Link",
+ });
+ expect(props.onClose).toHaveBeenCalled();
+ });
+
+ it("closes without selecting anything when no credential came back", () => {
+ const props = renderModal();
+
+ connectProps.current.onSuccess(undefined);
+
+ expect(props.onCredentialsCreate).not.toHaveBeenCalled();
+ expect(props.onClose).toHaveBeenCalled();
+ });
+
+ it("tolerates a credential with no title", () => {
+ const props = renderModal();
+
+ connectProps.current.onSuccess({
+ id: "cred-1",
+ type: "oauth2",
+ provider: "stripe_link",
+ title: null,
+ });
+
+ expect(props.onCredentialsCreate).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "cred-1", title: undefined }),
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/helpers.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/helpers.ts
index 438ba1e1f2..f3ab08360e 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/helpers.ts
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/helpers.ts
@@ -84,12 +84,14 @@ export function countSupportedTypes(
supportsApiKey: boolean,
supportsUserPassword: boolean,
supportsHostScoped: boolean,
+ supportsDeviceCode: boolean = false,
): number {
return [
supportsOAuth2,
supportsApiKey,
supportsUserPassword,
supportsHostScoped,
+ supportsDeviceCode,
].filter(Boolean).length;
}
@@ -98,9 +100,11 @@ export function getSupportedTypes(
supportsApiKey: boolean,
supportsUserPassword: boolean,
supportsHostScoped: boolean,
+ supportsDeviceCode: boolean = false,
): CredentialsType[] {
const types: CredentialsType[] = [];
if (supportsOAuth2) types.push("oauth2");
+ if (supportsDeviceCode) types.push("device_code");
if (supportsApiKey) types.push("api_key");
if (supportsUserPassword) types.push("user_password");
if (supportsHostScoped) types.push("host_scoped");
@@ -112,6 +116,7 @@ const CREDENTIAL_TYPE_LABELS: Record<CredentialsType, string> = {
api_key: "API Key",
user_password: "Password",
host_scoped: "Headers",
+ device_code: "Device Auth",
};
export function getCredentialTypeLabel(type: CredentialsType): string {
@@ -127,6 +132,9 @@ export function getCredentialTypeIcon(
if (type === "oauth2" && provider) {
return providerIcons[provider] ?? globeIcon;
}
+ if (type === "device_code" && provider) {
+ return providerIcons[provider] ?? globeIcon;
+ }
if (type === "user_password") return lockPasswordIcon;
if (type === "host_scoped") return lockIcon;
return fallbackIcon;
@@ -139,6 +147,7 @@ export function getActionButtonText(
supportsHostScoped: boolean,
hasExistingCredentials: boolean,
provider?: string,
+ supportsDeviceCode: boolean = false,
): string {
const multipleTypes =
countSupportedTypes(
@@ -146,6 +155,7 @@ export function getActionButtonText(
supportsApiKey,
supportsUserPassword,
supportsHostScoped,
+ supportsDeviceCode,
) > 1;
if (multipleTypes) {
@@ -160,12 +170,14 @@ export function getActionButtonText(
if (hasExistingCredentials) {
if (supportsOAuth2) return "Connect another account";
+ if (supportsDeviceCode) return "Connect another account";
if (supportsApiKey) return "Use a new API key";
if (supportsUserPassword) return "Add a new username and password";
if (supportsHostScoped) return "Update headers";
return "Add new credentials";
} else {
if (supportsOAuth2) return "Add account";
+ if (supportsDeviceCode) return "Add account";
if (supportsApiKey) return "Add API key";
if (supportsUserPassword) return "Add username and password";
if (supportsHostScoped) return "Add headers";
@@ -272,6 +284,7 @@ export function hasExistingHostCredential<
export type ActionTarget =
| "type_selector"
| "oauth"
+ | "device_code"
| "api_key"
| "user_password"
| "host_scoped"
@@ -283,9 +296,11 @@ export function resolveActionTarget(
supportsApiKey: boolean,
supportsUserPassword: boolean,
supportsHostScoped: boolean,
+ supportsDeviceCode: boolean = false,
): ActionTarget {
if (hasMultipleCredentialTypes) return "type_selector";
if (supportsOAuth2) return "oauth";
+ if (supportsDeviceCode) return "device_code";
if (supportsApiKey) return "api_key";
if (supportsUserPassword) return "user_password";
if (supportsHostScoped) return "host_scoped";
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
index ad738014d6..a02ee189ff 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
@@ -54,6 +54,7 @@ export function useCredentialsInput({
] = useState(false);
const [isHostScopedCredentialsModalOpen, setHostScopedCredentialsModalOpen] =
useState(false);
+ const [isDeviceAuthModalOpen, setDeviceAuthModalOpen] = useState(false);
const [isCredentialTypeSelectorOpen, setCredentialTypeSelectorOpen] =
useState(false);
const [isOAuth2FlowInProgress, setOAuth2FlowInProgress] = useState(false);
@@ -172,6 +173,7 @@ export function useCredentialsInput({
providerName,
supportsApiKey,
supportsOAuth2,
+ supportsDeviceCode,
supportsUserPassword,
supportsHostScoped,
savedCredentials,
@@ -361,6 +363,7 @@ export function useCredentialsInput({
supportsApiKey,
supportsUserPassword,
supportsHostScoped,
+ supportsDeviceCode,
) > 1;
const supportedTypes = getSupportedTypes(
@@ -368,6 +371,7 @@ export function useCredentialsInput({
supportsApiKey,
supportsUserPassword,
supportsHostScoped,
+ supportsDeviceCode,
);
function handleActionButtonClick() {
@@ -377,6 +381,7 @@ export function useCredentialsInput({
supportsApiKey,
supportsUserPassword,
supportsHostScoped,
+ supportsDeviceCode,
);
switch (target) {
case "type_selector":
@@ -385,6 +390,9 @@ export function useCredentialsInput({
case "oauth":
handleOAuthLogin();
break;
+ case "device_code":
+ setDeviceAuthModalOpen(true);
+ break;
case "api_key":
setAPICredentialsModalOpen(true);
break;
@@ -459,6 +467,7 @@ export function useCredentialsInput({
providerName,
supportsApiKey,
supportsOAuth2,
+ supportsDeviceCode,
supportsUserPassword,
supportsHostScoped,
hasMultipleCredentialTypes,
@@ -472,6 +481,7 @@ export function useCredentialsInput({
isAPICredentialsModalOpen,
isUserPasswordCredentialsModalOpen,
isHostScopedCredentialsModalOpen,
+ isDeviceAuthModalOpen,
isCredentialTypeSelectorOpen,
isOAuth2FlowInProgress,
oAuthPopupBlocked,
@@ -486,10 +496,12 @@ export function useCredentialsInput({
supportsHostScoped,
userCredentials.length > 0,
provider,
+ supportsDeviceCode,
),
setAPICredentialsModalOpen,
setUserPasswordCredentialsModalOpen,
setHostScopedCredentialsModalOpen,
+ setDeviceAuthModalOpen,
setCredentialTypeSelectorOpen,
setCredentialToDelete,
handleActionButtonClick,
diff --git a/autogpt_platform/frontend/src/components/contextual/DeviceAuth/DeviceAuthConnectButton.tsx b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/DeviceAuthConnectButton.tsx
new file mode 100644
index 0000000000..bf274886e0
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/DeviceAuthConnectButton.tsx
@@ -0,0 +1,115 @@
+"use client";
+
+import {
+ Cancel01Icon,
+ LinkSquare01Icon,
+ Loading03Icon,
+} from "@hugeicons/core-free-icons";
+
+import { Icon } from "@/components/atoms/Icon/Icon";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
+
+import { useDeviceAuthConnect } from "./useDeviceAuthConnect";
+
+interface Props {
+ provider: string;
+ providerName: string;
+ onSuccess: (credentials?: CredentialsMetaResponse) => void;
+}
+
+export function DeviceAuthConnectButton({
+ provider,
+ providerName,
+ onSuccess,
+}: Props) {
+ const { connect, cancel, phase, userCode, verificationUrl } =
+ useDeviceAuthConnect({ provider, onSuccess });
+
+ // `awaiting_user` spans the initiate round-trip, when there is no code and
+ // no URL yet. Rendering the code panel then shows an empty box above a link
+ // whose href="" resolves to the current page.
+ if (phase === "awaiting_user" && !userCode) {
+ return (
+ <div className="flex flex-col gap-3">
+ <Text variant="body" className="text-zinc-600">
+ Requesting a code from {providerName}…
+ </Text>
+ <div className="flex items-center gap-2 text-zinc-500">
+ <Icon icon={Loading03Icon} size={16} className="animate-spin" />
+ <Text variant="small">Starting device authorization…</Text>
+ </div>
+ </div>
+ );
+ }
+
+ if (phase === "idle" || phase === "error" || phase === "done") {
+ return (
+ <div className="flex flex-col gap-3">
+ <Text variant="body" className="text-zinc-600">
+ {providerName} uses device authorization. Click below, then follow the
+ link to approve access.
+ </Text>
+ <Button type="button" variant="primary" size="large" onClick={connect}>
+ Connect {providerName}
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-4">
+ <Text variant="body" className="text-zinc-600">
+ Open the link below and enter the code to connect your {providerName}{" "}
+ account.
+ </Text>
+
+ <div className="flex flex-col gap-3 rounded-lg border border-zinc-200 bg-zinc-50 p-4">
+ <div className="flex flex-col gap-1">
+ <Text variant="small" className="font-medium text-zinc-500">
+ Your code
+ </Text>
+ {/* unmask={false}: Text unmasks for session replay by default, and
+ this is a live authorization code — it must not be recorded. */}
+ <Text
+ variant="h3"
+ as="p"
+ unmask={false}
+ className="select-all text-center font-mono text-2xl tracking-widest text-zinc-800"
+ >
+ {userCode}
+ </Text>
+ </div>
+
+ <a
+ href={verificationUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center justify-center gap-2 rounded-md bg-zinc-900 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-zinc-800"
+ >
+ Open {providerName}
+ <Icon icon={LinkSquare01Icon} size={16} />
+ </a>
+ </div>
+
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-zinc-500">
+ <Icon icon={Loading03Icon} size={16} className="animate-spin" />
+ <Text variant="small">Waiting for approval…</Text>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="small"
+ onClick={cancel}
+ rightIcon={<Icon icon={Cancel01Icon} size={14} />}
+ >
+ Cancel
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/components/contextual/DeviceAuth/__tests__/DeviceAuthConnectButton.test.tsx b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/__tests__/DeviceAuthConnectButton.test.tsx
new file mode 100644
index 0000000000..49c2d79ba3
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/__tests__/DeviceAuthConnectButton.test.tsx
@@ -0,0 +1,71 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+import { DeviceAuthConnectButton } from "../DeviceAuthConnectButton";
+
+const state = {
+ connect: vi.fn(),
+ cancel: vi.fn(),
+ phase: "idle" as string,
+ userCode: "",
+ verificationUrl: "",
+};
+
+vi.mock("../useDeviceAuthConnect", () => ({
+ useDeviceAuthConnect: () => state,
+}));
+
+function renderButton() {
+ return render(
+ <DeviceAuthConnectButton
+ provider="stripe_link"
+ providerName="Stripe Link"
+ onSuccess={vi.fn()}
+ />,
+ );
+}
+
+describe("DeviceAuthConnectButton", () => {
+ it("offers a connect action before the flow starts", () => {
+ state.phase = "idle";
+ state.userCode = "";
+ renderButton();
+
+ expect(screen.getByRole("button")).toBeTruthy();
+ });
+
+ it("shows the code phrase and the approval link while waiting", () => {
+ state.phase = "polling";
+ state.userCode = "glow-relish-chaste-soft";
+ state.verificationUrl = "https://app.link.com/device/setup?code=glow";
+ renderButton();
+
+ expect(screen.getByText("glow-relish-chaste-soft")).toBeTruthy();
+ const link = screen.getByRole("link") as HTMLAnchorElement;
+ expect(link.href).toContain("app.link.com/device/setup");
+ });
+
+ it("keeps the code phrase out of session replay", () => {
+ // `Text` adds `sentry-unmask` by default; this is a live authorization
+ // code, so it must not be recorded. Regression test for that default.
+ state.phase = "polling";
+ state.userCode = "glow-relish-chaste-soft";
+ renderButton();
+
+ const code = screen.getByText("glow-relish-chaste-soft");
+ expect(code.className).not.toContain("sentry-unmask");
+ });
+
+ // Between clicking Connect and the initiate call returning there is no code
+ // and no URL yet. Rendering the code panel then showed an empty box above an
+ // "Open Stripe Link" link with href="" that just reloaded the builder.
+ it("shows a starting state instead of an empty code and a dead link", () => {
+ state.phase = "awaiting_user";
+ state.userCode = "";
+ state.verificationUrl = "";
+ const { container } = renderButton();
+
+ expect(screen.getByText(/Starting device authorization/)).toBeTruthy();
+ expect(container.querySelector("a")).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/DeviceAuth/__tests__/useDeviceAuthConnect.test.ts b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/__tests__/useDeviceAuthConnect.test.ts
new file mode 100644
index 0000000000..6b7e8f3bcd
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/__tests__/useDeviceAuthConnect.test.ts
@@ -0,0 +1,352 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { createElement, type ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ postV1InitiateDeviceCodeOauthFlow,
+ postV1PollDeviceCodeOauthFlowForCompletion,
+} from "@/app/api/__generated__/endpoints/integrations/integrations";
+
+import { useDeviceAuthConnect } from "../useDeviceAuthConnect";
+
+vi.mock("@/app/api/__generated__/endpoints/integrations/integrations", () => ({
+ postV1InitiateDeviceCodeOauthFlow: vi.fn(),
+ postV1PollDeviceCodeOauthFlowForCompletion: vi.fn(),
+ getGetV1ListCredentialsQueryKey: () => ["credentials"],
+}));
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ toast: vi.fn(),
+}));
+
+const initiate = vi.mocked(postV1InitiateDeviceCodeOauthFlow);
+const poll = vi.mocked(postV1PollDeviceCodeOauthFlowForCompletion);
+
+function initiated(overrides: Record<string, unknown> = {}) {
+ return {
+ status: 200,
+ data: {
+ state_token: "state_1",
+ user_code: "glow-relish-chaste-soft",
+ verification_url: "https://app.link.com/device/setup",
+ verification_url_complete: "https://app.link.com/device/setup?code=glow",
+ expires_in: 600,
+ interval: 5,
+ ...overrides,
+ },
+ } as never;
+}
+
+function makeWrapper() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return createElement(QueryClientProvider, { client }, children);
+ };
+}
+
+function render(onSuccess = vi.fn()) {
+ return renderHook(
+ () => useDeviceAuthConnect({ provider: "stripe_link", onSuccess }),
+ { wrapper: makeWrapper() },
+ );
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ vi.clearAllMocks();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("useDeviceAuthConnect", () => {
+ it("surfaces the code phrase and the completed verification URL", async () => {
+ initiate.mockResolvedValue(initiated());
+ poll.mockResolvedValue({
+ status: 200,
+ data: { status: "pending" },
+ } as never);
+
+ const { result } = render();
+ await act(async () => {
+ await result.current.connect();
+ });
+
+ expect(result.current.userCode).toBe("glow-relish-chaste-soft");
+ // The completed URL carries the code, so prefer it when present.
+ expect(result.current.verificationUrl).toBe(
+ "https://app.link.com/device/setup?code=glow",
+ );
+ expect(result.current.phase).toBe("polling");
+ });
+
+ it("falls back to the plain verification URL when there is no complete form", async () => {
+ initiate.mockResolvedValue(initiated({ verification_url_complete: null }));
+ poll.mockResolvedValue({
+ status: 200,
+ data: { status: "pending" },
+ } as never);
+
+ const { result } = render();
+ await act(async () => {
+ await result.current.connect();
+ });
+
+ expect(result.current.verificationUrl).toBe(
+ "https://app.link.com/device/setup",
+ );
+ });
+
+ it("reports an error phase when initiation does not return 200", async () => {
+ // The generated client returns a union including error responses; the hook
+ // must narrow on the discriminant rather than assume success.
+ initiate.mockResolvedValue({
+ status: 401,
+ data: { detail: "nope" },
+ } as never);
+
+ const { result } = render();
+ await act(async () => {
+ await result.current.connect();
+ });
+
+ expect(result.current.phase).toBe("error");
+ expect(poll).not.toHaveBeenCalled();
+ });
+
+ it("does not strand the previous poll loop when connect is called twice", async () => {
+ initiate.mockResolvedValue(initiated());
+ poll.mockResolvedValue({
+ status: 200,
+ data: { status: "pending" },
+ } as never);
+
+ const { result } = render();
+ await act(async () => {
+ await result.current.connect();
+ });
+ await act(async () => {
+ await result.current.connect();
+ });
+
+ // Two initiations, but the first loop was cancelled — so advancing time
+ // must not produce polls from both.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+ expect(initiate).toHaveBeenCalledTimes(2);
+ expect(poll.mock.calls.length).toBeLessThanOrEqual(1);
+ });
+
+ it("clamps an out-of-range interval from the provider", async () => {
+ // The interval drives a setTimeout: 0 would spin the loop.
+ initiate.mockResolvedValue(initiated({ interval: 0 }));
+ poll.mockResolvedValue({
+ status: 200,
+ data: { status: "pending" },
+ } as never);
+
+ const { result } = render();
+ await act(async () => {
+ await result.current.connect();
+ });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2_000);
+ });
+ // Unclamped, a 0 interval spins: this would be hundreds of calls in 2s.
+ expect(poll.mock.calls.length).toBeLessThanOrEqual(1);
+ });
+
+ it("completes and notifies once the provider approves", async () => {
+ initiate.mockResolvedValue(initiated({ interval: 1 }));
+ poll.mockResolvedValue({
+ status: 200,
+ data: { status: "approved", credentials: { id: "cred_1" } },
+ } as never);
+ const onSuccess = vi.fn();
+
+ const { result } = render(onSuccess);
+ await act(async () => {
+ await result.current.connect();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_500);
+ });
+
+ await waitFor(() => expect(result.current.phase).toBe("done"));
+ expect(onSuccess).toHaveBeenCalled();
+ });
+
+ it("stops polling when the provider denies", async () => {
+ initiate.mockResolvedValue(initiated({ interval: 1 }));
+ poll.mockResolvedValue({
+ status: 200,
+ data: { status: "denied" },
+ } as never);
+
+ const { result } = render();
+ await act(async () => {
+ await result.current.connect();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1_500);
+ });
+
+ await waitFor(() => expect(result.current.phase).toBe("error"));
+ const callsAfterTerminal = poll.mock.calls.length;
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+ expect(poll.mock.calls.length).toBe(callsAfterTerminal);
+ });
+
+ it("works again after a remount", async () => {
+ // The unmount ref survives a remount, so a stale `true` would silently
+ // no-op every callback and the flow would appear dead the second time.
+ initiate.mockResolvedValue(initiated());
+ poll.mockResolvedValue({
+ status: 200,
+ data: { status: "pending" },
+ } as never);
+
+ const first = render();
+ await act(async () => {
+ await first.result.current.connect();
+ });
+ first.unmount();
+
+ const second = render();
+ await act(async () => {
+ await second.result.current.connect();
+ });
+
+ expect(second.result.current.userCode).toBe("glow-relish-chaste-soft");
+ expect(second.result.current.phase).toBe("polling");
+ });
+
+ it("does not resume polling when cancelled mid-request", async () => {
+ initiate.mockResolvedValue(initiated());
+ let releasePoll: (v: unknown) => void = () => {};
+ poll.mockReturnValue(
+ new Promise((resolve) => {
+ releasePoll = resolve;
+ }) as never,
+ );
+
+ const { result } = render();
+ await act(async () => {
+ await result.current.connect();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+
+ // Cancel while the request is in flight, then let it resolve. Clearing the
+ // timeout cannot retire a request already sent, so without a run-id guard
+ // the resolved poll re-arms the loop after the user walked away.
+ act(() => result.current.cancel());
+ const callsAtCancel = poll.mock.calls.length;
+ await act(async () => {
+ releasePoll({ status: 200, data: { status: "pending" } });
+ await vi.advanceTimersByTimeAsync(20_000);
+ });
+
+ expect(poll.mock.calls.length).toBe(callsAtCancel);
+ expect(result.current.phase).toBe("idle");
+ });
+
+ it("does not fire success for a flow the user already cancelled", async () => {
+ initiate.mockResolvedValue(initiated());
+ let releasePoll: (v: unknown) => void = () => {};
+ poll.mockReturnValue(
+ new Promise((resolve) => {
+ releasePoll = resolve;
+ }) as never,
+ );
+
+ const onSuccess = vi.fn();
+ const { result } = render(onSuccess);
+ await act(async () => {
+ await result.current.connect();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+
+ act(() => result.current.cancel());
+ await act(async () => {
+ // The user had in fact approved on their phone by now.
+ releasePoll({
+ status: 200,
+ data: { status: "approved", credentials: { id: "cred-1" } },
+ });
+ await vi.advanceTimersByTimeAsync(1_000);
+ });
+
+ expect(onSuccess).not.toHaveBeenCalled();
+ });
+
+ it("rides out a transient poll failure instead of ending the flow", async () => {
+ initiate.mockResolvedValue(initiated());
+ poll
+ .mockRejectedValueOnce(new Error("network blip"))
+ .mockResolvedValue({ status: 200, data: { status: "pending" } } as never);
+
+ const { result } = render();
+ await act(async () => {
+ await result.current.connect();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+
+ // The device code is still valid upstream; one blip in a ten-minute
+ // window must not force the user to start over.
+ expect(result.current.phase).toBe("polling");
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+ expect(result.current.phase).toBe("polling");
+ });
+
+ it("gives up after repeated consecutive failures", async () => {
+ initiate.mockResolvedValue(initiated());
+ poll.mockRejectedValue(new Error("still down"));
+
+ const { result } = render();
+ await act(async () => {
+ await result.current.connect();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(30_000);
+ });
+
+ await waitFor(() => expect(result.current.phase).toBe("error"));
+ });
+
+ it("reports approval without guessing a credential when none is returned", async () => {
+ initiate.mockResolvedValue(initiated());
+ poll.mockResolvedValue({
+ status: 200,
+ data: { status: "approved" },
+ } as never);
+
+ const onSuccess = vi.fn();
+ const { result } = render(onSuccess);
+ await act(async () => {
+ await result.current.connect();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5_000);
+ });
+
+ await waitFor(() => expect(onSuccess).toHaveBeenCalledWith(undefined));
+ expect(result.current.phase).toBe("done");
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.ts b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.ts
new file mode 100644
index 0000000000..e29581bf39
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/DeviceAuth/useDeviceAuthConnect.ts
@@ -0,0 +1,206 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+
+import {
+ getGetV1ListCredentialsQueryKey,
+ postV1InitiateDeviceCodeOauthFlow,
+ postV1PollDeviceCodeOauthFlowForCompletion,
+} from "@/app/api/__generated__/endpoints/integrations/integrations";
+import { toast } from "@/components/molecules/Toast/use-toast";
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
+
+interface Args {
+ provider: string;
+ /**
+ * Receives the credential the poll returned, so a caller that has to select
+ * it (the builder's credentials input) doesn't have to re-fetch and guess
+ * which of the provider's credentials is the new one.
+ */
+ onSuccess: (credentials?: CredentialsMetaResponse) => void;
+}
+
+type Phase = "idle" | "awaiting_user" | "polling" | "done" | "error";
+
+const MAX_CONSECUTIVE_POLL_FAILURES = 3;
+
+export function useDeviceAuthConnect({ provider, onSuccess }: Args) {
+ const queryClient = useQueryClient();
+ const [phase, setPhase] = useState<Phase>("idle");
+ const [userCode, setUserCode] = useState("");
+ const [verificationUrl, setVerificationUrl] = useState("");
+
+ const isUnmountedRef = useRef(false);
+ const pollingRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const intervalRef = useRef(5);
+ // Identifies the live loop. Clearing the timeout cannot cancel a request
+ // already in flight, so a cancel mid-round-trip would let the resolved poll
+ // re-arm the loop — and two overlapping connect() calls would leave two live
+ // loops with only the newest in pollingRef. Each loop captures its id and
+ // stops if it is no longer the current one.
+ const runIdRef = useRef(0);
+ // A flow stays open ~10 minutes. One blip in that window must not end it.
+ const consecutiveFailuresRef = useRef(0);
+
+ useEffect(() => {
+ // Reset on mount: the ref survives a remount (StrictMode, or reopening the
+ // dialog), and a stale would make every callback below no-op.
+ isUnmountedRef.current = false;
+ return () => {
+ isUnmountedRef.current = true;
+ if (pollingRef.current) clearTimeout(pollingRef.current);
+ };
+ }, []);
+
+ const stopPolling = useCallback(() => {
+ if (pollingRef.current) {
+ clearTimeout(pollingRef.current);
+ pollingRef.current = null;
+ }
+ }, []);
+
+ const poll = useCallback(
+ async (token: string, runId: number) => {
+ if (isUnmountedRef.current || runId !== runIdRef.current) return;
+
+ try {
+ const response = await postV1PollDeviceCodeOauthFlowForCompletion(
+ provider,
+ { state_token: token },
+ );
+
+ if (isUnmountedRef.current || runId !== runIdRef.current) return;
+
+ if (response.status !== 200) {
+ throw new Error("Device auth poll failed");
+ }
+ consecutiveFailuresRef.current = 0;
+ const { status, credentials } = response.data;
+
+ if (status === "approved") {
+ setPhase("done");
+ stopPolling();
+ toast({ title: "Connected via device auth", variant: "success" });
+ await queryClient.invalidateQueries({
+ queryKey: getGetV1ListCredentialsQueryKey(),
+ });
+ onSuccess(credentials ?? undefined);
+ return;
+ }
+
+ if (status === "slow_down") {
+ intervalRef.current = Math.min(intervalRef.current + 5, 30);
+ }
+
+ if (status === "denied" || status === "expired") {
+ setPhase("error");
+ stopPolling();
+ toast({
+ title:
+ status === "denied"
+ ? "Authorization denied"
+ : "Authorization expired",
+ description:
+ status === "denied"
+ ? "The authorization request was denied."
+ : "The authorization request expired. Please try again.",
+ variant: "destructive",
+ });
+ return;
+ }
+
+ // pending or slow_down — schedule next poll
+ pollingRef.current = setTimeout(
+ () => poll(token, runId),
+ intervalRef.current * 1000,
+ );
+ } catch (error) {
+ if (isUnmountedRef.current || runId !== runIdRef.current) return;
+
+ // The device code is still valid at the provider for the rest of the
+ // window, so a wifi switch or a proxy 502 should not force the user to
+ // start over with a code they have already entered.
+ consecutiveFailuresRef.current += 1;
+ if (consecutiveFailuresRef.current < MAX_CONSECUTIVE_POLL_FAILURES) {
+ pollingRef.current = setTimeout(
+ () => poll(token, runId),
+ intervalRef.current * 1000,
+ );
+ return;
+ }
+
+ setPhase("error");
+ stopPolling();
+ toast({
+ title: "Device auth polling failed",
+ description:
+ error instanceof Error ? error.message : "Unexpected error",
+ variant: "destructive",
+ });
+ }
+ },
+ [provider, onSuccess, queryClient, stopPolling],
+ );
+
+ async function connect() {
+ // A second click would strand the first poll loop, which keeps polling a
+ // token nothing reads any more. Bumping the run id also retires any poll
+ // already in flight, which clearing the timeout cannot do.
+ stopPolling();
+ const runId = ++runIdRef.current;
+ consecutiveFailuresRef.current = 0;
+ setPhase("awaiting_user");
+ try {
+ const response = await postV1InitiateDeviceCodeOauthFlow(provider);
+
+ if (isUnmountedRef.current || runId !== runIdRef.current) return;
+
+ if (response.status !== 200) {
+ throw new Error("Device auth initiation failed");
+ }
+ const data = response.data;
+ setUserCode(data.user_code);
+ setVerificationUrl(
+ data.verification_url_complete || data.verification_url,
+ );
+ // Clamp: this drives a setTimeout, so a 0 or absurd value from the
+ // provider would either spin the loop or stall it forever.
+ intervalRef.current = Math.min(Math.max(data.interval || 5, 1), 60);
+
+ // Start polling. Use the clamped value, not the raw one — an upstream
+ // `interval: 0` would otherwise spin the first poll immediately.
+ setPhase("polling");
+ pollingRef.current = setTimeout(
+ () => poll(data.state_token, runId),
+ intervalRef.current * 1000,
+ );
+ } catch (error) {
+ if (isUnmountedRef.current || runId !== runIdRef.current) return;
+ setPhase("error");
+ toast({
+ title: "Device auth initiation failed",
+ description:
+ error instanceof Error ? error.message : "Unexpected error",
+ variant: "destructive",
+ });
+ }
+ }
+
+ function cancel() {
+ // Retires any in-flight poll as well as the scheduled one.
+ runIdRef.current += 1;
+ stopPolling();
+ setPhase("idle");
+ setUserCode("");
+ setVerificationUrl("");
+ }
+
+ return {
+ connect,
+ cancel,
+ phase,
+ userCode,
+ verificationUrl,
+ };
+}
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView.tsx
index aba82f1ca9..b3feca7a2b 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/ConnectMethodView/ConnectMethodView.tsx
@@ -3,6 +3,7 @@
import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";
import { Icon } from "@/components/atoms/Icon/Icon";
import { Text } from "@/components/atoms/Text/Text";
+import { DeviceAuthConnectButton } from "@/components/contextual/DeviceAuth/DeviceAuthConnectButton";
import { ProviderAvatar } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ProviderAvatar";
import type { ApiKeyConnectFormValues } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/schema";
import { UnsupportedNotice } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/UnsupportedNotice";
@@ -17,6 +18,7 @@ import {
GlobeIcon,
Key01Icon,
SecurityCheckIcon,
+ SmartPhone01Icon,
UserIcon,
} from "@hugeicons/core-free-icons";
import type { IconSvgElement } from "@hugeicons/react";
@@ -28,10 +30,12 @@ interface Props {
onSelectMethod: (method: AuthMethod) => void;
apiKeyForm: UseFormReturn<ApiKeyConnectFormValues>;
onApiKeySubmit: (values: ApiKeyConnectFormValues) => void;
+ onDeviceAuthSuccess: () => void;
}
-const METHOD_ORDER: AuthMethod[] = [
+export const METHOD_ORDER: AuthMethod[] = [
AuthType.oauth2,
+ AuthType.device_code,
AuthType.api_key,
AuthType.user_password,
AuthType.host_scoped,
@@ -67,6 +71,11 @@ const METHOD_COPY: Record<
description: "Scope credentials to one host.",
icon: GlobeIcon,
},
+ [AuthType.device_code]: {
+ label: "Device auth",
+ description: "Approve on your phone with a short code.",
+ icon: SmartPhone01Icon,
+ },
};
// The connect step behind a provider click: logo pair, "Connect AutoGPT
@@ -78,6 +87,7 @@ export function ConnectMethodView({
onSelectMethod,
apiKeyForm,
onApiKeySubmit,
+ onDeviceAuthSuccess,
}: Props) {
const methods = METHOD_ORDER.filter((method) =>
provider.supportedAuthTypes.includes(method),
@@ -190,6 +200,12 @@ export function ConnectMethodView({
providerName={provider.name}
onSubmit={onApiKeySubmit}
/>
+ ) : method === AuthType.device_code ? (
+ <DeviceAuthConnectButton
+ provider={provider.id}
+ providerName={provider.name}
+ onSuccess={onDeviceAuthSuccess}
+ />
) : (
<UnsupportedNotice providerName={provider.name} />
)}
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/DetailView.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/DetailView.tsx
index 338c66770e..45b8bb86b4 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/DetailView.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/DetailView.tsx
@@ -28,6 +28,7 @@ interface Props {
const TAB_PRIORITY: AuthMethod[] = [
AuthType.oauth2,
+ AuthType.device_code,
AuthType.api_key,
AuthType.user_password,
AuthType.host_scoped,
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MethodPanel.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MethodPanel.tsx
index 72442fbc02..82fc634208 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MethodPanel.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/MethodPanel.tsx
@@ -6,14 +6,16 @@ import {
type ConnectableProvider,
} from "../../helpers";
import { ApiKeyConnectForm } from "./ApiKeyConnectForm";
+import { DeviceAuthConnectButton } from "@/components/contextual/DeviceAuth/DeviceAuthConnectButton";
import { OAuthConnectButton } from "./OAuthConnectButton";
import { UnsupportedNotice } from "./UnsupportedNotice";
const TAB_LABEL: Record<AuthMethod, string> = {
[AuthType.oauth2]: "OAuth",
- [AuthType.api_key]: "API key",
- [AuthType.user_password]: "User / password",
+ [AuthType.api_key]: "API key", // pragma: allowlist secret
+ [AuthType.user_password]: "User / password", // pragma: allowlist secret
[AuthType.host_scoped]: "Host",
+ [AuthType.device_code]: "Device auth",
};
interface Props {
@@ -44,6 +46,15 @@ export function MethodPanel({ method, provider, onSuccess }: Props) {
/>
);
}
+ if (method === AuthType.device_code) {
+ return (
+ <DeviceAuthConnectButton
+ provider={provider.id}
+ providerName={provider.name}
+ onSuccess={onSuccess}
+ />
+ );
+ }
return (
<UnsupportedNotice
providerName={provider.name}
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/helpers.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/helpers.ts
index c5a5717032..ca55d61bea 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/helpers.ts
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/helpers.ts
@@ -25,6 +25,7 @@ const TYPE_LABELS: Record<CredentialType, string> = {
oauth2: "OAuth",
user_password: "User/Password",
host_scoped: "Host-scoped",
+ device_code: "Device auth",
};
export function typeBadgeLabel(type: CredentialType): string {
diff --git a/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts b/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts
index 40eb3d6d11..9c270cfd1a 100644
--- a/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts
+++ b/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts
@@ -1,6 +1,9 @@
import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api";
import { describe, expect, it } from "vitest";
-import { getSupportedCredentialTypes } from "../useCredentials";
+import {
+ deriveAuthMethods,
+ getSupportedCredentialTypes,
+} from "../useCredentials";
const schema: BlockIOCredentialsSubSchema = {
type: "object",
@@ -35,3 +38,54 @@ describe("getSupportedCredentialTypes", () => {
]);
});
});
+
+describe("deriveAuthMethods", () => {
+ it("maps each credential type to its connect method", () => {
+ expect(deriveAuthMethods(["api_key"])).toMatchObject({
+ supportsApiKey: true,
+ supportsOAuth2: false,
+ supportsDeviceCode: false,
+ });
+ expect(deriveAuthMethods(["oauth2"])).toMatchObject({
+ supportsOAuth2: true,
+ supportsDeviceCode: false,
+ });
+ expect(deriveAuthMethods(["host_scoped"])).toMatchObject({
+ supportsHostScoped: true,
+ });
+ expect(deriveAuthMethods(["user_password"])).toMatchObject({
+ supportsUserPassword: true,
+ });
+ });
+
+ // The regression: Stripe Link blocks list both types because a device-code
+ // grant stores an oauth2 credential. Offering both put an OAuth tab in front
+ // of a provider with no client secret, so connecting failed with
+ // "Provider 'stripe_link' does not support OAuth".
+ it("lets device_code shadow oauth2 so only the working method is offered", () => {
+ expect(deriveAuthMethods(["oauth2", "device_code"])).toMatchObject({
+ supportsDeviceCode: true,
+ supportsOAuth2: false,
+ });
+ });
+
+ it("still offers other methods alongside device auth", () => {
+ expect(
+ deriveAuthMethods(["oauth2", "device_code", "api_key"]),
+ ).toMatchObject({
+ supportsDeviceCode: true,
+ supportsOAuth2: false,
+ supportsApiKey: true,
+ });
+ });
+
+ it("offers nothing when no types are supported", () => {
+ expect(deriveAuthMethods([])).toEqual({
+ supportsApiKey: false,
+ supportsDeviceCode: false,
+ supportsOAuth2: false,
+ supportsUserPassword: false,
+ supportsHostScoped: false,
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/hooks/useCredentials.ts b/autogpt_platform/frontend/src/hooks/useCredentials.ts
index 8c6076fc14..3814d75dda 100644
--- a/autogpt_platform/frontend/src/hooks/useCredentials.ts
+++ b/autogpt_platform/frontend/src/hooks/useCredentials.ts
@@ -9,6 +9,7 @@ import {
BlockIOCredentialsSubSchema,
CredentialsMetaResponse,
CredentialsProviderName,
+ CredentialsType,
} from "@/lib/autogpt-server-api";
import { getHostFromUrl } from "@/lib/utils/url";
@@ -70,6 +71,7 @@ export type CredentialsData =
schema: BlockIOCredentialsSubSchema;
supportsApiKey: boolean;
supportsOAuth2: boolean;
+ supportsDeviceCode: boolean;
supportsUserPassword: boolean;
supportsHostScoped: boolean;
isLoading: true;
@@ -79,6 +81,7 @@ export type CredentialsData =
schema: BlockIOCredentialsSubSchema;
supportsApiKey: boolean;
supportsOAuth2: boolean;
+ supportsDeviceCode: boolean;
supportsUserPassword: boolean;
supportsHostScoped: boolean;
isLoading: false;
@@ -99,6 +102,35 @@ export function getSupportedCredentialTypes(
return schema.credentials_types;
}
+/**
+ * Maps a block's accepted credential types to the connect methods its UI
+ * should offer.
+ *
+ * These are usually the same list, but a device-code grant produces an
+ * ordinary OAuth2 credential — so such a block accepts `oauth2` (otherwise
+ * saved credentials stop matching) while `device_code` is what the user must
+ * actually go through. Letting `device_code` shadow `oauth2` keeps the UI
+ * from offering an authorization-code redirect the provider has no client
+ * secret for, which is what made these blocks unconnectable.
+ */
+export function deriveAuthMethods(supportedTypes: readonly CredentialsType[]) {
+ const authMethods = getConnectableCredentialTypes(supportedTypes);
+ return {
+ supportsApiKey: authMethods.includes("api_key"),
+ supportsDeviceCode: authMethods.includes("device_code"),
+ supportsOAuth2: authMethods.includes("oauth2"),
+ supportsUserPassword: authMethods.includes("user_password"),
+ supportsHostScoped: authMethods.includes("host_scoped"),
+ };
+}
+
+export function getConnectableCredentialTypes(
+ supportedTypes: readonly CredentialsType[],
+) {
+ const usesDeviceAuth = supportedTypes.includes("device_code");
+ return supportedTypes.filter((type) => type !== "oauth2" || !usesDeviceAuth);
+}
+
export default function useCredentials(
credsInputSchema: BlockIOCredentialsSubSchema,
nodeInputValues?: Record<string, any>,
@@ -149,10 +181,13 @@ export default function useCredentials(
...credsInputSchema,
credentials_types: supportedTypes,
};
- const supportsApiKey = supportedTypes.includes("api_key");
- const supportsOAuth2 = supportedTypes.includes("oauth2");
- const supportsUserPassword = supportedTypes.includes("user_password");
- const supportsHostScoped = supportedTypes.includes("host_scoped");
+ const {
+ supportsApiKey,
+ supportsDeviceCode,
+ supportsOAuth2,
+ supportsUserPassword,
+ supportsHostScoped,
+ } = deriveAuthMethods(supportedTypes);
// No provider means maybe it's still loading
if (!provider) {
@@ -171,6 +206,7 @@ export default function useCredentials(
schema: effectiveSchema,
supportsApiKey,
supportsOAuth2,
+ supportsDeviceCode,
supportsUserPassword,
supportsHostScoped,
savedCredentials,
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
index 92145eb1b3..7bea5f2777 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
@@ -194,7 +194,8 @@ export type CredentialsType =
| "api_key"
| "oauth2"
| "user_password"
- | "host_scoped";
+ | "host_scoped"
+ | "device_code";
export type Credentials =
| APIKeyCredentials
diff --git a/docs/integrations/README.md b/docs/integrations/README.md
index 07199a8eea..0f4f841598 100644
--- a/docs/integrations/README.md
+++ b/docs/integrations/README.md
@@ -185,6 +185,12 @@ Below is a comprehensive list of all available blocks, categorized by their prim
| [Retrieve Information](block-integrations/data.md#retrieve-information) | Reads back a key-value pair previously saved by PersistInformationBlock |
| [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 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 Subscription Trigger](block-integrations/stripe/triggers.md#stripe-subscription-trigger) | Triggers on Stripe subscription events (new, upgrade, cancel) |
## Text Processing
diff --git a/docs/integrations/SUMMARY.md b/docs/integrations/SUMMARY.md
index 482d20d2ec..b422ed59da 100644
--- a/docs/integrations/SUMMARY.md
+++ b/docs/integrations/SUMMARY.md
@@ -122,6 +122,8 @@
* [Smartlead Campaign](block-integrations/smartlead/campaign.md)
* [Stagehand Blocks](block-integrations/stagehand/blocks.md)
* [Stripe Triggers](block-integrations/stripe/triggers.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)
* [System Store Operations](block-integrations/system/store_operations.md)
* [Tavily Crawl](block-integrations/tavily/crawl.md)
diff --git a/docs/integrations/block-integrations/stripe_link/profile.md b/docs/integrations/block-integrations/stripe_link/profile.md
new file mode 100644
index 0000000000..fd27329b93
--- /dev/null
+++ b/docs/integrations/block-integrations/stripe_link/profile.md
@@ -0,0 +1,57 @@
+# Stripe Link Profile
+<!-- MANUAL: file_description -->
+_Add a description of this category of blocks._
+<!-- END MANUAL -->
+
+## Stripe Link Get Shipping Address
+
+### What it is
+Get the delivery addresses saved on the user's Link wallet, with the default one resolved for you. Use it for any purchase that ships something.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+_Add technical explanation here._
+<!-- END MANUAL -->
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the request failed | str |
+| addresses | Every shipping address on the account, each with an `id`, `is_default` and an `address` object | List[Dict[str, Any]] |
+| default_address | The address object marked default, or the first one if none is. Empty when the account has no addresses. | Dict[str, Any] |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+_Add practical use case examples here._
+<!-- END MANUAL -->
+
+---
+
+## Stripe Link Get User Info
+
+### What it is
+Get the Link account holder's name, email and phone. Use it to fill in a checkout that asks who the buyer is. Pairs with Get Shipping Address for anything physical.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+_Add technical explanation here._
+<!-- END MANUAL -->
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the request failed | str |
+| name | Full name on the Link account | str |
+| first_name | Given name | str |
+| last_name | Family name | str |
+| email | Email on the Link account | str |
+| phone | Phone number in E.164 format, e.g. +15551234567 | str |
+
+### 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.md
new file mode 100644
index 0000000000..738c9af9f0
--- /dev/null
+++ b/docs/integrations/block-integrations/stripe_link/spend_request.md
@@ -0,0 +1,133 @@
+# Stripe Link Spend Request
+<!-- MANUAL: file_description -->
+_Add a description of this category of blocks._
+<!-- END MANUAL -->
+
+## Stripe Link Create Card Spend Request
+
+### What it is
+Create a Stripe Link spend request for a one-time virtual card. Self-hosted only; on AutoGPT Cloud use the Shared Payment Token flow with the MPP blocks instead.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+_Add technical explanation here._
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| payment_method_id | ID of the payment method to use (from list payment methods) | str | Yes |
+| merchant_name | Name of the merchant for this purchase | str | Yes |
+| merchant_url | URL of the merchant website | str | Yes |
+| context | Description of the purchase context (min 100 characters). Shown to the user when they approve the request. | str | Yes |
+| amount | Amount in the currency's smallest unit — cents for USD, but whole units for zero-decimal currencies like JPY (max 50000) | int | Yes |
+| currency | 3-letter ISO currency code | str | No |
+| request_approval | If true, immediately sends a push notification to the user for approval. Otherwise, call request-approval separately. | bool | No |
+| test_mode | Use test mode (fake card 4242424242424242) | bool | No |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the request failed | str |
+| spend_request_id | ID of the created spend request | str |
+| status | Status: created, pending_approval, approved, denied, etc. | str |
+| approval_url | URL the user can visit to approve (if not using push) | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+_Add practical use case examples here._
+<!-- END MANUAL -->
+
+---
+
+## 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.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+_Add technical explanation here._
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| spend_request_id | ID of the spend request to check (e.g., lsrq_...) | str | Yes |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the request failed | str |
+| status | Current status: pending_approval, approved, denied, expired. Wait for `approved` before spending the credential. | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+_Add practical use case examples here._
+<!-- END MANUAL -->
+
+---
+
+## Stripe Link List Payment Methods
+
+### What it is
+List payment methods from a Stripe Link wallet
+
+### How it works
+<!-- MANUAL: how_it_works -->
+_Add technical explanation here._
+<!-- END MANUAL -->
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the request failed | str |
+| payment_methods | List of payment methods in the Link wallet | List[Dict[str, Any]] |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+_Add practical use case examples here._
+<!-- END MANUAL -->
+
+---
+
+## 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.
+
+### How it works
+<!-- MANUAL: how_it_works -->
+_Add technical explanation here._
+<!-- END MANUAL -->
+
+### Inputs
+
+| Input | Description | Type | Required |
+|-------|-------------|------|----------|
+| spend_request_id | ID of an approved spend request (e.g., lsrq_...) | str | Yes |
+
+### Outputs
+
+| Output | Description | Type |
+|--------|-------------|------|
+| error | Error message if the request failed | str |
+| status | Current status of the spend request | str |
+| card_number | Virtual card number. Single-use, capped at the approved amount, and expires at `valid_until`. Stored in clear text with the execution record and readable through the execution-results API — do not enable this block where PCI compliance matters. | str |
+| card_cvc | Virtual card CVC. Stored in clear text with the execution record, same as `card_number`. Retaining a CVC after authorization is prohibited under PCI DSS 3.2. | str |
+| card_exp_month | Card expiry month | int |
+| card_exp_year | Card expiry year | int |
+| card_brand | Card brand (visa, mastercard, etc.) | str |
+| valid_until | ISO timestamp when the virtual card expires | str |
+
+### Possible use case
+<!-- MANUAL: use_case -->
+_Add practical use case examples here._
+<!-- END MANUAL -->
+
+---