Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /api /routes /auth_bridge.py
| """ | |
| 🔐 Auth Bridge - Verbindet lokale Kimi CLI mit Web Interface | |
| Nutzt den lokalen Kimi Token für Web-Auth | |
| """ | |
| import json | |
| import logging | |
| import os | |
| from pathlib import Path | |
| from fastapi import APIRouter, Depends, HTTPException | |
| from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer | |
| from pydantic import BaseModel | |
| # Import proper JWT auth | |
| from api.auth_simple import verify_token | |
| # Try to use the new kimi-auth-bridge module | |
| try: | |
| from kimi_auth_bridge import KimiAuthBridge | |
| KIMI_AUTH_BRIDGE_AVAILABLE = True | |
| except ImportError: | |
| KIMI_AUTH_BRIDGE_AVAILABLE = False | |
| logger = logging.getLogger(__name__) | |
| router = APIRouter(prefix="/auth-bridge", tags=["Auth Bridge"]) | |
| security = HTTPBearer(auto_error=False) | |
| class KimiLocalAuth(BaseModel): | |
| """Auth via lokale Kimi CLI""" | |
| device_token: str = None # Optional - wird automatisch gelesen | |
| def get_local_kimi_token() -> str: | |
| """Lese lokalen Kimi Token von Server""" | |
| try: | |
| # Versuche Kimi credentials zu lesen | |
| home = Path.home() | |
| # Erweiterte Pfad-Suche für verschiedene Kimi CLI Versionen | |
| credential_paths = [ | |
| # Kimi CLI (Code) - aktueller Standard | |
| home / ".kimi" / "credentials" / "kimi-code.json", | |
| # Standard Linux/macOS | |
| home / ".config/kimi/credentials.json", | |
| home / ".kimi/credentials.json", | |
| # macOS Application Support | |
| home / "Library/Application Support/kimi/credentials.json", | |
| home / "Library/Preferences/kimi/credentials.json", | |
| # Linux alternative | |
| home / ".local/share/kimi/credentials.json", | |
| # Windows | |
| Path(os.environ.get("APPDATA", "")) / "kimi" / "credentials.json", | |
| Path(os.environ.get("LOCALAPPDATA", "")) / "kimi" / "credentials.json", | |
| Path(os.environ.get("APPDATA", "")) / "kimi" / "credentials" / "kimi-code.json", | |
| # Session-basiert (neuere Kimi CLI) | |
| home / ".kimi" / "sessions" / "credentials.json", | |
| ] | |
| for cred_path in credential_paths: | |
| if cred_path.exists(): | |
| try: | |
| with open(cred_path, "r") as f: | |
| data = json.load(f) | |
| # Versuche verschiedene Token-Formate | |
| token = data.get("access_token") or data.get("token") or data.get("api_key") or data.get("key") | |
| if token and len(token) > 10: | |
| logger.info(f"Token found in: {cred_path}") | |
| return token | |
| except Exception as e: | |
| logger.warning(f"Could not read {cred_path}: {e}") | |
| continue | |
| # Alternative: Environment Variable | |
| env_token = os.getenv("KIMI_ACCESS_TOKEN") or os.getenv("KIMI_API_KEY") | |
| if env_token: | |
| logger.info("Token from environment variable") | |
| return env_token | |
| logger.info("No token found in standard paths") | |
| return None | |
| except Exception as e: | |
| logger.error(f"Could not read local token: {e}") | |
| return None | |
| def verify_kimi_token_local(token: str) -> bool: | |
| """Verifiziere Kimi Token via CLI oder direkt""" | |
| import shutil | |
| import subprocess | |
| # Get CLI paths | |
| kimi_path = shutil.which("kimi") | |
| kimicli_path = shutil.which("kimicli") | |
| # Methode 1: Versuche kimi status | |
| if kimi_path: | |
| try: | |
| result = subprocess.run( | |
| [kimi_path, "status"], | |
| capture_output=True, | |
| text=True, | |
| timeout=10, | |
| env={**os.environ, "KIMI_ACCESS_TOKEN": token}, | |
| ) | |
| if result.returncode == 0: | |
| output_lower = result.stdout.lower() | |
| if any(x in output_lower for x in ["authenticated", "logged in", "✓", "valid", "ready"]): | |
| logger.info("Token verified via 'kimi status'") | |
| return True | |
| except Exception as e: | |
| logger.warning(f"'kimi status' failed: {e}") | |
| else: | |
| logger.info("'kimi' command not found") | |
| # Methode 2: Versuche kimicli (ältere Version) | |
| if kimicli_path: | |
| try: | |
| result = subprocess.run( | |
| [kimicli_path, "status"], | |
| capture_output=True, | |
| text=True, | |
| timeout=10, | |
| env={**os.environ, "KIMI_ACCESS_TOKEN": token}, | |
| ) | |
| if result.returncode == 0: | |
| logger.info("Token verified via 'kimicli status'") | |
| return True | |
| except Exception: | |
| pass | |
| # Methode 3: Token-Format prüfen (Fallback für Entwicklung) | |
| # Wenn Token vorhanden und aussieht wie ein gültiger Kimi Token, akzeptieren | |
| if token and len(token) > 30: | |
| # Kimi Tokens sind typischerweise JWTs oder lange Strings | |
| logger.info("Token accepted (format check, no CLI verification)") | |
| return True | |
| return False | |
| async def local_kimi_auth_status( | |
| credentials: HTTPAuthorizationCredentials = Depends(security), | |
| ): | |
| """ | |
| Prüfe ob lokale Kimi CLI authentifiziert ist | |
| 🔒 AUTH REQUIRED - Gibt KEIN Token zurück (nur Status) | |
| """ | |
| # SECURITY: Require valid JWT before revealing any token status | |
| verify_token(credentials) | |
| token = get_local_kimi_token() | |
| if not token: | |
| return { | |
| "authenticated": False, | |
| "message": "Keine lokale Kimi CLI gefunden oder nicht eingeloggt", | |
| "method": "Lokale CLI nicht verfügbar", | |
| "checked_paths": [ | |
| "~/.config/kimi/credentials.json", | |
| "~/.kimi/credentials.json", | |
| "~/Library/Application Support/kimi/credentials.json", | |
| "KIMI_ACCESS_TOKEN env", | |
| ], | |
| } | |
| # Verifiziere Token | |
| is_valid = verify_kimi_token_local(token) | |
| if is_valid: | |
| # SECURITY: Never return the real token. Only a masked preview. | |
| token_preview = f"{token[:4]}...{token[-4:]}" | |
| return { | |
| "authenticated": True, | |
| "token_preview": token_preview, | |
| "method": "local_kimi_cli", | |
| "message": "✅ Lokale Kimi CLI ist authentifiziert!", | |
| } | |
| else: | |
| return { | |
| "authenticated": False, | |
| "message": "Lokaler Token ungültig oder abgelaufen", | |
| "method": "local_kimi_cli", | |
| "token_found": True, | |
| "token_length": len(token), | |
| } | |
| async def auto_login_with_local_kimi( | |
| credentials: HTTPAuthorizationCredentials = Depends(security), | |
| ): | |
| """ | |
| Automatischer Login via lokale Kimi CLI | |
| 🔒 AUTH REQUIRED - Returns Kimi token ONLY to authenticated users | |
| """ | |
| # SECURITY: Require valid JWT before disclosing Kimi access token | |
| verify_token(credentials) | |
| token = get_local_kimi_token() | |
| if not token: | |
| raise HTTPException( | |
| status_code=401, | |
| detail="Keine lokale Kimi CLI gefunden. Bitte manuell einloggen.", | |
| ) | |
| # Verifiziere | |
| if not verify_kimi_token_local(token): | |
| raise HTTPException( | |
| status_code=401, | |
| detail="Lokaler Kimi Token ungültig. Bitte 'kimi login' ausführen.", | |
| ) | |
| # SECURITY: Only return the Kimi token to authenticated users. | |
| # Create a separate session token for web auth instead of exposing Kimi token directly. | |
| from api.auth_simple import create_access_token | |
| session_token = create_access_token({"sub": "admin", "role": "admin"}) | |
| return { | |
| "access_token": session_token, # Own JWT session token, NOT the Kimi token | |
| "kimi_token_available": True, | |
| "token_type": "bearer", | |
| "expires_in": 3600, | |
| "method": "local_kimi_auto", | |
| "message": "✅ Automatisch via lokaler Kimi CLI eingeloggt!", | |
| } | |
| async def bridge_check(): | |
| """Überprüfe Auth Bridge Status""" | |
| # Try new kimi-auth-bridge module first | |
| if KIMI_AUTH_BRIDGE_AVAILABLE: | |
| try: | |
| bridge = KimiAuthBridge() | |
| is_auth = bridge.is_authenticated() | |
| return { | |
| "bridge_available": True, | |
| "local_kimi_installed": is_auth, | |
| "can_auto_login": is_auth, | |
| "token_found": is_auth, | |
| "token_valid": is_auth, | |
| "home_dir": str(Path.home()), | |
| "module": "kimi_auth_bridge", | |
| "api_base": bridge.get_api_base() if is_auth else None, | |
| "model": bridge.get_default_model() if is_auth else None, | |
| "message": ( | |
| "✅ Auth Bridge bereit - Auto-Login möglich!" | |
| if is_auth | |
| else "⚠️ Keine lokale Kimi CLI gefunden oder Token ungültig" | |
| ), | |
| } | |
| except Exception: | |
| pass | |
| # Fallback to legacy method | |
| token = get_local_kimi_token() | |
| is_valid = verify_kimi_token_local(token) if token else False | |
| return { | |
| "bridge_available": token is not None, | |
| "local_kimi_installed": token is not None, | |
| "can_auto_login": is_valid, | |
| "token_found": token is not None, | |
| "token_valid": is_valid, | |
| "home_dir": str(Path.home()), | |
| "message": ( | |
| "✅ Auth Bridge bereit - Auto-Login möglich!" | |
| if is_valid | |
| else "⚠️ Keine lokale Kimi CLI gefunden oder Token ungültig" | |
| ), | |
| } | |
Xet Storage Details
- Size:
- 9.59 kB
- Xet hash:
- 9aed9aab92dbd6ecb02d5f42886bf16abc5ea8d874633068063ba4ddc85d166e
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.