Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1969 lines (1713 loc) · 84.3 KB
/
Copy pathapp.py
File metadata and controls
1969 lines (1713 loc) · 84.3 KB
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# =============================================================================
# RETRODB - Main Flask Application
# =============================================================================
# A retro gaming ROM library manager with web interface
# Features: ROM scanning, metadata scraping, beautiful cyberpunk UI
# =============================================================================
from werkzeug.exceptions import HTTPException
from flask import Flask, render_template, request, redirect, url_for, jsonify, session, g, send_from_directory, abort
import gzip
import os
import sys
import logging
import json
import re
import secrets
import time
from datetime import timedelta
from zoneinfo import available_timezones
# Decompression-bomb cap (Pillow MAX_IMAGE_PIXELS) is set canonically from
# config.IMAGE_MAX_PIXELS at import time in services/image_utils.py and
# services/game_media_service.py — the single source of truth. A hardcoded
# value here was silently overridden by those modules (import order), so it's
# intentionally not set in app.py.
# ---------------------------------------------------------------------------
# ROCm GPU environment — MUST be set before any library loads ROCm/MIOpen.
# Overrides gfx1032 (RX 6600-series) to use gfx1030 pre-compiled kernels,
# forces MIOpen algorithm benchmarking, and cleans stale GPU cache.
# ---------------------------------------------------------------------------
if os.path.exists('/dev/kfd'):
_miopen_cache = os.path.join(os.path.expanduser('~'), '.cache', 'realesrgan', 'miopen')
os.makedirs(_miopen_cache, exist_ok=True)
os.environ['HSA_OVERRIDE_GFX_VERSION'] = '10.3.0'
os.environ['MIOPEN_FIND_MODE'] = '3'
os.environ['MIOPEN_USER_DB_PATH'] = _miopen_cache
os.environ['MIOPEN_CUSTOM_CACHE_DIR'] = _miopen_cache
# Clean stale gfx1032 cache that conflicts with gfx1030 override
import glob as _glob
_stale = None
for _stale in _glob.glob(os.path.join(_miopen_cache, 'gfx1032*')):
try:
os.remove(_stale)
except OSError:
pass
del _miopen_cache, _glob, _stale
# Import configuration
import config
# Import settings manager for user-editable settings
import settings_manager
# Import log manager for file-based logging
import log_manager
# Import services layer
from services.atomic_io import atomic_write_json
from services.database import query
from services.auth import (
hash_password, get_current_user, get_user_settings,
has_permission, login_required
)
from services.game_utils import (
get_rating_image_map_js, get_rating_system_names_js,
get_rating_crossmap_js, RATING_SYSTEM_KEYS
)
from services.template_filters import register_filters as _register_template_filters
from services.database_init import init_database, ensure_user_tables
from services.assets import asset_url
from services.settings_validators import ALLOWED_THEMES
from services.api_helpers import handle_api_errors, success as api_success, error as api_error
from services.analytics import (
build_analytics_context,
)
# Pre-compute static rating data (derived from constants, never changes)
_RATING_IMG_MAP_JS = get_rating_image_map_js()
_RATING_SYS_NAMES_JS = get_rating_system_names_js()
_RATING_TO_TIER_JS, _TIER_TO_RATING_JS = get_rating_crossmap_js()
# =============================================================================
# FLASK APP INITIALIZATION
# =============================================================================
app = Flask(__name__)
_register_template_filters(app)
# Register asset_url as a Jinja global so it is available in every template
# (including partials rendered without the context processor, e.g. bare
# `jinja_env.get_template(...).render(...)` in tests / tools).
app.jinja_env.globals['asset_url'] = asset_url
def _get_secret_key():
"""Get or generate a persistent secret key for Flask sessions.
Priority: RETRODB_SECRET_KEY env var > data/.secret_key file > auto-generated.
"""
# Check environment variable first (useful for Docker deployments)
env_key = os.environ.get('RETRODB_SECRET_KEY')
if env_key:
return env_key
key_path = os.path.join(config.BASE_DIR, 'data', '.secret_key')
os.makedirs(os.path.dirname(key_path), exist_ok=True)
try:
if os.path.exists(key_path):
with open(key_path, 'r') as f:
key = f.read().strip()
if key:
return key
except OSError:
pass
# Generate new key
key = secrets.token_hex(32)
# Pass 45.5 — atomic_write_text chmods the tmpfile to 0o600 *before*
# the os.replace, so the final path never exists at the umask default
# (typically 0o644). The previous form was open→write→chmod, which
# left a brief world-readable window holding the secret key.
try:
from services.atomic_io import atomic_write_text
atomic_write_text(key_path, key, mode=0o600)
except OSError:
pass
return key
app.secret_key = _get_secret_key()
# Session cookie hardening
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
# Operators fronting RetroDB with a TLS reverse proxy should set
# RETRODB_SECURE_COOKIES=true so the browser drops the session cookie on
# any plain-HTTP request. Default off: on a localhost HTTP deploy the flag
# would silently break login (browser refuses to send the cookie).
app.config['SESSION_COOKIE_SECURE'] = (
os.environ.get('RETRODB_SECURE_COOKIES', '').lower() in ('true', '1', 'yes')
)
app.config['MAX_CONTENT_LENGTH'] = config.MAX_UPLOAD_BYTES
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)
# Pass 33.1 — reverse-proxy deploys (nginx / Caddy in front of waitress).
# Behind a proxy, `request.remote_addr` is always the proxy's loopback
# address, so the IP-based login rate limiter (`services.security.
# rate_limit_login`) and flask-limiter both collapse everyone into the
# same bucket — a self-DoS + trivial bypass. Wiring werkzeug's ProxyFix
# middleware reads X-Forwarded-For (and friends) and rewrites remote_addr
# accordingly. Gated on RETRODB_TRUST_PROXY so a localhost deploy without
# a proxy won't start honouring attacker-controlled forwarded headers.
# See docs/PROXY-DEPLOY.md (added in this pass) for the trust contract.
if os.environ.get('RETRODB_TRUST_PROXY', '').lower() in ('true', '1', 'yes'):
from werkzeug.middleware.proxy_fix import ProxyFix
# Trust exactly one hop of X-Forwarded-For / X-Forwarded-Proto /
# X-Forwarded-Host — the single reverse proxy directly in front. If
# your deployment chains proxies, increase these and audit every hop.
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=0)
logger_startup = logging.getLogger(__name__)
logger_startup.info(
"RETRODB_TRUST_PROXY=1 — ProxyFix installed; trusting one hop of "
"X-Forwarded-For / Proto / Host"
)
# =============================================================================
# INTERNATIONALIZATION (Pass 43.1 — i18n foundation)
# =============================================================================
# Flask-Babel with source-text message IDs (the gettext standard): strings are
# wrapped {{ _('Save') }} and the English source IS the catalog key. Per-locale
# .po/.mo catalogs live under translations/ (committed; bundled in retrodb.spec).
from flask_babel import Babel
from services.i18n import available_locales, TRANSLATIONS_DIR
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
app.config['BABEL_TRANSLATION_DIRECTORIES'] = TRANSLATIONS_DIR
def select_locale():
"""Locale-selection chain: user pref -> session -> Accept-Language -> 'en'.
Every branch is guarded by membership in available_locales(), so a
stale/removed locale never raises — it degrades to 'en'.
"""
locales = available_locales()
# 1. logged-in user's saved preference (g.user_settings is a plain dict;
# .get() returns None for a legacy row predating the column).
if g.get('user_settings'):
pref = g.user_settings.get('locale_preference')
if pref and pref in locales:
return pref
# 2. transient per-session switch — intentionally retained but unreachable
# in v1 (no UI writes session['locale']); kept for a future
# anon-switcher. Not dead code.
sess = session.get('locale')
if sess and sess in locales:
return sess
# 3. browser Accept-Language
best = request.accept_languages.best_match(locales)
if best:
return best
# 4. default
return 'en'
babel = Babel(app, locale_selector=select_locale)
# Settings "Language" dropdown reads these (services/i18n.py is the single
# source of truth shared with the selector chain + the route validator).
from services.i18n import locale_display_name
app.jinja_env.globals['available_locales'] = available_locales
app.jinja_env.globals['locale_display_name'] = locale_display_name
# i18n display helpers (Pass 43.2/43.3). All three are Jinja globals called once
# per full-page render in base.html — NOT routed through inject_config (which
# fires per-partial). flask_babel.gettext is the request-aware translator; using
# the active locale, js_i18n_map() builds window.I18N and field_labels_map()
# builds window.FIELD_LABELS. See docs/specs/i18n.md §6/§7.
from flask_babel import gettext as _flask_gettext
from services.i18n_labels import display_field_value, field_labels_map
from services.js_i18n_strings import JS_I18N_KEYS
def js_i18n_map():
"""{ msgid: translation } for the JS-used msgids, active locale (window.I18N)."""
return {msgid: _flask_gettext(msgid) for msgid in JS_I18N_KEYS}
app.jinja_env.globals['display_field_value'] = display_field_value
app.jinja_env.globals['field_labels_map'] = field_labels_map
app.jinja_env.globals['js_i18n_map'] = js_i18n_map
def current_locale_tag():
"""Active locale as an HTML lang tag (underscore -> hyphen, e.g. pt_BR ->
pt-BR) for the <html lang> attribute. Defaults to 'en' outside a request."""
from flask_babel import get_locale
locale = get_locale()
return str(locale).replace('_', '-') if locale else 'en'
app.jinja_env.globals['current_locale_tag'] = current_locale_tag
# =============================================================================
# STATIC IMAGES — frozen-aware fallback route
# =============================================================================
# Pass 46.3 part 2 — `/static/images/<path>` paths span two roots in a
# PyInstaller bundle: scraped media + uploaded avatars live under
# config.IMAGE_PATH (writable, next to the launcher), while bundled defaults
# (placeholder.png, hardware/, ratings/, systems/, controllers/, default
# avatars/) are baked into config.STATIC_PATH/images (read-only MEIPASS).
# Try the user dir first, fall back to the bundle. In a non-frozen install
# both roots resolve to the same directory and the fallback is a no-op.
_BUNDLE_IMAGE_DIR = os.path.join(config.STATIC_PATH, 'images')
@app.route('/static/images/<path:filepath>')
def serve_static_image(filepath):
user_full = os.path.join(config.IMAGE_PATH, filepath)
if os.path.isfile(user_full):
return send_from_directory(config.IMAGE_PATH, filepath)
bundle_full = os.path.join(_BUNDLE_IMAGE_DIR, filepath)
if os.path.isfile(bundle_full):
return send_from_directory(_BUNDLE_IMAGE_DIR, filepath)
abort(404)
# =============================================================================
# RATE LIMITING
# =============================================================================
try:
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(
get_remote_address,
app=app,
default_limits=[], # No global default — only apply per-route
storage_uri="memory://",
)
except ImportError:
limiter = None
# =============================================================================
# REGISTER BLUEPRINTS
# =============================================================================
# Original blueprints
from routes.auth import bp as auth_bp
from routes.trophies import bp as trophies_bp
from routes.achievements import bp as achievements_bp
from routes.tools import tools_bp
from routes.reports import reports_bp
from routes.scraper import scraper_bp
app.register_blueprint(auth_bp)
app.register_blueprint(trophies_bp)
app.register_blueprint(achievements_bp)
app.register_blueprint(tools_bp)
app.register_blueprint(reports_bp)
app.register_blueprint(scraper_bp)
# New extracted blueprints
from routes.clz_import import bp as clz_import_bp
from routes.controllers import bp as controllers_bp
from routes.bonus_discs import bp as bonus_discs_bp
from routes.settings import bp as settings_bp
from routes.systems import bp as systems_bp
from routes.games import bp as games_bp
from routes.games_hltb import bp as games_hltb_bp
from routes.games_ai import bp as games_ai_bp
from routes.games_search import bp as games_search_bp
from routes.games_media import bp as games_media_bp
from routes.maintenance import bp as maintenance_bp
from routes.bulk_scrape import bp as bulk_scrape_bp
from routes.ra_sync import bp as ra_sync_bp
from routes.scrape_logs import logs_bp
from routes.collections import bp as collections_bp
from routes.collector_trophies import bp as collector_trophies_bp
from routes.museum import bp as museum_bp
from routes.platform_import import bp as platform_import_bp
from routes.steam_achievements import bp as steam_achievements_bp
from routes.xbox_achievements import bp as xbox_achievements_bp
from routes.game_imports import bp as game_imports_bp
from routes.launch import bp as launch_bp
from routes.emulators import bp as emulators_bp
from routes.launch_settings import bp as launch_settings_bp
app.register_blueprint(clz_import_bp)
app.register_blueprint(controllers_bp)
app.register_blueprint(bonus_discs_bp)
app.register_blueprint(settings_bp)
app.register_blueprint(systems_bp)
app.register_blueprint(games_bp)
app.register_blueprint(games_hltb_bp)
app.register_blueprint(games_ai_bp)
app.register_blueprint(games_search_bp)
app.register_blueprint(games_media_bp)
app.register_blueprint(maintenance_bp)
app.register_blueprint(bulk_scrape_bp)
app.register_blueprint(ra_sync_bp)
app.register_blueprint(logs_bp)
app.register_blueprint(collections_bp)
app.register_blueprint(collector_trophies_bp)
app.register_blueprint(museum_bp)
app.register_blueprint(platform_import_bp)
app.register_blueprint(steam_achievements_bp)
app.register_blueprint(xbox_achievements_bp)
app.register_blueprint(game_imports_bp)
app.register_blueprint(launch_bp)
app.register_blueprint(emulators_bp)
app.register_blueprint(launch_settings_bp)
# Pass 44 — expose has_permission to templates as has_perm() so the ▶ Play
# button can be permission-gated in game_detail.html without leaking
# launch URLs to viewers.
from services.auth import has_permission as _has_permission_for_template
app.jinja_env.globals['has_perm'] = _has_permission_for_template
# =============================================================================
# PER-ROUTE RATE LIMITS (applied after blueprint registration)
# =============================================================================
def _rate_limit(endpoint, spec):
"""Pass 34.4 — apply a rate-limit rule to a view function by endpoint,
hard-failing at import time if the endpoint was renamed / removed.
Previously every call used ``app.view_functions.get(endpoint, lambda: None)``
which silently swapped in a no-op decorator — a renamed route would
break its rate-limiter coverage with no log line, and the next audit
pass would miss it. Raising here surfaces the regression before the
process ever serves a request.
"""
if not limiter:
return
view = app.view_functions.get(endpoint)
if view is None:
raise RuntimeError(
f"Pass 34.4: rate-limiter endpoint '{endpoint}' is not registered "
f"(did the route get renamed?)"
)
# Install the wrapper. Decorating `view` and discarding the result
# registers the limit under a name the request-time lookup never matches,
# so nothing was enforced (Pass 59.73).
app.view_functions[endpoint] = limiter.limit(spec)(view)
if limiter:
# Expensive AI/scraping endpoints
_rate_limit('games_ai.api_game_ai_fill', "10 per minute")
_rate_limit('bulk_scrape.api_bulk_scrape_job_start', "5 per minute")
# Login brute force protection (supplements existing IP-based rate limiting)
_rate_limit('auth.api_login', "10 per minute")
# Heavy admin endpoints — on a localhost deploy the realistic risk is
# the operator double-clicking, not a malicious DoS, but matching the
# existing login/bulk-scrape pattern costs nothing.
_rate_limit('maintenance.api_restart', "2 per minute")
_rate_limit('maintenance.api_scan', "3 per minute")
_rate_limit('maintenance.api_database_optimize', "3 per minute")
_rate_limit('maintenance.api_image_resize_start', "3 per minute")
_rate_limit('settings.api_backup', "3 per minute")
# Pass 25.9 — rate-limit additional expensive endpoints. Numbers match
# the roadmap targets: AI-fill 30/hr, HLTB 60/hr, museum generate
# 20/hr, trophy refresh 10/hr. The per-minute ceilings below are the
# equivalents that Flask-Limiter's syntax expresses naturally; the
# 30-per-hour target for games_ai.api_game_ai_fill is already covered
# by the 10-per-minute rule above (60/hr effective).
_rate_limit('games_hltb.api_hltb_lookup', "60 per hour")
_rate_limit('games_hltb.api_hltb_search', "60 per hour")
_rate_limit('games_hltb.api_hltb_bulk_start', "5 per hour")
_rate_limit('museum.generate_system', "20 per hour")
_rate_limit('museum.generate_all', "2 per hour")
_rate_limit('collector_trophies.refresh_trophies', "10 per hour")
# Pass 41.10.D — heavy filesystem walks; cap at 5/min so a misclick in
# the UI or a runaway script can't hammer the disk on a multi-user host.
_rate_limit('tools.api_archive_scanner_scan', "5 per minute")
_rate_limit('tools.api_chd_converter_scan', "5 per minute")
_rate_limit('tools.api_chd_verify_scan', "5 per minute")
_rate_limit('tools.api_duplicate_finder_scan', "5 per minute")
_rate_limit('tools.api_screenshot_dedup_scan', "5 per minute")
# Pass 39.7 — same family as Pass 41.10.D: walks the filesystem under
# @login_required only (non-editor users can hit it), one cap per minute
# since a single scan can take seconds on large libraries.
_rate_limit('reports.api_reports_multidisc_scan', "5 per minute")
# Pass 45.8 — third-party-API fan-out endpoints. Each call below issues
# tens-to-hundreds of remote requests against Steam / Xbox Live / PSN
# / IGDB / RAWG / TGDB. A misclick or stuck XHR loop can burn API
# quota or trigger account bans (PSN especially has aggressive
# per-account rate-limits). Caps mirror the Pass 41.10.D pattern:
# 5/min for "fetch the whole library" actions (rare admin-driven);
# 2/hour for "bulk refresh / sync everything" actions
# (cron-like, never legitimate to run every minute).
_rate_limit('platform_import.api_steam_fetch_library', "5 per minute")
_rate_limit('platform_import.api_steam_import', "5 per minute")
_rate_limit('platform_import.api_steam_sync_achievements', "2 per hour")
_rate_limit('platform_import.api_xbox_fetch_library', "5 per minute")
_rate_limit('platform_import.api_xbox_import', "5 per minute")
_rate_limit('platform_import.api_xbox_sync_achievements', "2 per hour")
_rate_limit('platform_import.api_psn_fetch_library', "5 per minute")
_rate_limit('platform_import.api_psn_import', "5 per minute")
_rate_limit('steam_achievements.api_steam_sync_all', "2 per hour")
_rate_limit('xbox_achievements.api_xbox_sync_all', "2 per hour")
_rate_limit('trophies.api_psn_sync_all', "2 per hour")
_rate_limit('trophies.api_psn_bulk_refresh_start', "2 per hour")
_rate_limit('collections.api_scrape_all_wishlist', "2 per hour")
# Per-source scraper credit-check probes: a stuck UI poll loop can
# otherwise issue 60 calls/minute against TGDB / IGDB / etc.
_rate_limit('scraper.api_check_scraper', "30 per minute")
_rate_limit('scraper.api_scraper_allowance', "30 per minute")
# =============================================================================
# REQUEST-SCOPED DB CONNECTION CLEANUP
# =============================================================================
@app.teardown_appcontext
def close_request_db(exception):
"""Close the request-scoped database connection if one was opened."""
db = g.pop('db', None)
if db is not None:
try:
db.execute("PRAGMA optimize")
except Exception:
pass
db.close()
# =============================================================================
# SECURITY HEADERS
# =============================================================================
@app.after_request
def set_security_headers(response):
"""Add security headers to every response.
X-XSS-Protection is intentionally omitted — the XSS Auditor was removed
from Chromium/Edge and retained only in Safari, where leaving the header
unset matches modern OWASP guidance.
"""
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
response.headers['Permissions-Policy'] = (
'browsing-topics=(), camera=(), microphone=(), geolocation=(), '
'payment=(), usb=(), interest-cohort=(), accelerometer=(), '
'gyroscope=(), magnetometer=(), midi=()'
)
# HSTS only when the operator has flagged TLS is in front. On plain HTTP
# localhost the header is ignored anyway, but sending it unconditionally
# would be misleading.
if app.config.get('SESSION_COOKIE_SECURE'):
response.headers['Strict-Transport-Security'] = (
'max-age=31536000; includeSubDomains'
)
# CSP ships in Report-Only until inline event handlers across templates
# have been migrated to delegated listeners. The policy below is what we
# intend to enforce — currently it surfaces violations in the browser
# console so operators / devs can spot regressions before flipping to
# enforcing mode. Nonce is per-request and exposed via {{ csp_nonce }}.
nonce = g.get('csp_nonce', '')
if nonce:
response.headers['Content-Security-Policy-Report-Only'] = (
"default-src 'self'; "
f"script-src 'self' 'nonce-{nonce}' https://cdn.jsdelivr.net; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
"img-src 'self' data: blob:; "
"font-src 'self' https://fonts.gstatic.com; "
"connect-src 'self'; "
"media-src 'self'; "
"object-src 'none'; "
"frame-ancestors 'self'; "
"base-uri 'self'; "
"form-action 'self'"
)
return response
# Pass 21.2 — opt-out gzip compression for JSON responses. Waitress ships no
# compression so large card/filter payloads go over the wire uncompressed.
# Reverse-proxied deploys (Caddy, nginx) already compress at the edge; set
# RETRODB_DISABLE_GZIP=1 there to skip the double work.
_GZIP_ENABLED = os.environ.get('RETRODB_DISABLE_GZIP', '').lower() not in ('1', 'true', 'yes')
_GZIP_MIN_BYTES = 1024
@app.after_request
def compress_response(response):
"""gzip JSON responses >1 KB when the client advertises Accept-Encoding: gzip.
Skips streamed/direct-passthrough responses, already-encoded bodies, and
non-compressible status codes (204, 304). Adds Vary: Accept-Encoding so
shared caches never serve a gzipped body to a client that did not ask for
it.
"""
if not _GZIP_ENABLED:
return response
# `direct_passthrough` bodies (send_file, StreamResponse) must not be
# materialised — compressing them would break the streaming contract.
if response.direct_passthrough:
return response
if response.status_code < 200 or response.status_code in (204, 304):
return response
if response.headers.get('Content-Encoding'):
return response
ctype = response.content_type or ''
if 'json' not in ctype and 'javascript' not in ctype:
return response
if 'gzip' not in (request.headers.get('Accept-Encoding') or ''):
# Even when we don't compress, advertise that the response varies by
# Accept-Encoding so the browser cache keys on it correctly.
response.headers.setdefault('Vary', 'Accept-Encoding')
return response
data = response.get_data()
if len(data) < _GZIP_MIN_BYTES:
response.headers.setdefault('Vary', 'Accept-Encoding')
return response
compressed = gzip.compress(data, compresslevel=6)
response.set_data(compressed)
response.headers['Content-Encoding'] = 'gzip'
response.headers['Content-Length'] = str(len(compressed))
existing_vary = response.headers.get('Vary', '')
if existing_vary:
if 'accept-encoding' not in existing_vary.lower():
response.headers['Vary'] = f"{existing_vary}, Accept-Encoding"
else:
response.headers['Vary'] = 'Accept-Encoding'
return response
@app.after_request
def log_slow_request(response):
"""Log a WARNING for handlers that exceed config.SLOW_REQUEST_MS.
Pairs with SLOW_QUERY_MS — DB slowness vs. whole-handler slowness are
distinct signals. Probe endpoints are exempted so /health polling noise
never lands in the log. Disabled entirely when SLOW_REQUEST_MS == 0.
"""
threshold = getattr(config, 'SLOW_REQUEST_MS', 0)
if threshold <= 0 or request.endpoint in _PROBE_ENDPOINTS:
return response
start = g.get('request_start_time')
if start is None:
return response
elapsed_ms = (time.perf_counter() - start) * 1000
if elapsed_ms > threshold:
logger.warning(
f"slow_request {request.method} {request.path} "
f"{elapsed_ms:.0f}ms status={response.status_code}"
)
return response
# =============================================================================
# HEALTH & READINESS PROBES
# =============================================================================
# Cheap unauthenticated endpoints for systemd / Docker / reverse-proxy probes.
# /health is process-alive (no DB hit); /ready exercises the DB so it catches
# lock-held / corrupt-schema states. Both are exempted from first-time-setup
# redirect and slow-request logging so they stay silent in the common case.
@app.route('/health')
def health_probe():
return jsonify({'status': 'alive', 'version': config.APP_VERSION}), 200
@app.route('/ready')
def ready_probe():
try:
from services.database import get_request_db
db = get_request_db()
db.execute("SELECT 1").fetchone()
return jsonify({'status': 'ready'}), 200
except Exception as e:
logger.warning(f"readiness probe failed: {e}")
return jsonify({'status': 'not_ready', 'error': str(e)}), 503
# Endpoints exempted from first-time-setup redirects and slow-request log noise.
_PROBE_ENDPOINTS = frozenset({'health_probe', 'ready_probe'})
# =============================================================================
# GLOBAL ERROR HANDLERS
# =============================================================================
@app.errorhandler(404)
def handle_not_found(e):
# Pass 34.1: API paths return the standard envelope.
if request.path.startswith('/api/'):
return api_error('Not found', 404)
return render_template('base.html'), 404
@app.errorhandler(500)
def handle_internal_error(e):
# Include the traceback — without it, the white-page 500 leaves the
# operator with only `str(e)` to debug from. Pass 34.1: API body via
# shared error() helper; non-API path stays HTML.
logger.error(f"Internal server error: {e}", exc_info=True)
if request.path.startswith('/api/'):
return api_error('Internal server error', 500)
return render_template('base.html'), 500
@app.errorhandler(413)
def handle_request_too_large(e):
"""Werkzeug raises this from MAX_CONTENT_LENGTH when the view first reads
the request body. @handle_api_errors re-raises HTTPException so it lands
here (Pass 59.45). Default page is bare HTML — give the user a hint about
the per-file cap and where the global limit comes from.
"""
mb = config.MAX_UPLOAD_BYTES // (1024 * 1024)
msg = (
f"Upload exceeds the {mb} MB request limit. "
"Each image is also capped at 10 MB; try resizing oversized files "
"or upload them one at a time. "
"Operators can raise the global cap via RETRODB_MAX_UPLOAD_MB."
)
if request.path.startswith('/api/'):
return api_error(msg, 413)
return msg, 413
@app.errorhandler(HTTPException)
def handle_http_exception(e):
"""Any other HTTP error on /api/* answers with the envelope and its real
status. @handle_api_errors lets HTTPException through (Pass 59.45), so a
malformed JSON body's 400 or an abort(403) arrives here. The handlers for
specific codes above take precedence; page requests keep Werkzeug's page.
"""
if request.path.startswith('/api/'):
return api_error(e.description or e.name, e.code or 500)
return e
@app.errorhandler(429)
def handle_rate_limited(e):
"""Flask-Limiter's default 429 is a plain page; /api/* callers read
JSON (Pass 59.73)."""
if request.path.startswith('/api/'):
from flask_babel import gettext as _
return api_error(_('Too many requests. Please wait and try again.'), 429)
return e
# =============================================================================
# USER SESSION SETUP
# =============================================================================
@app.before_request
def assign_request_id():
"""Assign a short correlation ID to every request.
Stamped onto every log record via log_manager.install_request_id_factory()
so a single grep across logs/*.log reconstructs a full request trace.
8-char hex (~32 bits) is enough entropy for per-request uniqueness
within a single operator's install and reads cleanly in logs.
"""
g.request_id = secrets.token_hex(4)
g.request_start_time = time.perf_counter()
# Per-request CSP nonce — 128 bits, base64-url. Templates that embed
# inline <script> blocks may opt into the enforced CSP by adding
# nonce="{{ csp_nonce }}"; while the policy ships in report-only mode
# that migration can happen template-by-template without breaking pages.
g.csp_nonce = secrets.token_urlsafe(16)
@app.before_request
def load_user():
"""Load current user before each request"""
g.user = get_current_user()
if g.user:
g.user_settings = get_user_settings(g.user['id'])
else:
g.user_settings = None
# Ensure a CSRF token exists in the session
if '_csrf_token' not in session:
session['_csrf_token'] = secrets.token_hex(32)
@app.before_request
def validate_csrf():
"""Validate CSRF token on state-changing requests.
Checks the X-CSRF-Token header against the session token for POST/PUT/DELETE.
Exempt: login, setup, static files, and GET/HEAD/OPTIONS requests.
"""
if request.method in ('GET', 'HEAD', 'OPTIONS'):
return
if not request.endpoint:
return
# Exempt endpoints that must work without a CSRF token
csrf_exempt = {
'static', 'serve_static_image',
'auth.api_login', 'auth.login', 'setup_api',
'setup_browse_folders',
}
if request.endpoint in csrf_exempt:
return
# Check X-CSRF-Token header or _csrf_token form field
session_token = session.get('_csrf_token', '')
if not session_token:
return jsonify({'success': False, 'error': 'Invalid or missing CSRF token'}), 403
token = request.headers.get('X-CSRF-Token', '') or request.form.get('_csrf_token', '')
if not secrets.compare_digest(token, session_token):
return jsonify({'success': False, 'error': 'Invalid or missing CSRF token'}), 403
@app.before_request
def check_first_time_setup():
"""Redirect to setup wizard on first launch"""
# Skip for static files, the setup route itself, and API endpoints used by setup
if not request.endpoint or request.endpoint in ('static', 'serve_static_image',
'setup_page', 'setup_api',
'setup_browse_folders',
'api_timezones',
'auth.api_login', 'auth.login', 'auth.logout'):
return
if request.endpoint in _PROBE_ENDPOINTS:
return
# Check if setup has been completed
user_settings = settings_manager.load_settings()
has_rom_path = bool(user_settings.get('rom_path') or getattr(config, 'ROM_PATH', ''))
setup_done = user_settings.get('setup_completed', False)
if not setup_done and not has_rom_path:
return redirect(url_for('setup_page'))
@app.before_request
def check_force_password_change():
"""Redirect admin users who must change their default password"""
if not g.get('user'):
return
if not g.user.get('force_password_change'):
return
# Allow access to password change endpoint, logout, static, and setup
allowed_endpoints = ('auth.api_change_password', 'auth.api_force_change_password',
'auth.logout', 'static', 'serve_static_image',
'setup_page', 'setup_api')
if request.endpoint in allowed_endpoints:
return
# Pass 59.77: an /api/* caller reads JSON. The HTML page with a 200 read
# as success to every fetch() caller.
if request.path.startswith('/api/'):
from flask_babel import gettext as _
return api_error(_('Password change required'), 403)
# Return the force change password page
return render_template('force_change_password.html'), 200
# Get effective paths (settings.json overrides config.py if set)
def get_rom_path():
return settings_manager.get_effective_path('rom_path', config.ROM_PATH)
def get_esde_gamelists_path():
return settings_manager.get_effective_path('esde_gamelists_path', getattr(config, 'ESDE_GAMELISTS_PATH', ''))
def get_esde_media_path():
return settings_manager.get_effective_path('esde_downloaded_media_path', getattr(config, 'ESDE_DOWNLOADED_MEDIA_PATH', ''))
def get_rpcs3_trophy_path():
return settings_manager.get_effective_path('rpcs3_trophy_path', getattr(config, 'RPCS3_TROPHY_PATH', ''))
# Make config available to templates
app.config['APP_VERSION'] = config.APP_VERSION
app.config['APP_DESCRIPTION'] = config.APP_DESCRIPTION
app.config['ROM_PATH'] = get_rom_path()
app.config['DB_PATH'] = config.DB_PATH
app.config['RPCS3_TROPHY_PATH'] = get_rpcs3_trophy_path()
# Set up logging — install the request-id factory FIRST so basicConfig's
# handler already has access to %(request_id)s on the very first record.
log_manager.install_request_id_factory()
# Pass 41.3.A — install the redactor before basicConfig, then again after it
# (below) to attach it to the StreamHandler basicConfig creates.
# install_global_redactor is idempotent. The handler filters are what redact
# records propagating from child loggers; the root-logger filter only sees
# records created on root itself (Pass 59.41).
log_manager.install_global_redactor()
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(request_id)s - %(name)s - %(levelname)s - %(message)s'
)
# Re-run to attach the redactor filter to the StreamHandler basicConfig just
# created. CategoryFileHandler already attaches its own redactor; this adds
# the console-stream safety net that the CategoryFileHandler path cannot cover.
log_manager.install_global_redactor()
logger = logging.getLogger(__name__)
# Waitress logs a WARNING every time a request queues — with a 16-thread pool
# and 20+ parallel XHRs per page load, this fires dozens of times per
# navigation and drowns the actual log. Queueing at depth 1–2 is normal and
# not actionable. Bump the threshold so only sustained back-pressure (ERROR)
# surfaces. See waitress/task.py — "Task queue depth is N" is the message.
logging.getLogger('waitress.queue').setLevel(logging.ERROR)
# Pass 34.3 — removed log_to_category + system_log. Neither had any
# importers (routes/ra_sync.py and routes/achievements.py each define
# their own local system_log). Categorised logs flow through
# log_manager.CategoryFileHandler, installed via setup_all_logging().
# =============================================================================
# JINJA2 FILTERS — moved to services/template_filters.py
# Registered below after app creation.
# =============================================================================
def get_avatar_url(user, user_settings_row):
"""Get the avatar URL for a user, or None to fall back to role emoji"""
if not user_settings_row:
return None
avatar = user_settings_row.get('avatar', '') if hasattr(user_settings_row, 'get') else (user_settings_row['avatar'] if 'avatar' in user_settings_row.keys() else '')
if not avatar:
return None
if avatar.startswith('default_'):
return f'/static/images/avatars/{avatar}.svg'
return f'/static/images/avatars/{avatar}'
# Pass 34.2 — mtime-keyed cache for the ai-scraper-enabled read. Previous
# implementation re-parsed scraper_settings.json on every Jinja render.
_AI_SCRAPER_CACHE = {'mtime': None, 'enabled': False}
_AI_SCRAPER_KEY_MAP = {
'gemini': 'ai_gemini_api_key',
'openai': 'ai_openai_api_key',
'claude': 'ai_claude_api_key',
}
def _ai_scraper_enabled_cached():
try:
from routes.scraper import SCRAPER_SETTINGS_FILE as _ssf
if not os.path.exists(_ssf):
_AI_SCRAPER_CACHE['mtime'] = None
_AI_SCRAPER_CACHE['enabled'] = False
return False
mtime = os.path.getmtime(_ssf)
if _AI_SCRAPER_CACHE['mtime'] == mtime:
return _AI_SCRAPER_CACHE['enabled']
with open(_ssf, 'r') as _f:
_ss = json.load(_f)
_ak = _ss.get('api_keys', {})
_prov = _ak.get('ai_provider', '')
_key = _AI_SCRAPER_KEY_MAP.get(_prov, '')
enabled = bool(_prov and _ak.get(_key, '') and _ss.get('enabled', {}).get('ai', False))
_AI_SCRAPER_CACHE['mtime'] = mtime
_AI_SCRAPER_CACHE['enabled'] = enabled
return enabled
except Exception:
# non-fatal — missing/invalid scraper_settings.json just hides the
# AI Fill button in the UI.
return False
def _user_theme(user_settings_obj):
"""The logged-in user's saved theme, or None (Pass 59.38).
Emitted into base.html's FOUC block as the fallback when this browser has
no theme in localStorage, so the theme follows the user across devices.
Re-validated here as well as on write: a row written before the write
validation existed may hold any string.
"""
if not user_settings_obj:
return None
theme = dict(user_settings_obj).get('theme_preference')
return theme if theme in ALLOWED_THEMES else None
@app.context_processor
def inject_config():
"""Make config, user settings, and current user available to all templates"""
user_settings = settings_manager.load_settings()
# Get per-user timezone for JS and template use
user_tz = 'UTC'
user_settings_obj = g.get('user_settings')
if user_settings_obj:
if hasattr(user_settings_obj, 'get'):
user_tz = user_settings_obj.get('timezone', 'UTC') or 'UTC'
elif hasattr(user_settings_obj, 'keys') and 'timezone' in user_settings_obj.keys():
user_tz = user_settings_obj['timezone'] or 'UTC'
# Check if AI scraper is configured (for showing AI Fill button).
# Pass 34.2 — mtime-cache the scraper_settings.json read. inject_config
# fires on every Jinja render (dashboard, library, modal partials,
# cards); the pre-34.2 implementation parsed the JSON file on every
# one of those, which at ~30-50 renders per page-navigation is a
# noticeable fixed cost. Matches the pattern settings_manager already
# uses for its own JSON.
ai_scraper_enabled = _ai_scraper_enabled_cached()
return {
'config': config,
'user_settings': user_settings,
'current_user': g.get('user'),
'current_user_settings': g.get('user_settings'),
'user_theme': _user_theme(g.get('user_settings')),
'has_permission': has_permission,
'get_avatar_url': get_avatar_url,
# Pass 34.6 — asset_url is already registered as a Jinja global
# at line 89, so it's available in every template including those
# rendered outside a request context (tests). Removed from
# inject_config to avoid double registration; the global wins.
'user_timezone': user_tz,
'csrf_token': session.get('_csrf_token', ''),
'ai_scraper_enabled': ai_scraper_enabled,
'rating_image_map_js': _RATING_IMG_MAP_JS,
'rating_system_names_js': _RATING_SYS_NAMES_JS,
'rating_system_keys': RATING_SYSTEM_KEYS,
'rating_to_tier_js': _RATING_TO_TIER_JS,
'tier_to_rating_js': _TIER_TO_RATING_JS,
'collector_rank': _get_collector_rank_safe(),
'csp_nonce': g.get('csp_nonce', ''),
}
def _get_collector_rank_safe():
"""Return the current collector rank, or a zeroed placeholder if the
trophies module / table isn't ready yet (e.g. first boot before the
table has been populated). The sidebar badge reads this on every
render, so it must never raise."""
try:
from routes.collector_trophies import get_current_rank
return get_current_rank()
except Exception:
return None
# =============================================================================
# HELPER FUNCTIONS FOR MAIN PAGES
# =============================================================================
def get_stats():
"""Get library statistics - optimized single query"""
try:
stats = query("""
SELECT
(SELECT COUNT(*) FROM systems) as total_systems,
(SELECT COUNT(*) FROM games) as total_games,
(SELECT COUNT(*) FROM games WHERE scraped = 1) as scraped_games,
(SELECT SUM(COALESCE(file_size, 0)) FROM games) as total_storage,
(SELECT COUNT(*) FROM games WHERE completion_status IN ('completed', '100_percent')) as completed_games,
(SELECT SUM(earned_achievements) FROM game_achievement_progress) as total_earned_achievements,
(SELECT SUM(total_achievements) FROM game_achievement_progress) as total_available_achievements
""", one=True)
total_games = stats['total_games'] or 0
completed = stats['completed_games'] or 0
completion_rate = round((completed / total_games * 100) if total_games > 0 else 0, 1)
# Parse HLTB playtime estimates to get total hours