Commit Graph

5158 Commits

Author SHA1 Message Date
Georges-Antoine Assi
258d7a8892 Merge remote-tracking branch 'origin/master' into feat/retroarch-cloud-sync 2026-09-24 16:17:32 -04:00
Georges-Antoine Assi
5bf63796c0 feat(sync): keep the game library browsable for the kiosk guest
The kiosk guest may PROPFIND the root and browse or download under
roms/, as it can in the web UI. The manifest, saves, states, blobs and
OPTIONS still challenge it, so RetroArch sends credentials.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 16:09:18 -04:00
Georges-Antoine Assi
603e3b0c93 fix(sync): keep state screenshots separate per core
RetroArch names a slot's state the same under every core, and its
screenshot was filed per ROM, so two cores' `<rom>.state.png` shared
one file and one row. File them under a per-core screenshots folder,
upsert by path, and only match a state to a screenshot in its own core's
folder or the ROM-level one.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 16:02:00 -04:00
Sam Dornan
abd061f59a perf(backend): read the gallery sorts out of an index (#4647)
* perf(backend): read the nullable gallery sorts out of an index

Sorting the gallery by release date, rating or HowLongToBeat time placed
unset roms last with `ORDER BY <column> IS NULL, <column>`. The leading
term is an expression, so MariaDB and MySQL could not read the order out
of `idx_roms_<column>` and filesorted instead. PostgreSQL had the mirror
problem descending: `DESC NULLS LAST` does not match the index's own
order, so it fell back to a sequential scan.

Neither engine paid this once. v2 window fetches send no sidecars, so
each scroll window is its own `ORDER BY ... LIMIT 72 OFFSET n` over the
full filtered set, and `roms` carries a JSON metadata blob per provider
on every row.

Each column now carries a STORED `_unset` flag with an
`idx_roms_<column>_sort` pair the ascending sort leads with, and
PostgreSQL gets an `idx_roms_<column>_desc` for the descending one. Row
order is unchanged in both directions.

Measured on PostgreSQL 16 over 120k roms, first page:

  ascending    30.6 ms / 8109 buffers -> 0.074 ms / 13 buffers
  descending   33.5 ms / 8091 buffers -> 0.112 ms / 14 buffers

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

* fix(backend): rebuild a sort index MariaDB narrowed instead of dropped

Testing the previous commit against MariaDB rather than PostgreSQL alone
turned up a real bug in it.

The two engines leave a dropped generated column in different states:
PostgreSQL drops every index that reads it, while MariaDB and MySQL keep
a composite one over the columns that survive. `_restore_generated_indexes`
only created indexes missing by name, so on MariaDB the rebuild path in
`ensure_roms_columns` (a chain predating 0123) would leave
`idx_roms_<column>_sort` narrowed to the unset flag alone and the
ascending gallery sort walking half an index.

It now reconciles on the columns an index spans, not just its name, and
`_drop_index_sql` gives the two dialects their own DROP INDEX spelling.

Also corrects the flag columns' comments: MariaDB accepts no NOT NULL on
a generated column in either position, so they are nullable in the DDL on
both engines. `IS NULL` never evaluates to NULL, so no row carries one.

Verified on MariaDB 10.11 over 120k roms. The ascending page went from
`rows=116503, Using index; Using filesort` to `rows=72, Using index`,
134 ms to 6 ms, with the same plan once the rom_user join is added.
Migration, schema and flag values also checked under utf8mb3_unicode_ci,
the collation these expressions are most fragile under.

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

* style(backend): give the sort-flag rationale one home

Greptile flagged the comment blocks in this PR against CLAUDE.md's
comment discipline. The length was a symptom: the same explanation of
why MariaDB cannot index the NULLS LAST emulation appeared in four
places. It now lives once, beside `SORTABLE_NULLABLE_ROM_COLUMNS`, and
the other sites say only what is local to them.

No behaviour change; the migration docstrings are left as they are,
matching the narrative style every recent revision uses.

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

* fix(backend): drop the sort indexes with the rest of the catalog

Copilot pointed out that `ensure_roms_columns` installs the `_unset`
columns long before 0129 runs, so a chain that stops short and then
downgrades leaves them behind. Checking that turned up a real leak next
to it: 0108's downgrade, which the module documents as removing whatever
of the catalog such a chain still carries, was leaving two indexes.

A descending sort index reads a value column this module inherited
rather than added, so `drop_roms_columns` re-adds that column and the
index over it survives. `_drop_sort_indexes` now takes them explicitly.
PostgreSQL only, since no other engine has those indexes.

The flag columns themselves are not a leak: the catalog front-loads every
column it owns, so at 0127 the table already carries 0123's
`generated_keywords`, `generated_themes` and `generated_rating_count`
too. Verified on both engines that a 0128 to 0127 downgrade leaves the
table writable with the flags still computing, and that re-upgrading
restores the pair, narrowed index included.

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

* style(backend): tighten the teardown docstrings and the test annotation

Two more from Greptile, both worth taking even though the reasoning
behind each was off.

`_drop_sort_indexes` and its test now carry a summary plus one line,
matching `drop_roms_columns` right above them, and the parametrized
metadata argument is typed instead of a bare `dict`.

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

* perf(backend): index the remaining gallery sorts (#4644)

* perf(backend): span the gallery sort indexes through the id tiebreak

The gallery appends `id` to every ORDER BY, but `idx_roms_<column>_sort`
stopped at the value and `idx_roms_<column>_desc` at the value alone. On
PostgreSQL that leaves every tie to be sorted, and unset metadata is a single
tie covering the whole bucket: a scroll window inside it fell back to a Seq
Scan and an external merge sort. Both indexes now carry `id` in the sort's own
direction, which InnoDB was already appending for MariaDB and MySQL.

Measured on 120k roms, a window at offset 100000 (inside the unset bucket),
all three columns, both directions:

  PostgreSQL ascending   119 ms, external merge sort  ->  15 ms, index only
  PostgreSQL descending   92 ms, incremental sort     ->  13 ms, index only
  MariaDB, both          already index-only; unchanged

No sort node remains in any of the twelve plans. Also trims the docstrings and
comments this change touches to the repo's one-or-two-line rule.

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

* test(backend): pin the reflected order of the descending sort indexes

The existing assertion read column names only, which a default ascending index
satisfies just as well, and `AUTOGENERATE_EXEMPT_INDEX_NAMES` keeps the drift
check away from these. Asserts the reflected `column_sorting` instead, and its
absence on the ascending pair.

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

* fix(backend): declare the unset flags nullable, as their DDL is

`Mapped[bool]` inferred NOT NULL while both engines create the column nullable,
MariaDB because it takes no NOT NULL on a generated column. The four generated
columns beside them already match their DDL. The annotation stays `bool`, since
`IS NULL` never yields NULL.

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

* fix(backend): renumber the gallery sort revisions after 0132

master gained its own 0129-0132 while this branch was open, and both
chains started from 0128_hltb_main_story_column, leaving alembic with
two heads (`upgrade head` fails with MultipleHeads).

0129_indexed_gallery_sorts -> 0133, now revising 0132_audit_events;
0130_gallery_sort_indexes -> 0134. No content change.

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

* fix(backend): re-chain the renamed gallery sort revisions onto 0132

The previous commit renamed the files but left their revision IDs and
parent as they were. 0133 now revises 0132_audit_events, and both IDs
match their filenames.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 14:56:43 -05:00
Georges-Antoine Assi
6691489773 chore(sync): review-polish pass
- Rewrite the RetroArch Cloud Sync architecture section: add the PSP,
  kiosk, size cap and missing-file behavior, drop the stale hash note
- Document SYNC_RETROARCH_PSP_SERIAL_MAP in env.template and the env table
- Trim two docstrings and reuse CLIENT_DEVICE_IDENTIFIER for the device type

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:53:22 -04:00
Georges-Antoine Assi
7e7e5a671d refactor(sync): apply simplify pass
- Enforce the upload size cap on streamed bytes in the middleware, so
  chunked uploads to every guarded route are bounded, not just RetroArch
- Flag vanished assets missing_from_fs from the manifest instead of
  re-hashing them every sync
- Batch state screenshot lookups, filter PSP bundles in SQL, hash files
  in one thread hop, and read only the requested PSP bundle members
- Reuse remove_screenshot and content_hash_of_bytes, merge the save and
  state PUT branches, drop dead checks and trim docstrings and tests

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:50:49 -04:00
Georges-Antoine Assi
918afcf1df fix(sync): apply code-review xhigh findings
- Stream RetroArch PUT bodies with a byte cap, so a chunked upload
  can't bypass the Content-Length check and exhaust memory
- Map shared core folders back to the mednafen_* ids the web player uses
- Enforce PSP bundle limits on write, return 409 for invalid bundles,
  and never delete an unreadable bundle when removing one member
- Challenge the kiosk guest so RetroArch sends credentials
- Move a slot-matched state's row with its bytes, scan saves under the
  name actually written
- Reject NUL path segments and core folder names over the emulator
  column length
- Cache PSP bundle member hashes in the manifest

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:34:05 -04:00
Sam Dornan
d084723bfb fix(hltb): accept token-only sessions and discover the endpoint when GitHub fails (#4758)
* fix(hltb): accept token-only sessions from /init

HowLongToBeat's /api/search/site/init now returns only a token and the
site's own search sends just x-auth-token. parse_session still required
hpKey and hpVal, so every mint read as "no session" and all HLTB lookups
(and the endpoint discovery workflow) silently returned nothing. The
honeypot pair is now optional and only sent when HLTB issues it.

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

* review: share the honeypot check and narrow optional mock calls

Move the both-fields honeypot check into HLTBSession.honeypot() so the
headers and body cannot drift apart, drop the historical note from its
comment, and assert mock call args are not None before reading kwargs.

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

* feat(hltb): discover the search endpoint from HLTB when GitHub fails

If the endpoint fixture can't be fetched from GitHub, run the same
build-manifest discovery the weekly workflow uses against HLTB itself,
and fall back to the fixture bundled in the image rather than the stale
hard-coded /api/find. The discovery helpers now log instead of printing
so their output joins RomM's logs. Search requests also send an Origin
header, as the browser does for HLTB's same-origin POST.

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

* fix(hltb): keep a malformed discovery response from aborting scans

parse_session and the discovery validator called .get() on whatever JSON
HLTB returned, so a non-object body raised AttributeError out of
initialize() and aborted the scan. Both now reject non-object JSON, and
the handler logs any discovery failure and keeps the bundled endpoint.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 14:20:47 -05:00
Sam Dornan
2badf9e11d fix(hltb): match search results by their aliases too (#4760)
HLTB search results carry `game_alias`, a comma-separated list of
alternate titles (often the Japanese or regional name), but only
`game_name` was scored. "Rockman X (Japan)" matched "Rockman EXE WS"
instead of "Mega Man X" (alias "Rockman X"), and "Seiken Densetsu 3
(Japan)" matched nothing although "Trials of Mana" carries that alias.

Each result is now scored against its name and every alias, keeping the
best score per game, as howlongtobeatpy does. The match still returns
the game's real name and id. Real names are listed before aliases so an
alias repeating another result's name cannot take its match.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 14:09:14 -05:00
Sam Dornan
164c2e39d8 fix(hltb): retry a separated title with the separator dropped (#4759)
* fix(hltb): retry a separated title with the separator dropped

get_rom rewrites " - " as ": " before searching, but HowLongToBeat
returns nothing for "pokemon: emerald version" (or the dashed form),
while "pokemon emerald version" finds "Pokémon Emerald Version". The
tail-only retry ("emerald version") scores under the 0.85 gate, so the
ROM went unmatched.

_search_and_match now retries "<head> <tail>" before the looser
tail-only search. The split is still on the colon only, so in-word
hyphens ("spider-man 2") trigger no retries.

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

* refactor(hltb): trim the search docstring and type the test fakes

Addresses review: the docstring is one sentence, and the search_games
fakes carry the parameter and return annotations the real method has.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 14:08:22 -05:00
Georges-Antoine Assi
638a21f88b fix(sync): don't log missing files when hashing the RetroArch manifest
Every manifest read (GET and each PROPFIND) hashes every save and state
row, and failures aren't cached, so a DB row whose file is gone logged a
debug line on every sync. A missing file is expected there; other OSErrors
are still logged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 14:50:25 -04:00
Georges-Antoine Assi
49e8d380e9 refactor(sync): rename the RetroArch blob handler to retroarch_sync
FSRetroArchSyncBlobHandler becomes FSRetroArchSyncHandler, and
SYNC_RETROARCH_BLOB_BASE_PATH becomes SYNC_RETROARCH_BASE_PATH, stored
under /romm/retroarch_sync.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 14:20:06 -04:00
Georges-Antoine Assi
4c85d7f263 feat(sync): register RetroArch as a device on first sync
Each manifest.server fetch creates the user's RetroArch device if it is
missing, or bumps its last_seen, so RetroArch shows up alongside the
user's other devices. RetroArch's requests carry no install identity, so
it is one device per user, deduped on client_device_identifier.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 14:10:53 -04:00
Georges-Antoine Assi
7c7f27d701 refactor(sync): mount RetroArch Cloud Sync under /api/sync/retroarch
The manifest protocol is RetroArch's own, so name it after RetroArch
rather than its WebDAV transport, and group it with the existing sync
code: endpoints/sync/ becomes a package with the RetroArch router as a
subroute, and the handlers move under handler/sync/retroarch/. Settings
move into the SYNC config section as SYNC_RETROARCH_*.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 14:07:39 -04:00
Georges-Antoine Assi
66fb93eca1 refactor(webdav-cloud-sync): rename cloud_sync to webdav_cloud_sync
Group the handler modules under handler/webdav_cloud_sync/ (sync_handler,
psp, emulator_names, browser) and rename the endpoint, blob handler, tests,
config settings, storage folders and cache keys to match. The route moves
from /api/cloud-sync to /api/webdav-cloud-sync.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 13:54:23 -04:00
Georges-Antoine Assi
67884fba8f refactor(cloud-sync): rename PSP_SERIAL_MAP to CLOUD_SYNC_PSP_SERIAL_MAP
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 13:50:31 -04:00
Georges-Antoine Assi
a28943ba14 refactor(cloud-sync): move settings into their own config section
Buffer pending PSP save files under cache/cloud_sync instead of a
top-level cloud_sync_psp_pending folder.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 13:47:36 -04:00
Sam Dornan
2ffe41c516 test(backend): catch column nullability drift between models and migrations (#4756)
* test(backend): catch column nullability drift between models and migrations

Alembic's autogenerate ignores a nullability mismatch on a generated
column whenever the model leaves `nullable=` unset, which `Mapped[...]`
inference does. Such a mismatch surfaced in review on #4647 with no
check here able to see it.

Two guards close the gap:
- a reflection test comparing every mapped column's nullability (and
  existence) against the migrated schema, skipping views;
- a static test requiring every database-filled column to pass
  `nullable=` explicitly, so autogenerate compares it again.

The five existing `FetchedValue` columns on `roms` now declare
`nullable=True`, matching their DDL. No schema change.

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

* test(backend): check server_onupdate in the database-filled nullability guard

Alembic skips the nullability comparison whenever the reflected column
is generated, so a column mapped with only `server_onupdate=FetchedValue()`
is just as invisible to autogenerate as one with `server_default`.

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

* test(backend): trim the drift test docstrings to one sentence

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 12:41:02 -05:00
Georges-Antoine Assi
0553dcae78 fix(cloud-sync): address Greptile and CodeQL review findings
- Resolve PSP folder paths from the same bundle set the manifest lists
  (visible ROM, unslotted, newest per folder), so GET/PUT/DELETE can no
  longer hit a slotted history bundle or a hidden ROM's bundle.
- Split validate_path's base-directory case out of its startswith guard,
  so CodeQL recognizes the guard as a py/path-injection sanitizer.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 13:34:26 -04:00
Georges-Antoine Assi
65c49444fc chore(cloud-sync): review-polish pass
Trim the remaining multi-line test docstrings and blob comment, and drop
the -- dash stand-ins.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 12:01:48 -04:00
Georges-Antoine Assi
d5d9196db3 refactor(cloud-sync): apply simplify pass
- Hoist the file MD5 onto FSHandler; drop the blob handler copy
- Share path splitting, slot recency, cached MD5 and ROM visibility helpers
- Remove dead code (get_state_by_path, RomFile.file_ids, unused params)
- Scope WebDAV rom listing to one query; look up a single platform by slug
- Query saves once per manifest and batch ROM name resolution
- Read only the requested PSP bundle member; hash bundles from memory
- Single separator-safe lexical check in validate_path; same joined-path
  validation in write_file_streamed
- Stop stripping + on ROM rename, the download path encodes it (#2746)
- Trim comments to the repo's comment rules

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 11:55:32 -04:00
Georges-Antoine Assi
9e7933ae97 fix(cloud-sync): apply code-review xhigh findings
- Bound /api/cloud-sync uploads with the asset size limit
- Cap PSP bundle member count and uncompressed size
- Keep PSP writes and deletes on the existing bundle row, one member at a time
- Match PSP bundles by exact folder, support the no-core-folder layout
- Reject . and .. PSP segments; map parse_sfo struct errors and write
  errors to 4xx
- Require ROMS_READ for roms/ browsing
- Clear missing_from_fs on overwrite
- Resolve state screenshots by exact name, never a gallery screenshot
- Round-trip unknown core folder names exactly
- Keep + allowed in the shared sanitizer, strip it only on ROM rename (#2746)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 11:31:51 -04:00
Georges-Antoine Assi
c591ffc163 feat(sync): name the ROM in sync:conflict and log failed sync emits
Every sync:conflict emitter now sends rom_name, so the v2 toast names the
game without hunting through frontend caches. Push-pull emits from the
conflict branch with the matched save's rom_id and comparison reason
instead of rom_id=0. All emit_sync_* helpers go through
socket_handler.emit_to_user, so a broker failure is logged rather than
counted as a failed sync.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 11:05:42 -04:00
Georges-Antoine Assi
cf113a8fd7 simplify: emit negotiate conflicts sequentially under one deadline
With the emits off the response path, the semaphore and gather fan-out
bought nothing. The conflict tests share the module-level negotiate helper
and an emit patch, and the toast tests share their install and fire setup.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 10:56:05 -04:00
Georges-Antoine Assi
008dee6c27 ci: validate the joined write_file path for CodeQL
The remaining py/path-injection alerts flowed through write_file's
filename argument (cloud-sync blob PUTs), which only went through
os.path.basename. Validating the full directory + filename path routes
it through validate_path's normpath guard too.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 10:53:24 -04:00
Georges-Antoine Assi
419372ac6c review: emit negotiate conflicts from a background task
asyncio.run in the threadpool drove the process-wide socket write manager
from a throwaway loop, racing the main loop and leaking Redis pools. The
events now go out after the response on the app loop. Also logs timeouts
distinctly, corrects the connection comments, and unmounts test hosts.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 10:53:07 -04:00
Georges-Antoine Assi
be31b99f1b Merge remote-tracking branch 'origin/master' into feat/surface-save-sync-conflicts
# Conflicts:
#	frontend/src/v2/layouts/AppLayout.vue
2026-09-24 10:41:34 -04:00
Georges-Antoine Assi
899f859a9b ci: satisfy bandit and CodeQL path-injection checks
Swap xml.sax.saxutils.escape for html.escape(quote=False), which bandit
does not flag as an XML parser import. Add a normpath + startswith guard
to validate_path so CodeQL recognizes it as a path-injection sanitizer.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 10:34:37 -04:00
Georges-Antoine Assi
f6607c8ede Merge pull request #4537 from rommapp/renovate/major-mariadb
chore(deps): update mariadb docker tag to v13
2026-09-24 10:31:24 -04:00
Georges-Antoine Assi
e81bcef430 review: only advertise cloud-sync assets their path resolves back to
Addresses Greptile's review on #3904: a manifest path carries no platform,
so a same-named ROM on another platform (or a save whose file name matches
no ROM) was advertised under a path GET/PUT/DELETE resolve elsewhere.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 08:26:14 -04:00
Georges-Antoine Assi
7808bf004b Merge remote-tracking branch 'origin/master' into feat/retroarch-cloud-sync
# Conflicts:
#	backend/handler/database/states_handler.py
#	backend/tests/utils/test_filesystem.py
2026-09-24 08:22:22 -04:00
zurdi
c2c2dd6380 refactor(audit): address Greptile's second review
- The audit read endpoint keeps the access decision but hands the
  category filter to the DB handler, which expands it to actions.
- Trim the log viewer's header comment to two lines and drop its
  em-dashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:03:45 +02:00
zurdi
fabbeef3f1 fix(audit): address the Greptile review
- Record a firmware or rom delete once its row is gone, with whether the
  file actually left the disk, even when cleaning up after it fails.
- Record a download only once there's a response to send, so a missing
  file or a failed zip isn't logged.
- Release a download's, sign-in's or reset request's dedupe claim when its
  event can't be stored, so a retry records it.
- Count the games a collection actually gained or lost.
- Queue the reset-request event before the email, which stops the tasks
  after it when it fails.
- Let an event's data be a lookup, run inside the recorder's error
  handling, for the hide, unhide and permission events.
- Follow a query change while the Events tab stays open, and don't show a
  load error once it has closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 12:55:23 +02:00
zurdi
6ffaf53281 chore(audit): mark the audit action names as bandit false positives
Bandit's B105 reads the password-reset and client-token action names as
hardcoded passwords.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 12:42:16 +02:00
zurdi
92f9776772 refactor(audit): apply the second pr-ready simplify pass
- Event log: watch the scroller's own container and web font loads through
  vueuse, re-measure only for a font the rows use, and keep the measurers
  when only the width changes.
- Measure each word once on one shared canvas, and stop counting lines at
  the clamp.
- Set the row geometry once on the list, from one source for the padding
  and gap, instead of on every row.
- Share the file-and-size detail between downloads and player loads, read
  the collection cover change off the saved data, and use recorded_events()
  in the play-session test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 10:28:24 +02:00
zurdi
a779fa41f7 fix(audit): apply the second pr-ready code review
- Re-measure the phone event rows whenever a web font finishes loading,
  and when a scrollbar narrows the rows, not only at mount.
- Log only the kind of an audit claim key when Redis fails, since a
  failed sign-in's key holds the text typed as the username.
- Make play-session ingest take the caller's permissions explicitly, so
  no caller skips the hidden-rom check by leaving them out.
- Read an empty collection cover URL as no cover, as the other fields do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 10:18:57 +02:00
zurdi
5cccceea60 fix(audit): close the gaps left open by the pr-ready review
- A failed login keeps the attempted username only when it names an
  account, so a password typed into the username box is never stored.
- Gunicorn trusts X-Forwarded-For only from loopback and private ranges
  (FORWARDED_ALLOW_IPS, documented in env.template), so a client can no
  longer choose the address the audit log and rate limits see.
- A player's fetch (purpose=play) is recorded as rom.player_load instead
  of being skipped, so the marker can't hide a download.
- Play-session ingest treats a rom hidden from the caller as unknown, so
  its session and rom.play event don't name it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 08:08:53 +02:00
zurdi
72c4dc7ecb docs(audit): apply the pr-ready review polish
Trim comments to what the code can't say, type the remaining test
fixtures, and document the audit_events table, GET /api/audit-events
and the cleanup_audit_log task in the backend architecture guide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 02:49:27 +02:00
zurdi
d9d65d8b56 refactor(audit): apply the pr-ready simplify pass
- record() takes the request as its actor, and a target can be a
  function: the lookups that name it now run inside the recorder's error
  handling, and for downloads only once the dedupe lets them record.
  That also restores the minimal visibility query on the file route.
- One changed_fields/change pair for rom, user, collection and platform
  edits, one collection helper, AuditActor.anonymous, a shared
  count_in_window and current_device_id, one test helper for recorded
  events and one fixture for audit events.
- The describers share simple/counted/visibility builders and the
  eventData readers with notifications, join lists per locale, and treat
  any *.delete as unlinked.
- EventLog builds one item list with the phase folded in, keeps each
  event's sentence across pages, formats days once, and loads users
  through the users store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 02:45:12 +02:00
zurdi
6298e7bf8c fix(audit): apply the pr-ready code review
- Hide events on roms of a hidden platform from non-admins.
- Pin later pages to the highest matching id the API returns, not the
  first row's: rows are ordered by when they happened, so a play synced
  late has a higher id than newer events and was dropped.
- Cap recorded failed sign-ins per address, dedupe reset requests and
  record them in the background with the email, and hash claim keys.
- Keep another user's private collection by id only in bulk downloads.
- Check a Range start without int(), which raises past 4300 digits.
- Clear the list when a reload fails, load more only once it's shown,
  report a cover change only when the user made one, label only rom and
  platform unhides, accept an actor kind the API doesn't know.
- One client IP helper, date-fns for today and yesterday, one time
  formatter for the list, no em-dashes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 02:30:47 +02:00
zurdi
c2a72b322e feat(audit): search the audit log by IP address too
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 01:46:16 +02:00
zurdi
1aa614c321 fix(audit): report only the rom fields a user edited
A save turns null cover and manual urls into empty strings, and a rename
re-derives the sort name; neither is an edit of its own. Also fixes the
test helpers the first local run caught.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 01:33:29 +02:00
zurdi
66deda768c feat(audit): record scans, tasks, sign-ins and account changes
Scans leave a start and an end with their stats, or who stopped them;
manual task runs, sign-ins by session, token and OIDC, failed sign-ins
(one per address and username a minute), password resets, account and
permission changes, client tokens and device approvals each leave an
event. UI settings saves and avatar changes are left out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 01:24:36 +02:00
zurdi
b65ca93bfb feat(audit): record library and collection changes
Uploads, physical adds, edits, manual matches, unmatches and deletes of
roms and their files, platform and firmware changes, config changes and
collection edits each leave an event. An edit that moves a provider id
is a match; a save that changes nothing is not recorded. Favourites are
left out, since every heart toggle is a collection add or remove.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 01:19:22 +02:00
zurdi
283c92c278 feat(audit): record downloads and plays
A ROM, file or bulk download is recorded once per caller within ten
minutes, and only when a transfer starts from the first byte, so range
requests and retries don't multiply it. In-browser players mark their
fetch with purpose=play, and the session they report becomes a rom.play
event instead. Feeds and QR links still count as downloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 01:14:34 +02:00
zurdi
0afbe2ef57 feat(audit): add the audit_events table, recorder and read API
A persistent record of what users, or RomM itself, did. Admins read
everyone's events through GET /api/audit-events; anyone else gets only
their own. Events older than AUDIT_LOG_RETENTION_DAYS (90 by default,
0 keeps them) are pruned nightly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 01:05:59 +02:00
Zurdi
eaba9c70d1 Merge pull request #4743 from rommapp/claude/rq-workers-restart-loop-588783
fix(docker): stop the watchdog from spawning duplicate RQ workers
2026-09-24 00:01:21 +02:00
zurdi
5cd71a244c simplify: pin the RQ worker PID write with a plain substring check
The test checks the one line the watchdog relies on, next to the keepalive
pair instead of between it, and the comment states RQ's late write once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:17:21 +02:00
zurdi
ce36d3f0fb review: guard the RQ worker PID file and comment it where it is written
Adds a test that start_rq_worker records $! instead of passing --pid, and
moves the comment next to the line it explains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:14:34 +02:00
zurdi
56a9609303 fix(scan): read a kept blob only when it holds lists of strings
Addresses Greptile's review: an edit of a ROM's raw metadata stores
whatever JSON it is given, so a skipped source's stored blob can be a
list or a string, and a dump_* value a bare string. Reading it assumed an
object and would have crashed the ROM's scan or split a tag into
characters; anything else is now read as no tags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 19:25:56 +02:00