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.

fix(marketplace): keep shared Google grants alive and flag dead OAuth clients

rubenluetke10-beep085b370e5e0f
diff --git a/jarvis/marketplace/auth/base.py b/jarvis/marketplace/auth/base.py
index 04a4fc0196..6e2bd8aecc 100644
--- a/jarvis/marketplace/auth/base.py
+++ b/jarvis/marketplace/auth/base.py
@@ -96,7 +96,18 @@ def sanitize_provider_error(detail: str, *, limit: int = 160) -> str:
lowered = detail.lower()
if "access_denied" in lowered:
message = "Authorization was declined. Try again when access is approved."
- elif "invalid_client" in lowered or "unauthorized_client" in lowered:
+ elif any(
+ code in lowered
+ for code in (
+ "invalid_client",
+ "unauthorized_client",
+ # Google answers a deleted or disabled OAuth client with these
+ # codes instead of invalid_client. Unmapped, they fell through to
+ # the generic text and the refresh retried forever as transient.
+ "deleted_client",
+ "disabled_client",
+ )
+ ):
message = "invalid_client: The provider does not accept this app registration."
elif "invalid_grant" in lowered:
message = "Authorization expired or was revoked. Connect again."
diff --git a/jarvis/marketplace/auth/oauth_pkce_loopback.py b/jarvis/marketplace/auth/oauth_pkce_loopback.py
index ef84bf8a44..ab930e73fc 100644
--- a/jarvis/marketplace/auth/oauth_pkce_loopback.py
+++ b/jarvis/marketplace/auth/oauth_pkce_loopback.py
@@ -99,6 +99,27 @@ def _basic_token_header(client_id: str, secret: str | None, method: str) -> dict
return {"Authorization": "Basic " + base64.b64encode(credentials).decode("ascii")}
+def _refresh_expires_at(payload: dict) -> datetime | None:
+ """When the provider caps the refresh grant itself, return when it ends.
+
+ Google sends ``refresh_token_expires_in`` when a grant has a fixed lifetime
+ (an OAuth app in Testing status, or access the user granted for a limited
+ time). No refresh can extend it, so it is stored where it is learned
+ instead of surfacing days later as an unexplained reconnect.
+ """
+ nested = payload.get("authed_user")
+ raw = (nested.get("refresh_token_expires_in") if isinstance(nested, dict) else None) or (
+ payload.get("refresh_token_expires_in")
+ )
+ try:
+ seconds = int(raw)
+ except (TypeError, ValueError):
+ return None
+ if seconds <= 0:
+ return None
+ return datetime.now(UTC) + timedelta(seconds=seconds)
+
+
@dataclass
class _PendingPkceFlow:
config: PkceLoopbackConfig
@@ -306,6 +327,17 @@ class PkceLoopbackHandler:
scope = payload.get("authed_user", {}).get("scope") or payload.get("scope")
if scope:
extra["scope"] = scope
+ grant_ends = _refresh_expires_at(payload)
+ if grant_ends is not None:
+ extra["refresh_expires_at"] = grant_ends.isoformat()
+ log.warning(
+ "plugin %s: the provider limits this sign-in to %.1f days (ends %s); "
+ "refreshing cannot extend it. For Google this usually means the "
+ "OAuth app is in Testing status.",
+ pending.config.plugin_id,
+ (grant_ends - datetime.now(UTC)).total_seconds() / 86_400,
+ grant_ends.isoformat(timespec="minutes"),
+ )
# Bind the refresh token to the exact OAuth client that obtained it.
# A user can later replace/delete the family-level client secret (or a
# recovered keyring can expose an older value), but OAuth refresh tokens
@@ -382,6 +414,9 @@ class PkceLoopbackHandler:
)
extra = dict(current.extra)
extra["token_endpoint_auth_method"] = auth_method
+ grant_ends = _refresh_expires_at(payload)
+ if grant_ends is not None:
+ extra["refresh_expires_at"] = grant_ends.isoformat()
if not bound_client_id:
# A successful legacy refresh proves which currently configured
# client owns the grant. Persist that pair now so later config or
diff --git a/jarvis/marketplace/revoke.py b/jarvis/marketplace/revoke.py
index ac471fc724..410118dc4c 100644
--- a/jarvis/marketplace/revoke.py
+++ b/jarvis/marketplace/revoke.py
@@ -17,6 +17,7 @@ visit the provider's own connected-apps page.
from __future__ import annotations
import logging
+from urllib.parse import urlparse
import httpx
@@ -25,12 +26,27 @@ from jarvis.marketplace.catalog import (
OAuthPkceLoopbackAuth,
PluginSpec,
)
-from jarvis.marketplace.token_store import Tokens
+from jarvis.marketplace.token_store import Tokens, TokenStore
log = logging.getLogger(__name__)
_TIMEOUT_SECONDS = 6.0
+# Revocation endpoints that end the grant for the whole OAuth project, not just
+# the token presented. Google documents it: "Revocation removes all OAuth 2.0
+# scopes previously granted to a project, invalidating any issued access or
+# refresh tokens for all clients registered under that project." Gmail, Drive,
+# Calendar, YouTube Music, YouTube Studio and Google Cloud share one client, so
+# revoking on one plugin's disconnect silently killed every other Google plugin.
+_PROJECT_WIDE_REVOCATION_HOSTS = frozenset({"oauth2.googleapis.com", "accounts.google.com"})
+# Google client ids are "<project number>-<id>.apps.googleusercontent.com"; the
+# project number is what a project-wide revocation is scoped to.
+_GOOGLE_CLIENT_SUFFIX = ".apps.googleusercontent.com"
+
+# Outcome when revocation was deliberately skipped because another connection
+# still depends on the same provider grant.
+REVOCATION_SHARED = "shared"
+
def revocation_url(spec: PluginSpec) -> str | None:
"""The provider's RFC 7009 endpoint for this plugin, if it declares one."""
@@ -44,6 +60,83 @@ def revocation_url(spec: PluginSpec) -> str | None:
return None
+def revokes_whole_project(endpoint: str) -> bool:
+ """Whether revoking at ``endpoint`` ends every grant of the OAuth project."""
+ return (urlparse(endpoint).hostname or "").lower() in _PROJECT_WIDE_REVOCATION_HOSTS
+
+
+def _grant_owner(tokens: Tokens) -> str | None:
+ """The OAuth project (Google) or client a stored grant belongs to."""
+ client_id = tokens.extra.get("client_id")
+ if not client_id:
+ return None
+ if client_id.endswith(_GOOGLE_CLIENT_SUFFIX) and "-" in client_id:
+ return "project:" + client_id.split("-", 1)[0]
+ return "client:" + client_id
+
+
+def _shares_grant(plugin_id: str, tokens: Tokens, other_id: str, other: Tokens) -> bool:
+ owner, other_owner = _grant_owner(tokens), _grant_owner(other)
+ if owner and other_owner:
+ return owner == other_owner
+ # A grant stored before Jarvis persisted its issuing client: fall back to
+ # the secret family both plugins resolve their OAuth client from.
+ from jarvis.marketplace.connect_helpers import oauth_client_family
+
+ family = oauth_client_family(plugin_id)
+ return family is not None and family == oauth_client_family(other_id)
+
+
+def shared_grant_holders(plugin_id: str, tokens: Tokens, store: TokenStore) -> list[str]:
+ """Other connected plugins whose grant a project-wide revocation would end.
+
+ Every stored connection counts, flagged ones included: a reconnect flag can
+ be wrong (the scheduler retries it daily), and Jarvis must never destroy a
+ grant it still holds just because one sibling was removed.
+ """
+ from jarvis.marketplace.catalog_data import load_catalog
+
+ holders: list[str] = []
+ for spec in load_catalog().plugins:
+ if spec.id == plugin_id:
+ continue
+ try:
+ other = store.load(spec.id)
+ except Exception: # noqa: BLE001 - an unreadable sibling is still a holder
+ log.info("plugin %s token unreadable; treating it as a shared holder", spec.id)
+ holders.append(spec.id)
+ continue
+ if other is not None and _shares_grant(plugin_id, tokens, spec.id, other):
+ holders.append(spec.id)
+ return holders
+
+
+async def revoke_unless_shared(
+ spec: PluginSpec,
+ tokens: Tokens,
+ store: TokenStore,
+ *,
+ transport: httpx.AsyncBaseTransport | None = None,
+) -> str:
+ """Revoke at the provider unless that would end other plugins' grants too.
+
+ Returns :data:`REVOCATION_SHARED` when the provider revokes per project and
+ another stored connection belongs to the same project; the last plugin of
+ the project to disconnect then revokes the grant for all of them.
+ """
+ endpoint = revocation_url(spec) or tokens.extra.get("revocation_endpoint")
+ if endpoint and revokes_whole_project(endpoint):
+ holders = shared_grant_holders(spec.id, tokens, store)
+ if holders:
+ log.info(
+ "plugin %s: provider revocation skipped; it would also end the grant of %s",
+ spec.id,
+ ", ".join(holders),
+ )
+ return REVOCATION_SHARED
+ return await revoke_tokens(spec, tokens, transport=transport)
+
+
async def revoke_tokens(
spec: PluginSpec,
tokens: Tokens,
diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.py
index 2533831783..3d4b421312 100644
--- a/jarvis/ui/web/marketplace_routes.py
+++ b/jarvis/ui/web/marketplace_routes.py
@@ -76,7 +76,7 @@ from jarvis.marketplace.discord_connect import (
on_discord_disconnected,
)
from jarvis.marketplace.instance_url import InstanceUrlError, normalize_instance_url
-from jarvis.marketplace.revoke import revoke_tokens
+from jarvis.marketplace.revoke import revoke_unless_shared
from jarvis.marketplace.telegram_connect import (
on_telegram_connected,
on_telegram_disconnected,
@@ -155,6 +155,9 @@ class _PluginStatusMeta:
# then says "unknown" rather than inventing a cause.
reauth_reason: str | None = None
reauth_at: str | None = None
+ # When the provider itself ends the refresh grant (Google: an OAuth app in
+ # Testing status). ``None`` when the provider stated no fixed lifetime.
+ refresh_expires_at: str | None = None
def _plugin_status_meta(plugin_id: str, store: TokenStore) -> _PluginStatusMeta:
@@ -183,6 +186,7 @@ def _plugin_status_meta(plugin_id: str, store: TokenStore) -> _PluginStatusMeta:
reauth_at=(
tokens.reauth_at.isoformat() if tokens.needs_reauth and tokens.reauth_at else None
),
+ refresh_expires_at=tokens.extra.get("refresh_expires_at") or None,
)
@@ -379,6 +383,7 @@ async def list_plugins(response: Response) -> dict[str, Any]:
item["last_refreshed"] = meta.last_refreshed
item["reauth_reason"] = meta.reauth_reason
item["reauth_at"] = meta.reauth_at
+ item["refresh_expires_at"] = meta.refresh_expires_at
item["unavailable_reason"] = None
if spec.id == "amd_gpu" and spec.auth.mode == "local":
from jarvis.marketplace.amd_mcp import amd_unavailable_reason
@@ -995,7 +1000,7 @@ async def disconnect(plugin_id: str, request: Request) -> dict[str, Any]:
try:
tokens = store.load(plugin_id)
if tokens is not None:
- revocation = await revoke_tokens(spec, tokens)
+ revocation = await revoke_unless_shared(spec, tokens, store)
except Exception as exc: # noqa: BLE001 - never block the disconnect
log.info("plugin %s revocation skipped: %s", plugin_id, exc)
revocation = "failed"
@@ -1020,8 +1025,10 @@ 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.
+ # "revoked" | "unsupported" | "failed" | "shared" — so the UI can say
+ # honestly whether the user still has to remove the app at the
+ # provider. "shared": other connected plugins still use the same
+ # project-wide grant (Google), so it stays until the last one goes.
"revocation": revocation,
}
@@ -1650,7 +1657,7 @@ async def community_uninstall(plugin_id: str) -> dict[str, Any]:
revocation = "unsupported"
if tokens is not None:
try:
- revocation = await revoke_tokens(spec, tokens)
+ revocation = await revoke_unless_shared(spec, tokens, store)
except Exception as exc: # noqa: BLE001 - never block the uninstall
log.info("plugin %s revocation skipped: %s", plugin_id, exc)
revocation = "failed"
diff --git a/tests/unit/marketplace/test_google_grant_lifecycle.py b/tests/unit/marketplace/test_google_grant_lifecycle.py
new file mode 100644
index 0000000000..bca7030e7e
--- /dev/null
+++ b/tests/unit/marketplace/test_google_grant_lifecycle.py
@@ -0,0 +1,363 @@
+"""Google grant lifecycle regressions.
+
+Gmail, Drive, Calendar, YouTube Music, YouTube Studio and Google Cloud share
+one Google OAuth client. Three defects made those connections die or lie:
+
+* Google's revocation is project-wide: revoking one plugin's token on
+ disconnect ended the grant of every other Google plugin.
+* Google answers a deleted or disabled OAuth client with ``deleted_client`` /
+ ``disabled_client``. Those codes were not recognized, so the refresh was
+ retried as "transient" forever and the card never offered Reconnect.
+* A grant Google caps in time (``refresh_token_expires_in``, sent while the
+ OAuth app is in Testing status) was not recorded, so the 7-day death came
+ without warning.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+
+from jarvis.marketplace.auth.base import sanitize_provider_error
+from jarvis.marketplace.auth.oauth_pkce_loopback import (
+ PkceLoopbackConfig,
+ PkceLoopbackHandler,
+ _PendingPkceFlow,
+)
+from jarvis.marketplace.catalog import PluginSpec
+from jarvis.marketplace.catalog_data import load_catalog
+from jarvis.marketplace.refresh_scheduler import REVOKED, reauth_reason_for, refresh_plugin_token
+from jarvis.marketplace.revoke import (
+ REVOCATION_SHARED,
+ revoke_unless_shared,
+ revokes_whole_project,
+)
+from jarvis.marketplace.token_store import (
+ REAUTH_CLIENT_REJECTED,
+ InMemoryBackend,
+ Tokens,
+ TokenStore,
+)
+
+GOOGLE_CLIENT = "123456789012-abc.apps.googleusercontent.com"
+OTHER_PROJECT_CLIENT = "999999999999-xyz.apps.googleusercontent.com"
+TEST_CLIENT_SECRET = "unit-test-client-secret" # noqa: S105
+
+
+def _google_tokens(client_id: str = GOOGLE_CLIENT, refresh: str = "rt") -> Tokens:
+ return Tokens(access="at", refresh=refresh, extra={"client_id": client_id})
+
+
+def _recording_transport(seen: list[httpx.Request]) -> httpx.MockTransport:
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request)
+ return httpx.Response(200)
+
+ return httpx.MockTransport(handler)
+
+
+def _gmail() -> PluginSpec:
+ spec = load_catalog().by_id("gmail")
+ assert spec is not None
+ return spec
+
+
+# --------------------------------------------------------------------------
+# Project-wide revocation
+# --------------------------------------------------------------------------
+
+
+def test_google_revocation_endpoints_are_project_wide() -> None:
+ assert revokes_whole_project("https://oauth2.googleapis.com/revoke")
+ assert revokes_whole_project("https://accounts.google.com/o/oauth2/revoke")
+ assert not revokes_whole_project("https://slack.com/api/auth.revoke")
+
+
+async def test_disconnecting_one_google_plugin_keeps_the_shared_grant() -> None:
+ """Revoking Gmail's token would end Drive's grant too, so it is skipped."""
+ store = TokenStore(InMemoryBackend())
+ store.save("gmail", _google_tokens(refresh="gmail-rt"))
+ store.save("google_drive", _google_tokens(refresh="drive-rt"))
+ seen: list[httpx.Request] = []
+
+ outcome = await revoke_unless_shared(
+ _gmail(), store.load("gmail"), store, transport=_recording_transport(seen)
+ )
+
+ assert outcome == REVOCATION_SHARED
+ assert seen == [], "no revocation request may reach Google"
+
+
+async def test_the_last_google_plugin_revokes_the_grant() -> None:
+ store = TokenStore(InMemoryBackend())
+ store.save("gmail", _google_tokens())
+ seen: list[httpx.Request] = []
+
+ outcome = await revoke_unless_shared(
+ _gmail(), store.load("gmail"), store, transport=_recording_transport(seen)
+ )
+
+ assert outcome == "revoked"
+ assert len(seen) == 1
+ assert "token=rt" in seen[0].content.decode()
+
+
+async def test_a_flagged_sibling_still_protects_the_grant() -> None:
+ """A reconnect flag can be wrong and self-heals; never destroy its grant."""
+ store = TokenStore(InMemoryBackend())
+ store.save("gmail", _google_tokens())
+ store.save(
+ "google_calendar",
+ Tokens(
+ access="at",
+ refresh="cal-rt",
+ extra={"client_id": GOOGLE_CLIENT},
+ needs_reauth=True,
+ ),
+ )
+ seen: list[httpx.Request] = []
+
+ outcome = await revoke_unless_shared(
+ _gmail(), store.load("gmail"), store, transport=_recording_transport(seen)
+ )
+
+ assert outcome == REVOCATION_SHARED
+ assert seen == []
+
+
+async def test_a_sibling_from_another_google_project_does_not_block_revocation() -> None:
+ store = TokenStore(InMemoryBackend())
+ store.save("gmail", _google_tokens())
+ store.save("google_drive", _google_tokens(client_id=OTHER_PROJECT_CLIENT))
+ seen: list[httpx.Request] = []
+
+ outcome = await revoke_unless_shared(
+ _gmail(), store.load("gmail"), store, transport=_recording_transport(seen)
+ )
+
+ assert outcome == "revoked"
+ assert len(seen) == 1
+
+
+async def test_a_legacy_sibling_without_a_bound_client_is_matched_by_family() -> None:
+ """Grants stored before the client id was persisted share by family."""
+ store = TokenStore(InMemoryBackend())
+ store.save("gmail", _google_tokens())
+ store.save("google_drive", Tokens(access="at", refresh="legacy-rt"))
+ seen: list[httpx.Request] = []
+
+ outcome = await revoke_unless_shared(
+ _gmail(), store.load("gmail"), store, transport=_recording_transport(seen)
+ )
+
+ assert outcome == REVOCATION_SHARED
+ assert seen == []
+
+
+async def test_a_per_token_provider_still_revokes_with_siblings() -> None:
+ """Only project-wide revocation is guarded; other providers revoke one token."""
+ spec = PluginSpec.model_validate(
+ {
+ "id": "gmail",
+ "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": "https://example.test/revoke",
+ "client_id": "cid",
+ "scopes": ["read"],
+ },
+ }
+ )
+ store = TokenStore(InMemoryBackend())
+ store.save("gmail", Tokens(access="at", refresh="rt", extra={"client_id": "cid"}))
+ store.save("google_drive", Tokens(access="at", refresh="rt2", extra={"client_id": "cid"}))
+ seen: list[httpx.Request] = []
+
+ outcome = await revoke_unless_shared(
+ spec, store.load("gmail"), store, transport=_recording_transport(seen)
+ )
+
+ assert outcome == "revoked"
+ assert len(seen) == 1
+
+
+async def test_disconnect_route_keeps_the_other_google_plugins_connected(monkeypatch) -> None:
+ from starlette.requests import Request
+
+ from jarvis.ui.web import marketplace_routes
+
+ store = TokenStore(InMemoryBackend())
+ store.save("gmail", _google_tokens(refresh="gmail-rt"))
+ store.save("google_drive", _google_tokens(refresh="drive-rt"))
+ calls: list[str] = []
+
+ async def _no_network(*args, **kwargs): # noqa: ANN002, ANN003
+ calls.append("revoke")
+ return "revoked"
+
+ monkeypatch.setattr(marketplace_routes, "TokenStore", lambda: store)
+ monkeypatch.setattr(marketplace_routes, "_refresh_plugin_in_live_registry", lambda _p: None)
+ monkeypatch.setattr("jarvis.marketplace.revoke.revoke_tokens", _no_network)
+
+ request = Request({"type": "http", "app": None, "headers": []})
+ body = await marketplace_routes.disconnect("gmail", request)
+
+ assert body["revocation"] == REVOCATION_SHARED
+ assert calls == []
+ assert store.load("gmail") is None
+ assert store.load("google_drive") is not None
+
+
+# --------------------------------------------------------------------------
+# Deleted / disabled OAuth client
+# --------------------------------------------------------------------------
+
+
[email protected]("code", ["deleted_client", "disabled_client"])
+def test_deleted_or_disabled_client_is_a_client_rejection(code: str) -> None:
+ body = '{"error": "' + code + '"}'
+ message = "refresh HTTP 401: " + sanitize_provider_error(body)
+ assert reauth_reason_for(message) == REAUTH_CLIENT_REJECTED
+ assert code not in sanitize_provider_error(code + " The OAuth client was deleted.")
+
+
+async def test_refresh_against_a_deleted_client_flags_reconnect(monkeypatch) -> None:
+ async def _fake_post(self, url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003
+ return httpx.Response(
+ 401,
+ json={"error": "deleted_client", "error_description": "The OAuth client was deleted."},
+ )
+
+ monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post)
+ cfg = PkceLoopbackConfig(
+ plugin_id="gmail",
+ authorization_url="https://accounts.google.com/o/oauth2/v2/auth",
+ token_url="https://oauth2.googleapis.com/token", # noqa: S106
+ client_id=GOOGLE_CLIENT,
+ client_secret=TEST_CLIENT_SECRET,
+ callback_port=0,
+ scopes=["https://mail.google.com/"],
+ )
+ store = TokenStore(InMemoryBackend())
+ store.save("gmail", _google_tokens())
+
+ attempt = await refresh_plugin_token(
+ "gmail", store, lambda _pid: PkceLoopbackHandler(cfg), force=True
+ )
+
+ assert attempt.outcome == REVOKED
+ saved = store.load("gmail")
+ assert saved.needs_reauth
+ assert saved.reauth_reason == REAUTH_CLIENT_REJECTED
+
+
+# --------------------------------------------------------------------------
+# Time-limited grants (Testing status)
+# --------------------------------------------------------------------------
+
+
+def _google_cfg() -> PkceLoopbackConfig:
+ return PkceLoopbackConfig(
+ plugin_id="google_calendar",
+ authorization_url="https://accounts.google.com/o/oauth2/v2/auth",
+ token_url="https://oauth2.googleapis.com/token", # noqa: S106
+ client_id=GOOGLE_CLIENT,
+ client_secret=TEST_CLIENT_SECRET,
+ callback_port=0,
+ scopes=["https://www.googleapis.com/auth/calendar"],
+ )
+
+
+async def test_exchange_records_when_google_ends_a_time_limited_grant(monkeypatch) -> None:
+ from datetime import UTC, datetime, timedelta
+
+ async def _fake_post(self, url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003
+ return httpx.Response(
+ 200,
+ json={
+ "access_token": "access",
+ "refresh_token": "refresh",
+ "expires_in": 3599,
+ "refresh_token_expires_in": 604799,
+ },
+ )
+
+ monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post)
+ cfg = _google_cfg()
+ pending = _PendingPkceFlow(
+ config=cfg, callback_server=None, code_verifier="v", redirect_uri="http://127.0.0.1:3122"
+ )
+
+ tokens = await PkceLoopbackHandler(cfg)._exchange(pending, code="code") # noqa: SLF001
+
+ ends = datetime.fromisoformat(tokens.extra["refresh_expires_at"])
+ assert timedelta(days=6, hours=23) < ends - datetime.now(UTC) <= timedelta(days=7)
+
+
+async def test_a_production_grant_records_no_end(monkeypatch) -> None:
+ async def _fake_post(self, url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003
+ return httpx.Response(
+ 200, json={"access_token": "access", "refresh_token": "refresh", "expires_in": 3599}
+ )
+
+ monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post)
+ cfg = _google_cfg()
+ pending = _PendingPkceFlow(
+ config=cfg, callback_server=None, code_verifier="v", redirect_uri="http://127.0.0.1:3122"
+ )
+
+ tokens = await PkceLoopbackHandler(cfg)._exchange(pending, code="code") # noqa: SLF001
+
+ assert "refresh_expires_at" not in tokens.extra
+
+
+async def test_refresh_updates_the_recorded_grant_end(monkeypatch) -> None:
+ async def _fake_post(self, url, *args, **kwargs): # noqa: ANN001, ANN002, ANN003
+ return httpx.Response(
+ 200,
+ json={"access_token": "new", "expires_in": 3599, "refresh_token_expires_in": 3600},
+ )
+
+ monkeypatch.setattr(httpx.AsyncClient, "post", _fake_post)
+
+ refreshed = await PkceLoopbackHandler(_google_cfg()).refresh(_google_tokens())
+
+ assert refreshed.access == "new"
+ assert "refresh_expires_at" in refreshed.extra
+
+
+async def test_list_plugins_serves_the_grant_end(monkeypatch) -> None:
+ from fastapi import Response
+
+ from jarvis.ui.web import marketplace_routes
+
+ store = TokenStore(InMemoryBackend())
+ store.save(
+ "gmail",
+ Tokens(access="at", extra={"refresh_expires_at": "2026-10-09T12:00:00+00:00"}),
+ )
+ monkeypatch.setattr(marketplace_routes, "TokenStore", lambda: store)
+
+ payload = await marketplace_routes.list_plugins(Response())
+ gmail = next(p for p in payload["plugins"] if p["id"] == "gmail")
+ drive = next(p for p in payload["plugins"] if p["id"] == "google_drive")
+
+ assert gmail["refresh_expires_at"] == "2026-10-09T12:00:00+00:00"
+ assert drive["refresh_expires_at"] is None