Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(marketplace): end the grant at the provider on disconnect

Ruben Lütkeef34ee328f28
diff --git a/jarvis/marketplace/auth/oauth_dcr.py b/jarvis/marketplace/auth/oauth_dcr.py
index e346a57384..c4b5235521 100644
--- a/jarvis/marketplace/auth/oauth_dcr.py
+++ b/jarvis/marketplace/auth/oauth_dcr.py
@@ -81,6 +81,10 @@ class _PendingFlow:
token_endpoint: str
client_id: str
resource: str | None = None
+ # RFC 7009 endpoint from discovery, persisted with the tokens so a later
+ # disconnect can actually end the grant at the provider instead of only
+ # deleting our local copy.
+ revocation_endpoint: str | None = None
def _well_known_candidates(issuer: str) -> list[str]:
@@ -294,6 +298,7 @@ class HostedMcpDcrHandler:
token_endpoint=meta["token_endpoint"],
client_id=client_id,
resource=resource,
+ revocation_endpoint=meta.get("revocation_endpoint") or None,
)
return AuthSession(
@@ -385,6 +390,10 @@ class HostedMcpDcrHandler:
extra["token_endpoint"] = pending.token_endpoint
if pending.resource:
extra["resource"] = pending.resource
+ if pending.revocation_endpoint:
+ # A DCR client is ephemeral, so its revocation endpoint is only
+ # knowable from the discovery document used at connect time.
+ extra["revocation_endpoint"] = pending.revocation_endpoint
return Tokens(
access=access,
refresh=refresh,
diff --git a/jarvis/marketplace/revoke.py b/jarvis/marketplace/revoke.py
new file mode 100644
index 0000000000..88070b8937
--- /dev/null
+++ b/jarvis/marketplace/revoke.py
@@ -0,0 +1,109 @@
+"""Best-effort token revocation at the provider on disconnect.
+
+Removing a plugin used to delete only the LOCAL token: the authorization stayed
+alive in the user's account at the provider, showing "Personal Jarvis" as a
+connected app forever. `revocation_url` has been in the catalog schema (and
+populated for Google, Slack and Asana) since the beginning without anything ever
+reading it.
+
+Deliberately best-effort and non-blocking for the disconnect itself. Removing
+the local credential is the part the user asked for and it must always succeed;
+a provider that is unreachable, has already dropped the grant, or does not
+implement RFC 7009 must not turn "disconnect" into an error. The outcome is
+reported back so the UI can tell the user honestly whether they still need to
+visit the provider's own connected-apps page.
+"""
+
+from __future__ import annotations
+
+import logging
+
+import httpx
+
+from jarvis.marketplace.catalog import (
+ OAuthDeviceFlowAuth,
+ OAuthPkceLoopbackAuth,
+ PluginSpec,
+)
+from jarvis.marketplace.token_store import Tokens
+
+log = logging.getLogger(__name__)
+
+_TIMEOUT_SECONDS = 6.0
+
+
+def revocation_url(spec: PluginSpec) -> str | None:
+ """The provider's RFC 7009 endpoint for this plugin, if it declares one."""
+ auth = spec.auth
+ if isinstance(auth, OAuthPkceLoopbackAuth):
+ return auth.revocation_url
+ if isinstance(auth, OAuthDeviceFlowAuth):
+ return getattr(auth, "revocation_url", None)
+ # DCR plugins learn their revocation endpoint from discovery at connect
+ # time; it is persisted with the tokens rather than in the catalog.
+ return None
+
+
+async def revoke_tokens(
+ spec: PluginSpec,
+ tokens: Tokens,
+ *,
+ transport: httpx.AsyncBaseTransport | None = None,
+) -> str:
+ """Ask the provider to drop the grant. Returns a short outcome word.
+
+ ``revoked`` - the provider accepted the request
+ ``unsupported`` - no endpoint is known for this plugin
+ ``failed`` - we tried and the provider refused or was unreachable
+ """
+ endpoint = revocation_url(spec) or tokens.extra.get("revocation_endpoint")
+ if not endpoint:
+ return "unsupported"
+
+ # Revoking the REFRESH token invalidates the whole grant at every provider
+ # that follows RFC 7009 §2.1; revoking only the access token would leave the
+ # grant renewable. Fall back to the access token when no refresh exists
+ # (a PAT-style or non-refreshable grant).
+ token = tokens.refresh or tokens.access
+ if not token:
+ return "unsupported"
+
+ body = {
+ "token": token,
+ "token_type_hint": "refresh_token" if tokens.refresh else "access_token",
+ }
+ client_id = tokens.extra.get("client_id")
+ if client_id:
+ body["client_id"] = client_id
+ client_secret = tokens.extra.get("client_secret")
+ if client_secret:
+ body["client_secret"] = client_secret
+
+ try:
+ async with httpx.AsyncClient(
+ timeout=httpx.Timeout(_TIMEOUT_SECONDS), transport=transport
+ ) as client:
+ response = await client.post(
+ endpoint,
+ data=body,
+ headers={
+ "Content-Type": "application/x-www-form-urlencoded",
+ "User-Agent": "Personal-Jarvis/1.0",
+ },
+ )
+ except Exception as exc: # noqa: BLE001 - the local disconnect still stands
+ log.info("plugin %s revocation could not be delivered: %s", spec.id, exc)
+ return "failed"
+
+ # RFC 7009 §2.2: a server returns 200 for a successful revocation AND for a
+ # token it does not recognize — an already-dead grant is the outcome we
+ # wanted anyway. Some providers answer 204.
+ if response.status_code in (200, 204):
+ return "revoked"
+ log.info(
+ "plugin %s revocation refused: HTTP %s %s",
+ spec.id,
+ response.status_code,
+ response.text[:120],
+ )
+ return "failed"
diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.py
index 771f26cf80..325a21dc59 100644
--- a/jarvis/ui/web/marketplace_routes.py
+++ b/jarvis/ui/web/marketplace_routes.py
@@ -44,6 +44,7 @@ from jarvis.marketplace.discord_connect import (
on_discord_connected,
on_discord_disconnected,
)
+from jarvis.marketplace.revoke import revoke_tokens
from jarvis.marketplace.telegram_connect import (
on_telegram_connected,
on_telegram_disconnected,
@@ -584,9 +585,26 @@ async def oauth_callback(code: str = "", state: str = "", error: str = "") -> HT
@router.delete("/plugins/{plugin_id}")
async def disconnect(plugin_id: str, request: Request) -> dict[str, Any]:
catalog = load_catalog()
- if catalog.by_id(plugin_id) is None:
+ spec = catalog.by_id(plugin_id)
+ if spec is None:
raise HTTPException(status_code=404, detail=f"plugin {plugin_id!r} not in catalog")
- TokenStore().delete(plugin_id)
+
+ # Tell the provider to drop the grant BEFORE the local token is gone —
+ # afterwards there is nothing left to revoke with. Deleting the local
+ # credential is what the user asked for and must always happen, so a
+ # provider that is unreachable or does not implement revocation only
+ # changes what we report, never whether the disconnect succeeds.
+ store = TokenStore()
+ revocation = "unsupported"
+ try:
+ tokens = store.load(plugin_id)
+ if tokens is not None:
+ revocation = await revoke_tokens(spec, tokens)
+ except Exception as exc: # noqa: BLE001 - never block the disconnect
+ log.info("plugin %s revocation skipped: %s", plugin_id, exc)
+ revocation = "failed"
+
+ store.delete(plugin_id)
_refresh_plugin_in_live_registry(plugin_id)
if plugin_id == "telegram":
try:
@@ -606,4 +624,7 @@ async def disconnect(plugin_id: str, request: Request) -> dict[str, Any]:
"plugin_id": plugin_id,
"status": "not_connected",
"live_applied": live_applied,
+ # "revoked" | "unsupported" | "failed" — so the UI can say honestly
+ # whether the user still has to remove the app at the provider.
+ "revocation": revocation,
}
diff --git a/tests/unit/marketplace/test_revoke.py b/tests/unit/marketplace/test_revoke.py
new file mode 100644
index 0000000000..7ee577d6bf
--- /dev/null
+++ b/tests/unit/marketplace/test_revoke.py
@@ -0,0 +1,163 @@
+"""Disconnect must also end the grant AT THE PROVIDER.
+
+Removing a plugin used to delete only the local token, leaving the
+authorization alive in the user's account — the provider kept listing the app
+as connected forever. `revocation_url` sat unused in the catalog schema the
+whole time.
+
+The second half of the contract matters just as much: revocation is
+best-effort. The user asked for the credential to be removed, so an unreachable
+or non-compliant provider must never turn a disconnect into a failure.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+
+from jarvis.marketplace.catalog import PluginSpec
+from jarvis.marketplace.revoke import revoke_tokens
+from jarvis.marketplace.token_store import Tokens
+
+
+def _pkce_spec(revocation_url: str | None) -> PluginSpec:
+ return PluginSpec.model_validate(
+ {
+ "id": "demo",
+ "display_name": "Demo",
+ "description": "d",
+ "category": "Developer",
+ "logo_slug": "demo",
+ "auth": {
+ "mode": "oauth_pkce_loopback",
+ "authorization_url": "https://example.test/authorize",
+ "token_url": "https://example.test/token",
+ "revocation_url": revocation_url,
+ "client_id": "cid",
+ "scopes": ["read"],
+ },
+ }
+ )
+
+
+def _transport(record: list[httpx.Request], status: int = 200) -> httpx.MockTransport:
+ def handler(request: httpx.Request) -> httpx.Response:
+ record.append(request)
+ return httpx.Response(status)
+
+ return httpx.MockTransport(handler)
+
+
+async def test_revokes_the_refresh_token_not_just_the_access_token() -> None:
+ """RFC 7009 §2.1: revoking the refresh token kills the whole grant.
+ Revoking only the access token would leave it renewable."""
+ seen: list[httpx.Request] = []
+ outcome = await revoke_tokens(
+ _pkce_spec("https://example.test/revoke"),
+ Tokens(access="at", refresh="rt", extra={"client_id": "cid"}),
+ transport=_transport(seen),
+ )
+
+ assert outcome == "revoked"
+ assert len(seen) == 1
+ body = seen[0].content.decode()
+ assert "token=rt" in body
+ assert "token_type_hint=refresh_token" in body
+ assert "client_id=cid" in body
+
+
+async def test_falls_back_to_the_access_token_when_there_is_no_refresh() -> None:
+ seen: list[httpx.Request] = []
+ outcome = await revoke_tokens(
+ _pkce_spec("https://example.test/revoke"),
+ Tokens(access="at"),
+ transport=_transport(seen),
+ )
+
+ assert outcome == "revoked"
+ assert "token=at" in seen[0].content.decode()
+
+
+async def test_unknown_token_still_counts_as_revoked() -> None:
+ """RFC 7009 §2.2 returns 200 for a token the server does not recognize —
+ an already-dead grant is exactly the state we wanted."""
+ outcome = await revoke_tokens(
+ _pkce_spec("https://example.test/revoke"),
+ Tokens(access="at", refresh="rt"),
+ transport=_transport([], status=200),
+ )
+ assert outcome == "revoked"
+
+
+async def test_a_provider_without_an_endpoint_is_reported_not_attempted() -> None:
+ seen: list[httpx.Request] = []
+ outcome = await revoke_tokens(
+ _pkce_spec(None),
+ Tokens(access="at", refresh="rt"),
+ transport=_transport(seen),
+ )
+
+ assert outcome == "unsupported"
+ assert seen == [], "nothing to call, so nothing may be called"
+
+
+async def test_a_dcr_plugin_uses_the_endpoint_discovered_at_connect_time() -> None:
+ """A DCR client is ephemeral, so its revocation endpoint is only knowable
+ from the discovery document — it is persisted with the tokens."""
+ seen: list[httpx.Request] = []
+ spec = PluginSpec.model_validate(
+ {
+ "id": "dcr",
+ "display_name": "Dcr",
+ "description": "d",
+ "category": "Developer",
+ "logo_slug": "dcr",
+ "auth": {
+ "mode": "hosted_mcp_oauth_dcr",
+ "discovery_url": "https://mcp.example.test/mcp",
+ "mcp_url": "https://mcp.example.test/mcp",
+ },
+ }
+ )
+
+ outcome = await revoke_tokens(
+ spec,
+ Tokens(
+ access="at",
+ refresh="rt",
+ extra={"revocation_endpoint": "https://as.example.test/revoke"},
+ ),
+ transport=_transport(seen),
+ )
+
+ assert outcome == "revoked"
+ assert str(seen[0].url) == "https://as.example.test/revoke"
+
+
+async def test_an_unreachable_provider_never_blocks_the_disconnect() -> None:
+ def explode(request: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("no route to host", request=request)
+
+ outcome = await revoke_tokens(
+ _pkce_spec("https://example.test/revoke"),
+ Tokens(access="at", refresh="rt"),
+ transport=httpx.MockTransport(explode),
+ )
+
+ assert outcome == "failed", "reported honestly, and NOT raised"
+
+
+async def test_a_refusal_is_reported_rather_than_swallowed() -> None:
+ outcome = await revoke_tokens(
+ _pkce_spec("https://example.test/revoke"),
+ Tokens(access="at", refresh="rt"),
+ transport=_transport([], status=400),
+ )
+ assert outcome == "failed"