Commit Graph

25 Commits

Author SHA1 Message Date
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
Sam Dornan
6215ab341e Disable redis-py maintenance notifications probe (#5015) 2026-10-02 07:58:20 -04:00
Sam Dornan
d828706ef9 perf(backend): pipeline multi-command Redis writes (#4858)
* perf(backend): pipeline multi-command Redis writes

- upload_chunk records a chunk with SADD, EXPIRE and SCARD in one
  transaction instead of three round trips, so a failure between them
  can no longer leave the chunk set without a TTL.
- bind_to_login_session does its SADD and EXPIRE in one transaction for
  the same reason.
- close_login_sessions reads and deletes a session's socket set in one
  transaction, so a socket binding in between is not dropped unseen.
- Logout deletes the session and removes it from the user's set in one
  pipeline.
- complete_chunked_upload reads the chunk set once instead of SCARD then
  SMEMBERS; cancel and invalidate_filter_values_cache delete their keys
  in one call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv

* fix(backend): refuse a socket bind that lands after its session's revocation

- bind_to_login_session checks the login session still exists in the
  same transaction as its SADD. Revocation deletes the session before it
  reads the socket set, so a bind that finds it gone removes itself and
  authenticate treats the socket as anonymous.
- complete_chunked_upload keeps its SCARD fast path and reads the
  members only to name the missing chunks.
- cancel_chunked_upload removes the temporary files before touching
  Redis.
- Tests check each pipelined write executes as one MULTI/EXEC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv

* fix(backend): close an upload session before removing its files on cancel

A chunk PUT that passes the session check after the temporary directory
is gone fails with a 500; deleting the session first turns it into a 404.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv

* fix(backend): answer a chunk write cut short by a cancel with 404

A PUT that passed the session check before the cancel removed its
directory fails writing; it now re-reads the session and returns the
same 404 as a PUT that arrives after the cancel, instead of a 500.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv

* chore(backend): remove a stray Redis snapshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 19:41:49 -05:00
nendo
f0c49b6a38 feat(devices): push downloads from the web UI to a device's download queue 2026-09-28 02:08:03 +09:00
Sam Dornan
e0df54cba5 chore(backend): enforce mypy's disallow_untyped_calls and disallow_untyped_decorators (#4827) 2026-09-26 20:21:54 -04:00
Georges-Antoine Assi
4bcc9da844 refactor(netplay): apply simplify pass
- Move connect-time user resolution and login-session binding into
  SocketHandler.authenticate, shared by the /ws and netplay servers.
- Add SocketHandler.get_session and drop the per-module copies.
- Fold disconnect into leave-room, and the user load into the ROM gate.
- Read the room password only from the field EmulatorJS sends.
- Close both servers' sockets for a revoked session concurrently.
- Correct the join-room password rule in the architecture doc.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:03:08 -04:00
Georges-Antoine Assi
2af79c1486 fix(netplay): apply code-review xhigh findings
- Bind netplay sockets to their login session, keying the socket set per
  channel so revoking a session closes sockets on both servers.
- Read the room password from the top-level field EmulatorJS sends, and
  compare it in constant time.
- Namespace Socket.IO room names so a room id cannot collide with a sid.
- Refuse a duplicate player id on join, and leave the current room before
  opening or joining another.
- Coerce client-supplied maxPlayers and names, and store the resolved ROM id.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 12:50:37 -04:00
zurdi
01483dd715 fix: disconnect a session's sockets when it is revoked
A socket joins its user's room, and an admin's the admin room, once at
connect time, so logging out or revoking a user's sessions left their open
sockets receiving notifications and the log stream. Each socket is now
recorded against the login session that opened it, and removing a session
disconnects those sockets on whichever worker holds them.

The main server takes one disconnect handler, so it moves next to the
connect handler and runs the activity cleanup as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 14:23:39 +02:00
zurdi
45fbb4fb7c fix: apply the second code-review pass
- The shared write manager passes the server's json_module, which a
  manager never attached to a server doesn't inherit; streaming pushes
  lost it when they moved onto that manager.
- The inbox drops a list requested before a reset, so a slow response for
  the previous user can't fill the next user's inbox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 13:31:14 +02:00
zurdi
bb5769e606 refactor: apply the simplify pass
- One home for pushing to a user's room: `SocketHandler.emit_to_user`, on a
  write-only manager kept per event loop and on the server's own channel.
  Streaming's push_to_user and the sync and scan emitters use it too.
- Notifications are stored in one transaction per send, so a broadcast is one
  commit, and pushed concurrently. Recipients are resolved from id and
  enabled only, and the actor is loaded with just the fields it shows.
- notify_user_or_admins holds the "whoever started it, else the admins"
  rule both the scan and the task runner applied by hand.
- A scan notifies from finish(), so no exit path can forget it.
- `data` is never null, dropping its guards; the toast host, the inbox and
  the admin form share one tone icon map; the inbox icon uses RAvatar.
- The store keeps its list when a socket echo changes nothing, and small
  dead parameters and duplicated lists are gone.
- The socket reconnect after a logout moved from the inbox to AppLayout,
  since every v2 feature depends on the socket's identity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 13:04:18 +02:00
zurdi
57311dc99a fix: apply the security-audit and code-review passes
Security:
- The netplay socket server shared the main server's Redis channel while
  letting unauthenticated clients name their own rooms, so a netplay socket
  in room `user:N` or `admin` received that user's pushes and the admin log
  stream. Netplay now has a channel of its own.
- Notifying other users also requires users.write on the token, so an admin
  token scoped to me.write can only notify its owner.
- The create payload rejects NUL characters, NaN/Infinity in data and an
  empty recipients list instead of failing in the database; mark-read takes
  at most as many ids as an inbox holds.

Correctness and cleanup:
- The inbox is cleared whenever the signed-in user changes, so a failed
  fetch can't leave the previous user's notifications on screen.
- Enter no longer sends the admin form, where an unfinished title would go
  out to everyone.
- A notification without its own icon shows its level's, in the list and in
  a pushed toast alike, from one LEVEL_ICONS map.
- One write-only Redis manager per event loop instead of one per push.
- Tests for the inbox socket wiring; em-dashes and long docstrings trimmed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:47:11 +02:00
Sam Dornan
4542998510 fix(backend): make type ignores honest and replace mypy trunk-ignores with fixes (#4711)
* fix(backend): make type ignores match what mypy reports

Third in the staged series clearing the errors #4655 made visible.
Whole-project mypy: 91 errors in 26 files -> 64 in 23.

Twenty `# type: ignore[assignment]` comments in
endpoints/responses/rom.py never suppressed anything. The request-scoped
values `from_orm_with_request` attaches to a Rom (rom_user, has_notes,
user_saves and the rest) are not declared on the model, so mypy reports
`attr-defined`; it does so under 1.19 as well as 2.3, so the code was
wrong when the comments were written rather than drifting since. They
now name the error they were meant to silence.

Seventy-nine ignores across 24 files suppressed nothing at all under
`--warn-unused-ignores`, and are removed. One of them,
`utils/zip_cache.py`, keeps its `attr-defined` code for the private
`zipfile._get_compressor` and drops only `assignment`. The unused set is
identical under mypy 2.3.0 and 2.3.1, and removing them leaves the error
count unchanged under both, so none was quietly needed.

The two `filter` helpers typed as `[QueryT: Select | Update | Delete]`
bound the TypeVar to the union, so `query.filter(...)` returned the union
and could not be assigned back to `QueryT`. Constraining it to the three
types lets mypy check each one separately, and the callers are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

* fix(backend): replace mypy and ASYNC240 trunk-ignores with real fixes

A `trunk-ignore` only suppresses when Trunk runs the linter. Plain mypy
does not read them, so the 13 on mypy findings were all still errors to
`mypy .` and would fail a whole-project check. Each now has a fix.

endpoints/tasks.py: `common_data` was a plain dict literal unpacked into
eight TypedDict constructors, so mypy saw `dict[str, Any]` and could not
match its keys. It holds exactly the fields of BaseTaskStatusResponse and
is now annotated as one, so the unpacking is checked.

handler/metadata/gamelist_handler.py: both media maps were inferred as
`dict[str, str]`, so indexing the TypedDict with their keys was
unprovable. Their keys are now typed `GamelistMediaKey`, the Literal of
the TypedDict's fields. A misspelt map key is now an error at the entry;
before, only the index site could have noticed, and it was suppressed.

handler/metadata/playmatch_handler.py: `attr` was a bare `str`. A TypeIs
guard narrows it to the five lookup attributes, and the frozenset is
derived from that Literal so the names live in one place. mypy now checks
that each name is a real PlaymatchRomMatch key. It does not check that
each takes an int, since mypy is lenient about value types on a union key;
that still rests on which five names are listed.

endpoints/search.py: the per-source tuples mixed ROM-list and handler
types, which mypy joined to `object`. The dict is now annotated with what
the loop uses: Mapping rows and the MetadataHandler base.

tests/handler/metadata/test_launchbox_handler.py: `Path.stat()` inside an
async test (ASYNC240) now goes through `anyio.Path`, as the rest of the
codebase already does.

Whole-project mypy: 64 errors in 23 files -> 51 in 20, identical under
2.3.0 and 2.3.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

* fix(backend): keep gamelist media keys in one place

Review pointed out that `GamelistMediaKey` repeated all fourteen fields
of GamelistMetadataMedia. Python has no `keyof`, so any Literal of a
TypedDict's keys is a second declaration of them, and a field added to
the TypedDict would be left out of it without any error.

The three index sites go back to suppressing `literal-required`, now as
`# type: ignore[literal-required]` so plain mypy reads it as well as
Trunk. The TypedDict stays the only declaration of the key set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-22 16:02:39 -05:00
Georges-Antoine Assi
09dbb2e244 use redis to store netplay data 2025-12-07 12:02:35 -05:00
Georges-Antoine Assi
8c769a5fe8 hacks with working netplayu 2025-11-21 19:15:20 -05:00
Georges-Antoine Assi
95c506aec0 Add github action to update HLTB API url 2025-11-17 15:27:48 -05:00
Georges-Antoine Assi
5c0bd9c418 [ROMM-2657] Safe access env vars with defaults 2025-11-15 14:54:21 -05:00
Michael Manganiello
e4e3928d1b misc: Apply import sorting 2025-09-04 11:17:00 -03:00
Georges-Antoine Assi
603f6ec5af Add options to gunicorn call 2025-08-26 18:16:52 -04:00
Michael Manganiello
d837070ad0 fix: SocketIO JSON dumps with sane defaults
Similar to how `engineio` provides a JSON-compatible module, this change
adds a custom JSON encoder with support for additional types.

Changing SocketIO's JSON module fixes the encoding issue when the
scanning process tried to send a datetime, failing and the frontend not
displaying the scanned game (commonly, when it had sibling games)
2025-01-12 00:41:15 -03:00
Michael Manganiello
b81fbc5820 fix: Improve handling of Redis URL
This change replaces the creation of Redis URL, from a simple string
interpolation, to using `yarl.URL`. The main benefit, besides not
forgetting to set all five different variables on every Redis client
initialization, is that user credentials are correctly URL-encoded, if
present.

Up until now, if a password had special characters, it could break the
generated URL.

This change also introduces support for a `REDIS_SSL` setting, which
allows the user to specify if the Redis connection should use SSL or not.
2024-10-11 21:41:19 -03:00
Georges-Antoine Assi
880345f20c ruff-only pre-commit 2024-05-18 12:05:57 -04:00
Georges-Antoine Assi
1a2c914045 refactor handlers out into own files 2024-05-05 12:45:56 -04:00
Georges-Antoine Assi
f259e1b1d0 fix scanning after socketio upgrade 2024-03-18 09:47:15 -04:00
Georges-Antoine Assi
6bcadec702 everything we need for 3.0 2024-02-01 18:13:16 -05:00
Zurdi
4b9e76f550 backend structure refactor 2024-01-12 23:44:27 +01:00