Two comments described HTML documents as sanitized on ingest. Nothing
sanitizes them: the only `sanitize_*` helpers cover filenames and usernames,
and `is_html_document_file` is consulted at serve time only. The sandboxing
CSP and the viewer's iframe sandbox are the whole defence, so describe them
that way, and pin the header with a test before someone drops it believing
the sanitizer exists.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The size checks around the extraction read `ZipInfo.file_size`, which is
whatever the uploader put in the header, and the check on the finished file
only ran once the member had been written in full. An archive whose method
zipfile cannot decode goes through 7zz, which decompresses it itself and
ignores that header, so a small declared size passed the pre-check while the
real member filled the disk.
Count the bytes as they are written and stop at the cap, which makes the
check on the finished file redundant.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Addresses Copilot review feedback on PR #4617.
The Docker dev image's bind-mounted .git is host-owned while the
romm-dev container runs as root; git 2.35.2+ refuses that mismatch
as "dubious ownership" and rev-parse fails, so GIT_BRANCH silently
stayed null and the UI kept showing "development" in the very
workflow the mount was added for. Pass safe.directory scoped to
this one read-only invocation instead of touching global git config.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TDMqXzXexRgC89YxeNjn9q
Trunk Check failed on the PR: bandit flags importing subprocess
(B404) and invoking "git" by name instead of an absolute path
(B607), on top of the B603 shell=False call already suppressed.
Both are accepted here for the same reason B603 was: git is
resolved from PATH by design so this works across dev setups
(Docker and bare-metal alike), and the arguments are hardcoded.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TDMqXzXexRgC89YxeNjn9q
- AboutDialog's links list was a static array read once at setup, so it
never picked up a later heartbeat update; made it a computed.
- useVersionDisplay's GitHub tree link blanket-encoded the branch name,
breaking "/" as a path separator (e.g. "feature/foo"); now encodes
each segment. Deduped the dev-build/branch check into one computed.
- Trimmed two over-long comments/docstrings per house style.
- Added coverage: a CalledProcessError case for get_git_branch, and a
full test file for useVersionDisplay.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TDMqXzXexRgC89YxeNjn9q
Local checkouts have no release tag, so heartbeat.SYSTEM.VERSION always
falls back to the literal string "development". Add a GIT_BRANCH field
(backend-resolved via git, display-only, not used in the version string
that also feeds outbound User-Agent headers) and use it in the About
dialog and the auth-screen VersionTag so a dev build shows the branch
being worked on instead.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TDMqXzXexRgC89YxeNjn9q
Simplify pass over the animated cover change:
- Encode animated small covers as WebP whatever the source, which drops
the per-format GIF/APNG blending params and makes their WebP copy a
plain file copy.
- Fold the is_animated gate into frame_durations and decode the small
cover's frames in the same pass that reads their durations.
- Write uploaded animated artwork through the atomic write_file.
- Share test fixture constants and the animation encoder, and pin the
per-frame pixel budget with a GIF whose canvas grows mid-animation.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Code-review pass over the animated cover change:
- Cap the pixels decoded across an animation (MAX_ANIMATION_PIXELS),
counted per frame since a GIF canvas can grow mid-animation, so an
oversized animation falls back to its first frame.
- Fall back to the first frame when a later frame fails to decode,
instead of dropping the cover or escaping the error handlers.
- Store uploaded animated artwork as uploaded, like downloaded covers.
- Re-encode composited frames so each replaces the last (no GIF/APNG
ghost trails), and keep GIF loop counts when converting to WebP.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The small cover and the WebP copies were written through PIL, which keeps
only the first frame, so an animated SteamGridDB cover showed as a still
image everywhere once applied. Resize and convert every frame with its
timing, copy WebP sources instead of re-encoding them, and keep all
frames of uploaded animated artwork.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sort title id sources with the natural key the models already compute,
give the compressed suffixes one home, and let SigilService reject a
container itself rather than trusting every caller to.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Order discs by their number so "Disc 2" precedes "Disc 10", test one
rule for containers sigil cannot read, and drop the unreachable
OSError handler around Path.is_file.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Treat every disc descriptor as a disc, not just .cue
playlist_files keyed on .cue alone, so a Dreamcast .gdi set, a CloneCD
.ccd set and an Alcohol .mds set all fell through to "every file is a
disc" -- the descriptor and the raw tracks it cannot boot without were
listed side by side.
The three readers of the rule each got that wrong in their own way: the
playlist shipped inside the download zip named non-bootable tracks, and
the in-browser disc swapper offered them as discs.
Key on a set of descriptor extensions instead, so no one sheet format is
privileged over the others. The shape is unchanged -- descriptors if any,
else everything -- and so is the download zip, which lists every file
regardless.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* Keep a disc that stands on its own beside a descriptor
Selecting descriptors and discarding everything else assumed a multi-file
ROM is all one format. It is not: a .chd sitting beside a .gdi boots on
its own, and returning only the .gdi dropped it from the playlist and
from the swapper's targets.
Exclude the raw tracks a sheet points at instead of keeping only sheets.
The tracks are still not discs, so every case the previous commit fixed
stays fixed, and a disc no sheet describes now survives.
This also settles the same bug on the .cue path, which predates this
branch: disc1.cue + disc1.bin + disc2.chd used to list the cue alone.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* Count a sheet's audio tracks as tracks
A .cue names its CDDA tracks the same way it names its data track, so a
.wav or .flac beside one is data, not a disc. The playlist listed them.
Brings the list in step with the shell's own in src/main/discs/m3u.ts,
which has carried the audio formats since it was written.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Trigger names are schema-wide, so the fixed probe name could name an
operator's own trigger, and DROP TRIGGER IF EXISTS would really remove it.
A fresh uuid per call makes the statement a guaranteed no-op, so the only
error it can raise is the refusal it is looking for.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A module-level exception tuple freezes zipfile.BadZipFile, but seven test
modules reload the zipfile module, which rebinds the class. After any of
them runs, a corrupt archive escaped the handler and surfaced as a raw
BadZipFile instead of a 400. Look the class up at raise time instead.
NotImplementedError goes with it, being a RuntimeError subclass.
Declare each rebuilt entry's final size instead of passing force_zip64,
so zipfile marks an entry ZIP64 only when it needs to; a patched ROM
handed to a basic unzip implementation was otherwise rejected even though
the unpatched archive loaded fine.
Drop the extracted and patched intermediates once they are consumed,
rather than holding three full-size copies for the life of the download.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- `rebuild_generated_columns` owns the index drop, since it is the one
place a column is dropped, so 0123's downgrade gets it too.
- `ensure_roms_columns` builds its action list first and runs on it, and
no longer re-reflects the table to re-test a column it just added.
- One list behind `STEAM_FED_COLUMNS`, and `INHERITED_COLUMNS` says what
the set difference at the use site used to.
- 0112 builds the view through `roms_metadata_view_sql`, and 0126 drops
the add-column branch the shared copy made unreachable.
- Tests share one generated-expression helper and read index and column
names off the module that owns them.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
- `drop_roms_columns` drops a composite index that still spans a column
it removes before the ALTER: MariaDB and MySQL would otherwise keep the
index over the remaining columns, so 0126's unique index left by a run
that died before its stamp would become UNIQUE (platform_id).
- `ensure_roms_columns` recreates `roms_metadata` whenever it is absent,
so a run that died between its ALTER and the CREATE VIEW gets the view
back on the replay instead of only when a rebuild is pending.
- A generated column the engine does not reflect as computed counts as
not reading Steam and is rebuilt, rather than raising a KeyError.
- One home for the `steam_metadata` column name, imported by 0123.
- Tests pin the lost view, the leftover MariaDB default and the surviving
unique index; the ALTER recorder matches `roms` as a whole word.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
0108 adds every column of the 5.3.0 catalog, so a chain that stopped
before a later revision and then downgrades to 0107 used to keep that
revision's columns, including a NOT NULL full_path_hash on MariaDB that
5.2.0 could no longer insert around. `drop_roms_columns()` now removes
whatever of the catalog is still there in one ALTER TABLE, restores the
pre-Steam expressions on the 0098 columns, recreates the view over what
remains and drops the PostgreSQL enum type.
The plain column list no longer needs a connection, so the enum type is
created just before the ALTER that needs it and dropped through one
helper shared with 0116.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Every ALTER TABLE roms copies the whole table: the FULLTEXT index from
0084 rules out ALGORITHM=INSTANT (its hidden FTS_DOC_ID column survives
even a DROP INDEX), and a STORED generated column takes ALGORITHM=COPY on
every engine. The 5.2.0 -> 5.3.0 chain issued 21 such ALTERs, one per
revision, so a library with a JSON blob per provider on every row paid
for 21 copies.
`utils/roms_columns.py` now declares every column the chain puts on
`roms`, plain and generated, and `ensure_roms_columns()` adds whatever
the table lacks in a single ALTER TABLE. Each revision that used to add
its own columns calls it instead, so the first one to run on a database
does the copy and the rest find their columns in place. A table whose
generated columns predate 0123 is recognised by the provider they do not
read yet and rebuilt at the current definition in the same statement.
On MariaDB the copy also fills `full_path_hash` through a column
referencing DEFAULT that is dropped right after, so 0126 no longer runs a
whole-table UPDATE through the roms_facets triggers followed by a NOT NULL
rebuild.
Measured on a 73k-ROM copy of the dev library (MariaDB 11.3.2, 128 MB
buffer pool): 168.5s -> 48.9s for 5.2.0 -> head, with one 16s copy where
there were 21 rebuilds. The resulting schema is identical to the old
chain's on MariaDB and PostgreSQL, and a fresh install lands on the same
schema on MariaDB 10.11.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The gate tested command names alembic never passes: it hands its environment
the per-command `fn` name, so `do_stamp` and `display_version` are what reach
it. Pin that with a canary over the closure the gate matches.
Probe before reading the applied heads, so only a server that refuses pays for
the lookup and the other dialects pay nothing, and fold the tests into the
module they mirror.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Verified against MariaDB 10.11, 11.3 and 11.8 with binary logging on: BINLOG
ADMIN does not lift the denial, only SUPER or the global flag does, and MySQL
8.4 never denies at all. The message said otherwise.
The probe also ran for every command that loads this env, so `current` and
`stamp` failed over a privilege they never need, while a downgrade at head
skipped the probe and could still half-drop a schema. Gate it on the commands
that execute revisions instead.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
MySQL and MariaDB reject every trigger statement, DROP TRIGGER IF EXISTS
included, while binary logging is on and the database user holds neither
SUPER nor BINLOG ADMIN. Ten revisions install triggers, so any of them
could abort startup with a raw traceback and leave a half-migrated schema
behind.
Probe the privilege once, before the first pending revision runs, and
fail with the two server-side fixes spelled out.
Fixes#3932
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Review polish over the whole change: every comment block over two lines
cut back, and the two carrying change history rather than current
behaviour rewritten to describe what the code does now.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
Three defects the review pass turned up:
`from_stored_criteria` raised on a smart collection whose stored
`filter_criteria` holds a value the model rejects. That JSON is written
unvalidated and read in a loop over every smart collection, so one bad row
stopped all the later ones from refreshing on any ROM write, and 500'd a
public smart collection. It now drops the entries it cannot honour, which
is what the criteria reader did before it validated anything.
Two comments claimed `metadata_providers` matches id columns on `Rom`. It
matches them on the facets mirror, so a reader trusting the comment
concludes the filter needs no join and cross-joins `roms_facets` into the
query. Corrected, and pinned by a test asserting every registered filter
joins the mirror exactly once.
`as_query_dependency` silently mis-built a route for a field with an alias
or a `default_factory`, the latter sharing one mutable default across
requests. Both now fail at startup, and the helper has the tests it
shipped without.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
Give the "which columns does this table already have" set a home as
`column_names`, and define `has_column` over it: 0098, 0112 and 0123 each
spelled it inline, and 0112 paid one full reflection of `roms` per candidate
column.
Use the builtin idempotency flags wherever they reach. 0121 was the last
revision guarding a column and an index by hand, and 0122 had two code paths
emitting the same statements; both now match 0111/0126/0128.
Skip 0126's digest backfill once the column is NOT NULL, so a replay no longer
full-scans `roms` to match zero rows.
Drop the test helpers that re-derived what `_schema_of` already returns, and
collapse the four-way `has_column` parametrize, two cases of which were really
schema assertions about 0112 and 0121.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The filter vocabulary (13 multi-value filters with their logic operators,
plus the boolean and scope filters) was written out in five places: the
`/api/roms` query parameters, `filter_roms`'s 63-line signature, the
`kwargs.get` block in `get_roms_scalar`, the criteria translation in
`get_smart_collection_criteria`, and the `is_unscoped` test that decides
what may be cached.
That last one is the dangerous copy. The gallery's sidecar caches are keyed
on user/order/grouping but not on the filters, so a filter missing from
`is_unscoped` would let one user's narrowed gallery be stored under, and
served from, the shared "all" key.
`RomFilterParams` becomes the single home. The route takes it as a
dependency, `filter_roms` reads its fields, and smart collections rebuild
it from their stored criteria (legacy `selected_*` keys and the
`platform_id` scalar included, keeping `from_stored_criteria` the only
place that knows about them). `has_filters` now reads the model's own
fields, so a filter added later counts towards the cache gate without
anyone remembering to list it, and a test asserts that for every field.
The route reaches the model through `as_query_dependency` rather than
`Annotated[RomFilterParams, Query()]`, because FastAPI expands a query
model into its fields only when the model is a route's *only* query
parameter. `/api/roms` has a dozen others, so the native form would leave
one required parameter named `filters`: the schema would advertise it, the
generated client would be built from that, and a request carrying the
fields themselves would be rejected. A dependency's parameters are
flattened individually, so building one from the model keeps the fields.
An endpoint test pins that, since the failure is silent.
The API contract is unchanged: `/api/roms` still takes the same 58 query
parameters with identical types, descriptions, defaults and constraints,
and regenerating the frontend types from the new schema produces a
byte-identical `src/__generated__`. Only the order of the parameters in
the OpenAPI array differs, since FastAPI lists a dependency's parameters
after the route's own.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLreYqGLgHJLei6NThVXCz
MySQL and MariaDB auto-commit each DDL statement, so a revision that dies
partway keeps what it created while alembic_version stays behind. Every
start after that replays it and dies on a duplicate object, hiding whatever
actually stopped the upgrade and leaving the instance on a half-migrated
schema.
Eleven revisions create something ahead of a step that can fail. Most take
the guard alembic already offers; three need more:
- 0122 declares its indexes inline so InnoDB adopts one for the foreign key,
and alembic issues those as their own statements, so `if_not_exists` on
the table would not cover them. It reflects the table instead and fills in
whichever index is missing.
- 0123 rebuilds its generated columns in one ALTER TABLE, so it now drops
only the columns that are there and re-adds them all.
- 0126 resumes at whichever of its four steps the previous run reached.
`full_path_digest_sql` also coalesces a NULL fs_path/fs_name to match
`compute_full_path_hash`, since the disagreement folded the whole row to
NULL and aborted 0126 at its NOT NULL step.
Combines #4479 and #4481, whose fixes are carried here in full.
Co-Authored-By: Sam Dornan <sam.dornan@athleticgreens.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The schema key, its version and the keys they cover were three constants per
store, retyped at each of the six places that used them and interchangeable
enough that one store's version could be checked against another's keys. They
are a `VersionedCacheStore` now, so a store is declared once and the startup
drop is a loop over a table.
The two reader gates were the same four lines, and a third read path was
still checking the data key without the stamp, so the LaunchBox entry points
disagreed about what populated meant. All three call one helper.
The drop probed each key before deleting it, spending a round trip per key to
learn what `unlink` reports anyway, and `delete` freed the store on the main
thread. Both imports also merge into their hashes, so each now drops a stale
store itself rather than trusting the drop to have happened at startup.
The alternate name index holds the bare id its reader wants, like the two
title indexes beside it, and follows through the same helper.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The readers tolerated both the old and the new shape of every index this
branch changed, which left two shapes supported forever and, on an install
whose scheduled update is off, meant the old store answered every lookup
and the saving never landed at all.
Each store now carries a schema stamp. A store whose stamp is missing or
stale reads as unpopulated, is dropped at startup, and has its import
queued the way the WebP backfill is, so the shape change causes the
rebuild instead of being worked around. The readers know one shape again.
The projection each store is written with moves next to its key, and the
three stores that had none get one: Mame.xml kept 24 fields per record to
serve `Name`, Files.xml kept the platform and filename its cache key
already carries, and an alternate name entry kept the name it is stored
under. Together with the image list that is ~135MB.
Measured against the real dump: the eight LaunchBox hashes hold 385MB, and
a store stamped by an earlier release is dropped at startup for 386MB of
`used_memory` reclaimed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`preferred_username` was stored verbatim, so a provider that issues
`first.last` created an account whose username RomM's own rules reject.
The account works for login but cannot be edited afterwards: every write
through the users endpoints re-runs `validate_username` on it.
Coerce the name to the allowed charset at registration, falling back to
the email local part when nothing usable survives, and suffix it until it
is free since the column is unique.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Comment and docstring pass over the `released_days` change: cut the copies of
rationale that already live next to the thing they describe, and drop the
sentences defending obvious choices.
`RELEASED_DAY_REGEX` now carries the calendar ranges, so a match is a valid day
and `parse_released_days` needs no sentinel pair and no second range check.
`release_day_ranges` stops re-sorting what `epoch_ms_in_ranges` already sorts.
`anniversaryQuery`'s return type is a named export, so the widget imports it
instead of unwrapping a `ReturnType`, and the widget's two reset paths share
`showEmptyDay`.
`loadMore` is `loadNextPage`, since it appends one page rather than the rest.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`GET /api/roms` already does what `/roms/anniversaries` hand-rolled: it selects
ordered ids over the filtered set, takes the total from that index, hydrates
only the page asked for, and re-projects the rows into id order. So the widget
now asks it for a page rather than owning an endpoint that pulls the whole day.
`released_days` on the list endpoint takes days as "M-D", matching any year, and
`released_before_year` bounds them. Both go through `filter_roms`, so the same
day-of-year match is available to the gallery filters and to smart-collection
criteria, and the range union stays where it was: still sargable, still a
covering index range scan on `idx_roms_generated_first_release_date`, no SQL
date function and no dialect branching. Verified on a 73k-rom database that the
plan through the list endpoint's join is unchanged: `type=range`,
`Using where; Using index`, no filesort.
The filter means exactly what it says, so the calendar policy moved to the
client, where the clock it depends on already lived. `anniversaryQuery` picks
the days and the year bound off the viewer's own date: it skips 1 January,
where several providers park year-only metadata, rolls 29 February onto 28
February in a non-leap year, and bounds the years at the viewer's own. The
server no longer has to second-guess a timezone offset, so the 31 December
asked for on 1 January UTC correction is gone rather than fixed.
Consequences for the widget: the counter is the day's real total instead of one
clipped at a 500-row ceiling that no longer exists, and a card costs one page
of 24 rather than up to 4 MB up front. Paging backwards stays in memory;
only moving past the loaded pages fetches, with the spinner on the arrow so
focus is never yanked mid-page. A failed page keeps the card on screen.
`released_days` is added to the list endpoint's unscoped-cache gate: the
sidecar keys encode no filters, so a narrowed page must not be served under the
shared "all" key. Covered by a test that primes the unscoped key first.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>