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(grok): recognize scoped subscription logins across agent accounts

rubenluetke10-beepbe2684cdbe04
diff --git a/jarvis/agent_accounts.py b/jarvis/agent_accounts.py
index 40e23b063b..985c5c8f50 100644
--- a/jarvis/agent_accounts.py
+++ b/jarvis/agent_accounts.py
@@ -853,6 +853,22 @@ def describe(account: AgentAccount) -> AccountSnapshot:
return _describe_claude(account)
if account.platform == "codex":
return _describe_codex(account)
+ if account.platform == "grok-build":
+ from jarvis.grok_build_auth import grok_build_login_in
+
+ connected, mode, email = grok_build_login_in(account.config_dir)
+ subscription = connected and mode == "subscription"
+ return AccountSnapshot(
+ account=account,
+ connected=subscription,
+ mode=mode,
+ email=email,
+ message=(
+ "Connected via Grok Build subscription."
+ if subscription
+ else _not_signed_in_message(account)
+ ),
+ )
return _describe_generic(account)
diff --git a/jarvis/grok_build_auth.py b/jarvis/grok_build_auth.py
index e98e07d6c1..387119a284 100644
--- a/jarvis/grok_build_auth.py
+++ b/jarvis/grok_build_auth.py
@@ -16,6 +16,7 @@ reachable under ``pythonw.exe``.
No secret value is ever logged: only the binary name and connection booleans.
"""
+
from __future__ import annotations
import base64
@@ -52,6 +53,32 @@ _ISO_HOME_MARKER = ".jarvis_src_mtime"
# token VALUE is never read into business logic (same rule as Google ToS copy).
_LOGIN_FILES: tuple[str, ...] = ("auth.json",)
+# Public CLI OAuth client, from xai-grok-login/src/config.rs (not a secret).
+_DEFAULT_AUTH_SCOPE = "https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"
+
+
+def _auth_record(auth: dict[str, Any]) -> dict[str, Any]:
+ """Select the CLI's current issuer/client entry, preserving old flat files.
+
+ Grok Build 1.x stores an AuthStore map, not a flat token object. Never
+ borrow an unrelated issuer's cached login to mark the active one ready.
+ See xai-org/grok-build, xai-grok-login/src/{model,config}.rs.
+ """
+ scope = _DEFAULT_AUTH_SCOPE
+ for prefix in ("GROK_OIDC", "GROK_OAUTH2"):
+ issuer = os.environ.get(f"{prefix}_ISSUER")
+ client = os.environ.get(f"{prefix}_CLIENT_ID")
+ if issuer and client:
+ scope = f"{issuer.rstrip('/')}::{client}"
+ break
+ if scope in auth:
+ record = auth[scope]
+ return record if isinstance(record, dict) else {}
+ if "xai::api_key" in auth:
+ record = auth["xai::api_key"]
+ return record if isinstance(record, dict) else {}
+ return auth
+
def grok_build_install_command(platform: str | None = None) -> str:
"""Official Grok Build installer for the current OS."""
@@ -111,6 +138,20 @@ def _derive_auth(auth: dict[str, Any] | None) -> tuple[bool, str]:
"""
if not isinstance(auth, dict):
return False, "unknown"
+ auth = _auth_record(auth)
+ if "auth_mode" in auth:
+ # The current CLI calls the bearer field `key`. An API-key entry or
+ # unknown/retired auth mode must never become a subscription merely
+ # because it also has a refresh_token or profile attached.
+ key = auth.get("key")
+ present = isinstance(key, str) and bool(key.strip())
+ if auth["auth_mode"] == "api_key":
+ return (True, "api_key") if present else (False, "unknown")
+ if auth["auth_mode"] == "oidc":
+ refresh = auth.get("refresh_token")
+ renewable = isinstance(refresh, str) and bool(refresh.strip())
+ return (True, "subscription") if present or renewable else (False, "unknown")
+ return False, "unknown"
tokens = auth.get("tokens")
if isinstance(tokens, dict) and any(
isinstance(tokens.get(k), str) and tokens.get(k).strip()
@@ -152,6 +193,7 @@ def _email_from_id_token(token: str | None) -> str | None:
def _email_from_auth(auth: dict[str, Any] | None) -> str | None:
if not isinstance(auth, dict):
return None
+ auth = _auth_record(auth)
for key in ("email", "user_email"):
value = auth.get(key)
if isinstance(value, str) and value.strip():
@@ -277,9 +319,7 @@ def grok_build_provider_ready(status: GrokBuildAuthStatus) -> bool:
Subscription-only on this card: the xAI API key lives on the separate
Grok brain/subagent card. A missing binary must never paint Ready.
"""
- return bool(
- status.installed and status.connected and status.mode == "subscription"
- )
+ return bool(status.installed and status.connected and status.mode == "subscription")
class GrokBuildAuthService:
@@ -349,9 +389,7 @@ class GrokBuildAuthService:
version = self._probe_version(binary)
connected, mode, email = grok_build_login_in(self._home_dir())
if connected and mode == "subscription":
- message = (
- f"Connected as {email}" if email else "Connected via SuperGrok / X Premium+"
- )
+ message = f"Connected as {email}" if email else "Connected via SuperGrok / X Premium+"
elif connected and mode == "api_key":
message = "API key present in Grok Build auth (use the xAI Grok card for API billing)"
else:
@@ -370,9 +408,7 @@ class GrokBuildAuthService:
"""Spawn ``grok login`` in a visible terminal. Raises if the CLI is absent."""
binary = self._resolve_binary()
if binary is None:
- raise FileNotFoundError(
- f"Grok Build CLI not found. {grok_build_install_hint()}"
- )
+ raise FileNotFoundError(f"Grok Build CLI not found. {grok_build_install_hint()}")
argv = [binary, "login"]
log.info("Starting Grok Build login (interactive grok login)")
try:
diff --git a/tests/unit/test_agent_accounts.py b/tests/unit/test_agent_accounts.py
index 4b9000b2b7..80f3c1ae39 100644
--- a/tests/unit/test_agent_accounts.py
+++ b/tests/unit/test_agent_accounts.py
@@ -35,6 +35,36 @@ def _isolated_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
# ------------------------------------------------------------------ built-in
+ "auth, expected",
+ [
+ ({}, False),
+ ({"xai::api_key": {"auth_mode": "api_key", "key": "test-api-key"}}, False),
+ (
+ {
+ "https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828": {
+ "auth_mode": "oidc",
+ "key": "test-bearer",
+ "email": "[email protected]",
+ }
+ },
+ True,
+ ),
+ ],
+)
+def test_grok_account_requires_subscription_material(auth, expected, monkeypatch):
+ for prefix in ("GROK_OIDC", "GROK_OAUTH2"):
+ for suffix in ("ISSUER", "CLIENT_ID"):
+ monkeypatch.delenv(f"{prefix}_{suffix}", raising=False)
+ account = agent_accounts.active_account("grok-build")
+ account.config_dir.mkdir(parents=True)
+ (account.config_dir / "auth.json").write_text(json.dumps(auth), encoding="utf-8")
+ snapshot = agent_accounts.describe(account)
+ assert snapshot.connected is expected
+ if expected:
+ assert snapshot.email == "[email protected]"
+
+
def test_every_platform_offers_its_builtin_account_with_no_store() -> None:
"""A fresh install has one usable account per CLI and no file at all."""
for platform in agent_accounts.platforms():
@@ -222,9 +252,7 @@ def test_an_added_account_pins_its_own_directory() -> None:
def test_spawn_env_inherits_rather_than_replaces() -> None:
"""A bare {VAR: dir} would strip PATH and the agent binary would vanish."""
account = agent_accounts.create_account("claude", "Second seat")
- env = agent_accounts.spawn_env(
- "claude", account.id, base={"PATH": "/usr/bin", "TERM": "xterm"}
- )
+ env = agent_accounts.spawn_env("claude", account.id, base={"PATH": "/usr/bin", "TERM": "xterm"})
assert env["PATH"] == "/usr/bin"
assert env["TERM"] == "xterm"
assert env["CLAUDE_CONFIG_DIR"] == str(account.config_dir)
@@ -634,7 +662,7 @@ def test_two_genuinely_different_subscriptions_are_never_flagged() -> None:
def test_accounts_without_a_readable_email_are_never_grouped() -> None:
- """"Both unknown" is not evidence of sameness — it is absence of evidence."""
+ """ "Both unknown" is not evidence of sameness — it is absence of evidence."""
first = agent_accounts.create_account("claude", "Seat A")
second = agent_accounts.create_account("claude", "Seat B")
for account in (first, second):
diff --git a/tests/unit/test_grok_build_auth.py b/tests/unit/test_grok_build_auth.py
index 1021f026db..ecd05b09ff 100644
--- a/tests/unit/test_grok_build_auth.py
+++ b/tests/unit/test_grok_build_auth.py
@@ -1,9 +1,12 @@
"""Grok Build auth service — status / login parsing, isolated worker home."""
+
from __future__ import annotations
import json
from pathlib import Path
+import pytest
+
from jarvis.grok_build_auth import (
GrokBuildAuthService,
GrokBuildAuthStatus,
@@ -15,11 +18,103 @@ from jarvis.grok_build_auth import (
prepare_worker_home,
)
+_CLI_SCOPE = "https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"
-def test_derive_auth_subscription_tokens() -> None:
- connected, mode = _derive_auth(
- {"tokens": {"access_token": "tok", "refresh_token": "ref"}}
+
[email protected](autouse=True)
+def isolated_auth_scope(monkeypatch):
+ for prefix in ("GROK_OIDC", "GROK_OAUTH2"):
+ for suffix in ("ISSUER", "CLIENT_ID"):
+ monkeypatch.delenv(f"{prefix}_{suffix}", raising=False)
+
+
+def test_current_cli_store_connects_cards_and_agent_picker(monkeypatch, tmp_path):
+ from jarvis.ui.web.agent_chat_routes import _cli_subscription_connected
+
+ (tmp_path / "auth.json").write_text(
+ json.dumps(
+ {
+ _CLI_SCOPE: {
+ "key": "test-bearer",
+ "auth_mode": "oidc",
+ "refresh_token": "test-refresh",
+ "email": "[email protected]",
+ },
+ "https://other.example::client": {
+ "key": "other",
+ "auth_mode": "oidc",
+ "email": "[email protected]",
+ },
+ }
+ ),
+ encoding="utf-8",
)
+ service = GrokBuildAuthService(grok_home_dir=tmp_path)
+ monkeypatch.setattr(service, "_resolve_binary", lambda: "grok")
+ monkeypatch.setattr(service, "_probe_version", lambda _: "grok 1.0.13")
+ status = service.status()
+ assert grok_build_provider_ready(status)
+ assert _cli_subscription_connected("grok-cli", status)
+ assert status.user_email == "[email protected]"
+ assert "test-bearer" not in json.dumps(status.to_dict())
+ assert "test-refresh" not in json.dumps(status.to_dict())
+
+
+ "record",
+ [
+ {},
+ None,
+ "invalid",
+ {"email": "[email protected]"},
+ {"auth_mode": "oidc", "key": " "},
+ {"auth_mode": "external", "key": "test-key", "refresh_token": "test-refresh"},
+ {"auth_mode": "web_login", "key": "test-key"},
+ ],
+)
+def test_scoped_invalid_or_unsupported_login_is_disconnected(record):
+ assert _derive_auth({_CLI_SCOPE: record}) == (False, "unknown")
+
+
+def test_scoped_api_key_is_never_a_subscription():
+ assert _derive_auth(
+ {
+ "xai::api_key": {
+ "key": "test-api-key",
+ "auth_mode": "api_key",
+ "refresh_token": "test-refresh",
+ }
+ }
+ ) == (True, "api_key")
+
+
+def test_cli_scope_does_not_borrow_another_login(monkeypatch):
+ auth = {_CLI_SCOPE: {"key": "test-bearer", "auth_mode": "oidc"}}
+ monkeypatch.setenv("GROK_OIDC_ISSUER", "https://tenant.example/")
+ monkeypatch.setenv("GROK_OIDC_CLIENT_ID", "test-client")
+ assert _derive_auth(auth) == (False, "unknown")
+ auth["https://tenant.example::test-client"] = {
+ "key": "tenant-test-bearer",
+ "auth_mode": "oidc",
+ "email": "[email protected]",
+ }
+ assert _derive_auth(auth) == (True, "subscription")
+ assert _email_from_auth(auth) == "[email protected]"
+
+
+def test_scoped_refreshable_login_is_recognized():
+ assert _derive_auth(
+ {
+ _CLI_SCOPE: {
+ "auth_mode": "oidc",
+ "refresh_token": "test-refresh",
+ }
+ }
+ ) == (True, "subscription")
+
+
+def test_derive_auth_subscription_tokens() -> None:
+ connected, mode = _derive_auth({"tokens": {"access_token": "tok", "refresh_token": "ref"}})
assert connected is True
assert mode == "subscription"