diff --git a/.github/workflows/update-hltb-api-url.yml b/.github/workflows/update-hltb-api-url.yml new file mode 100644 index 000000000..c1c9ed636 --- /dev/null +++ b/.github/workflows/update-hltb-api-url.yml @@ -0,0 +1,43 @@ +name: Update HowLongToBeat API URL + +on: + workflow_dispatch: + +permissions: + contents: write + pull-requests: write + +jobs: + update-hltb-api-url: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install uv + uses: astral-sh/setup-uv@v6.7.0 + + - name: Install python + run: | + uv python install 3.13 + + - name: Install dependencies + run: | + uv sync + + - name: Run HLTB API URL discovery script + run: | + cd backend + uv run python -m utils.update_hltb_api_url + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v7 + with: + add-paths: | + backend/handler/metadata/fixtures/hltb_api_url + commit-message: "Update HLTB API URL [skip CI]" + branch: update-hltb-api-url + sign-commits: true + title: "Update HLTB API URL [skip CI]" + reviewers: | + gantoine diff --git a/backend/alembic/versions/0033_rom_file_and_hashes.py b/backend/alembic/versions/0033_rom_file_and_hashes.py index 7adb3b56e..b623227ab 100644 --- a/backend/alembic/versions/0033_rom_file_and_hashes.py +++ b/backend/alembic/versions/0033_rom_file_and_hashes.py @@ -24,6 +24,7 @@ def upgrade() -> None: if is_postgresql(connection): rom_file_category_enum = ENUM( + "GAME", "DLC", "HACK", "MANUAL", @@ -39,6 +40,7 @@ def upgrade() -> None: rom_file_category_enum.create(connection, checkfirst=False) else: rom_file_category_enum = sa.Enum( + "GAME", "DLC", "HACK", "MANUAL", diff --git a/backend/config/__init__.py b/backend/config/__init__.py index 6ea6d3ae3..2fca3cb0d 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -1,219 +1,221 @@ import os -from typing import Final +from typing import Final, overload import yarl from dotenv import load_dotenv +from utils.database import safe_int, safe_str_to_bool + load_dotenv() -def str_to_bool(value: str) -> bool: - return value.strip().lower() in ("1", "true", "yes", "on") +# Supplying a string literal for fallback guarantees a `str` result +@overload +def _get_env(var: str, fallback: str) -> str: ... +@overload +def _get_env(var: str, fallback: None = None) -> str | None: ... -ROMM_BASE_URL = os.environ.get("ROMM_BASE_URL", "http://0.0.0.0") -ROMM_PORT = int(os.environ.get("ROMM_PORT", 8080)) +def _get_env(var: str, fallback: str | None = None) -> str | None: + val = os.environ.get(var) or fallback + return val.strip() if val else val + + +ROMM_BASE_URL: Final[str] = _get_env("ROMM_BASE_URL", "http://0.0.0.0") +ROMM_PORT: Final[int] = safe_int(_get_env("ROMM_PORT"), 8080) # GUNICORN -DEV_MODE: Final = str_to_bool(os.environ.get("DEV_MODE", "false")) -DEV_HOST: Final = os.environ.get("DEV_HOST", "127.0.0.1") -DEV_PORT: Final = int(os.environ.get("DEV_PORT", "5000")) -DEV_SQL_ECHO: Final = str_to_bool(os.environ.get("DEV_SQL_ECHO", "false")) +DEV_MODE: Final[bool] = safe_str_to_bool(_get_env("DEV_MODE")) +DEV_HOST: Final[str] = _get_env("DEV_HOST", "127.0.0.1") +DEV_PORT: Final[int] = safe_int(_get_env("DEV_PORT"), 5000) +DEV_SQL_ECHO: Final[bool] = safe_str_to_bool(_get_env("DEV_SQL_ECHO")) # PATHS -ROMM_BASE_PATH: Final = os.environ.get("ROMM_BASE_PATH", "/romm") -ROMM_TMP_PATH: Final = os.environ.get("ROMM_TMP_PATH", None) -LIBRARY_BASE_PATH: Final = f"{ROMM_BASE_PATH}/library" -RESOURCES_BASE_PATH: Final = f"{ROMM_BASE_PATH}/resources" -ASSETS_BASE_PATH: Final = f"{ROMM_BASE_PATH}/assets" -FRONTEND_RESOURCES_PATH: Final = "/assets/romm/resources" +ROMM_BASE_PATH: Final[str] = _get_env("ROMM_BASE_PATH", "/romm") +ROMM_TMP_PATH: Final[str | None] = _get_env("ROMM_TMP_PATH") +LIBRARY_BASE_PATH: Final[str] = f"{ROMM_BASE_PATH}/library" +RESOURCES_BASE_PATH: Final[str] = f"{ROMM_BASE_PATH}/resources" +ASSETS_BASE_PATH: Final[str] = f"{ROMM_BASE_PATH}/assets" +FRONTEND_RESOURCES_PATH: Final[str] = "/assets/romm/resources" # SEVEN ZIP -SEVEN_ZIP_TIMEOUT: Final = int(os.environ.get("SEVEN_ZIP_TIMEOUT", 60)) +SEVEN_ZIP_TIMEOUT: Final[int] = safe_int(_get_env("SEVEN_ZIP_TIMEOUT"), 60) # DATABASE -DB_HOST: Final[str | None] = os.environ.get("DB_HOST", "127.0.0.1") or None -DB_PORT: Final[int | None] = ( - int(os.environ.get("DB_PORT", 3306)) if os.environ.get("DB_PORT") != "" else None -) -DB_USER: Final[str | None] = os.environ.get("DB_USER") -DB_PASSWD: Final[str | None] = os.environ.get("DB_PASSWD") -DB_NAME: Final[str] = os.environ.get("DB_NAME", "romm") -DB_QUERY_JSON: Final[str | None] = os.environ.get("DB_QUERY_JSON") -ROMM_DB_DRIVER: Final[str] = os.environ.get("ROMM_DB_DRIVER", "mariadb") +DB_HOST: Final[str] = _get_env("DB_HOST", "127.0.0.1") +DB_PORT: Final[int] = safe_int(_get_env("DB_PORT", "3306")) +DB_USER: Final[str | None] = _get_env("DB_USER") +DB_PASSWD: Final[str | None] = _get_env("DB_PASSWD") +DB_NAME: Final[str] = _get_env("DB_NAME", "romm") +DB_QUERY_JSON: Final[str | None] = _get_env("DB_QUERY_JSON") +ROMM_DB_DRIVER: Final[str] = _get_env("ROMM_DB_DRIVER", "mariadb") # REDIS -REDIS_HOST: Final = os.environ.get("REDIS_HOST", "127.0.0.1") -REDIS_PORT: Final = int(os.environ.get("REDIS_PORT", 6379)) -REDIS_PASSWORD: Final = os.environ.get("REDIS_PASSWORD") -REDIS_USERNAME: Final = os.environ.get("REDIS_USERNAME", "") -REDIS_DB: Final = int(os.environ.get("REDIS_DB", 0)) -REDIS_SSL: Final = str_to_bool(os.environ.get("REDIS_SSL", "false")) -REDIS_URL: Final = yarl.URL.build( - scheme="rediss" if REDIS_SSL else "redis", - user=REDIS_USERNAME or None, - password=REDIS_PASSWORD or None, - host=REDIS_HOST, - port=REDIS_PORT, - path=f"/{REDIS_DB}", +REDIS_HOST: Final[str] = _get_env("REDIS_HOST", "127.0.0.1") +REDIS_PORT: Final[int] = safe_int(_get_env("REDIS_PORT"), 6379) +REDIS_PASSWORD: Final[str | None] = _get_env("REDIS_PASSWORD") +REDIS_USERNAME: Final[str | None] = _get_env("REDIS_USERNAME") +REDIS_DB: Final[int] = safe_int(_get_env("REDIS_DB"), 0) +REDIS_SSL: Final[bool] = safe_str_to_bool(_get_env("REDIS_SSL")) +REDIS_URL: Final[str] = str( + yarl.URL.build( + scheme="rediss" if REDIS_SSL else "redis", + user=REDIS_USERNAME or None, + password=REDIS_PASSWORD or None, + host=REDIS_HOST, + port=REDIS_PORT, + path=f"/{REDIS_DB}", + ) ) # IGDB -IGDB_CLIENT_ID: Final[str] = os.environ.get( - "IGDB_CLIENT_ID", os.environ.get("CLIENT_ID", "") -).strip() -IGDB_CLIENT_SECRET: Final[str] = os.environ.get( - "IGDB_CLIENT_SECRET", os.environ.get("CLIENT_SECRET", "") -).strip() +IGDB_CLIENT_ID: Final[str | None] = _get_env("IGDB_CLIENT_ID") +IGDB_CLIENT_SECRET: Final[str | None] = _get_env("IGDB_CLIENT_SECRET") # MOBYGAMES -MOBYGAMES_API_KEY: Final[str] = os.environ.get("MOBYGAMES_API_KEY", "").strip() +MOBYGAMES_API_KEY: Final[str | None] = _get_env("MOBYGAMES_API_KEY") # SCREENSCRAPER -SCREENSCRAPER_USER: Final[str] = os.environ.get("SCREENSCRAPER_USER", "") -SCREENSCRAPER_PASSWORD: Final[str] = os.environ.get("SCREENSCRAPER_PASSWORD", "") +SCREENSCRAPER_USER: Final[str | None] = _get_env("SCREENSCRAPER_USER") +SCREENSCRAPER_PASSWORD: Final[str | None] = _get_env("SCREENSCRAPER_PASSWORD") # STEAMGRIDDB -STEAMGRIDDB_API_KEY: Final[str] = os.environ.get("STEAMGRIDDB_API_KEY", "").strip() +STEAMGRIDDB_API_KEY: Final[str | None] = _get_env("STEAMGRIDDB_API_KEY") # RETROACHIEVEMENTS -RETROACHIEVEMENTS_API_KEY: Final[str] = os.environ.get("RETROACHIEVEMENTS_API_KEY", "") -REFRESH_RETROACHIEVEMENTS_CACHE_DAYS: Final[int] = int( - os.environ.get("REFRESH_RETROACHIEVEMENTS_CACHE_DAYS", 30) +RETROACHIEVEMENTS_API_KEY: Final[str | None] = _get_env("RETROACHIEVEMENTS_API_KEY") +REFRESH_RETROACHIEVEMENTS_CACHE_DAYS: Final[int] = safe_int( + _get_env("REFRESH_RETROACHIEVEMENTS_CACHE_DAYS"), 30 ) # LAUNCHBOX -LAUNCHBOX_API_ENABLED: Final[bool] = str_to_bool( - os.environ.get("LAUNCHBOX_API_ENABLED", "false") -) +LAUNCHBOX_API_ENABLED: Final[bool] = safe_str_to_bool(_get_env("LAUNCHBOX_API_ENABLED")) # PLAYMATCH -PLAYMATCH_API_ENABLED: Final[bool] = str_to_bool( - os.environ.get("PLAYMATCH_API_ENABLED", "false") -) +PLAYMATCH_API_ENABLED: Final[bool] = safe_str_to_bool(_get_env("PLAYMATCH_API_ENABLED")) # HASHEOUS -HASHEOUS_API_ENABLED: Final[bool] = str_to_bool( - os.environ.get("HASHEOUS_API_ENABLED", "false") -) +HASHEOUS_API_ENABLED: Final[bool] = safe_str_to_bool(_get_env("HASHEOUS_API_ENABLED")) # THEGAMESDB -TGDB_API_ENABLED: Final[bool] = str_to_bool(os.environ.get("TGDB_API_ENABLED", "false")) +TGDB_API_ENABLED: Final[bool] = safe_str_to_bool(_get_env("TGDB_API_ENABLED")) # FLASHPOINT -FLASHPOINT_API_ENABLED: Final = str_to_bool( - os.environ.get("FLASHPOINT_API_ENABLED", "false") +FLASHPOINT_API_ENABLED: Final[bool] = safe_str_to_bool( + _get_env("FLASHPOINT_API_ENABLED") ) # HOWLONGTOBEAT -HLTB_API_ENABLED: Final = str_to_bool(os.environ.get("HLTB_API_ENABLED", "false")) +HLTB_API_ENABLED: Final[bool] = safe_str_to_bool(_get_env("HLTB_API_ENABLED")) # AUTH -ROMM_AUTH_SECRET_KEY: Final[str] = os.environ.get("ROMM_AUTH_SECRET_KEY", "") +ROMM_AUTH_SECRET_KEY: Final[str | None] = _get_env("ROMM_AUTH_SECRET_KEY") if not ROMM_AUTH_SECRET_KEY: raise ValueError("ROMM_AUTH_SECRET_KEY environment variable is not set!") -SESSION_MAX_AGE_SECONDS: Final = int( - os.environ.get("SESSION_MAX_AGE_SECONDS", 14 * 24 * 60 * 60) +SESSION_MAX_AGE_SECONDS: Final[int] = safe_int( + _get_env("SESSION_MAX_AGE_SECONDS"), 14 * 24 * 60 * 60 ) # 14 days, in seconds -DISABLE_CSRF_PROTECTION = str_to_bool( - os.environ.get("DISABLE_CSRF_PROTECTION", "false") +DISABLE_CSRF_PROTECTION: Final[bool] = safe_str_to_bool( + _get_env("DISABLE_CSRF_PROTECTION") ) -DISABLE_DOWNLOAD_ENDPOINT_AUTH = str_to_bool( - os.environ.get("DISABLE_DOWNLOAD_ENDPOINT_AUTH", "false") +DISABLE_DOWNLOAD_ENDPOINT_AUTH: Final[bool] = safe_str_to_bool( + _get_env("DISABLE_DOWNLOAD_ENDPOINT_AUTH") ) -DISABLE_USERPASS_LOGIN = str_to_bool(os.environ.get("DISABLE_USERPASS_LOGIN", "false")) -DISABLE_SETUP_WIZARD = str_to_bool(os.environ.get("DISABLE_SETUP_WIZARD", "false")) +DISABLE_USERPASS_LOGIN: Final[bool] = safe_str_to_bool( + _get_env("DISABLE_USERPASS_LOGIN") +) +DISABLE_SETUP_WIZARD: Final[bool] = safe_str_to_bool(_get_env("DISABLE_SETUP_WIZARD")) # OIDC -OIDC_ENABLED: Final = str_to_bool(os.environ.get("OIDC_ENABLED", "false")) -OIDC_PROVIDER: Final = os.environ.get("OIDC_PROVIDER", "") -OIDC_CLIENT_ID: Final = os.environ.get("OIDC_CLIENT_ID", "").strip() -OIDC_CLIENT_SECRET: Final = os.environ.get("OIDC_CLIENT_SECRET", "").strip() -OIDC_CLAIM_ROLES: Final = os.environ.get("OIDC_CLAIM_ROLES", "").strip() -OIDC_ROLE_VIEWER: Final = os.environ.get("OIDC_ROLE_VIEWER", "").strip() -OIDC_ROLE_EDITOR: Final = os.environ.get("OIDC_ROLE_EDITOR", "").strip() -OIDC_ROLE_ADMIN: Final = os.environ.get("OIDC_ROLE_ADMIN", "").strip() -OIDC_REDIRECT_URI: Final = os.environ.get("OIDC_REDIRECT_URI", "") -OIDC_SERVER_APPLICATION_URL: Final = os.environ.get("OIDC_SERVER_APPLICATION_URL", "") -OIDC_TLS_CACERTFILE: Final = os.environ.get("OIDC_TLS_CACERTFILE", None) +OIDC_ENABLED: Final[bool] = safe_str_to_bool(_get_env("OIDC_ENABLED")) +OIDC_PROVIDER: Final[str] = _get_env("OIDC_PROVIDER", "") +OIDC_CLIENT_ID: Final[str] = _get_env("OIDC_CLIENT_ID", "") +OIDC_CLIENT_SECRET: Final[str] = _get_env("OIDC_CLIENT_SECRET", "") +OIDC_REDIRECT_URI: Final[str] = _get_env("OIDC_REDIRECT_URI", "") +OIDC_SERVER_APPLICATION_URL: Final[str] = _get_env("OIDC_SERVER_APPLICATION_URL", "") +OIDC_CLAIM_ROLES: Final[str] = _get_env("OIDC_CLAIM_ROLES", "") +OIDC_ROLE_VIEWER: Final[str | None] = _get_env("OIDC_ROLE_VIEWER") +OIDC_ROLE_EDITOR: Final[str | None] = _get_env("OIDC_ROLE_EDITOR") +OIDC_ROLE_ADMIN: Final[str | None] = _get_env("OIDC_ROLE_ADMIN") +OIDC_TLS_CACERTFILE: Final[str | None] = _get_env("OIDC_TLS_CACERTFILE") # SCANS -SCAN_TIMEOUT: Final = int(os.environ.get("SCAN_TIMEOUT", 60 * 60 * 4)) # 4 hours -SCAN_WORKERS: Final = max(1, int(os.environ.get("SCAN_WORKERS", "1"))) +SCAN_TIMEOUT: Final[int] = safe_int(_get_env("SCAN_TIMEOUT"), 60 * 60 * 4) # 4 hours +SCAN_WORKERS: Final[int] = max(1, safe_int(_get_env("SCAN_WORKERS"), 1)) # TASKS -TASK_TIMEOUT: Final = int(os.environ.get("TASK_TIMEOUT", 60 * 5)) # 5 minutes -TASK_RESULT_TTL: Final = int( - os.environ.get("TASK_RESULT_TTL", 24 * 60 * 60) +TASK_TIMEOUT: Final[int] = safe_int(_get_env("TASK_TIMEOUT"), 60 * 5) # 5 minutes +TASK_RESULT_TTL: Final[int] = safe_int( + _get_env("TASK_RESULT_TTL"), 24 * 60 * 60 ) # 24 hours -ENABLE_RESCAN_ON_FILESYSTEM_CHANGE: Final = str_to_bool( - os.environ.get("ENABLE_RESCAN_ON_FILESYSTEM_CHANGE", "false") +ENABLE_RESCAN_ON_FILESYSTEM_CHANGE: Final[bool] = safe_str_to_bool( + _get_env("ENABLE_RESCAN_ON_FILESYSTEM_CHANGE") ) -RESCAN_ON_FILESYSTEM_CHANGE_DELAY: Final = int( - os.environ.get("RESCAN_ON_FILESYSTEM_CHANGE_DELAY", 5) # 5 minutes +RESCAN_ON_FILESYSTEM_CHANGE_DELAY: Final[int] = safe_int( + _get_env("RESCAN_ON_FILESYSTEM_CHANGE_DELAY"), 5 # 5 minutes ) -ENABLE_SCHEDULED_RESCAN: Final = str_to_bool( - os.environ.get("ENABLE_SCHEDULED_RESCAN", "false") +ENABLE_SCHEDULED_RESCAN: Final[bool] = safe_str_to_bool( + _get_env("ENABLE_SCHEDULED_RESCAN") ) -SCHEDULED_RESCAN_CRON: Final = os.environ.get( +SCHEDULED_RESCAN_CRON: Final[str] = _get_env( "SCHEDULED_RESCAN_CRON", "0 3 * * *", # At 3:00 AM every day ) -ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB: Final = str_to_bool( - os.environ.get("ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB", "false") +ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB: Final[bool] = safe_str_to_bool( + _get_env("ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB") ) -SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON: Final = os.environ.get( +SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON: Final[str] = _get_env( "SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON", "0 4 * * *", # At 4:00 AM every day ) -ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA: Final = str_to_bool( - os.environ.get("ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA", "false") +ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA: Final[bool] = safe_str_to_bool( + _get_env("ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA") ) -SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON: Final = os.environ.get( +SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON: Final[str] = _get_env( "SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON", "0 4 * * *", # At 4:00 AM every day ) -ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP: Final = str_to_bool( - os.environ.get("ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP", "false") +ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP: Final[bool] = safe_str_to_bool( + _get_env("ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP") ) -SCHEDULED_CONVERT_IMAGES_TO_WEBP_CRON: Final = os.environ.get( +SCHEDULED_CONVERT_IMAGES_TO_WEBP_CRON: Final[str] = _get_env( "SCHEDULED_CONVERT_IMAGES_TO_WEBP_CRON", "0 4 * * *", # At 4:00 AM every day ) -ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC: Final[bool] = str_to_bool( - os.environ.get("ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC", "false") +ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC: Final[bool] = safe_str_to_bool( + _get_env("ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC") ) -SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON: Final[str] = os.environ.get( +SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON: Final[str] = _get_env( "SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON", "0 4 * * *", # At 4:00 AM every day ) # EMULATION -DISABLE_EMULATOR_JS = str_to_bool(os.environ.get("DISABLE_EMULATOR_JS", "false")) -DISABLE_RUFFLE_RS = str_to_bool(os.environ.get("DISABLE_RUFFLE_RS", "false")) +DISABLE_EMULATOR_JS: Final[bool] = safe_str_to_bool(_get_env("DISABLE_EMULATOR_JS")) +DISABLE_RUFFLE_RS: Final[bool] = safe_str_to_bool(_get_env("DISABLE_RUFFLE_RS")) # FRONTEND -UPLOAD_TIMEOUT = int(os.environ.get("UPLOAD_TIMEOUT", 600)) -KIOSK_MODE = str_to_bool(os.environ.get("KIOSK_MODE", "false")) +UPLOAD_TIMEOUT: Final[int] = safe_int(_get_env("UPLOAD_TIMEOUT"), 600) +KIOSK_MODE: Final[bool] = safe_str_to_bool(_get_env("KIOSK_MODE")) # LOGGING -LOGLEVEL: Final = os.environ.get("LOGLEVEL", "INFO").upper() -FORCE_COLOR: Final = str_to_bool(os.environ.get("FORCE_COLOR", "false")) -NO_COLOR: Final = str_to_bool(os.environ.get("NO_COLOR", "false")) +LOGLEVEL: Final[str] = _get_env("LOGLEVEL", "INFO").upper() +FORCE_COLOR: Final[bool] = safe_str_to_bool(_get_env("FORCE_COLOR")) +NO_COLOR: Final[bool] = safe_str_to_bool(_get_env("NO_COLOR")) # YOUTUBE -YOUTUBE_BASE_URL: Final = os.environ.get( +YOUTUBE_BASE_URL: Final[str] = _get_env( "YOUTUBE_BASE_URL", "https://www.youtube.com" ).rstrip("/") # TINFOIL -TINFOIL_WELCOME_MESSAGE: Final = os.environ.get( +TINFOIL_WELCOME_MESSAGE: Final[str] = _get_env( "TINFOIL_WELCOME_MESSAGE", "RomM Switch Library" ) # SENTRY -SENTRY_DSN: Final = os.environ.get("SENTRY_DSN", None) +SENTRY_DSN: Final[str | None] = _get_env("SENTRY_DSN") # TESTING -IS_PYTEST_RUN: Final = bool(os.environ.get("PYTEST_VERSION", False)) +IS_PYTEST_RUN: Final = bool(_get_env("PYTEST_VERSION")) diff --git a/backend/endpoints/collections.py b/backend/endpoints/collections.py index 0cbc91edf..4cae8badf 100644 --- a/backend/endpoints/collections.py +++ b/backend/endpoints/collections.py @@ -214,6 +214,9 @@ def get_collection(request: Request, id: int) -> CollectionSchema: if not collection: raise CollectionNotFoundInDatabaseException(id) + if collection.user_id != request.user.id and not collection.is_public: + raise CollectionPermissionError(id) + return CollectionSchema.model_validate(collection) @@ -252,6 +255,9 @@ def get_smart_collection(request: Request, id: int) -> SmartCollectionSchema: if not smart_collection: raise CollectionNotFoundInDatabaseException(id) + if smart_collection.user_id != request.user.id and not smart_collection.is_public: + raise CollectionPermissionError(id) + return SmartCollectionSchema.model_validate(smart_collection) @@ -408,6 +414,9 @@ async def delete_collection( collection = db_collection_handler.get_collection(id) if not collection: raise CollectionNotFoundInDatabaseException(id) + + if collection.user_id != request.user.id: + raise CollectionPermissionError(id) log.info(f"Deleting {hl(collection.name, color=BLUE)} from database") db_collection_handler.delete_collection(id) diff --git a/backend/endpoints/feeds.py b/backend/endpoints/feeds.py index 3a53a234c..11905f21a 100644 --- a/backend/endpoints/feeds.py +++ b/backend/endpoints/feeds.py @@ -1,22 +1,23 @@ from collections.abc import Sequence +from datetime import datetime from typing import Annotated from urllib.parse import quote from fastapi import HTTPException from fastapi import Path as PathVar from fastapi import Request -from fastapi.responses import Response +from fastapi.responses import JSONResponse, Response from starlette.datastructures import URLPath from config import ( DISABLE_DOWNLOAD_ENDPOINT_AUTH, - FRONTEND_RESOURCES_PATH, TINFOIL_WELCOME_MESSAGE, ) from decorators.auth import protected_route from endpoints.responses.feeds import ( WEBRCADE_SLUG_TO_TYPE_MAP, WEBRCADE_SUPPORTED_PLATFORM_SLUGS, + FPKGiFeedItemSchema, KekatsuDSItemSchema, PKGiFeedPS3ItemSchema, PKGiFeedPSPItemSchema, @@ -105,17 +106,13 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema: rom=download_url, ), ) - if rom.path_cover_s: + if rom.path_cover_small: category_item["thumbnail"] = str( - URLPath( - f"{FRONTEND_RESOURCES_PATH}/{rom.path_cover_s}" - ).make_absolute_url(request.base_url) + URLPath(rom.path_cover_small).make_absolute_url(request.base_url) ) - if rom.path_cover_l: + if rom.path_cover_large: category_item["background"] = str( - URLPath( - f"{FRONTEND_RESOURCES_PATH}/{rom.path_cover_l}" - ).make_absolute_url(request.base_url) + URLPath(rom.path_cover_large).make_absolute_url(request.base_url) ) category_items.append(category_item) @@ -181,10 +178,11 @@ async def tinfoil_index_feed( tdb_match = SWITCH_TITLEDB_REGEX.search(rom.fs_name) pid_match = SWITCH_PRODUCT_ID_REGEX.search(rom.fs_name) if tdb_match: - _search_term, index_entry = ( - await meta_igdb_handler._switch_titledb_format( - tdb_match, rom.fs_name - ) + ( + _search_term, + index_entry, + ) = await meta_igdb_handler._switch_titledb_format( + tdb_match, rom.fs_name ) if index_entry: key = str(index_entry.get("nsuId", None)) @@ -193,10 +191,11 @@ async def tinfoil_index_feed( **index_entry ).model_dump() elif pid_match: - _search_term, index_entry = ( - await meta_igdb_handler._switch_productid_format( - pid_match, rom.fs_name - ) + ( + _search_term, + index_entry, + ) = await meta_igdb_handler._switch_productid_format( + pid_match, rom.fs_name ) if index_entry: key = str(index_entry.get("nsuId", None)) @@ -476,6 +475,59 @@ def pkgi_psp_feed( ) +def _format_release_date(timestamp: int | None) -> str | None: + """Format release date to MM-DD-YYYY format""" + if not timestamp: + return None + + return datetime.fromtimestamp(timestamp / 1000).strftime("%m-%d-%Y") + + +@protected_route( + router.get, + "/fpkgi/{platform_slug}", + [] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ], +) +def fpkgi_feed(request: Request, platform_slug: str) -> Response: + """ + https://github.com/ItsJokerZz/FPKGi + + Args: + request (Request): Fastapi Request object + platform_slug (str): Platform slug (ps4, ps5) + + Returns: + Response: JSON file in FPKGi format + """ + platform = db_platform_handler.get_platform_by_fs_slug(platform_slug) + if not platform: + raise HTTPException( + status_code=404, detail=f"Platform {platform_slug} not found" + ) + + roms = db_rom_handler.get_roms_scalar(platform_id=platform.id) + response_data = {} + + for rom in roms: + download_url = generate_rom_download_url(request, rom) + response_data[download_url] = FPKGiFeedItemSchema( + name=rom.name or rom.fs_name, + size=rom.fs_size_bytes, + region=rom.regions[0] if rom.regions else None, + version=rom.revision or None, + release=_format_release_date(rom.metadatum.first_release_date), + min_fw=None, + cover_url=str( + URLPath(rom.path_cover_large).make_absolute_url(request.base_url) + ), + ).model_dump() + + return JSONResponse( + content={"DATA": response_data}, + headers={"Cache-Control": "no-cache"}, + ) + + @protected_route( router.get, "/kekatsu/{platform_slug}", diff --git a/backend/endpoints/responses/feeds.py b/backend/endpoints/responses/feeds.py index 7043e56c8..0f2166ffe 100644 --- a/backend/endpoints/responses/feeds.py +++ b/backend/endpoints/responses/feeds.py @@ -213,6 +213,18 @@ class PKGiFeedPSVitaItemSchema(BaseModel): checksum: str +# FPKGi feed format +# Source: https://github.com/ItsJokerZz/FPKGi +class FPKGiFeedItemSchema(BaseModel): + name: str + size: int + region: str | None + version: str | None + release: str | None + min_fw: str | None + cover_url: str | None + + # Kekatsu DS feed format # Source: https://github.com/cavv-dev/Kekatsu-DS class KekatsuDSItemSchema(BaseModel): diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index d4e2a93b9..b5d5426c6 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -36,7 +36,6 @@ from config import ( DEV_MODE, DISABLE_DOWNLOAD_ENDPOINT_AUTH, LIBRARY_BASE_PATH, - str_to_bool, ) from decorators.auth import protected_route from endpoints.responses import BulkOperationResponse @@ -66,7 +65,7 @@ from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log from models.rom import Rom -from utils.database import safe_int +from utils.database import safe_int, safe_str_to_bool from utils.filesystem import sanitize_filename from utils.hashing import crc32_to_hex from utils.nginx import FileRedirectResponse, ZipContentLine, ZipResponse @@ -567,7 +566,7 @@ async def get_rom_content( raise RomNotFoundInDatabaseException(id) # https://muos.dev/help/addcontent#what-about-multi-disc-content - hidden_folder = str_to_bool(request.query_params.get("hidden_folder", "")) + hidden_folder = safe_str_to_bool(request.query_params.get("hidden_folder", "")) files = list(db_rom_handler.get_rom_files(rom.id)) if file_ids: @@ -930,21 +929,24 @@ async def update_rom( "path_cover_l": path_cover_l, } ) + else: + cleaned_data.update({"url_cover": rom.url_cover}) - if data.get( - "url_manual", "" - ) != rom.url_manual or not fs_resource_handler.manual_exists(rom): + url_manual = data.get("url_manual", rom.url_manual) + if url_manual != rom.url_manual or not fs_resource_handler.manual_exists(rom): path_manual = await fs_resource_handler.get_manual( rom=rom, overwrite=True, - url_manual=str(data.get("url_manual") or ""), + url_manual=url_manual, ) cleaned_data.update( { - "url_manual": data.get("url_manual", rom.url_manual), + "url_manual": url_manual, "path_manual": path_manual, } ) + else: + cleaned_data.update({"url_manual": rom.url_manual}) # Handle RetroAchievements badges when the ID has changed if cleaned_data["ra_id"] and int(cleaned_data["ra_id"]) != rom.ra_id: @@ -1052,6 +1054,13 @@ async def add_rom_manuals( try: async for chunk in request.stream(): parser.data_received(chunk) + + db_rom_handler.update_rom( + id, + { + "path_manual": f"{manuals_path}/{rom.id}.pdf", + }, + ) except ClientDisconnect: log.error("Client disconnected during upload") cleanup_partial_file() @@ -1063,17 +1072,6 @@ async def add_rom_manuals( detail="There was an error uploading the manual", ) from exc - path_manual = await fs_resource_handler.get_manual( - rom=rom, overwrite=False, url_manual=None - ) - - db_rom_handler.update_rom( - id, - { - "path_manual": path_manual, - }, - ) - return Response() diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index 08be4ca26..8dbbe0965 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -102,7 +102,7 @@ class ScanStats: def _get_socket_manager() -> socketio.AsyncRedisManager: """Connect to external socketio server""" - return socketio.AsyncRedisManager(str(REDIS_URL), write_only=True) + return socketio.AsyncRedisManager(REDIS_URL, write_only=True) async def _identify_firmware( diff --git a/backend/handler/auth/middleware/csrf_middleware.py b/backend/handler/auth/middleware/csrf_middleware.py new file mode 100644 index 000000000..09168dc09 --- /dev/null +++ b/backend/handler/auth/middleware/csrf_middleware.py @@ -0,0 +1,169 @@ +# Original source: https://github.com/frankie567/starlette-csrf +# Copyright (c) 2021 Sebastien Delisle +# MIT License + +import functools +import http.cookies +import secrets +from re import Pattern +from typing import Optional, cast + +from itsdangerous import BadSignature +from itsdangerous.url_safe import URLSafeSerializer +from starlette.datastructures import URL, MutableHeaders +from starlette.requests import Request +from starlette.responses import PlainTextResponse, Response +from starlette.types import ASGIApp, Message, Receive, Scope, Send + + +class CSRFMiddleware: + def __init__( + self, + app: ASGIApp, + secret: str, + *, + required_urls: Optional[list[Pattern]] = None, + exempt_urls: Optional[list[Pattern]] = None, + sensitive_cookies: Optional[set[str]] = None, + safe_methods: Optional[set[str]] = None, + cookie_name: str = "csrftoken", + cookie_path: str = "/", + cookie_domain: Optional[str] = None, + cookie_secure: bool = False, + cookie_httponly: bool = False, + cookie_samesite: str = "lax", + header_name: str = "x-csrftoken", + ) -> None: + if safe_methods is None: + safe_methods = {"GET", "HEAD", "OPTIONS", "TRACE"} + + self.app = app + self.serializer = URLSafeSerializer(secret, "csrftoken") + self.secret = secret + self.required_urls = required_urls + self.exempt_urls = exempt_urls + self.sensitive_cookies = sensitive_cookies + self.safe_methods = safe_methods + self.cookie_name = cookie_name + self.cookie_path = cookie_path + self.cookie_domain = cookie_domain + self.cookie_secure = cookie_secure + self.cookie_httponly = cookie_httponly + self.cookie_samesite = cookie_samesite + self.header_name = header_name + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + # Skip CSRF check if not an HTTP request, like websockets + if scope["type"] != "http": + await self.app(scope, receive, send) + return None + + request = Request(scope, receive) + + # Skip CSRF check if Authorization header is present + auth_scheme = request.headers.get("Authorization", "").split(" ", 1)[0].lower() + if auth_scheme == "bearer" or auth_scheme == "basic": + await self.app(scope, receive, send) + return None + + csrf_cookie = request.cookies.get(self.cookie_name) + + if self._url_is_required(request.url) or ( + request.method not in self.safe_methods + and not self._url_is_exempt(request.url) + and self._has_sensitive_cookies(request.cookies) + ): + submitted_csrf_token = await self._get_submitted_csrf_token(request) + current_user_id = request.user.id if request.user.is_authenticated else None + if ( + not csrf_cookie + or not submitted_csrf_token + or not self._csrf_tokens_match( + csrf_cookie, submitted_csrf_token, current_user_id + ) + ): + response = self._get_error_response(request) + await response(scope, receive, send) + return + + send = functools.partial(self.send, send=send, scope=scope) + await self.app(scope, receive, send) + + async def send(self, message: Message, send: Send, scope: Scope) -> None: + request = Request(scope) + csrf_cookie = request.cookies.get(self.cookie_name) + + if csrf_cookie is None: + message.setdefault("headers", []) + headers = MutableHeaders(scope=message) + + cookie: http.cookies.BaseCookie = http.cookies.SimpleCookie() + cookie_name = self.cookie_name + cookie[cookie_name] = self._generate_csrf_token( + request.user.id if request.user.is_authenticated else None + ) + cookie[cookie_name]["path"] = self.cookie_path + cookie[cookie_name]["secure"] = self.cookie_secure + cookie[cookie_name]["httponly"] = self.cookie_httponly + cookie[cookie_name]["samesite"] = self.cookie_samesite + if self.cookie_domain is not None: + cookie[cookie_name]["domain"] = self.cookie_domain # pragma: no cover + headers.append("set-cookie", cookie.output(header="").strip()) + + await send(message) + + def _has_sensitive_cookies(self, cookies: dict[str, str]) -> bool: + if not self.sensitive_cookies: + return True + for sensitive_cookie in self.sensitive_cookies: + if sensitive_cookie in cookies: + return True + return False + + def _url_is_required(self, url: URL) -> bool: + if not self.required_urls: + return False + for required_url in self.required_urls: + if required_url.match(url.path): + return True + return False + + def _url_is_exempt(self, url: URL) -> bool: + if not self.exempt_urls: + return False + for exempt_url in self.exempt_urls: + if exempt_url.match(url.path): + return True + return False + + async def _get_submitted_csrf_token(self, request: Request) -> Optional[str]: + return request.headers.get(self.header_name) + + def _generate_csrf_token(self, user_id: int | None = None) -> str: + obj = {"token": secrets.token_urlsafe(128), "user_id": user_id} + return cast(str, self.serializer.dumps(obj)) + + def _csrf_tokens_match( + self, document_cookie: str, header_cookie: str, user_id: int | None + ) -> bool: + try: + decoded_doc_cookie = self.serializer.loads(document_cookie) + decoded_header_cookie = self.serializer.loads(header_cookie) + + # Verify that the tokens match, the user IDs match + # and the user_id matches the authenticated user + return ( + secrets.compare_digest( + decoded_doc_cookie["token"], decoded_header_cookie["token"] + ) + and decoded_doc_cookie["user_id"] == decoded_header_cookie["user_id"] + and decoded_doc_cookie["user_id"] == user_id + and decoded_header_cookie["user_id"] == user_id + ) + except (TypeError, BadSignature): + return False + + def _get_error_response(self, request: Request) -> Response: + return PlainTextResponse( + content="CSRF token verification failed", status_code=403 + ) diff --git a/backend/handler/auth/middleware.py b/backend/handler/auth/middleware/session_middleware.py similarity index 86% rename from backend/handler/auth/middleware.py rename to backend/handler/auth/middleware/session_middleware.py index efc624189..032c104d7 100644 --- a/backend/handler/auth/middleware.py +++ b/backend/handler/auth/middleware/session_middleware.py @@ -5,31 +5,11 @@ from joserfc import jwt from joserfc.errors import BadSignatureError from joserfc.jwk import OctKey from starlette.datastructures import MutableHeaders, Secret -from starlette.requests import HTTPConnection, Request +from starlette.requests import HTTPConnection from starlette.types import ASGIApp, Message, Receive, Scope, Send -from starlette_csrf.middleware import CSRFMiddleware from config import SESSION_MAX_AGE_SECONDS - -class CustomCSRFMiddleware(CSRFMiddleware): - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - # Skip CSRF check if not an HTTP request, like websockets - if scope["type"] != "http": - await self.app(scope, receive, send) - return None - - request = Request(scope, receive) - - # Skip CSRF check if Authorization header is present - auth_scheme = request.headers.get("Authorization", "").split(" ", 1)[0].lower() - if auth_scheme == "bearer" or auth_scheme == "basic": - await self.app(scope, receive, send) - return None - - await super().__call__(scope, receive, send) - - SecretKey = namedtuple("SecretKey", ("encode", "decode")) diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index 968fd73b5..11c0237bc 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -19,6 +19,10 @@ from utils.filesystem import iter_directories, iter_files TAG_REGEX = re.compile(r"\(([^)]+)\)|\[([^]]+)\]") EXTENSION_REGEX = re.compile(r"\.(([a-z]+\.)*\w+)$") +UUID_V4_REGEX = re.compile( + r"[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}", + re.IGNORECASE, +) LANGUAGES = ( ("Af", "Afrikaans"), @@ -215,6 +219,10 @@ class FSHandler: match = EXTENSION_REGEX.search(file_name) return match.group(1) if match else "" + def extract_uuid_v4_from_filename(self, file_name: str) -> str: + match = UUID_V4_REGEX.search(file_name) + return match.group(0) if match else "" + def exclude_single_files(self, files: list[str]) -> list[str]: excluded_extensions = cm.get_config().EXCLUDED_SINGLE_EXT excluded_names = cm.get_config().EXCLUDED_SINGLE_FILES diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index fdfca012c..b5ee0c05e 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -9,7 +9,7 @@ import zipfile import zlib from collections.abc import Callable, Iterator from pathlib import Path -from typing import IO, Any, Final, Literal, TypedDict +from typing import IO, Any, Final, Literal, TypedDict, cast import magic import zipfile_inflate64 # trunk-ignore(ruff/F401): Patches zipfile to support Enhanced Deflate @@ -58,6 +58,18 @@ COMPRESSED_FILE_EXTENSIONS = frozenset( ) ) +# CHD (Compressed Hunks of Data) v5 format constants +# See: https://github.com/mamedev/mame/blob/master/src/lib/util/chd.h +CHD_SIGNATURE: Final = b"MComprHD" +CHD_SIGNATURE_LENGTH: Final = 8 +CHD_MIN_HEADER_LENGTH: Final = 16 # Minimum to read signature and version +CHD_V5_HEADER_LENGTH: Final = 124 # Total v5 header size +CHD_VERSION_OFFSET: Final = 12 # Bytes offset for version field +CHD_VERSION_LENGTH: Final = 4 # Version is a uint32 +CHD_V5_SHA1_OFFSET: Final = 84 # Combined raw+meta SHA1 offset in v5 +CHD_V5_SHA1_LENGTH: Final = 20 # SHA1 is 20 bytes +CHD_V5_VERSION: Final = 5 # CHD v5 identifier + NON_HASHABLE_PLATFORMS = frozenset( ( UPS.AMAZON_ALEXA, @@ -182,6 +194,92 @@ def read_bz2_file(file_path: Path) -> Iterator[bytes]: yield chunk +def extract_chd_hash(file_path: Path) -> str | None: + """ + Extract the embedded SHA1 hash from a CHD (Compressed Hunks of Data) v5 file header. + + Only CHD v5 files are supported, matching MAMERedump's database. + + CHD v5 files store the combined raw+meta SHA1 hash in the header. + This hash is what ROM databases use for CHD identification, since it includes + metadata like CD track layouts which are essential for proper disc image + identification. + + For reference, check out "chd.h" in the MAME source tree. + + ---------------------------------- Why? ---------------------------------- + CHDMAN does not produce nor guarantee stable, byte-for-byte identical + outputs for a given disc image. (Including HD images.) + + For this reason, the CHD format embeds the original source data hash in + its header, allowing different CHD files to be verified as equivalent + even when their compressed representations differ. + -------------------------------------------------------------------------- + + Args: + file_path: Path to the CHD file + + Returns: + SHA1 hash as hex string, or None if file is not a valid CHD v5 file or parsing fails + """ + try: + with open(file_path, "rb") as f: + # Read the v5 header and extract the embedded SHA1 + header = f.read(CHD_V5_HEADER_LENGTH) + + # Check for "MComprHD" signature + if ( + len(header) < CHD_MIN_HEADER_LENGTH + or header[:CHD_SIGNATURE_LENGTH] != CHD_SIGNATURE + ): + return None + + # Extract and verify version (big-endian uint32) + version_end = CHD_VERSION_OFFSET + CHD_VERSION_LENGTH + version = int.from_bytes(header[CHD_VERSION_OFFSET:version_end], "big") + + # Only support v5 CHD files + if version != CHD_V5_VERSION: + return None + + # Extract combined raw+meta SHA1 from v5 header + sha1_end = CHD_V5_SHA1_OFFSET + CHD_V5_SHA1_LENGTH + if len(header) < sha1_end: + return None + sha1_bytes = header[CHD_V5_SHA1_OFFSET:sha1_end] + return sha1_bytes.hex() + except OSError: + return None + + +class CHDHashWrapper: + """ + Wrapper class that mimics hashlib hash objects but returns a pre-computed hash. + + This class provides a hashlib-compatible interface for pre-computed hashes + extracted from CHD v5 file headers. It implements the same methods and attributes + as hashlib hash objects (digest(), hexdigest(), update(), and name). + """ + + def __init__(self, hash_hex: str, name: str): + self.hash_hex = hash_hex + self.name = name + # Store the digest as bytes + self._digest = bytes.fromhex(hash_hex) + + def hexdigest(self) -> str: + """Return the hash as a hexadecimal string.""" + return self.hash_hex + + def digest(self) -> bytes: + """Return the hash as bytes.""" + return self._digest + + def update(self, data: bytes | bytearray) -> None: + """No-op update method for compatibility with hashlib interface.""" + pass + + def category_matches(category: str, path_parts: list[str]): return category in path_parts or f"{category}s" in path_parts @@ -504,6 +602,17 @@ class FSRomsHandler(FSHandler): for chunk in read_bz2_file(file_path): update_hashes(chunk) + elif extension == ".chd" or file_type == "application/x-mame-chd": + chd_hash = extract_chd_hash(file_path) + if chd_hash: + sha1_h = cast(Any, CHDHashWrapper(chd_hash, name="sha1")) + rom_sha1_h = cast(Any, CHDHashWrapper(chd_hash, name="sha1")) + else: + # Not a valid v5 CHD, treat as basic file + # This ensures CRC32 and MD5 are still calculated for non-v5 CHDs + for chunk in read_basic_file(file_path): + update_hashes(chunk) + else: for chunk in read_basic_file(file_path): update_hashes(chunk) diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index 023cf84c6..9602bd02c 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -54,6 +54,21 @@ class BaseRom(TypedDict): url_manual: NotRequired[str] +SENSITIVE_KEYS = { + "Authorization", + "Client-ID", + "Client-Secret", + "client_id", + "client_secret", + "api_key", + "ssid", + "sspassword", + "devid", + "devpassword", + "y", +} + + # This caches results to avoid repeated normalization of the same search term @lru_cache(maxsize=1024) def _normalize_search_term( @@ -232,47 +247,24 @@ class MetadataHandler(abc.ABC): return search_term - def _mask_sensitive_values(self, values: dict[str, str]) -> dict[str, str]: + def _mask_sensitive_values(self, values: dict[str, str | None]) -> dict[str, str]: """ - Mask sensitive values (headers or params), leaving only the first 3 and last 3 characters of the token. - This is valid for a dictionary with any of the following keys: - - "Authorization" (Bearer token) - - "Client-ID" - - "Client-Secret" - - "client_id" - - "client_secret" - - "api_key" - - "ssid" - - "sspassword" - - "devid" - - "devpassword" - - "y" (RA API key) + Mask sensitive values (headers or params), leaving only the first 2 and last 2 characters of the token. """ - return { - key: ( - f"Bearer {values[key].split(' ')[1][:2]}***{values[key].split(' ')[1][-2:]}" - if key == "Authorization" and values[key].startswith("Bearer ") - else ( - f"{values[key][:2]}***{values[key][-2:]}" - if key - in { - "Client-ID", - "Client-Secret", - "client_id", - "client_secret", - "api_key", - "ssid", - "sspassword", - "devid", - "devpassword", - "y", - } - # Leave other keys unchanged - else values[key] - ) - ) - for key in values - } + masked_keys: dict[str, str] = {} + for key, val in values.items(): + if val is None: + masked_keys[key] = "" + continue + + if key == "Authorization" and val.startswith("Bearer "): + token = val.split(" ", 1)[1] + masked_keys[key] = f"Bearer {token[:2]}***{token[-2:]}" + elif key in SENSITIVE_KEYS: + masked_keys[key] = f"{val[:2]}***{val[-2:]}" + else: + masked_keys[key] = val + return masked_keys class UniversalPlatformSlug(enum.StrEnum): diff --git a/backend/handler/metadata/fixtures/hltb_api_url b/backend/handler/metadata/fixtures/hltb_api_url index 60057e260..06f903bfa 100644 --- a/backend/handler/metadata/fixtures/hltb_api_url +++ b/backend/handler/metadata/fixtures/hltb_api_url @@ -1 +1 @@ -https://howlongtobeat.com/api/locate/417443a51685d24b +https://howlongtobeat.com/api/locate/45b48b2d1685d24b \ No newline at end of file diff --git a/backend/handler/metadata/flashpoint_handler.py b/backend/handler/metadata/flashpoint_handler.py index ea0371645..fd91a8694 100644 --- a/backend/handler/metadata/flashpoint_handler.py +++ b/backend/handler/metadata/flashpoint_handler.py @@ -245,12 +245,14 @@ class FlashpointHandler(MetadataHandler): # Check if the filename is a UUID fs_name_no_tags = fs_rom_handler.get_file_name_with_no_tags(fs_name) - if is_valid_uuid(fs_name_no_tags): - return await self.get_rom_by_id(flashpoint_id=fs_name_no_tags) + file_uuid = fs_rom_handler.extract_uuid_v4_from_filename(fs_name_no_tags) + if is_valid_uuid(file_uuid): + return await self.get_rom_by_id(flashpoint_id=file_uuid) # Normalize the search term - search_term = fs_rom_handler.get_file_name_with_no_tags(fs_name) - search_term = self.normalize_search_term(search_term, remove_punctuation=False) + search_term = self.normalize_search_term( + fs_name_no_tags, remove_punctuation=False + ) # Search for games games = await self.search_games(search_term) diff --git a/backend/handler/metadata/launchbox_handler.py b/backend/handler/metadata/launchbox_handler.py index 5da3de952..c8cd5f6eb 100644 --- a/backend/handler/metadata/launchbox_handler.py +++ b/backend/handler/metadata/launchbox_handler.py @@ -5,9 +5,10 @@ from typing import Final, NotRequired, TypedDict import pydash -from config import LAUNCHBOX_API_ENABLED, str_to_bool +from config import LAUNCHBOX_API_ENABLED from handler.redis_handler import async_cache from logger.logger import log +from utils.database import safe_str_to_bool from .base_handler import BaseRom, MetadataHandler from .base_handler import UniversalPlatformSlug as UPS @@ -91,7 +92,7 @@ def extract_metadata_from_launchbox_rom( "first_release_date": first_release_date, "max_players": int(index_entry.get("MaxPlayers") or 0), "release_type": index_entry.get("ReleaseType", ""), - "cooperative": str_to_bool(index_entry.get("Cooperative") or "false"), + "cooperative": safe_str_to_bool(index_entry.get("Cooperative") or "false"), "youtube_video_id": extract_video_id_from_youtube_url( index_entry.get("VideoURL") ), diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 796a42537..910243960 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -18,7 +18,7 @@ class QueuePrio(Enum): LOW = "low" -redis_client = Redis.from_url(str(REDIS_URL)) +redis_client = Redis.from_url(REDIS_URL) high_prio_queue = Queue(name=QueuePrio.HIGH.value, connection=redis_client) default_queue = Queue(name=QueuePrio.DEFAULT.value, connection=redis_client) @@ -33,7 +33,7 @@ def __get_sync_cache() -> Redis: return FakeRedis(version=7) # A separate client that auto-decodes responses is needed - client = Redis.from_url(str(REDIS_URL), decode_responses=True) + client = Redis.from_url(REDIS_URL, decode_responses=True) log.debug( f"Sync redis/valkey connection established in {os.path.splitext(os.path.basename(sys.argv[0]))[0]}" ) @@ -48,7 +48,7 @@ def __get_async_cache() -> AsyncRedis: return FakeAsyncRedis(version=7) # A separate client that auto-decodes responses is needed - client = AsyncRedis.from_url(str(REDIS_URL), decode_responses=True) + client = AsyncRedis.from_url(REDIS_URL, decode_responses=True) log.debug( f"Async redis/valkey connection established in {os.path.splitext(os.path.basename(sys.argv[0]))[0]}" ) diff --git a/backend/handler/socket_handler.py b/backend/handler/socket_handler.py index 03bed53f3..239ee2c99 100644 --- a/backend/handler/socket_handler.py +++ b/backend/handler/socket_handler.py @@ -1,7 +1,7 @@ import socketio # type: ignore from config import REDIS_URL -from utils import json as json_module +from utils import json_module class SocketHandler: @@ -12,7 +12,7 @@ class SocketHandler: json=json_module, logger=False, engineio_logger=False, - client_manager=socketio.AsyncRedisManager(str(REDIS_URL)), + client_manager=socketio.AsyncRedisManager(REDIS_URL), ping_timeout=60, ping_interval=25, max_http_buffer_size=1e6, # 1MB diff --git a/backend/main.py b/backend/main.py index b81478723..0331b78ad 100644 --- a/backend/main.py +++ b/backend/main.py @@ -44,7 +44,8 @@ from endpoints import ( ) from handler.auth.constants import ALGORITHM from handler.auth.hybrid_auth import HybridAuthBackend -from handler.auth.middleware import CustomCSRFMiddleware, SessionMiddleware +from handler.auth.middleware.csrf_middleware import CSRFMiddleware +from handler.auth.middleware.session_middleware import SessionMiddleware from handler.socket_handler import socket_handler from logger.formatter import LOGGING_CONFIG from utils import get_version @@ -90,7 +91,7 @@ app.add_middleware( if not IS_PYTEST_RUN and not DISABLE_CSRF_PROTECTION: # CSRF protection (except endpoints listed in exempt_urls) app.add_middleware( - CustomCSRFMiddleware, + CSRFMiddleware, cookie_name="romm_csrftoken", secret=ROMM_AUTH_SECRET_KEY, exempt_urls=[re.compile(r"^/api/token.*"), re.compile(r"^/ws")], diff --git a/backend/tests/handler/auth/test_csrf_middleware.py b/backend/tests/handler/auth/test_csrf_middleware.py new file mode 100644 index 000000000..ecef1767a --- /dev/null +++ b/backend/tests/handler/auth/test_csrf_middleware.py @@ -0,0 +1,277 @@ +import asyncio +import re + +from itsdangerous import URLSafeSerializer +from starlette.applications import Starlette +from starlette.authentication import AuthCredentials, AuthenticationBackend +from starlette.middleware import Middleware +from starlette.middleware.authentication import AuthenticationMiddleware +from starlette.requests import Request +from starlette.responses import JSONResponse, PlainTextResponse +from starlette.routing import Route +from starlette.testclient import TestClient + +from config import ROMM_AUTH_SECRET_KEY +from handler.auth.constants import ALGORITHM +from handler.auth.middleware.csrf_middleware import CSRFMiddleware +from handler.auth.middleware.session_middleware import SessionMiddleware +from models.user import User + + +class BasicAuthBackend(AuthenticationBackend): + async def authenticate(self, conn): + return AuthCredentials(["authenticated"]), User(id=1, username="user_1") + + +# Test app factory +def create_test_app(**csrf_kwargs) -> Starlette: + """Return a Starlette app wired with CSRFMiddleware.""" + + async def get_handler(request: Request) -> PlainTextResponse: + return PlainTextResponse("OK") + + async def post_handler(request: Request) -> JSONResponse: + return JSONResponse({"status": "success"}) + + async def post_echo(request: Request) -> JSONResponse: + """Return the CSRF token that was sent.""" + token = request.headers.get(csrf_kwargs.get("header_name", "x-csrftoken")) + return JSONResponse({"token": token}) + + routes = [ + Route("/get", get_handler, methods=["GET", "HEAD", "OPTIONS", "TRACE"]), + Route("/post", post_handler, methods=["POST"]), + Route("/echo", post_echo, methods=["POST"]), + ] + middleware = [ + Middleware(AuthenticationMiddleware, backend=BasicAuthBackend()), + Middleware(CSRFMiddleware, secret="test-secret", **csrf_kwargs), + Middleware( + SessionMiddleware, + secret_key=ROMM_AUTH_SECRET_KEY, + session_cookie="romm_session", + same_site="strict", + https_only=False, + jwt_alg=ALGORITHM, + ), + ] + return Starlette(routes=routes, middleware=middleware) + + +class TestCSRFMiddleware: + def test_csrf_cookie_set_on_first_get(self) -> None: + """A GET request should set the CSRF cookie if none exists.""" + app = create_test_app() + client = TestClient(app) + + response = client.get("/get") + assert response.status_code == 200 + assert "csrftoken" in response.cookies + + def test_post_with_valid_token_succeeds(self) -> None: + """POST with correct CSRF header should pass.""" + app = create_test_app() + client = TestClient(app) + + # Obtain cookie + resp = client.get("/get") + cookie = resp.cookies["csrftoken"] + + # Post with token + resp = client.post("/post", headers={"x-csrftoken": cookie}) + assert resp.status_code == 200 + assert resp.json()["status"] == "success" + + def test_post_without_cookie_fails(self) -> None: + """POST without CSRF cookie should fail.""" + app = create_test_app() + client = TestClient(app) + + resp = client.post("/post") + assert resp.status_code == 403 + assert "CSRF token verification failed" in resp.text + + def test_post_without_header_fails(self) -> None: + """POST without CSRF header should fail.""" + app = create_test_app() + client = TestClient(app) + + # Obtain cookie but don't send header + client.get("/get") + resp = client.post("/post") + assert resp.status_code == 403 + + def test_post_with_bad_signature_fails(self) -> None: + """POST with tampered token should fail.""" + app = create_test_app() + client = TestClient(app) + + client.get("/get") + bad_token = "tampered-token" + resp = client.post("/post", headers={"x-csrftoken": bad_token}) + assert resp.status_code == 403 + + def test_safe_methods_bypass_csrf(self) -> None: + """GET/HEAD/OPTIONS/TRACE should never require CSRF.""" + app = create_test_app() + client = TestClient(app) + + for method in ("GET", "HEAD", "OPTIONS", "TRACE"): + resp = client.request(method, "/get") + assert resp.status_code == 200 + + def test_custom_header_name(self) -> None: + """Middleware should read the token from the configured header.""" + header_name = "x-xsrf-token" + app = create_test_app(header_name=header_name) + client = TestClient(app) + + cookie_resp = client.get("/get") + token = cookie_resp.cookies["csrftoken"] + + # Send with custom header + resp = client.post("/echo", headers={header_name: token}) + assert resp.status_code == 200 + assert resp.json()["token"] == token + + def test_custom_cookie_name(self) -> None: + """Middleware should use the configured cookie name.""" + cookie_name = "my_token" + app = create_test_app(cookie_name=cookie_name) + client = TestClient(app) + + resp = client.get("/get") + assert cookie_name in resp.cookies + + def test_cookie_attributes(self) -> None: + """Verify Secure, HttpOnly, SameSite, Path, Domain attributes.""" + app = create_test_app( + cookie_secure=True, + cookie_httponly=True, + cookie_samesite="strict", + cookie_path="/app", + cookie_domain=".example.com", + ) + client = TestClient(app) + + resp = client.get("/get") + set_cookie = resp.headers["set-cookie"].lower() + assert "secure" in set_cookie + assert "httponly" in set_cookie + assert "samesite=strict" in set_cookie + assert "path=/app" in set_cookie + assert "domain=.example.com" in set_cookie + + def test_exempt_urls(self) -> None: + """POST to exempt URLs should not require CSRF.""" + app = create_test_app(exempt_urls=[re.compile(r"^/post$")]) + client = TestClient(app) + + # No cookie/header needed + resp = client.post("/post") + assert resp.status_code == 200 + + def test_required_urls(self) -> None: + """POST to required URLs should always require CSRF even for safe methods.""" + app = create_test_app(required_urls=[re.compile(r"^/get$")], safe_methods=set()) + client = TestClient(app) + + # GET now requires token + resp = client.get("/get") + assert resp.status_code == 403 + + def test_sensitive_cookies(self) -> None: + """If no sensitive cookies exist, CSRF is not enforced.""" + app = create_test_app(sensitive_cookies={"session"}) + client = TestClient(app) + + # No sensitive cookie → POST allowed + resp = client.post("/post") + assert resp.status_code == 200 + + # Add sensitive cookie → POST blocked + client.cookies.set("session", "abc123") + resp = client.post("/post") + assert resp.status_code == 403 + + # Bypass rules # + def test_bearer_auth_bypass(self) -> None: + """Requests with Bearer/Basic Authorization header bypass CSRF.""" + app = create_test_app() + client = TestClient(app) + + resp = client.post("/post", headers={"Authorization": "Bearer token"}) + assert resp.status_code == 200 + + def test_non_http_scope_bypass(self) -> None: + """WebSocket (or other non-HTTP) scopes should pass through.""" + # Manual ASGI call; TestClient doesn't expose WebSocket easily + scope = {"type": "websocket", "path": "/ws", "headers": []} + + async def receive(): + return {} + + async def send(msg): + pass + + async def dummy_app(scope, receive, send): + await send({"type": "websocket.accept"}) + + middleware = CSRFMiddleware(dummy_app, secret="test") + asyncio.run(middleware(scope, receive, send)) # should not raise + + def test_token_generation_and_validation(self) -> None: + """Ensure tokens are signed and validated correctly.""" + app = create_test_app() + client = TestClient(app) + + # Extract cookie + resp = client.get("/get") + cookie = resp.cookies["csrftoken"] + + # Verify signature + serializer = URLSafeSerializer("test-secret", "csrftoken") + payload = serializer.loads(cookie) + assert "token" in payload + assert "user_id" in payload + + # Send same token back + resp = client.post("/echo", headers={"x-csrftoken": cookie}) + assert resp.status_code == 200 + assert resp.json()["token"] == cookie + + def test_user_id_mismatch_fails(self) -> None: + """Tokens issued for one user must not validate for another.""" + # We simulate two users by calling _generate_csrf_token with different IDs + mw = CSRFMiddleware(app=lambda s, r, se: None, secret="test") + user1_token = mw._generate_csrf_token(user_id=1) + + # user1_token should not validate for user_id=2 + assert not mw._csrf_tokens_match(user1_token, user1_token, user_id=2) + + def test_post_with_mismatched_but_valid_tokens_fails(self) -> None: + """POST with a valid header token that doesn't match the cookie token should fail.""" + app = create_test_app() + client = TestClient(app) + + # Obtain first token + resp1 = client.get("/get") + cookie1 = resp1.cookies["csrftoken"] + + # Obtain second token by clearing cookies to simulate a new session + client.cookies.clear() + resp2 = client.get("/get") + cookie2 = resp2.cookies["csrftoken"] + + assert cookie1 != cookie2 + + # Try to post with cookie from first session and header from second + client.cookies.set("csrftoken", cookie1) + resp = client.post("/post", headers={"x-csrftoken": cookie2}) + assert resp.status_code == 403 + + def test_bad_signature_returns_false(self) -> None: + """_csrf_tokens_match should return False on BadSignature.""" + mw = CSRFMiddleware(app=lambda s, r, se: None, secret="test") + ok = mw._csrf_tokens_match("bad-token", "bad-token", user_id=None) + assert ok is False diff --git a/backend/tests/handler/auth/test_session_middleware.py b/backend/tests/handler/auth/test_session_middleware.py new file mode 100644 index 000000000..89ff9a5c0 --- /dev/null +++ b/backend/tests/handler/auth/test_session_middleware.py @@ -0,0 +1,353 @@ +""" +Test suite for SessionMiddleware using JWT-based session management. +""" + +import time + +from joserfc import jwt +from joserfc.jwk import OctKey +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.requests import Request +from starlette.responses import JSONResponse, PlainTextResponse +from starlette.routing import Route +from starlette.testclient import TestClient + +from handler.auth.middleware.session_middleware import SessionMiddleware + + +def create_test_app(**middleware_kwargs) -> Starlette: + # Test app routes + async def homepage(request: Request) -> PlainTextResponse: + """Basic route that sets default session data.""" + request.session.setdefault("visited", 0) + request.session["visited"] += 1 + return PlainTextResponse("OK") + + async def set_session(request: Request) -> JSONResponse: + """Set specific session data.""" + data = await request.json() + request.session.update(data) + return JSONResponse({"session": dict(request.session)}) + + async def get_session(request: Request) -> JSONResponse: + """Get current session data.""" + return JSONResponse({"session": dict(request.session)}) + + async def clear_session_route(request: Request) -> PlainTextResponse: + """Clear the session.""" + request.session.clear() + return PlainTextResponse("Session cleared") + + async def modify_session(request: Request) -> JSONResponse: + """Modify session with provided data.""" + data = await request.json() + for key, value in data.items(): + if value is None: + request.session.pop(key, None) + else: + request.session[key] = value + return JSONResponse({"session": dict(request.session)}) + + """Create a test app with SessionMiddleware.""" + routes = [ + Route("/", homepage), + Route("/set", set_session, methods=["POST"]), + Route("/get", get_session), + Route("/clear", clear_session_route), + Route("/modify", modify_session, methods=["POST"]), + ] + kwargs = {"secret_key": "test-secret-key", **middleware_kwargs} + middleware = [Middleware(SessionMiddleware, **kwargs)] + return Starlette(routes=routes, middleware=middleware) + + +class TestSessionMiddleware: + def test_session_creation(self) -> None: + """Test that a session cookie is set on the first request.""" + app = create_test_app() + client = TestClient(app) + + response = client.get("/") + assert response.status_code == 200 + assert "session" in response.cookies + assert response.text == "OK" + + def test_session_reading(self) -> None: + """Test that session data can be read from the cookie on subsequent requests.""" + app = create_test_app() + client = TestClient(app) + + # First request sets session + response = client.get("/") + assert response.status_code == 200 + + # Second request should read the session + response = client.get("/get") + assert response.status_code == 200 + data = response.json() + assert "visited" in data["session"] + assert data["session"]["visited"] == 1 + + def test_session_modification(self) -> None: + """Test that session data can be modified and persisted across requests.""" + app = create_test_app() + client = TestClient(app) + + response = client.post("/set", json={"user": "test_user", "role": "admin"}) + assert response.status_code == 200 + assert response.json()["session"]["user"] == "test_user" + + response = client.get("/get") + assert response.status_code == 200 + data = response.json() + assert data["session"]["user"] == "test_user" + assert data["session"]["role"] == "admin" + + def test_session_clearing(self) -> None: + """Test that clearing the session removes the cookie.""" + app = create_test_app() + client = TestClient(app) + + response = client.post("/set", json={"user": "test_user"}) + assert response.status_code == 200 + + # Clear session + response = client.get("/clear") + assert response.status_code == 200 + + # Verify session is cleared + response = client.get("/get") + assert response.status_code == 200 + data = response.json() + assert data["session"] == {} + + def test_session_max_age(self) -> None: + """Test that the Max-Age attribute is set correctly.""" + max_age = 3600 + app = create_test_app(max_age=max_age) + client = TestClient(app) + + response = client.get("/") + assert response.status_code == 200 + + set_cookie_header = response.headers.get("set-cookie", "") + assert f"Max-Age={max_age}" in set_cookie_header + + def test_session_https_only(self) -> None: + """Test that the secure flag is set when https_only is True.""" + app = create_test_app(https_only=True) + client = TestClient(app) + + response = client.get("/") + assert response.status_code == 200 + + set_cookie_header = response.headers.get("set-cookie", "") + assert "secure" in set_cookie_header + + def test_session_same_site(self) -> None: + """Test that the samesite attribute is set correctly.""" + app = create_test_app(same_site="strict") + client = TestClient(app) + + response = client.get("/") + assert response.status_code == 200 + + set_cookie_header = response.headers.get("set-cookie", "") + assert "samesite=strict" in set_cookie_header + + def test_session_expiration_past(self) -> None: + """Test that an expired session is not loaded and a new one is created.""" + app = create_test_app() + client = TestClient(app) + + # Build a token that expired one hour ago + expired = int(time.time()) - 3600 + payload = {"user": "test_user", "exp": expired} + key = OctKey.import_key("test-secret-key") + token = jwt.encode({"alg": "HS256"}, payload, key=key) + + response = client.get("/get", cookies={"session": token}) + assert response.status_code == 200 + # middleware must reject the expired token → empty session + assert response.json()["session"] == {} + + def test_session_not_before_future(self) -> None: + """Test that a session with a 'not before' claim in the future is ignored.""" + app = create_test_app() + client = TestClient(app) + + # Build a token that is not valid until tomorrow + nbf = int(time.time()) + 86400 + payload = {"user": "test_user", "nbf": nbf} + key = OctKey.import_key("test-secret-key") + token = jwt.encode({"alg": "HS256"}, payload, key=key) + + response = client.get("/get", cookies={"session": token}) + assert response.status_code == 200 + # middleware must reject the future token → empty session + assert response.json()["session"] == {} + + def test_session_bad_signature(self) -> None: + """Test that a session with a bad signature is ignored and a new session is created.""" + app = create_test_app() + client = TestClient(app) + + # Create a session + response = client.post("/set", json={"user": "test_user"}) + assert response.status_code == 200 + + # Tamper with the cookie (simulate bad signature) + tampered_cookie = response.cookies["session"][:-10] + "tampereddata" + response = client.get("/get", cookies={"session": tampered_cookie}) + assert response.status_code == 200 + data = response.json() + + # Should have a new empty session, not the tampered one + assert "user" not in data["session"] + + def test_session_cookie_name(self) -> None: + """Test that custom session cookie name works.""" + custom_cookie_name = "my_session" + app = create_test_app(session_cookie=custom_cookie_name) + client = TestClient(app) + + response = client.get("/") + assert response.status_code == 200 + assert custom_cookie_name in response.cookies + assert "session" not in response.cookies + + def test_session_jwt_algorithm(self) -> None: + """Test that custom JWT algorithm works.""" + app = create_test_app(jwt_alg="HS256") + client = TestClient(app) + + response = client.post("/set", json={"user": "test_user"}) + assert response.status_code == 200 + + token = response.cookies["session"] + decoded = jwt.decode( + token, + key=OctKey.import_key("test-secret-key"), + algorithms=["HS256"], + ) + assert decoded.header["alg"] == "HS256" + + def test_session_data_modification(self) -> None: + """Test that session data can be modified correctly.""" + app = create_test_app() + client = TestClient(app) + + # Set initial data + response = client.post("/set", json={"counter": 1, "name": "Alice"}) + assert response.status_code == 200 + + # Modify data + response = client.post("/modify", json={"counter": 2, "name": None}) + assert response.status_code == 200 + data = response.json() + assert data["session"]["counter"] == 2 + assert "name" not in data["session"] # Should be removed + + # Verify changes persist + response = client.get("/get") + assert response.status_code == 200 + data = response.json() + assert data["session"]["counter"] == 2 + assert "name" not in data["session"] + + def test_session_empty_on_first_visit(self) -> None: + """Test that session is empty on first visit.""" + app = create_test_app() + client = TestClient(app) + + response = client.get("/get") + assert response.status_code == 200 + data = response.json() + assert data["session"] == {} + + def test_session_visits_counter(self) -> None: + """Test that the visits counter increments correctly.""" + app = create_test_app() + client = TestClient(app) + + # First visit + response = client.get("/") + assert response.status_code == 200 + + response = client.get("/get") + data = response.json() + assert data["session"]["visited"] == 1 + + # Second visit + response = client.get("/") + assert response.status_code == 200 + + response = client.get("/get") + data = response.json() + assert data["session"]["visited"] == 2 + + def test_session_with_special_characters(self) -> None: + """Test that session data with special characters works correctly.""" + app = create_test_app() + client = TestClient(app) + + special_data = { + "emoji": "🚀", + "unicode": "你好世界", + "special": "test@#$%^&*()", + "nested": {"list": [1, 2, 3], "dict": {"a": 1}}, + } + + response = client.post("/set", json=special_data) + assert response.status_code == 200 + + response = client.get("/get") + assert response.status_code == 200 + + data = response.json() + assert data["session"]["emoji"] == special_data["emoji"] + assert data["session"]["unicode"] == special_data["unicode"] + assert data["session"]["special"] == special_data["special"] + assert data["session"]["nested"] == special_data["nested"] + + +def test_full_session_lifecycle(): + """Test the complete lifecycle of a session.""" + app = create_test_app(max_age=3600) + client = TestClient(app) + + # Start with no session + response = client.get("/get") + assert response.status_code == 200 + assert response.json()["session"] == {} + + # Create a session + response = client.post("/set", json={"user": "test_user", "role": "user"}) + assert response.status_code == 200 + + # Verify session persists + response = client.get("/get") + assert response.status_code == 200 + data = response.json() + assert data["session"]["user"] == "test_user" + assert data["session"]["role"] == "user" + + # Modify session + response = client.post("/modify", json={"role": "admin"}) + assert response.status_code == 200 + + # Verify modification + response = client.get("/get") + assert response.status_code == 200 + data = response.json() + assert data["session"]["role"] == "admin" + + # Clear session + response = client.get("/clear") + assert response.status_code == 200 + + # Verify session is cleared + response = client.get("/get") + assert response.status_code == 200 + assert response.json()["session"] == {} diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index 2c0e957a8..6a8a80611 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1,11 +1,17 @@ import os +import shutil from pathlib import Path from unittest.mock import Mock import pytest from config.config_manager import LIBRARY_BASE_PATH, Config -from handler.filesystem.roms_handler import FileHash, FSRomsHandler +from handler.filesystem.roms_handler import ( + CHDHashWrapper, + FileHash, + FSRomsHandler, + extract_chd_hash, +) from models.platform import Platform from models.rom import Rom, RomFile, RomFileCategory @@ -623,3 +629,533 @@ class TestFSRomsHandler: assert ( rom_sha1 != translation_rom_file.sha1_hash ), "Main ROM hash should not include translation file" + + @pytest.mark.asyncio + async def test_get_rom_files_with_chd_v5_uses_internal_hash( + self, handler: FSRomsHandler, platform, tmp_path + ): + """Test that a CHD v5 file uses its internal hash and skips other hashing. + + This integration test verifies the complete CHD v5 hashing logic: + 1. For valid CHD v5 files, the embedded SHA1 hash from the file header is used + 2. CRC32 and MD5 hashes are NOT calculated from file contents + 3. The file is not double-processed by read_basic_file + 4. This prevents regressions in the if/elif archive type chain + """ + # Create a mock CHD v5 file in a temporary directory + chd_file = tmp_path / "test.chd" + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + internal_sha1 = "0123456789abcdef0123456789abcdef01234567" + header[84:104] = bytes.fromhex(internal_sha1) + chd_file.write_bytes( + header + b"This is extra file data to ensure file is not empty" + ) + + # Set up handler and rom object to point to the mock file + roms_path = tmp_path / platform.fs_slug / "roms" + roms_path.mkdir(parents=True) + shutil.copy(chd_file, roms_path / "test.chd") + + # Create a new handler instance with temp base path + test_handler = FSRomsHandler() + test_handler.base_path = tmp_path + + rom = Rom( + id=1, + fs_name="test.chd", + fs_path=str(roms_path.relative_to(tmp_path)), + platform=platform, + ) + + # Run the hashing process + rom_files, crc_hash, md5_hash, sha1_hash, _ = await test_handler.get_rom_files( + rom + ) + + # Assert that only SHA1 is populated, and it's from the header + assert len(rom_files) == 1 + assert sha1_hash == internal_sha1, "SHA1 should be from CHD v5 header" + assert rom_files[0].sha1_hash == internal_sha1 + + # CRC32 and MD5 should be empty/zero (not calculated) + assert crc_hash == "", f"CRC hash should be empty, got: {crc_hash}" + assert md5_hash == "", f"MD5 hash should be empty, got: {md5_hash}" + assert rom_files[0].crc_hash == "" + assert rom_files[0].md5_hash == "" + + @pytest.mark.asyncio + async def test_get_rom_files_with_non_v5_chd_fallback_to_std_hashing( + self, handler: FSRomsHandler, platform, tmp_path + ): + """Test that non-v5 CHD files fall back to standard file hashing. + + This ensures backward compatibility: if a .chd file is not version 5 + or doesn't have a valid v5 header, it should be treated as a regular + file and all hashes (CRC32, MD5, SHA1) are calculated from content. + """ + # Create a CHD v4 file (should not use internal hash logic) + chd_file = tmp_path / "old_format.chd" + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(4).to_bytes(4, "big") # Version 4, not 5 + + # Add some content + content = header + b"This is CHD v4 data that should be hashed as a normal file" + chd_file.write_bytes(content) + + # Set up handler and rom object + roms_path = tmp_path / platform.fs_slug / "roms" + roms_path.mkdir(parents=True) + shutil.copy(chd_file, roms_path / "old_format.chd") + + test_handler = FSRomsHandler() + test_handler.base_path = tmp_path + + rom = Rom( + id=1, + fs_name="old_format.chd", + fs_path=str(roms_path.relative_to(tmp_path)), + platform=platform, + ) + + # Run the hashing process + rom_files, crc_hash, md5_hash, sha1_hash, _ = await test_handler.get_rom_files( + rom + ) + + # All hashes should be populated (calculated from file content) + assert len(rom_files) == 1 + assert crc_hash != "", "CRC hash should be calculated for non-v5 CHD" + assert md5_hash != "", "MD5 hash should be calculated for non-v5 CHD" + assert sha1_hash != "", "SHA1 hash should be calculated for non-v5 CHD" + + # Verify they're actual hash values (not from an internal header) + assert rom_files[0].crc_hash == crc_hash + assert rom_files[0].md5_hash == md5_hash + assert rom_files[0].sha1_hash == sha1_hash + + +class TestExtractCHDHash: + """Test suite for extract_chd_hash function""" + + def test_extract_chd_hash_v5_valid(self, tmp_path): + """Test extracting hash from a valid CHD v5 file""" + chd_file = tmp_path / "test_v5.chd" + + # CHD v5 header structure (124 bytes minimum): + # Bytes 0-7: "MComprHD" magic signature + # Bytes 12-15: Version (5 in big-endian) + # Bytes 84-103: SHA1 hash (20 bytes) + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + # Use a test SHA1 hash + header[84:104] = bytes.fromhex("0123456789abcdef0123456789abcdef01234567") + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result is not None + assert isinstance(result, str) + assert len(result) == 40 # SHA1 hex is 40 characters + assert result == "0123456789abcdef0123456789abcdef01234567" + + def test_extract_chd_hash_v1_rejected(self, tmp_path): + """Test that CHD v1 files are rejected""" + chd_file = tmp_path / "test_v1.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(1).to_bytes(4, "big") # Version 1 + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result is None + + def test_extract_chd_hash_v2_rejected(self, tmp_path): + """Test that CHD v2 files are rejected""" + chd_file = tmp_path / "test_v2.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(2).to_bytes(4, "big") # Version 2 + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result is None + + def test_extract_chd_hash_v3_rejected(self, tmp_path): + """Test that CHD v3 files are rejected""" + chd_file = tmp_path / "test_v3.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(3).to_bytes(4, "big") # Version 3 + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result is None + + def test_extract_chd_hash_v4_rejected(self, tmp_path): + """Test that CHD v4 files are rejected""" + chd_file = tmp_path / "test_v4.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(4).to_bytes(4, "big") # Version 4 + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result is None + + def test_extract_chd_hash_invalid_magic(self, tmp_path): + """Test that files without CHD magic signature are rejected""" + chd_file = tmp_path / "invalid_magic.bin" + + header = bytearray(124) + header[0:8] = b"BadMagic" # Not "MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result is None + + def test_extract_chd_hash_truncated_header(self, tmp_path): + """Test that CHD v5 file with truncated header is rejected""" + chd_file = tmp_path / "truncated.chd" + + # Only write 100 bytes instead of required 124 + header = bytearray(100) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result is None + + def test_extract_chd_hash_nonexistent_file(self, tmp_path): + """Test that non-existent files are handled gracefully""" + nonexistent = tmp_path / "does_not_exist.chd" + + result = extract_chd_hash(nonexistent) + + assert result is None + + def test_extract_chd_hash_empty_file(self, tmp_path): + """Test that empty files are rejected""" + chd_file = tmp_path / "empty.chd" + chd_file.write_bytes(b"") + + result = extract_chd_hash(chd_file) + + assert result is None + + def test_extract_chd_hash_sha1_format(self, tmp_path): + """Test that SHA1 hash is correctly formatted as hex""" + chd_file = tmp_path / "test_format.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + + # Use a known SHA1 value + test_sha1 = bytes.fromhex("356a192b7913b04c54574d18c28d46e6395428ab") + header[84:104] = test_sha1 + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result == "356a192b7913b04c54574d18c28d46e6395428ab" + # Verify it's lowercase hex + assert result == result.lower() + # Verify it's 40 characters (SHA1 is 20 bytes = 40 hex chars) + assert len(result) == 40 + + def test_extract_chd_hash_with_wrapper(self, tmp_path): + """Test that extracted hash integrates properly with CHDHashWrapper""" + chd_file = tmp_path / "test_wrapper.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + test_sha1 = bytes.fromhex("0123456789abcdef0123456789abcdef01234567") + header[84:104] = test_sha1 + + chd_file.write_bytes(header) + + extracted_hash = extract_chd_hash(chd_file) + assert extracted_hash is not None + + # Should be usable with CHDHashWrapper + wrapper = CHDHashWrapper(extracted_hash, "sha1") + assert wrapper.hexdigest() == extracted_hash + assert len(wrapper.digest()) == 20 + # Verify digest bytes match the original + assert wrapper.digest() == test_sha1 + + def test_extract_chd_hash_unknown_version(self, tmp_path): + """Test that unknown CHD versions are rejected""" + chd_file = tmp_path / "test_unknown.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(99).to_bytes(4, "big") # Unknown version + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result is None + + def test_extract_chd_hash_multiple_different_hashes(self, tmp_path): + """Test that different SHA1 hashes are correctly extracted""" + test_cases = [ + "0000000000000000000000000000000000000000", + "ffffffffffffffffffffffffffffffffffffffff", + "356a192b7913b04c54574d18c28d46e6395428ab", + "da39a3ee5e6b4b0d3255bfef95601890afd80709", + ] + + for i, test_hash in enumerate(test_cases): + chd_file = tmp_path / f"test_hash_{i}.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + header[84:104] = bytes.fromhex(test_hash) + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result == test_hash, f"Hash mismatch for test case {i}" + + def test_extract_chd_hash_version_boundary_cases(self, tmp_path): + """Test version checking at boundaries (0, 1, 4, 5, 6)""" + test_versions = [ + (0, None), # Version 0 should return None + (1, None), # Version 1 should return None + (4, None), # Version 4 should return None + (5, "0123456789abcdef0123456789abcdef01234567"), # Version 5 should work + (6, None), # Version 6 should return None + ] + + for version, expected in test_versions: + chd_file = tmp_path / f"test_v{version}.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(version).to_bytes(4, "big") + header[84:104] = bytes.fromhex("0123456789abcdef0123456789abcdef01234567") + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + if expected is None: + assert result is None, f"Version {version} should return None" + else: + assert result == expected, f"Version {version} should return {expected}" + + def test_extract_chd_hash_file_too_short_for_magic(self, tmp_path): + """Test file that's too short to even contain magic + version""" + chd_file = tmp_path / "too_short.chd" + + # Only 8 bytes - has magic but no version + header = bytearray(8) + header[0:8] = b"MComprHD" + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result is None + + def test_extract_chd_hash_permission_error(self, tmp_path): + """Test graceful handling of permission errors""" + chd_file = tmp_path / "no_read_permission.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + + chd_file.write_bytes(header) + + # Remove read permissions + chd_file.chmod(0o000) + + try: + result = extract_chd_hash(chd_file) + assert result is None + finally: + # Restore permissions for cleanup + chd_file.chmod(0o644) + + def test_extract_chd_hash_real_header(self, tmp_path): + """Test extracting hash from real Pebble Beach Golf Links CHD v5 header + + This uses the actual 128-byte header from: + Pebble Beach Golf Links - Stadler ni Chousen (Japan).chd + + Header bytes (hex): + 00000000: 4d43 6f6d 7072 4844 0000 007c 0000 0005 MComprHD...|.... + 00000010: 6364 6c7a 6364 7a6c 6364 666c 0000 0000 cdlzcdzlcdfl.... + 00000020: 0000 0000 1a97 4e00 0000 0000 1119 b3d0 ......N......... + 00000030: 0000 0000 0000 007c 0000 4c80 0000 0990 .......|..L..... + 00000040: 8389 486c 34df 316d 1fd3 3997 a3ef ce8c ..Hl4.1m..9..... + 00000050: e9c9 6008 0167 fc76 f9e4 312e 6ab4 8fe9 ..`..g.v..1.j... + 00000060: 80d2 ce5b 23f7 75c2 0000 0000 0000 0000 ...[#.u......... + 00000070: 0000 0000 0000 0000 0000 0000 4348 5432 ............CHT2 + + The SHA1 hash (combined raw+meta) at bytes 84-103 is: + 0167 fc76 f9e4 312e 6ab4 8fe9 80d2 ce5b 23f7 75c2 + """ + chd_file = tmp_path / "Pebble Beach.chd" + + # Real 128-byte header from the file + real_header = bytes.fromhex( + "4d43 6f6d 7072 4844 0000 007c 0000 0005 " + "6364 6c7a 6364 7a6c 6364 666c 0000 0000 " + "0000 0000 1a97 4e00 0000 0000 1119 b3d0 " + "0000 0000 0000 007c 0000 4c80 0000 0990 " + "8389 486c 34df 316d 1fd3 3997 a3ef ce8c " + "e9c9 6008 0167 fc76 f9e4 312e 6ab4 8fe9 " + "80d2 ce5b 23f7 75c2 0000 0000 0000 0000 " + "0000 0000 0000 0000 0000 0000 4348 5432" + ) + + chd_file.write_bytes(real_header) + + result = extract_chd_hash(chd_file) + + # Expected SHA1 from the header at bytes 84-103 (20 bytes, as per chd.h) + expected_sha1 = "0167fc76f9e4312e6ab48fe980d2ce5b23f775c2" + + assert result is not None + assert result == expected_sha1 + assert len(result) == 40 + # Verify it matches what's in the header + assert bytes.fromhex(result) == real_header[84:104] + + def test_extract_chd_hash_with_extra_metadata(self, tmp_path): + """Test CHD v5 file with additional metadata beyond header + + Real CHD files often have map data and metadata after the 124-byte header. + The hash extraction should work correctly regardless of file size. + """ + chd_file = tmp_path / "test_with_metadata.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + test_sha1 = bytes.fromhex("0167fc76f9e4312e6ab48fe980d2ce5b23f775c2") + header[84:104] = test_sha1 + + # Write header plus extra data (simulating map and metadata) + extra_data = b"MAP_DATACOMPRESSED_DATA_GOES_HERE" * 100 + + chd_file.write_bytes(header + extra_data) + + result = extract_chd_hash(chd_file) + + assert result is not None + assert result == "0167fc76f9e4312e6ab48fe980d2ce5b23f775c2" + assert bytes.fromhex(result) == test_sha1 + + def test_extract_chd_hash_off_by_one_header_sizes(self, tmp_path): + """Test boundary conditions around minimum required header size (104 bytes)""" + test_cases = [ + (103, None), # 103 bytes - not enough for SHA1 region + ( + 104, + "0167fc76f9e4312e6ab48fe980d2ce5b23f775c2", + ), # 104 bytes - exactly enough + (123, "0167fc76f9e4312e6ab48fe980d2ce5b23f775c2"), # 123 bytes + (124, "0167fc76f9e4312e6ab48fe980d2ce5b23f775c2"), # Full v5 header + (125, "0167fc76f9e4312e6ab48fe980d2ce5b23f775c2"), # Extra byte + ] + + for size, expected in test_cases: + chd_file = tmp_path / f"test_size_{size}.chd" + + header = bytearray(size) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + if size >= 104: + header[84:104] = bytes.fromhex( + "0167fc76f9e4312e6ab48fe980d2ce5b23f775c2" + ) + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert ( + result == expected + ), f"Failed for size {size}: got {result}, expected {expected}" + + def test_extract_chd_hash_corrupted_header_data(self, tmp_path): + """Test handling of corrupted/invalid data in header fields""" + chd_file = tmp_path / "corrupted_header.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + # Corrupt the version field with invalid bytes + header[12:16] = b"\xff\xff\xff\xff" # This will be read as 4294967295 + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + # Should return None because version is not 5 + assert result is None + + def test_extract_chd_hash_zero_sha1(self, tmp_path): + """Test handling of all-zero SHA1 hash (edge case but valid)""" + chd_file = tmp_path / "zero_hash.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + # All-zero hash + header[84:104] = b"\x00" * 20 + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result == "0" * 40 + assert len(result) == 40 + + def test_extract_chd_hash_max_sha1(self, tmp_path): + """Test handling of maximum SHA1 hash (all 0xFF - edge case but valid)""" + chd_file = tmp_path / "max_hash.chd" + + header = bytearray(124) + header[0:8] = b"MComprHD" + header[12:16] = int(5).to_bytes(4, "big") + # All-FF hash + header[84:104] = b"\xff" * 20 + + chd_file.write_bytes(header) + + result = extract_chd_hash(chd_file) + + assert result == "f" * 40 + assert len(result) == 40 diff --git a/backend/utils/database.py b/backend/utils/database.py index 4145ca367..d923f8ba8 100644 --- a/backend/utils/database.py +++ b/backend/utils/database.py @@ -124,6 +124,14 @@ def json_array_contains_all( ) +def safe_str_to_bool(value: Any, default: bool = False) -> bool: + """Safely convert a value to bool, returning default if conversion fails.""" + try: + return value.strip().lower() in ("1", "true", "yes", "on") + except (ValueError, TypeError, AttributeError): + return default + + def safe_float(value: Any, default: float = 0.0) -> float: """Safely convert a value to float, returning default if conversion fails.""" try: diff --git a/backend/utils/json.py b/backend/utils/json_module.py similarity index 100% rename from backend/utils/json.py rename to backend/utils/json_module.py diff --git a/backend/utils/update_hltb_api_url.py b/backend/utils/update_hltb_api_url.py new file mode 100644 index 000000000..20b030657 --- /dev/null +++ b/backend/utils/update_hltb_api_url.py @@ -0,0 +1,133 @@ +# uv run python -m utils.update_hltb_api_url +""" +Utility script to update HowLongToBeat API URL by discovering the dynamic endpoint from the website +""" + +import re +import sys +from pathlib import Path + +import httpx + +# Precompiled regexes for better performance +APP_JS_REGEX = re.compile( + r'src=["\'](?P\/_next\/static\/chunks\/pages\/_app[^"\']+\.js)["\']' +) +APP_JS_FALLBACK_REGEX = re.compile(r'src=["\'](?P[^"\']*_app[^"\']+\.js)["\']') +ENDPOINT_TOKEN_REGEX = re.compile( + r'/api/(?P[a-zA-Z0-9_-]+)/["\']\.concat\(["\'](?P[0-9a-zA-Z]+)["\']\)\.concat\(["\'](?P[0-9a-zA-Z]+)["\']\)' +) + + +def fetch_hltb_app_script(base_url: str = "https://howlongtobeat.com") -> str | None: + """Fetch the HLTB app script from the site.""" + try: + with httpx.Client() as client: + # 1) Fetch homepage HTML + homepage_url = f"{base_url}/" + resp = client.get(homepage_url, timeout=15) + resp.raise_for_status() + html = resp.text + print(f"Fetched homepage: {homepage_url}") + + # 2) Find the Next.js _app chunk (typical pattern: "/_next/static/chunks/pages/_app-.js") + app_js_match = APP_JS_REGEX.search(html) + if not app_js_match: + # Fallback: any script path containing "_app" ending with .js + app_js_match = APP_JS_FALLBACK_REGEX.search(html) + if not app_js_match: + print("Could not locate HLTB _app JS chunk.") + return None + app_js_path = app_js_match.group("path") + print(f"Located app JS path: {app_js_path}") + + app_js_url = ( + app_js_path + if app_js_path.startswith("http") + else f"{base_url.rstrip('/')}/{app_js_path.lstrip('/')}" + ) + print(f"Constructed app JS URL: {app_js_url}") + + # 3) Download the _app JS chunk + js_resp = client.get(app_js_url, timeout=15) + js_resp.raise_for_status() + js_code = js_resp.text + print(f"Downloaded app JS chunk (size: {len(js_code)} chars)") + + return js_code + except (httpx.RequestError, httpx.HTTPStatusError) as e: + print(f"Error fetching HLTB app script: {e}", file=sys.stderr) + return None + + +def discover_hltb_endpoint(base_url: str = "https://howlongtobeat.com") -> str | None: + """Discover the current HLTB API endpoint by fetching and parsing the app script.""" + try: + # 1) Fetch the app script + js_code = fetch_hltb_app_script(base_url) + + if not js_code: + print("Could not fetch HLTB app script; using default search endpoint") + return None + + # 2) Extract the endpoint and tokens from the app script + token_match = ENDPOINT_TOKEN_REGEX.search(js_code) + if not token_match: + print( + "Could not extract HLTB endpoint and tokens from _app JS; using default search endpoint" + ) + return None + + endpoint = token_match.group("endpoint") + part1 = token_match.group("part1") + part2 = token_match.group("part2") + + print(f"Extracted endpoint: {endpoint}") + print(f"Extracted token part1: {part1}") + print(f"Extracted token part2: {part2}") + + # 3) Build the search URL + search_url = f"{base_url}/api/{endpoint}/{part1}{part2}" + print(f"Resolved HLTB search endpoint: {search_url}") + + return search_url + except (IOError, OSError) as e: + print( + f"Unexpected error discovering HLTB endpoint from site: {e}", + file=sys.stderr, + ) + return None + + +def main(): + """Main function to discover and update the HLTB API URL.""" + print("Starting HLTB API URL discovery...") + + search_url = discover_hltb_endpoint() + + if not search_url: + print("Failed to discover HLTB API URL") + sys.exit(1) + return + + # Write to the expected location + fixture_path = ( + Path(__file__).parent.parent + / "handler" + / "metadata" + / "fixtures" + / "hltb_api_url" + ) + + try: + with open(fixture_path, "w") as f: + f.write(search_url) + print(f"Successfully updated HLTB API URL to: {search_url}") + print(f"Written to: {fixture_path}") + except Exception as e: + print(f"Error writing to fixture file: {e}") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/frontend/package-lock.json b/frontend/package-lock.json index e709aa20f..243c2ed95 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -6557,10 +6557,11 @@ "dev": true }, "node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", "dev": true, + "license": "MIT", "dependencies": { "argparse": "^2.0.1" }, diff --git a/frontend/src/components/Details/ActionBar.vue b/frontend/src/components/Details/ActionBar.vue index 9d201820e..71c8c0747 100644 --- a/frontend/src/components/Details/ActionBar.vue +++ b/frontend/src/components/Details/ActionBar.vue @@ -5,6 +5,7 @@ import { useI18n } from "vue-i18n"; import AdminMenu from "@/components/common/Game/AdminMenu.vue"; import CopyRomDownloadLinkDialog from "@/components/common/Game/Dialog/CopyDownloadLink.vue"; import PlayBtn from "@/components/common/Game/PlayBtn.vue"; +import { useGameAnimation } from "@/composables/useGameAnimation"; import romApi from "@/services/api/rom"; import storeAuth from "@/stores/auth"; import storeDownload from "@/stores/download"; @@ -23,6 +24,10 @@ const isNDSRom = computed(() => { return isNintendoDSRom(props.rom); }); +const { boxartStyle } = useGameAnimation({ + rom: props.rom, +}); + async function copyDownloadLink(rom: DetailedRom) { const downloadLink = getDownloadLink({ rom, @@ -44,7 +49,15 @@ async function copyDownloadLink(rom: DetailedRom) {