#!/usr/bin/env python3 """ auth_refresh.py — Cron-friendly check and maintenance for NotebookLM auth. This script runs on a cron schedule to: 1. Call check_auth(live=True) to verify the current session is active. 2. If authenticated → run rotate_google_cookies() to refresh *PSIDTS tokens (maintenance). 3. If unauthenticated → attempt automated revive using Chrome headless profile. 4. If revive fails → log failure and exit (requires user interactive action). """ import os import sys import logging from datetime import datetime # Add project to path PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..') sys.path.insert(0, os.path.join(PROJECT_ROOT, 'integrations', 'notebooklm-mcp-cli', 'src')) from notebooklm_tools.core.auth import check_auth, get_auth_manager from notebooklm_tools.core.cookie_rotation import rotate_google_cookies # Configure logging LOG_FILE = "/var/log/notebooklm-auth.log" logging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', handlers=[ logging.FileHandler(LOG_FILE), logging.StreamHandler(sys.stdout) ] ) logger = logging.getLogger("auth_refresh") def main(): logger.info("=== Starting auth check and refresh job ===") profile_name = "default" # 1. Perform live auth check logger.info("Performing live authentication check...") res = check_auth(profile=profile_name, live=True, timeout=15) if res.valid: logger.info(f"✓ Authentication is VALID (Profile: {res.profile})") # 2. Proactive rotation of short-lived Google session cookies logger.info("Running proactive cookie rotation...") try: # We initialize a client to get the cookie jar from notebooklm_tools.core.client import NotebookLMClient manager = get_auth_manager(profile_name) p = manager.load_profile() client = NotebookLMClient( cookies=p.cookies, csrf_token=p.csrf_token or "", session_id=p.session_id or "", build_label=p.build_label or "", ) # Perform RotateCookies POST rot = rotate_google_cookies(client._client, force=True) if rot.success: logger.info("✓ Cookie rotation completed successfully!") # Save rotated cookies back to profile from notebooklm_tools.core.cookie_rotation import snapshot_cookie_input updated_cookies = snapshot_cookie_input(p.cookies, client._client.cookies) manager.save_profile( cookies=updated_cookies, csrf_token=client.csrf_token or p.csrf_token, session_id=client._session_id or p.session_id, build_label=client._bl or p.build_label, force=True ) logger.info("Rotated cookies saved to disk profile.") else: logger.warning(f"Cookie rotation skipped/failed: {rot.skipped_reason or rot.error}") client.close() except Exception as exc: logger.error(f"Failed during proactive cookie rotation: {exc}") logger.info("Job completed OK.") sys.exit(0) else: logger.warning(f"✗ Authentication is INVALID! Reason: {res.reason}") logger.info(f"Details: {res.details}") # 3. Attempt automated revive logger.info("Attempting automated auth recovery via Chrome headless revive...") import subprocess script_dir = os.path.dirname(os.path.abspath(__file__)) revive_script = os.path.join(script_dir, "revive_notebooklm_auth.sh") try: result = subprocess.run( [revive_script], capture_output=True, text=True, check=False ) logger.info("Revive stdout:\n" + result.stdout) if result.stderr: logger.error("Revive stderr:\n" + result.stderr) if result.returncode == 0: logger.info("✓ Automated auth recovery completed successfully!") sys.exit(0) else: logger.error("✗ Automated recovery failed! Manual login intervention required.") sys.exit(1) except Exception as e: logger.error(f"Failed to execute revive script: {e}") sys.exit(1) if __name__ == "__main__": main()