diff --git a/.github/workflows/update-hltb-api-url.yml b/.github/workflows/update-hltb-api-url.yml index cda147882..75a27d61c 100644 --- a/.github/workflows/update-hltb-api-url.yml +++ b/.github/workflows/update-hltb-api-url.yml @@ -2,6 +2,10 @@ name: Update HowLongToBeat API URL on: workflow_dispatch: + schedule: + # HLTB rotates the endpoint without notice, and the fixture is served to + # every install from master, so check weekly rather than on someone noticing. + - cron: "0 6 * * 1" permissions: contents: write diff --git a/backend/handler/metadata/fixtures/hltb_api_url b/backend/handler/metadata/fixtures/hltb_api_url index 07375418c..b6096765b 100644 --- a/backend/handler/metadata/fixtures/hltb_api_url +++ b/backend/handler/metadata/fixtures/hltb_api_url @@ -1 +1 @@ -https://howlongtobeat.com/api/bleed +https://howlongtobeat.com/api/search/site diff --git a/backend/handler/metadata/hltb_handler.py b/backend/handler/metadata/hltb_handler.py index c550c3337..a5536f882 100644 --- a/backend/handler/metadata/hltb_handler.py +++ b/backend/handler/metadata/hltb_handler.py @@ -293,6 +293,7 @@ class HLTBHandler(MetadataHandler): self.security_token: str | None = None self.hp_key: str | None = None self.hp_val: str | None = None + self._session_lock = asyncio.Lock() self.min_similarity_score: Final[float] = 0.85 @classmethod @@ -306,6 +307,13 @@ class HLTBHandler(MetadataHandler): # HLTB now requires a security token await self._fetch_security_token() + if not self._has_session(): + log.error( + "Could not establish a HowLongToBeat session at %s, lookups will " + "retry until one succeeds", + self.search_init_url, + ) + def _base_headers(self) -> dict[str, str]: # HLTB binds a session to the user agent that requested it, so every call # has to send the same one. @@ -317,6 +325,18 @@ class HLTBHandler(MetadataHandler): def _has_session(self) -> bool: return bool(self.security_token and self.hp_key and self.hp_val) + async def _ensure_session(self) -> bool: + """Mint a session if there is none, so a failed startup is not permanent.""" + if self._has_session(): + return True + + async with self._session_lock: + # A peer may have minted one while we waited for the lock. + if not self._has_session(): + await self._fetch_security_token() + + return self._has_session() + async def _fetch_search_endpoint(self) -> None: """Fetch the API endpoint URL from Github.""" if not HLTB_API_ENABLED: @@ -387,7 +407,7 @@ class HLTBHandler(MetadataHandler): :return: A dictionary with the json result. :raises HTTPException: If the request fails or the service is unavailable. """ - if not self._has_session(): + if not await self._ensure_session(): return {} httpx_client = ctx_httpx_client.get() diff --git a/backend/tests/handler/metadata/test_hltb_handler.py b/backend/tests/handler/metadata/test_hltb_handler.py index 39717d909..5809d3ce2 100644 --- a/backend/tests/handler/metadata/test_hltb_handler.py +++ b/backend/tests/handler/metadata/test_hltb_handler.py @@ -1,3 +1,4 @@ +import asyncio import json from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch @@ -281,12 +282,70 @@ async def test_connect_error_still_reports_connectivity(mock_ctx_httpx_client): async def test_request_returns_empty_without_a_session(mock_ctx_httpx_client): handler = HLTBHandler() mock_client = AsyncMock() + mock_client.get.return_value = _response(json_body={}) mock_ctx_httpx_client.get.return_value = mock_client - assert await handler._request("https://howlongtobeat.com/api/bleed", {}) == {} + assert await handler._request("https://howlongtobeat.com/api/search/site", {}) == {} mock_client.post.assert_not_awaited() +@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True) +@patch("handler.metadata.hltb_handler.ctx_httpx_client") +async def test_request_mints_a_session_a_failed_startup_never_got( + mock_ctx_httpx_client, +): + handler = HLTBHandler() + mock_client = AsyncMock() + mock_client.get.return_value = _response( + json_body={"token": "token-late", "hpKey": "ign_late", "hpVal": "val-late"} + ) + mock_client.post.return_value = _response(json_body={"data": []}) + mock_ctx_httpx_client.get.return_value = mock_client + + assert await handler._request( + "https://howlongtobeat.com/api/search/site", {"a": 1} + ) == {"data": []} + + kwargs = mock_client.post.await_args.kwargs + assert kwargs["headers"]["x-auth-token"] == "token-late" + assert kwargs["json"] == {"a": 1, "ign_late": "val-late"} + + +@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True) +@patch("handler.metadata.hltb_handler.ctx_httpx_client") +async def test_concurrent_lookups_mint_one_shared_session(mock_ctx_httpx_client): + handler = HLTBHandler() + mock_client = AsyncMock() + mint_reached = asyncio.Event() + mint_may_finish = asyncio.Event() + + async def blocking_mint(*args, **kwargs) -> MagicMock: + # Hold /init open so every other lookup reaches _ensure_session meanwhile. + mint_reached.set() + await mint_may_finish.wait() + return _response( + json_body={"token": "token-1", "hpKey": "ign_aaaa", "hpVal": "val-1"} + ) + + mock_client.get.side_effect = blocking_mint + mock_client.post.return_value = _response(json_body={"data": []}) + mock_ctx_httpx_client.get.return_value = mock_client + + lookups = [ + asyncio.create_task( + handler._request("https://howlongtobeat.com/api/search/site", {}) + ) + for _ in range(5) + ] + await mint_reached.wait() + mint_may_finish.set() + await asyncio.gather(*lookups) + + # A scan starts many lookups at once, and HLTB must not see a mint from each. + mock_client.get.assert_awaited_once() + assert mock_client.post.await_count == 5 + + @patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True) @patch("handler.metadata.hltb_handler.ctx_httpx_client") async def test_initialize_fetches_endpoint_then_session(mock_ctx_httpx_client): diff --git a/backend/tests/utils/test_update_hltb_api_url.py b/backend/tests/utils/test_update_hltb_api_url.py new file mode 100644 index 000000000..bd314840b --- /dev/null +++ b/backend/tests/utils/test_update_hltb_api_url.py @@ -0,0 +1,40 @@ +from utils.update_hltb_api_url import BUILD_MANIFEST_REGEX, candidate_search_routes + +# Abridged from the real manifest: the search route, its /init sibling, and the +# unrelated routes a naive "/api/search" match would also accept. +MANIFEST = """ +self.__BUILD_MANIFEST={"/api/forum/search":["x.js"],"/api/search/site":["y.js"], +"/api/search/site/init":["z.js"],"/api/stats/games":["w.js"],"/api/user":["v.js"]} +""" + + +def test_search_route_is_the_one_paired_with_a_session_mint(): + assert candidate_search_routes(MANIFEST) == ["/api/search/site"] + + +def test_a_route_without_an_init_sibling_is_not_a_candidate(): + assert candidate_search_routes('{"/api/search/site":[]}') == [] + + +def test_search_like_candidates_are_tried_first(): + manifest = '{"/api/aaa":[],"/api/aaa/init":[],"/api/search/site":[],"/api/search/site/init":[]}' + + assert candidate_search_routes(manifest) == ["/api/search/site", "/api/aaa"] + + +def test_build_manifest_is_located_by_its_hashed_build_id(): + html = '' + + match = BUILD_MANIFEST_REGEX.search(html) + + assert match is not None + assert match.group("path") == ( + "/_next/static/xXfhvAtyEbN6z1HpYBEoi/_buildManifest.js" + ) + + +def test_turbopack_chunks_are_not_mistaken_for_the_manifest(): + # The chunk names that replaced the old _app bundle must not match. + html = '' + + assert BUILD_MANIFEST_REGEX.search(html) is None diff --git a/backend/utils/update_hltb_api_url.py b/backend/utils/update_hltb_api_url.py index 90d9a344c..8dc9dbae0 100644 --- a/backend/utils/update_hltb_api_url.py +++ b/backend/utils/update_hltb_api_url.py @@ -5,99 +5,119 @@ Utility script to update HowLongToBeat API URL by discovering the dynamic endpoi import re import sys +import time from pathlib import Path import httpx +from utils import get_version from utils.context import create_httpx_client -# 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]+)["\']\)' +BASE_URL = "https://howlongtobeat.com" + +# Next.js lists every route it serves as a plain literal in _buildManifest.js, so +# discovery does not depend on how the app bundle happens to be built or minified. +BUILD_MANIFEST_REGEX = re.compile( + r'src=["\'](?P[^"\']*/_next/static/[^"\']+/_buildManifest\.js)["\']' ) +API_ROUTE_REGEX = re.compile(r'["\'](?P/api/[^"\']*)["\']') + +# HLTBHandler mints its session at f"{search_url}/init", so the search endpoint is +# the route the manifest pairs with an /init sibling. +SESSION_MINT_SUFFIX = "/init" +SESSION_FIELDS = ("token", "hpKey", "hpVal") -def fetch_hltb_app_script(base_url: str = "https://howlongtobeat.com") -> str | None: - """Fetch the HLTB app script from the site.""" - try: - with create_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}") +def _absolute_url(base_url: str, path: str) -> str: + if path.startswith("http"): + return path + return f"{base_url.rstrip('/')}/{path.lstrip('/')}" - # 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}") +def _base_headers(base_url: str) -> dict[str, str]: + return {"Referer": base_url, "User-Agent": f"RomM/{get_version()}"} - # 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) +def fetch_build_manifest(client: httpx.Client, base_url: str) -> str | None: + """Fetch the Next.js build manifest linked from the homepage.""" + homepage_url = f"{base_url.rstrip('/')}/" + response = client.get(homepage_url, headers=_base_headers(base_url), timeout=15) + response.raise_for_status() + print(f"Fetched homepage: {homepage_url}") + + match = BUILD_MANIFEST_REGEX.search(response.text) + if not match: + print("Could not locate the Next.js build manifest.", file=sys.stderr) return None + manifest_url = _absolute_url(base_url, match.group("path")) + print(f"Located build manifest: {manifest_url}") -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.""" + response = client.get(manifest_url, headers=_base_headers(base_url), timeout=15) + response.raise_for_status() + print(f"Downloaded build manifest (size: {len(response.text)} chars)") + + return response.text + + +def candidate_search_routes(manifest: str) -> list[str]: + """List the API routes that ship a session mint, most search-like first.""" + routes = set(API_ROUTE_REGEX.findall(manifest)) + candidates = [ + route for route in routes if f"{route}{SESSION_MINT_SUFFIX}" in routes + ] + + # Only an ordering hint, since every candidate is confirmed against the live API. + return sorted(candidates, key=lambda route: ("search" not in route, route)) + + +def mints_a_session(client: httpx.Client, base_url: str, search_url: str) -> bool: + """Check that the endpoint issues the session HLTBHandler needs to search.""" 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, + response = client.get( + f"{search_url}{SESSION_MINT_SUFFIX}", + params={"t": int(time.time())}, + headers=_base_headers(base_url), + timeout=15, ) + response.raise_for_status() + data = response.json() + except (httpx.RequestError, httpx.HTTPStatusError, ValueError) as e: + print(f"Rejected {search_url}: {e}") + return False + + if missing := [field for field in SESSION_FIELDS if not data.get(field)]: + print(f"Rejected {search_url}: session is missing {', '.join(missing)}") + return False + + print(f"Confirmed {search_url} mints a session") + return True + + +def discover_hltb_endpoint(base_url: str = BASE_URL) -> str | None: + """Discover the current HLTB search endpoint from the site's route table.""" + try: + with create_httpx_client() as client: + manifest = fetch_build_manifest(client, base_url) + if not manifest: + return None + + candidates = candidate_search_routes(manifest) + if not candidates: + print("No API route offers a session mint.", file=sys.stderr) + return None + print(f"Candidate search routes: {', '.join(candidates)}") + + for route in candidates: + search_url = f"{base_url.rstrip('/')}{route}" + if mints_a_session(client, base_url, search_url): + print(f"Resolved HLTB search endpoint: {search_url}") + return search_url + + print("No candidate route minted a session.", file=sys.stderr) + return None + except (httpx.RequestError, httpx.HTTPStatusError) as e: + print(f"Error discovering HLTB endpoint: {e}", file=sys.stderr) return None @@ -110,7 +130,6 @@ def main(): if not search_url: print("Failed to discover HLTB API URL") sys.exit(1) - return # Write to the expected location fixture_path = ( @@ -123,10 +142,10 @@ def main(): try: with open(fixture_path, "w") as f: - f.write(search_url) + f.write(f"{search_url}\n") print(f"Successfully updated HLTB API URL to: {search_url}") print(f"Written to: {fixture_path}") - except Exception as e: + except OSError as e: print(f"Error writing to fixture file: {e}") sys.exit(1)