File size: 4,948 Bytes
12f0507 2ab2d4a 12f0507 714c7f2 12f0507 2ab2d4a 714c7f2 12f0507 714c7f2 12f0507 2ab2d4a 12f0507 714c7f2 12f0507 2ab2d4a 12f0507 2ab2d4a 12f0507 2ab2d4a 12f0507 2ab2d4a 12f0507 714c7f2 12f0507 714c7f2 12f0507 714c7f2 2ab2d4a 714c7f2 2ab2d4a 714c7f2 2ab2d4a 714c7f2 2ab2d4a 12f0507 714c7f2 2ab2d4a 12f0507 c6f7384 12f0507 714c7f2 12f0507 714c7f2 12f0507 2ab2d4a 12f0507 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | 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
|