Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /api /middleware /cloudflare_auth.py
| """ | |
| Cloudflare Tunnel + Kimi Device Authentication Middleware. | |
| Provides Zero-Trust access control for Zen-AI-Pentest Web UI | |
| when accessed through Cloudflare Tunnel. | |
| Features: | |
| - Kimi Device Auth via QR Code | |
| - JWT session management | |
| - Mobile-optimized login flow | |
| - Cloudflare headers validation | |
| """ | |
| import os | |
| import secrets | |
| import time | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Any, Dict, Optional | |
| import jwt | |
| from fastapi import Request | |
| from fastapi.responses import JSONResponse, RedirectResponse | |
| # Try to import Kimi Auth Bridge | |
| try: | |
| from kimi_auth_bridge import AsyncKimiAuthBridge | |
| KIMI_AVAILABLE = True | |
| except ImportError: | |
| KIMI_AVAILABLE = False | |
| class DeviceAuthManager: | |
| """ | |
| Manages device authentication flow for Cloudflare Tunnel access. | |
| Flow: | |
| 1. User accesses zen-ai.your-domain.com | |
| 2. Redirected to /auth/device if no valid session | |
| 3. QR code displayed (scanned with Kimi app) | |
| 4. Device authorized via Kimi CLI | |
| 5. JWT session created | |
| 6. Redirect to main app | |
| """ | |
| def __init__(self): # noqa: D107 # noqa: D107 | |
| self.jwt_secret = os.getenv("JWT_SECRET", secrets.token_hex(32)) # noqa | |
| self.jwt_algorithm = "HS256" | |
| self.session_duration = timedelta(hours=24) | |
| self.pending_devices: Dict[str, Dict] = {} # device_code -> auth_data | |
| self.kimi_bridge = None | |
| if KIMI_AVAILABLE: | |
| self.kimi_bridge = AsyncKimiAuthBridge() | |
| def generate_device_code(self) -> str: | |
| """Generate a user-friendly device code.""" | |
| # Format: XXXX-XXXX (easy to type on mobile) | |
| code = secrets.token_hex(4).upper() | |
| return f"{code[:4]}-{code[4:]}" | |
| def create_device_auth_request(self) -> Dict[str, str]: | |
| """ | |
| Create a new device authentication request. | |
| Returns: | |
| Dict with device_code, verification_uri, expires_in | |
| """ | |
| device_code = self.generate_device_code() | |
| auth_data = { | |
| "device_code": device_code, | |
| "user_code": device_code.replace("-", ""), | |
| "verification_uri": "/auth/device/verify", | |
| "expires_in": 600, # 10 minutes | |
| "created_at": time.time(), | |
| "status": "pending", # pending, authorized, expired | |
| "kimi_token": None, | |
| "user_info": None, | |
| } | |
| self.pending_devices[device_code] = auth_data | |
| return { | |
| "device_code": device_code, | |
| "user_code": auth_data["user_code"], | |
| "verification_uri": auth_data["verification_uri"], | |
| "expires_in": auth_data["expires_in"], | |
| } | |
| async def verify_kimi_auth(self, device_code: str) -> bool: | |
| """ | |
| Verify if Kimi authentication is complete. | |
| This checks if the device has been authorized via Kimi CLI | |
| on the local machine. | |
| """ | |
| if device_code not in self.pending_devices: | |
| return False | |
| auth_data = self.pending_devices[device_code] | |
| # Check expiration | |
| elapsed = time.time() - auth_data["created_at"] | |
| if elapsed > auth_data["expires_in"]: | |
| auth_data["status"] = "expired" | |
| return False | |
| # Check if already authorized | |
| if auth_data["status"] == "authorized": | |
| return True | |
| # Try to get Kimi token (indicates local auth) | |
| if self.kimi_bridge and KIMI_AVAILABLE: | |
| try: | |
| # If we can get a token, user is authenticated | |
| token = await self.kimi_bridge.get_access_token() | |
| if token: | |
| auth_data["status"] = "authorized" | |
| auth_data["kimi_token"] = token | |
| auth_data["user_info"] = await self._get_user_info(token) | |
| return True | |
| except Exception: | |
| pass | |
| return False | |
| async def _get_user_info(self, token: str) -> Dict[str, Any]: | |
| """Get user info from Kimi token.""" | |
| # In production, decode token or call Kimi API | |
| return { | |
| "authenticated": True, | |
| "token_preview": f"{token[:10]}..." if token else None, | |
| } | |
| def create_session(self, device_code: str) -> str: | |
| """ | |
| Create JWT session after successful device auth. | |
| Returns: | |
| JWT token string | |
| """ | |
| if device_code not in self.pending_devices: | |
| raise ValueError("Invalid device code") | |
| auth_data = self.pending_devices[device_code] | |
| if auth_data["status"] != "authorized": | |
| raise ValueError("Device not authorized") | |
| payload = { | |
| "sub": auth_data["user_code"], # Subject | |
| "iat": datetime.now(timezone.utc), # Issued at | |
| "exp": datetime.now(timezone.utc) + self.session_duration, | |
| "device_code": device_code, | |
| "auth_method": "kimi_device", | |
| "user_info": auth_data.get("user_info", {}), | |
| } | |
| token = jwt.encode(payload, self.jwt_secret, algorithm=self.jwt_algorithm) | |
| # Clean up pending device | |
| del self.pending_devices[device_code] | |
| return token | |
| def verify_session(self, token: str) -> Optional[Dict[str, Any]]: | |
| """Verify JWT session token.""" | |
| try: | |
| payload = jwt.decode(token, self.jwt_secret, algorithms=[self.jwt_algorithm]) | |
| return payload | |
| except jwt.ExpiredSignatureError: | |
| return None | |
| except jwt.InvalidTokenError: | |
| return None | |
| def get_qr_data(self, device_code: str, base_url: str) -> str: | |
| """ | |
| Generate QR code data for mobile scanning. | |
| Format: kimi://device-auth?code=XXXX&uri=https://... | |
| """ | |
| auth_data = self.pending_devices.get(device_code) | |
| if not auth_data: | |
| return "" | |
| # Kimi app deep link or web fallback | |
| verification_url = f"{base_url}{auth_data['verification_uri']}?code={device_code}" | |
| # QR code data format | |
| return f"kimi://device-auth?code={device_code}&uri={verification_url}" | |
| class CloudflareAuthMiddleware: | |
| """ | |
| Middleware for Cloudflare Tunnel + Kimi Device Auth. | |
| Validates requests and enforces authentication. | |
| """ | |
| def __init__(self): | |
| self.auth_manager = DeviceAuthManager() | |
| self.protected_paths = ["/", "/dashboard", "/api", "/scans"] | |
| self.public_paths = ["/auth", "/health", "/static"] | |
| async def __call__(self, request: Request, call_next): | |
| """Process request through auth middleware.""" | |
| path = request.url.path | |
| # Allow public paths | |
| if any(path.startswith(p) for p in self.public_paths): | |
| return await call_next(request) | |
| # Check for existing session | |
| session_token = request.cookies.get("zen_session") | |
| if session_token: | |
| session = self.auth_manager.verify_session(session_token) | |
| if session: | |
| # Valid session - attach user info and continue | |
| request.state.user = session.get("user_info", {}) | |
| request.state.authenticated = True | |
| return await call_next(request) | |
| # Cloudflare headers available: CF-RAY, CF-IPCountry | |
| # No valid session - require auth | |
| if path.startswith("/api/"): | |
| # API returns JSON error | |
| return JSONResponse( | |
| status_code=401, | |
| content={ | |
| "error": "authentication_required", | |
| "message": "Valid session required", | |
| "auth_url": "/auth/device", | |
| }, | |
| ) | |
| else: | |
| # Web UI redirects to auth page | |
| return RedirectResponse(url="/auth/device", status_code=302) | |
| # FastAPI route handlers for device auth | |
| def create_auth_routes(auth_manager: DeviceAuthManager): | |
| """Create FastAPI routes for device authentication.""" | |
| from fastapi import APIRouter, Request | |
| from fastapi.responses import HTMLResponse, JSONResponse | |
| router = APIRouter(prefix="/auth", tags=["authentication"]) | |
| async def device_auth_page(request: Request): | |
| """Render device authentication page with QR code.""" | |
| auth_request = auth_manager.create_device_auth_request() | |
| base_url = str(request.base_url).rstrip("/") | |
| qr_data = auth_manager.get_qr_data(auth_request["device_code"], base_url) | |
| # Return HTML page with QR code | |
| html_content = f""" | |
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>Zen-AI-Pentest - Device Auth</title> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"> | |
| <style> | |
| body {{ | |
| font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; | |
| background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); | |
| min-height: 100vh; | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| margin: 0; | |
| color: #e2e8f0; | |
| }} | |
| .container {{ | |
| background: rgba(30, 41, 59, 0.8); | |
| backdrop-filter: blur(10px); | |
| border-radius: 16px; | |
| padding: 2rem; | |
| max-width: 400px; | |
| width: 90%; | |
| box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5); | |
| border: 1px solid rgba(255, 255, 255, 0.1); | |
| }} | |
| h1 {{ | |
| text-align: center; | |
| margin-bottom: 0.5rem; | |
| font-size: 1.5rem; | |
| }} | |
| .subtitle {{ | |
| text-align: center; | |
| color: #94a3b8; | |
| margin-bottom: 2rem; | |
| font-size: 0.875rem; | |
| }} | |
| .qr-container {{ | |
| background: white; | |
| padding: 1rem; | |
| border-radius: 12px; | |
| display: flex; | |
| justify-content: center; | |
| margin-bottom: 1.5rem; | |
| }} | |
| .code-display {{ | |
| background: rgba(15, 23, 42, 0.8); | |
| border: 2px solid #3b82f6; | |
| border-radius: 8px; | |
| padding: 1rem; | |
| text-align: center; | |
| margin-bottom: 1.5rem; | |
| }} | |
| .code {{ | |
| font-family: 'Courier New', monospace; | |
| font-size: 2rem; | |
| font-weight: bold; | |
| color: #3b82f6; | |
| letter-spacing: 0.2em; | |
| }} | |
| .instructions {{ | |
| text-align: center; | |
| font-size: 0.875rem; | |
| color: #94a3b8; | |
| line-height: 1.5; | |
| }} | |
| .status {{ | |
| margin-top: 1rem; | |
| padding: 0.75rem; | |
| border-radius: 8px; | |
| text-align: center; | |
| font-size: 0.875rem; | |
| display: none; | |
| }} | |
| .status.pending {{ | |
| background: rgba(59, 130, 246, 0.2); | |
| color: #3b82f6; | |
| display: block; | |
| }} | |
| .status.success {{ | |
| background: rgba(34, 197, 94, 0.2); | |
| color: #22c55e; | |
| display: block; | |
| }} | |
| .status.error {{ | |
| background: rgba(239, 68, 68, 0.2); | |
| color: #ef4444; | |
| display: block; | |
| }} | |
| .icon {{ | |
| font-size: 3rem; | |
| text-align: center; | |
| margin-bottom: 1rem; | |
| }} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="icon">🌙</div> | |
| <h1>Zen-AI-Pentest</h1> | |
| <p class="subtitle">Secure Device Authentication</p> | |
| <div class="qr-container"> | |
| <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data={qr_data}" | |
| alt="Scan with Kimi App" width="200" height="200"> | |
| </div> | |
| <div class="code-display"> | |
| <div class="code">{auth_request["device_code"]}</div> | |
| </div> | |
| <p class="instructions"> | |
| 1. Open <strong>Kimi App</strong> on your device<br> | |
| 2. Scan QR code or enter code above<br> | |
| 3. Click "Authorize Device" | |
| </p> | |
| <div id="status" class="status pending"> | |
| Waiting for authorization... | |
| </div> | |
| </div> | |
| <script> | |
| const deviceCode = '{auth_request["device_code"]}'; | |
| // Poll for authorization status | |
| async function checkStatus() {{ | |
| try {{ | |
| const response = await fetch(`/auth/device/status?code=${{deviceCode}}`); | |
| const data = await response.json(); | |
| const statusEl = document.getElementById('status'); | |
| if (data.authorized) {{ | |
| statusEl.className = 'status success'; | |
| statusEl.textContent = 'Authorized! Redirecting...'; | |
| window.location.href = '/dashboard'; | |
| return; | |
| }} else if (data.expired) {{ | |
| statusEl.className = 'status error'; | |
| statusEl.textContent = 'Code expired. Please refresh.'; | |
| return; | |
| }} | |
| // Continue polling | |
| setTimeout(checkStatus, 2000); | |
| }} catch (err) {{ | |
| console.error('Status check failed:', err); | |
| setTimeout(checkStatus, 5000); | |
| }} | |
| }} | |
| checkStatus(); | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| return HTMLResponse(content=html_content) | |
| async def device_auth_status(code: str): | |
| """Check device authorization status.""" | |
| authorized = await auth_manager.verify_kimi_auth(code) | |
| auth_data = auth_manager.pending_devices.get(code, {}) | |
| expired = auth_data.get("status") == "expired" | |
| if authorized: | |
| # Create session | |
| session_token = auth_manager.create_session(code) | |
| response = JSONResponse( | |
| { | |
| "authorized": True, | |
| "message": "Device authorized successfully", | |
| } | |
| ) | |
| # Set session cookie | |
| response.set_cookie( | |
| key="zen_session", | |
| value=session_token, | |
| httponly=True, | |
| secure=True, | |
| samesite="strict", | |
| max_age=86400, # 24 hours | |
| ) | |
| return response | |
| return JSONResponse( | |
| { | |
| "authorized": False, | |
| "expired": expired, | |
| "message": ("Waiting for authorization..." if not expired else "Code expired"), | |
| } | |
| ) | |
| async def logout(): | |
| """Clear session cookie.""" | |
| response = JSONResponse({"message": "Logged out"}) | |
| response.delete_cookie("zen_session") | |
| return response | |
| return router | |
| # Convenience functions | |
| def get_auth_manager() -> DeviceAuthManager: | |
| """Get configured DeviceAuthManager instance.""" | |
| return DeviceAuthManager() | |
| def create_cloudflare_middleware() -> CloudflareAuthMiddleware: | |
| """Create Cloudflare auth middleware.""" | |
| return CloudflareAuthMiddleware() | |
Xet Storage Details
- Size:
- 16.3 kB
- Xet hash:
- d53c925a95b6fa0be0484c3bf0d67b48f63e5d99b029d7edbbd9558ddd6e7feb
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.