Skip to content

The agent that grows with you

fix(auth): keep a refreshed account's tokens beside a guest in the shared store

Siddharth Balyancb757fac59c9
diff --git a/hermes_cli/anon_auth.py b/hermes_cli/anon_auth.py
index 195fb54f838..aee02ce2ae6 100644
--- a/hermes_cli/anon_auth.py
+++ b/hermes_cli/anon_auth.py
@@ -629,7 +629,8 @@ def _reconcile_and_provision(*, timeout_seconds: float, force: bool = False,
_auth_store_lock, _load_auth_store, _load_provider_state, _save_auth_store,
_store_provider_state, _resolve_verify)
from hermes_cli.auth_nous import (
- _nous_http_client, _nous_shared_store_lock, _read_shared_nous_state, _write_shared_nous_state)
+ _SHARED_RENEWAL_KEY, _nous_http_client, _nous_shared_store_lock, _read_shared_nous_state,
+ _write_shared_nous_state)
portal = _portal_base_url()
with _auth_store_lock():
auth_store = _load_auth_store()
@@ -637,7 +638,7 @@ def _reconcile_and_provision(*, timeout_seconds: float, force: bool = False,
with _nous_shared_store_lock(timeout_seconds=max(timeout_seconds, 5.0)):
shared = _read_shared_nous_state()
if shared and _shared_identity_key(shared) != _shared_identity_key(profile_state):
- state = dict(shared)
+ state = {k: v for k, v in shared.items() if k != _SHARED_RENEWAL_KEY} # another account's tokens
_store_provider_state(auth_store, "nous", state, set_active=not is_guest_state(state))
_save_auth_store(auth_store)
logger.debug("Nous identity adopted from the shared store")
diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.py
index 500ae1ec5ea..aeba8d6d0c2 100644
--- a/hermes_cli/auth_nous.py
+++ b/hermes_cli/auth_nous.py
@@ -410,12 +410,17 @@ _NOUS_SHARED_STATE_KEYS = (
"inference_base_url", "obtained_at", "expires_at",
# Guest (``auth_method: anonymous``) identity: the ``anon_`` credential is the refresh material.
"auth_method", "account_tier", "anon_token", "user_id", "org_id")
+# Shared-store key: an account's latest refresh, kept beside a different identity the store holds.
+_SHARED_RENEWAL_KEY = "renewal"
def _merge_shared_nous_oauth_state(state: dict[str, Any]) -> bool:
"""Copy fresher shared OAuth tokens into a profile-local Nous state."""
from hermes_cli.auth import _nonempty_str, _parse_iso_timestamp, _read_shared_nous_state
shared = _read_shared_nous_state() or {}
+ renewed = shared.get(_SHARED_RENEWAL_KEY)
+ if isinstance(renewed, dict) and _nous_identity(renewed) == _nous_identity(state):
+ shared = renewed
shared_refresh = shared.get("refresh_token")
if not _nonempty_str(shared_refresh):
return False # a free-tier identity has no refresh token; nothing to merge into an OAuth state
@@ -461,9 +466,10 @@ def _nous_identity(state: dict[str, Any]) -> tuple[str, Any]:
def _write_shared_nous_state(state: dict[str, Any], *, renewal: bool) -> None:
"""Persist a minimal copy of the Nous OAuth state to the shared store.
- A *renewal* (a token refresh) never replaces another identity the store holds: only a sign-in
- (or a mint) does, so only a sign-in can replace a guest there. An empty store takes a renewal,
- so profiles sharing one account keep their rotated refresh token in step.
+ The store holds one identity, which profiles adopt or import. Only a sign-in (or a mint) changes
+ it, so only a sign-in can replace a guest there. A *renewal* (a token refresh) of another
+ identity is kept beside it under ``renewal``: siblings on that account read their next
+ single-use refresh token from there (``_merge_shared_nous_oauth_state``).
Best-effort: failures are logged and swallowed; per-profile auth.json stays the source of truth.
"""
from hermes_cli.auth import _nonempty_str, _save_private_json
@@ -480,9 +486,13 @@ def _write_shared_nous_state(state: dict[str, Any], *, renewal: bool) -> None:
with _nous_shared_store_lock():
path = _nous_shared_store_path()
held = _read_shared_nous_state()
- if renewal and held is not None and _nous_identity(held) != _nous_identity(state):
- return
- note_replacement(held, state)
+ same = held is not None and _nous_identity(held) == _nous_identity(state)
+ if renewal and held is not None and not same:
+ shared = {**held, _SHARED_RENEWAL_KEY: _nous_shared_shape(state)}
+ else:
+ note_replacement(held, state)
+ if same and _SHARED_RENEWAL_KEY in held:
+ shared[_SHARED_RENEWAL_KEY] = held[_SHARED_RENEWAL_KEY]
_save_private_json(path, shared, sort_keys=True)
_oauth_trace(
"nous_shared_store_written", path=str(path),
diff --git a/tests/hermes_cli/test_guest_handoff_refresh.py b/tests/hermes_cli/test_guest_handoff_refresh.py
index 996b7d4a797..64eb17c948c 100644
--- a/tests/hermes_cli/test_guest_handoff_refresh.py
+++ b/tests/hermes_cli/test_guest_handoff_refresh.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import os
from types import SimpleNamespace
+import httpx
import pytest
from tests.hermes_cli import test_guest_handoff as _gh
@@ -104,3 +105,41 @@ def test_a_keepalive_refresh_does_not_sign_a_logged_out_profile_back_in(portal,
state = anon_auth.ensure_portal_identity(explicit=True)
assert anon_auth.is_guest_state(state) and state["anon_token"] == anon
assert _gh._records() == {} and portal.claims == []
+
+
+def test_profiles_sharing_an_account_stay_in_step_while_the_store_holds_a_guest(portal, monkeypatch, tmp_path):
+ """Refresh tokens are single use: a profile that refreshes with one a sibling already spent is
+ signed out. Siblings on one account learn each rotated token through the shared store."""
+ from hermes_cli import anon_auth, auth
+ spent, answer = set(), portal.handler
+
+ def single_use_refresh(request):
+ if request.url.path == "/api/oauth/token":
+ token = request.headers.get("x-nous-refresh-token")
+ if token in spent:
+ return httpx.Response(400, json={"error": "refresh_token_reused"})
+ spent.add(token)
+ return answer(request)
+
+ portal.handler = single_use_refresh
+ first, second, third = os.environ["HERMES_HOME"], tmp_path / "second-profile", tmp_path / "third-profile"
+ _gh._persist(_gh._account())
+ for home in (second, third):
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ assert anon_auth.ensure_portal_identity(explicit=True)["refresh_token"] == "rt_1" # adopts the account
+
+ monkeypatch.setenv("HERMES_HOME", first)
+ auth.logout_command(SimpleNamespace(provider="nous"))
+ anon = _gh._mint_guest()
+ for home in (second, first, third): # the guest's own token refresh sits between the two
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ _refresh_access_token()
+
+ assert auth.get_provider_auth_state("nous")["refresh_token"] == "rt_3"
+ assert _shared_anon_token() == anon and _gh._records() == {}
+ fourth = tmp_path / "fourth-profile"
+ fourth.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(fourth))
+ adopted = anon_auth.ensure_portal_identity(explicit=True)
+ assert adopted["anon_token"] == anon and "renewal" not in adopted
diff --git a/website/docs/developer-guide/cli-internals.md b/website/docs/developer-guide/cli-internals.md
index b389f399d84..e3bfe64c37a 100644
--- a/website/docs/developer-guide/cli-internals.md
+++ b/website/docs/developer-guide/cli-internals.md
@@ -167,8 +167,9 @@ call it:
- Only a sign-in changes which identity the shared store holds. Every `_write_shared_nous_state`
caller declares `renewal`: a token refresh (`renewal=True`) never replaces another identity there
(identity = the guest's `anon_` credential, or the account's JWT `sub`), so a refresh of one
- profile's account never replaces a guest another profile minted. An empty store still takes a
- refresh, which keeps profiles that share one account's rotating refresh token in step.
+ profile's account never replaces a guest another profile minted. That refresh is kept beside the
+ held identity under `renewal`, where sibling profiles on the same account read their next
+ single-use refresh token.
- `drain` runs the claim outside every lock, bounded to about 10 s (each record, lock wait, token
read and request counts against the budget): after a shared-store write, when a
`guest_handoff.deferred()` block exits (a surface that saves under its own lock, such as the desktop