Files
romm/backend/handler/activity_handler.py
Georges-Antoine Assi a688676de7 fix: enforce ROM visibility on assets, sync, collections, stats and scan events (#5498)
* fix(sync): cap play sessions on sync completion and require roms.user.write

The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(config): reject empty platform binding and version values

config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(collections): require smart collection criteria to be a JSON object

Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(stats): require roms.read on /api/stats

Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal

/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins

The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(saves): bound total decompressed size when hashing zip archives

Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.

The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(psp): clamp LZ4 literal and match copies to the ZISO block size

The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.

Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(auth): revoke OAuth tokens when a user's credentials change

A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.

Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.

The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(api): reject local file URLs for user-supplied covers and manuals

file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.

These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(resources): bound cover downloads and decodes

Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.

Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: fix mypy errors in the new tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: address Greptile review on permission and input hardening

- Date OAuth tokens to before the credential check, so a password change
  that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: apply code-review findings on permission hardening

Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: apply simplify pass on permission hardening

Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: apply review-polish pass on permission hardening

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: state that ROM visibility is enforced as access control

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(assets): hide saves, states, screenshots and memory cards on hidden ROMs

Visibility is access control, so per-id save/state/screenshot routes now 404
when the save's ROM is hidden from the caller (hidden ROM, hidden platform or
age limit), and the save/state lists and identifier lists leave those rows
out in SQL. GET /api/saves/summary 404s on a hidden ROM. Memory cards on a
hidden platform 404 on every per-id route, drop out of both lists, and can't
be created against a hidden platform.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(saves): answer a hidden ROM's save summary like a missing one

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(permissions): enforce ROM visibility in sync, installs and feeds

Hidden ROMs/platforms and age-limited ROMs are access control, so the
paths that skipped the caller's visibility now apply it:

- sync negotiate: saves on hidden ROMs are neither offered, paired nor
  reported as conflicts; a client save on one negotiates like an unknown ROM
- push-pull SSH sync: resolves the device owner's visibility and skips
  saves on hidden ROMs in both directions
- device installs: list and claim leave out requests whose ROM became
  hidden (they stay pending), and outcome notifications don't name it
- recommendations: a hidden seed ROM is no longer named
- music playlists: track_count counts only tracks on visible ROMs
- audit events: firmware targets on hidden platforms are filtered
- setup library: supported platforms honour the caller's visibility
- feeds: a hidden platform found by slug reads as missing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(visibility): hide ROMs from virtual collections, stats and scan events

Virtual collections apply the caller's visibility in SQL: a collection with
no visible member is left out (404 by id), member ids and covers skip hidden
ROMs, and the limit counts only visible collections.

Stats save, state and screenshot totals skip assets of hidden ROMs.

Scan events no longer broadcast to every socket. Progress and end events go
to a scan room that sockets of users holding platforms.write or tasks.run
join on connect. scanning_rom and scanning_platform go to the user rooms of
those followers who can see that ROM or platform, resolved once per scan
and grouped by visibility. get_rom_audience now builds on a shared
get_user_visibilities.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: apply code-review findings on ROM visibility enforcement

Match virtual collection members by ROM id, build the cover visibility clauses
once, filter feed platforms by visibility in SQL, resolve every id before a
batch save or state delete, filter push-pull saves in the query, and narrow the
hides query to the requested users.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: apply simplify pass on ROM visibility enforcement

Require an explicit visibility filter on the saves, states and memory card
queries, share one roms_facets visibility join and one owned-asset helper,
filter virtual collection members by hidden ids, batch the scan audience's
scope lookup, and move the empty-room emit guard into socket_handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: start the scan audience before emitting from scan_rom

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: apply humanizer pass on the visibility rule

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(streaming): don't mount a memory card on a hidden platform

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: address Greptile review on ROM visibility enforcement

Refresh a running scan's audience after a permission change, fix the precedence
of the scan-room join assertion, and narrow mock await_args before reading them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* revert: drop per-visibility scan event audience

Scan events go back to every socket. Removes handler/scan/audience.py,
the scan room join on connect, the permissions generation bump and the
batched OAuth scope resolution that only the audience used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:33:11 -05:00

386 lines
15 KiB
Python

"""Real-time user game activity tracking.
Stores ephemeral "currently playing" state in Redis. Each active session is a
Redis key with a short TTL, refreshed by periodic heartbeats from the client
(browser) or the device. When the TTL expires (no heartbeat received), the
session is considered ended automatically.
"""
from __future__ import annotations
import asyncio
import json
from contextlib import suppress
from datetime import datetime, timezone
from typing import Any, TypedDict, cast
from uuid import uuid4
from redis.exceptions import WatchError
from endpoints.responses.activity import ActivityClearSchema
from handler.database import (
db_device_handler,
db_permission_handler,
db_rom_handler,
db_save_handler,
db_user_handler,
)
from handler.redis_handler import async_cache
from handler.socket_handler import emit_to_rooms, socket_handler, user_room
from logger.logger import log
from utils.screenshots import continue_playing_screenshot
class ActivityEntry(TypedDict):
user_id: int
username: str
avatar_path: str
rom_id: int
rom_name: str
rom_cover_path: str # small cover path, may be empty
screenshot_path: str # "where they are" image (save/title/screenshot), may be empty
platform_slug: str
platform_name: str
device_id: str
device_type: str # "web", "grout", "argosy-launcher", "streaming", etc.
started_at: str # ISO 8601 timestamp
class ActivityHandler:
"""Redis-backed store for currently active game play sessions."""
ACTIVITY_TTL = 90 # seconds; refreshed by heartbeats
ROM_INDEX_TTL = 120 # slightly longer than ACTIVITY_TTL
KEY_PREFIX = "activity:user:"
ROM_INDEX_PREFIX = "activity:rom:"
REFRESH_DELAY = 5 # seconds; failed lookups within it share one refresh
# Held by the worker that will send the pending refresh. It outlives the
# delay so a worker that dies before sending frees it.
REFRESH_KEY = "activity:refresh:pending"
_refresh: asyncio.Task[None] | None = None
_flush: asyncio.Event | None = None
def _activity_key(self, user_id: int, device_id: str) -> str:
return f"{self.KEY_PREFIX}{user_id}:{device_id}"
def _rom_index_key(self, rom_id: int) -> str:
return f"{self.ROM_INDEX_PREFIX}{rom_id}"
def _member(self, user_id: int, device_id: str) -> str:
return f"{user_id}:{device_id}"
async def build_entry(
self,
*,
user_id: int,
device_id: str,
rom_id: int,
preserve_started_at: bool,
device_type: str | None = None,
) -> ActivityEntry | None:
"""Assemble an entry from the database, or None if the user or ROM is gone.
Args:
preserve_started_at: keep the start time of the entry already
stored, so refreshing does not reset the elapsed label.
device_type: what is being played on, for callers with no registered
device to read it from. Looked up from the device when omitted.
"""
user = db_user_handler.get_user(user_id)
if user is None:
log.debug(f"activity: unknown user_id {user_id}")
return None
rom = db_rom_handler.get_rom(rom_id)
if rom is None:
log.debug(f"activity: unknown rom_id {rom_id}")
return None
started_at = datetime.now(timezone.utc).isoformat()
if preserve_started_at:
existing = await self.get_active(user_id, device_id)
if existing:
started_at = existing["started_at"]
if device_type is None:
device = db_device_handler.get_device(device_id=device_id, user_id=user_id)
device_type = device.client if device else None
# "Where they are" image - the player's latest save screenshot, else the
# title screen / first gameplay screenshot (frontend falls back to cover).
latest_save = db_save_handler.get_latest_saves_for_roms(
user_id=user_id, rom_ids=[rom_id]
).get(rom_id)
platform = rom.platform
return ActivityEntry(
user_id=user.id,
username=user.username,
avatar_path=user.avatar_path or "",
rom_id=rom.id,
rom_name=rom.name or rom.fs_name,
rom_cover_path=rom.path_cover_s or "",
screenshot_path=continue_playing_screenshot(rom, latest_save) or "",
platform_slug=platform.slug if platform else "",
platform_name=((platform.custom_name or platform.name) if platform else ""),
device_id=device_id,
device_type=device_type or "web",
started_at=started_at,
)
async def publish_active(self, entry: ActivityEntry) -> None:
"""Store a session and send it to everyone allowed to see its ROM."""
previous = await self.get_active(entry["user_id"], entry["device_id"])
await self.set_active(entry)
rooms = await _audience_rooms(entry["rom_id"])
await self._emit("activity:update", dict(entry), rooms)
# Without this game's audience the refresh just sent covers everyone.
if rooms is not None and previous and previous["rom_id"] != entry["rom_id"]:
# Whoever saw the last game but can't see this one would keep its card.
stale = await _audience_rooms(previous["rom_id"])
await self._emit(
"activity:clear",
ActivityClearSchema(
user_id=entry["user_id"],
device_id=entry["device_id"],
rom_id=previous["rom_id"],
).model_dump(),
None if stale is None else sorted(set(stale) - set(rooms)),
)
async def publish_clear(self, user_id: int, device_id: str) -> int | None:
"""End a session and announce it. Returns the rom_id cleared, if any."""
rom_id = await self.clear_active(user_id, device_id)
if rom_id is None:
return None
await self._emit(
"activity:clear",
ActivityClearSchema(
user_id=user_id, device_id=device_id, rom_id=rom_id
).model_dump(),
await _audience_rooms(rom_id),
)
return rom_id
async def _emit(
self, event: str, payload: dict[str, Any], rooms: list[str] | None
) -> None:
# The REST app shares this process with the Socket.IO server, so emit
# through the already-initialised, Redis-backed server (it fans out
# across workers) rather than opening a manager per call.
if rooms is None:
# An unknown audience can't be sent the session; every client
# re-lists what it may see instead.
await self._queue_refresh()
return
try:
await emit_to_rooms(socket_handler.socket_server, event, payload, rooms)
except Exception as e: # noqa: BLE001
log.warning(f"Failed to broadcast {event}: {e}")
async def _queue_refresh(self) -> None:
"""Ask every socket to re-list, once for however many lookups fail meanwhile."""
loop = asyncio.get_running_loop()
pending = self._refresh
if pending is not None and not pending.done() and pending.get_loop() is loop:
return
# Each worker's broadcast reaches every socket, so workers share one claim.
token = uuid4().hex
try:
claimed = await async_cache.set(
self.REFRESH_KEY, token, nx=True, ex=2 * self.REFRESH_DELAY
)
except Exception as e: # noqa: BLE001
log.warning(f"Failed to claim activity:refresh: {e}")
claimed = True
if claimed:
self._flush = asyncio.Event()
self._refresh = loop.create_task(self._send_refresh(token, self._flush))
async def _send_refresh(self, token: str, flush: asyncio.Event) -> None:
with suppress(TimeoutError):
await asyncio.wait_for(flush.wait(), self.REFRESH_DELAY)
# Released first, so a lookup that fails from here on queues another.
# Only the claimant releases; an expired claim may be another worker's now.
try:
if await async_cache.get(self.REFRESH_KEY) in (token, token.encode()):
await async_cache.delete(self.REFRESH_KEY)
except Exception as e: # noqa: BLE001
log.warning(f"Failed to release activity:refresh: {e}")
try:
await socket_handler.socket_server.emit("activity:refresh", {})
except Exception as e: # noqa: BLE001
log.warning(f"Failed to broadcast activity:refresh: {e}")
async def flush_refresh(self) -> None:
"""Send a pending refresh now, so it isn't lost when the worker stops."""
pending, flush = self._refresh, self._flush
if pending is None or flush is None or pending.done():
return
flush.set()
await pending
async def set_active(self, entry: ActivityEntry) -> None:
"""Store or refresh a user's active play session."""
key = self._activity_key(entry["user_id"], entry["device_id"])
rom_key = self._rom_index_key(entry["rom_id"])
member = self._member(entry["user_id"], entry["device_id"])
async with async_cache.pipeline() as pipe:
await pipe.set(key, json.dumps(entry), ex=self.ACTIVITY_TTL)
await pipe.sadd(rom_key, member)
await pipe.expire(rom_key, self.ROM_INDEX_TTL)
await pipe.execute()
async def clear_active(self, user_id: int, device_id: str) -> int | None:
"""Clear a user's active play session. Returns the rom_id that was cleared, or None."""
key = self._activity_key(user_id, device_id)
raw = await async_cache.get(key)
if not raw:
return None
try:
entry = json.loads(raw)
rom_id = int(entry["rom_id"])
except (ValueError, KeyError, TypeError) as e:
log.warning(f"Failed to parse activity entry for cleanup: {e}")
await async_cache.delete(key)
return None
member = self._member(user_id, device_id)
async with async_cache.pipeline() as pipe:
await pipe.delete(key)
await pipe.srem(self._rom_index_key(rom_id), member)
await pipe.execute()
return rom_id
async def get_active(self, user_id: int, device_id: str) -> ActivityEntry | None:
"""Get a single active session by user and device."""
key = self._activity_key(user_id, device_id)
raw = await async_cache.get(key)
if not raw:
return None
try:
return cast(ActivityEntry | None, json.loads(raw))
except ValueError:
return None
async def get_all_active(self) -> list[ActivityEntry]:
"""Get all currently active play sessions across all users."""
pattern = f"{self.KEY_PREFIX}*"
keys = [key async for key in async_cache.scan_iter(match=pattern)]
if not keys:
return []
# Single round-trip for every value instead of a GET per key.
entries: list[ActivityEntry] = []
for raw in await async_cache.mget(keys):
if not raw:
continue
try:
entries.append(json.loads(raw))
except ValueError:
continue
return entries
async def get_active_for_rom(self, rom_id: int) -> list[ActivityEntry]:
"""Get all active play sessions for a specific ROM."""
rom_key = self._rom_index_key(rom_id)
members = await async_cache.smembers(rom_key)
entries: list[ActivityEntry] = []
malformed: list[str] = []
keys_by_member: dict[str, str] = {}
for raw_member in members:
# Decoded as the session middleware does, for a client that doesn't.
member = (
raw_member.decode() if isinstance(raw_member, bytes) else raw_member
)
try:
user_id_str, device_id = member.rsplit(":", 1)
user_id = int(user_id_str)
except ValueError:
malformed.append(member)
continue
keys_by_member[member] = self._activity_key(user_id, device_id)
raws = (
await async_cache.mget(list(keys_by_member.values()))
if keys_by_member
else []
)
stale: dict[str, str] = {}
for (member, key), raw in zip(keys_by_member.items(), raws, strict=True):
entry = _live_entry(raw, rom_id)
if entry is None:
stale[member] = key
else:
entries.append(entry)
if malformed or stale:
await self._drop_index_members(rom_id, malformed, stale)
return entries
async def _drop_index_members(
self, rom_id: int, malformed: list[str], stale: dict[str, str]
) -> None:
"""Remove members from a ROM's index, sparing any a heartbeat has revived."""
async with async_cache.pipeline() as pipe:
try:
if stale:
await pipe.watch(*stale.values())
raws = await pipe.mget(list(stale.values()))
still_stale = [
member
for member, raw in zip(stale, raws, strict=True)
if _live_entry(raw, rom_id) is None
]
else:
still_stale = []
if not (malformed or still_stale):
return
pipe.multi()
await pipe.srem(self._rom_index_key(rom_id), *malformed, *still_stale)
await pipe.execute()
except WatchError:
# A heartbeat raced this cleanup; the next read retries it.
pass
async def _audience_rooms(rom_id: int) -> list[str] | None:
"""The ROM's audience, or None if it can't be read, so publishing still succeeds."""
try:
return await asyncio.to_thread(_audience, rom_id)
except Exception: # noqa: BLE001 - activity is best-effort, like its broadcast
log.warning(f"Failed to resolve who can see ROM {rom_id}", exc_info=True)
return None
def _audience(rom_id: int) -> list[str]:
"""Sockets join their `user_room` on connect; anonymous sockets join none."""
rom = db_rom_handler.get_rom_visibility(rom_id)
if rom is None:
return []
return [
user_room(user_id) for user_id in db_permission_handler.get_rom_audience(rom)
]
def _live_entry(raw: str | bytes | None, rom_id: int) -> ActivityEntry | None:
"""The stored session, if it exists, parses and is still playing `rom_id`."""
if not raw:
return None
try:
entry = json.loads(raw)
except ValueError:
return None
if not isinstance(entry, dict) or entry.get("rom_id") != rom_id:
return None
return cast(ActivityEntry, entry)
activity_handler = ActivityHandler()