From cf82474e076a4137b874a709327c963ad00af104 Mon Sep 17 00:00:00 2001 From: Nicole Rappe Date: Sat, 18 Oct 2025 02:00:36 -0600 Subject: [PATCH] Improve refresh token DPAPI fallback and add reload logging --- Data/Agent/agent.py | 11 +++++++++++ Data/Agent/security.py | 21 ++++++++++++++------- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/Data/Agent/agent.py b/Data/Agent/agent.py index 718ca2d..8caf4d6 100644 --- a/Data/Agent/agent.py +++ b/Data/Agent/agent.py @@ -684,6 +684,17 @@ class AgentHttpClient: self.session.headers.update({"Authorization": f"Bearer {self.access_token}"}) else: self.session.headers.pop("Authorization", None) + try: + _log_agent( + "Reloaded tokens from disk " + f"guid={'yes' if self.guid else 'no'} " + f"access={'yes' if self.access_token else 'no'} " + f"refresh={'yes' if self.refresh_token else 'no'} " + f"expiry={self.access_expires_at}", + fname="agent.log", + ) + except Exception: + pass def auth_headers(self) -> Dict[str, str]: if self.access_token: diff --git a/Data/Agent/security.py b/Data/Agent/security.py index 663dafb..44bb577 100644 --- a/Data/Agent/security.py +++ b/Data/Agent/security.py @@ -227,16 +227,23 @@ class AgentKeyStore: try: with open(self._refresh_token_path, "rb") as fh: protected = fh.read() - raw = _unprotect(protected, scope_system=self.scope_system) - try: - return raw.decode("utf-8") - except Exception: - # Token may have been protected under the opposite DPAPI scope. - alt = _unprotect(protected, scope_system=not self.scope_system) - return alt.decode("utf-8") except Exception: return None + # Try both scopes (preferred first) and decode once a UTF-8 payload is recovered. + for scope_first in (self.scope_system, not self.scope_system): + try: + candidate = _unprotect(protected, scope_system=scope_first) + except Exception: + continue + if not candidate: + continue + try: + return candidate.decode("utf-8") + except Exception: + continue + return None + def clear_tokens(self) -> None: for path in (self._access_token_path, self._refresh_token_path, self._token_meta_path): try: