import logging import secrets from flask import Flask, request, jsonify, g logger = logging.getLogger(__name__) # Known download manager User-Agent signatures DOWNLOAD_MANAGERS = [ 'internet download manager', 'wget', 'aria2', 'axel', 'freedownloadmanager', 'fdm', 'jdownloader', 'eagleget', 'flashget', 'orbit', 'getright', 'dap', 'download accelerator', 'ninja', 'persepolis', 'uget', 'motrix', 'xdm', 'xtreme download', 'savefrom', 'tubedigger', 'keepvid', 'ytdl', 'video downloadhelper', ] # Known automation tool User-Agent signatures AUTOMATION_TOOLS = [ 'headlesschrome', 'phantomjs', 'selenium', 'puppeteer', 'playwright', 'webdriver', 'httrack', 'scrapy', ] def apply_security_headers(app: Flask): """Apply security headers to all responses - FORTRESS v3.""" @app.before_request def block_download_managers(): """Block requests from known download managers and automation tools.""" ua = (request.headers.get('User-Agent', '') or '').lower() # NOTE: 'curl' and 'python-requests' REMOVED from blocklist # They were blocking legitimate API testing and health checks for dm in DOWNLOAD_MANAGERS: if dm in ua: logger.warning(f"Blocked download manager: {dm} from {request.remote_addr}") return jsonify({'error': 'Acesso não autorizado'}), 403 for at in AUTOMATION_TOOLS: if at in ua: logger.warning(f"Blocked automation tool: {at} from {request.remote_addr}") return jsonify({'error': 'Acesso não autorizado'}), 403 if request.headers.get('X-Download-Manager'): return jsonify({'error': 'Acesso não autorizado'}), 403 # Generate nonce for this request g.csp_nonce = secrets.token_urlsafe(32) @app.after_request def set_headers(response): # --- Cache control --- if not response.content_type or 'text/html' in response.content_type or 'application/json' in response.content_type: response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = '0' # --- Standard security headers --- response.headers['X-Content-Type-Options'] = 'nosniff' # FORTRESS v3: Allow iframe embedding (HF Spaces uses iframes) # Only restrict video routes to same-origin is_video_route = ( request.path.startswith('/api/video-player/') or request.path.startswith('/api/video-stream/') or request.path.startswith('/api/video/') ) if is_video_route: response.headers['X-Frame-Options'] = 'SAMEORIGIN' # NOTE: X-Frame-Options REMOVED for main pages to allow HF Spaces iframe response.headers['X-XSS-Protection'] = '1; mode=block' response.headers['Referrer-Policy'] = 'no-referrer' # --- Permissions-Policy --- response.headers['Permissions-Policy'] = ( 'camera=(), microphone=(), geolocation=(), ' 'display-capture=(), screen-wake-lock=(), ' 'publickey-credentials-get=(), ' 'idle-detection=()' ) # FORTRESS v3: REMOVED Cross-Origin-Opener-Policy # It was breaking the app inside HF Spaces iframe # COEP: require-corp only for video routes if is_video_route: response.headers['Cross-Origin-Embedder-Policy'] = 'require-corp' # CORP: same-origin for media files only is_media_route = ( request.path.startswith('/api/images/') or request.path.startswith('/api/video-stream/') or request.path.startswith('/api/video/') or request.path.startswith('/api/media/') ) if is_media_route: response.headers['Cross-Origin-Resource-Policy'] = 'same-origin' # --- Image-specific headers --- if request.path.startswith('/api/images/'): response.headers['Content-Disposition'] = 'inline' response.headers['X-Robots-Tag'] = 'noindex, nofollow, noarchive, nosnippet' # --- CSP --- nonce = getattr(g, 'csp_nonce', '') csp = ( "default-src 'self'; " "script-src 'self' 'unsafe-inline' 'unsafe-eval'; " "style-src 'self' 'unsafe-inline'; " "img-src 'self' data: blob:; " "frame-src 'self'; " "frame-ancestors 'self' https://huggingface.co https://*.hf.space; " "media-src 'self' blob:; " "connect-src 'self' wss: ws: https://*.hf.space; " "font-src 'self' data:; " "object-src 'none'; " "base-uri 'self'; " "form-action 'self'; " "worker-src 'self' blob:;" ) response.headers['Content-Security-Policy'] = csp return response