Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Set baseline security headers and a Content-Security-Policy at the app level, and vendor Chart.js locally so the admin dashboard no longer loads it from a third-party CDN
Murtaza Nasir2948059bc73f
diff --git a/scripts/download_offline_deps.py b/scripts/download_offline_deps.pyindex 67c81cdd..80f7f187 100644--- a/scripts/download_offline_deps.py+++ b/scripts/download_offline_deps.py@@ -22,6 +22,7 @@ DEPENDENCIES = {"marked.min.js": "https://cdn.jsdelivr.net/npm/marked/marked.min.js","easymde.min.js": "https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js","axios.min.js": "https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js",+ "chart.umd.min.js": "https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js",}}diff --git a/src/app.py b/src/app.pyindex 4211ccf3..d9620b09 100644--- a/src/app.py+++ b/src/app.py@@ -428,6 +428,44 @@ app.config['SESSION_COOKIE_SECURE'] = ()app.config['SESSION_COOKIE_HTTPONLY'] = True # Still protect against XSSapp.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # CSRF protection++# --- Security response headers ---+# Set at the app level so a deployment WITHOUT a hardening reverse proxy is+# still protected (previously the app set only X-Robots-Tag, leaving direct /+# plain-proxy deployments with no clickjacking, MIME-sniffing, or CSP defense).+# All are `setdefault`-applied in add_security_headers so an operator's proxy+# can still override them.+#+# CSP note: the frontend loads Vue's full build (in-DOM template compiler, so+# script execution needs 'unsafe-eval') and bootstraps from inline <script>+# blocks in every template ('unsafe-inline'), so the script-src cannot be+# locked down without a frontend build step that precompiles templates and+# adds per-response nonces. The policy still meaningfully constrains object-src,+# base-uri, form-action, frame-ancestors, and the connect/img/media/font+# origins. Override the whole policy via CONTENT_SECURITY_POLICY, or disable+# the block with SECURITY_HEADERS_ENABLED=false.+SECURITY_HEADERS_ENABLED = os.environ.get('SECURITY_HEADERS_ENABLED', 'true').lower() == 'true'+_DEFAULT_CSP = (+ "default-src 'self'; "+ "script-src 'self' 'unsafe-inline' 'unsafe-eval'; "+ "style-src 'self' 'unsafe-inline'; "+ "img-src 'self' data: blob:; "+ "media-src 'self' blob: data:; "+ "font-src 'self' data:; "+ "connect-src 'self'; "+ "worker-src 'self' blob:; "+ "manifest-src 'self'; "+ "object-src 'none'; "+ "base-uri 'self'; "+ "form-action 'self'; "+ "frame-ancestors 'self'"+)+CONTENT_SECURITY_POLICY = os.environ.get('CONTENT_SECURITY_POLICY', _DEFAULT_CSP).strip()+# HSTS is only meaningful (and only emitted) over HTTPS. Configurable so+# operators terminating TLS elsewhere can tune or disable it.+HSTS_HEADER_VALUE = os.environ.get(+ 'HSTS_HEADER', 'max-age=63072000; includeSubDomains'+).strip()if app.config['SESSION_COOKIE_SECURE']:app.logger.info("Session cookies marked Secure (HTTPS-only)")else:@@ -780,6 +818,30 @@ def add_no_crawl_headers(response):response.headers['X-Robots-Tag'] = 'noindex, nofollow, noarchive, nosnippet, noimageindex'return response+[email protected]_request+def add_security_headers(response):+ """Set baseline security headers so the app is safe even without a+ hardening reverse proxy. Uses setdefault so a proxy that already sets a+ header wins (no duplicates). See the SECURITY_HEADERS config block above.+ """+ if not SECURITY_HEADERS_ENABLED:+ return response+ response.headers.setdefault('X-Frame-Options', 'SAMEORIGIN')+ response.headers.setdefault('X-Content-Type-Options', 'nosniff')+ response.headers.setdefault('Referrer-Policy', 'strict-origin-when-cross-origin')+ # Deny sensors the app never uses; allow mic + screen capture (recording).+ response.headers.setdefault(+ 'Permissions-Policy',+ 'geolocation=(), camera=(), microphone=(self), display-capture=(self), interest-cohort=()'+ )+ if CONTENT_SECURITY_POLICY:+ response.headers.setdefault('Content-Security-Policy', CONTENT_SECURITY_POLICY)+ # HSTS only over HTTPS (request.is_secure reflects X-Forwarded-Proto via ProxyFix).+ if HSTS_HEADER_VALUE and request.is_secure:+ response.headers.setdefault('Strict-Transport-Security', HSTS_HEADER_VALUE)+ return response+# --- No-Crawl System: Serve robots.txt ---@app.route('/robots.txt')def robots_txt():diff --git a/templates/admin.html b/templates/admin.htmlindex 2aa7a4c1..2e46853d 100644--- a/templates/admin.html+++ b/templates/admin.html@@ -15,7 +15,7 @@<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script><!-- All dependencies bundled locally for offline support --><script src="{{ url_for('static', filename='vendor/js/vue.global.js') }}"></script>-<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>+<script src="{{ url_for('static', filename='vendor/js/chart.umd.min.js') }}"></script><!-- All dependencies bundled locally for offline support --><link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}"><link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">diff --git a/tests/test_security_headers.py b/tests/test_security_headers.pynew file mode 100644index 00000000..32b7bda0--- /dev/null+++ b/tests/test_security_headers.py@@ -0,0 +1,49 @@+"""The app must set baseline security headers itself, so deployments without+a hardening reverse proxy are still protected. Previously only X-Robots-Tag+was set, leaving direct/plain-proxy installs with no clickjacking, MIME-sniff,+or CSP defense.+"""++import os+import sys++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app+++def _headers(path='/login', secure=False):+ client = app.test_client()+ env = {'HTTP_X_FORWARDED_PROTO': 'https'} if secure else {}+ return client.get(path, environ_overrides=env).headers+++def test_clickjacking_and_mime_headers_present():+ h = _headers()+ assert h.get('X-Frame-Options') == 'SAMEORIGIN'+ assert h.get('X-Content-Type-Options') == 'nosniff'+ assert h.get('Referrer-Policy') == 'strict-origin-when-cross-origin'+ assert 'Permissions-Policy' in h+++def test_csp_present_and_locks_dangerous_directives():+ csp = _headers().get('Content-Security-Policy', '')+ assert csp, 'CSP header missing'+ # These are the directives that add value even with the unavoidable+ # 'unsafe-inline'/'unsafe-eval' on scripts (Vue runtime compiler).+ assert "object-src 'none'" in csp+ assert "base-uri 'self'" in csp+ assert "form-action 'self'" in csp+ assert "frame-ancestors 'self'" in csp+ assert "default-src 'self'" in csp+++def test_hsts_only_over_https():+ assert 'Strict-Transport-Security' not in _headers(secure=False)+ assert 'Strict-Transport-Security' in _headers(secure=True)+++def test_permissions_policy_allows_mic_denies_geolocation():+ pp = _headers().get('Permissions-Policy', '')+ assert 'microphone=(self)' in pp+ assert 'geolocation=()' in pp