From b55a919d3ded864a8d6767f53fd50136c0fa6087 Mon Sep 17 00:00:00 2001 From: Astra Logical Date: Thu, 23 Jul 2026 12:04:10 -0400 Subject: [PATCH] Fix stale keys --- matrix_keycloak_bot.py | 38 +++++++------------------------------- 1 file changed, 7 insertions(+), 31 deletions(-) diff --git a/matrix_keycloak_bot.py b/matrix_keycloak_bot.py index ac66234..a37f565 100644 --- a/matrix_keycloak_bot.py +++ b/matrix_keycloak_bot.py @@ -30,8 +30,6 @@ KEYCLOAK_REALM = os.getenv("KEYCLOAK_REALM", "master") KEYCLOAK_CLIENT_ID = os.getenv("KEYCLOAK_CLIENT_ID", "nest-matrix-bot") KEYCLOAK_CLIENT_SECRET = os.getenv("KEYCLOAK_CLIENT_SECRET", "your-client-secret") -CREDENTIALS_FILE = "/app/store/credentials.json" - # In-memory tracking of active requests (Event ID -> Request Info) pending_requests = {} @@ -147,7 +145,7 @@ def get_requestable_groups(username: str) -> tuple[bool, str]: except KeycloakError as e: return False, f"Keycloak API error: {str(e)}" except Exception as e: - return False, f"Unexpected error: {str(e)}" + return False, f"⚠️ Unexpected error: {str(e)}" # ------------------------------------------------------------------------------ @@ -322,34 +320,7 @@ async def main(): # 1. Initialize client client = Client(base_url=MATRIX_HOMESERVER, mxid=MATRIX_BOT_USER) - # 2. Session Persistence - session_restored = False - if os.path.exists(CREDENTIALS_FILE): - log.info("Restoring existing Matrix session...") - try: - with open(CREDENTIALS_FILE, "r") as f: - creds = json.load(f) - client.api.token = creds["access_token"] - client.mxid = creds["user_id"] - client.device_id = creds["device_id"] - session_restored = True - except (json.JSONDecodeError, KeyError) as e: - log.warning(f"Corrupted credentials file ({e}). Forcing new login...") - - if not session_restored: - log.info(f"Logging in to {MATRIX_HOMESERVER}...") - resp = await client.login(password=MATRIX_BOT_PASSWORD, device_name="KEYCLOAK_ACCESS_BOT") - - os.makedirs(os.path.dirname(CREDENTIALS_FILE), exist_ok=True) - with open(CREDENTIALS_FILE, "w") as f: - json.dump({ - "access_token": client.api.token, - "user_id": client.mxid, - "device_id": client.device_id, - }, f) - log.info("Logged in and saved credentials.") - - # 3. Attach Custom Memory Crypto & State Stores + # 2. Attach Custom Memory Crypto & State Stores first so keys align with login state_store = CustomMemoryStateStore(client.mxid) client.state_store = state_store @@ -358,6 +329,11 @@ async def main(): await machine.load() client.crypto = machine + # 3. Perform Fresh Login on Startup (Syncs device ID and crypto keys correctly) + log.info(f"Logging in to {MATRIX_HOMESERVER}...") + await client.login(password=MATRIX_BOT_PASSWORD, device_name="KEYCLOAK_ACCESS_BOT") + log.info("Successfully logged in with fresh device session.") + # 4. Register Event Handlers client.add_event_handler(EventType.ROOM_MEMBER, on_invite) client.add_event_handler(EventType.ROOM_MESSAGE, on_message)