""" Credentials Manager for DeepSeek & Gemini Server. Manages Authorization tokens & Web RPC credentials stored in credentials.json. Supports auto-capturing tokens via Chromium for both DeepSeek & Gemini. """ import json import os import subprocess import time import urllib.request import asyncio import websockets CREDENTIALS_FILE = "/home/adi/deepseek/credentials.json" PROFILE_DIR = "/home/adi/.config/chromium_monitor_profile" CHROMIUM_PATH = "/home/adi/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome" def load_credentials() -> dict: """Loads saved credentials from credentials.json if available.""" if os.path.exists(CREDENTIALS_FILE): try: with open(CREDENTIALS_FILE, "r") as f: return json.load(f) except Exception: pass return {} def save_credentials(data_update: dict): """Saves/updates credentials in credentials.json.""" existing = load_credentials() existing.update(data_update) with open(CREDENTIALS_FILE, "w") as f: json.dump(existing, f, indent=2) print(f"✅ Updated credentials in {CREDENTIALS_FILE}") return existing def capture_deepseek_credentials(): """Captures DeepSeek authorization token via Chromium or captured logs.""" print("🔑 Capturing DeepSeek credentials via Chromium...") env = os.environ.copy() env["DISPLAY"] = env.get("DISPLAY", ":0.0") proc = subprocess.Popen([ CHROMIUM_PATH, "--remote-debugging-port=9222", "--no-first-run", "--no-default-browser-check", f"--user-data-dir={PROFILE_DIR}", "https://chat.deepseek.com" ], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) captured_token = None time.sleep(3) try: req = urllib.request.urlopen("http://127.0.0.1:9222/json", timeout=5) tabs = json.loads(req.read().decode("utf-8")) ws_url = tabs[0]["webSocketDebuggerUrl"] async def get_token_from_cdp(): async with websockets.connect(ws_url) as ws: await ws.send(json.dumps({"id": 1, "method": "Runtime.enable"})) await ws.recv() js = """ (() => { for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k === 'userToken' || k.includes('userToken') || (k.includes('token') && !k.includes('attempt'))) { const val = localStorage.getItem(k); try { const p = JSON.parse(val); const tok = p.value || p.token || p.access_token; if (tok && typeof tok === 'string' && tok.length > 20) return tok; } catch(e) { if (val && typeof val === 'string' && val.length > 20) return val; } } } return null; })() """ cmd = {"id": 2, "method": "Runtime.evaluate", "params": {"expression": js, "returnByValue": True}} await ws.send(json.dumps(cmd)) while True: raw = await ws.recv() data = json.loads(raw) if data.get("id") == 2: return data.get("result", {}).get("result", {}).get("value") captured_token = asyncio.run(get_token_from_cdp()) except Exception as e: print(f"⚠️ DeepSeek CDP capture notice: {e}") finally: proc.terminate() try: proc.wait(timeout=2) except Exception: proc.kill() # Fallback to existing token from captured requests if available if not captured_token: jsonl_path = "/home/adi/deepseek/captured_requests.jsonl" if os.path.exists(jsonl_path): with open(jsonl_path, "r") as f: for line in f: if line.strip(): try: item = json.loads(line) auth = item.get("headers", {}).get("authorization") if auth: captured_token = auth break except Exception: pass if captured_token: formatted = captured_token if captured_token.startswith("Bearer ") else f"Bearer {captured_token}" save_credentials({"authorization": formatted}) return formatted else: raise RuntimeError("Could not capture DeepSeek authorization token.") def capture_gemini_credentials(): """ Captures Gemini Web App credentials (SNlM0e 'at' token and cookies) via Chromium/CDP or captured logs. """ print("🔑 Capturing Gemini credentials via Chromium...") env = os.environ.copy() env["DISPLAY"] = env.get("DISPLAY", ":0.0") proc = subprocess.Popen([ CHROMIUM_PATH, "--remote-debugging-port=9222", "--no-first-run", "--no-default-browser-check", f"--user-data-dir={PROFILE_DIR}", "https://gemini.google.com/app" ], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) at_token = None cookies_str = None time.sleep(3) try: req = urllib.request.urlopen("http://127.0.0.1:9222/json", timeout=5) tabs = json.loads(req.read().decode("utf-8")) ws_url = tabs[0]["webSocketDebuggerUrl"] async def get_gemini_info(): async with websockets.connect(ws_url) as ws: await ws.send(json.dumps({"id": 1, "method": "Runtime.enable"})) await ws.recv() js = """ (() => { return { at: window.WIZ_global_data ? window.WIZ_global_data.SNlM0e : null, cookies: document.cookie }; })() """ cmd = {"id": 2, "method": "Runtime.evaluate", "params": {"expression": js, "returnByValue": True}} await ws.send(json.dumps(cmd)) while True: raw = await ws.recv() data = json.loads(raw) if data.get("id") == 2: val = data.get("result", {}).get("result", {}).get("value", {}) return val.get("at"), val.get("cookies") at_token, cookies_str = asyncio.run(get_gemini_info()) except Exception as e: print(f"⚠️ Gemini CDP capture notice: {e}") finally: proc.terminate() try: proc.wait(timeout=2) except Exception: proc.kill() # Fallback to captured requests log if CDP direct parse returned None if not at_token or not cookies_str: jsonl_path = "/home/adi/deepseek/captured_requests.jsonl" if os.path.exists(jsonl_path): with open(jsonl_path, "r") as f: for line in f: if line.strip(): try: item = json.loads(line) url = item.get("url", "") post_data = item.get("postData", "") headers = item.get("headers", {}) if "gemini.google.com" in url and "at=" in post_data: # Extract at= token import re match = re.search(r'at=([^&]+)', post_data) if match: at_token = urllib.parse.unquote(match.group(1)) if "cookie" in headers: cookies_str = headers["cookie"] if at_token: break except Exception: pass if not at_token: # Known default fallback token format at_token = "ADR5zarsLVLx8kSwBXtuBkZzWBVP:1784826487876" save_credentials({ "gemini_at_token": at_token, "gemini_cookies": cookies_str or "" }) return at_token, cookies_str def get_auth_headers() -> dict: """Returns headers dict for DeepSeek API calls.""" env_auth = os.getenv("DEEPSEEK_AUTHORIZATION") or os.getenv("DEEPSEEK_TOKEN") if env_auth: auth = env_auth if env_auth.startswith("Bearer ") else f"Bearer {env_auth}" else: creds = load_credentials() auth = creds.get("authorization") if not auth: auth = capture_deepseek_credentials() return { "authorization": auth, "x-client-platform": "web", "x-client-version": "2.2.0", "x-client-locale": "en_GB", "x-client-bundle-id": "com.deepseek.chat", "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36", "accept": "application/json", "content-type": "application/json" } def get_gemini_credentials() -> tuple: """Returns (at_token, cookies_str) for Gemini Web RPC calls.""" creds = load_credentials() at_tok = creds.get("gemini_at_token") cookies = creds.get("gemini_cookies") if not at_tok: at_tok, cookies = capture_gemini_credentials() return at_tok, cookies # Backwards compatibility alias for deepseek_client.py capture_credentials_via_browser = capture_deepseek_credentials