ScreenScraper returns the account's allowances on every response, but only
maxthreads was read. Use the rest:
- Pace requests against the reported maxrequestspermin (falling back to the
documented threads x 50), so fast lookups can no longer overrun the
per-minute budget without ever exceeding the thread cap.
- Report the remaining daily and unrecognized-ROM quotas after each platform
and at the end of a scan, and warn once when either drops below 10%.
- Hint once per scan when SCAN_WORKERS is below the thread allowance (scans
slower than the account allows) or above it (extra workers just queue).
- Raise a distinct error when a request is refused twice for exceeding the
rate, so the ROM is reported as skipped in the scan summary instead of being
saved with no ScreenScraper data.
- Route ScreenScraper media downloads (covers, screenshots, manuals, mixed
media) through the same limiters, since they are api2 endpoints that count
against the same allowances, and derive their timeout from the account's
advertised download speed.
Fixes#3978
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Addresses the Greptile review on #3952.
- Reject oversized asset uploads from Content-Length in middleware, before
FastAPI parses and spools the multipart body to temporary storage. The
handler-level check stays as a backstop for chunked requests.
- Apply the limit to screenshot fields on the save, state and standalone
screenshot endpoints, not just the primary file.
- Clamp the autocleanup limit to at least 1 so a non-positive value cannot
wipe every save in a slot.
- Document the new settings in env.template.
Rename MAX_SAVE_UPLOAD_SIZE_BYTES to MAX_ASSET_UPLOAD_SIZE_BYTES now that it
covers states and screenshots too.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- Fix CORS misconfiguration: replace allow_origins=[*] with configurable
ROMM_CORS_ALLOWED_ORIGINS env var to prevent cross-origin session hijacking
- Make session and CSRF cookie Secure flag configurable via
ROMM_SESSION_SECURE_COOKIE for deployments behind TLS-terminating proxies
- Harden sanitize_filename() with os.path.basename() to strip directory
traversal components and reject . / .. entries
- Add upload size limit (MAX_SAVE_UPLOAD_SIZE_BYTES, default 512MiB) to
saves and states endpoints to prevent denial of service
- Cap autocleanup_limit parameter (MAX_AUTOCLEANUP_LIMIT, default 100) to
prevent unbounded resource accumulation
remove_persisted_cover swallowed OSError, so clearing cover_path
regardless dropped the only reference to a file still on disk. It now
reports whether the file is gone, and the path is kept for the next scan
to retry when it isn't.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A member that failed or timed out mid-archive ended the member stream
silently, so the caller kept the composite hash built from the members
that happened to succeed. Raise ArchiveReadError instead and fall back to
hashing the archive's raw bytes, with no archive_members recorded.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The bundled 7zz is built without the RAR codec (unRAR license), so it can
neither list nor extract RAR members. Every content-based match silently
came up empty for .rar: no RetroAchievements hash and no CRC/MD5/SHA-1 for
hash-database providers.
RAR listing and extraction now go through libarchive's bsdtar, added to the
images as libarchive-tools. Listing uses an mtree rewrite (libarchive's only
machine-readable listing) and member names are escaped before being handed
back to bsdtar, which matches them as globs.
Fixes#3884
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A platform folder created on disk (optionally bound in Library
Management) has no database row until its first scan imports a ROM, so
it was invisible to the scan platform picker and a first scan could not
be triggered for it. The picker also filtered to rom_count > 0, hiding
even zero-ROM database platforms (e.g. those created via romm-cli).
Backend:
- Add GET /platforms/filesystem returning folders on disk without a
database row yet (locally-resolved metadata, id -1, rom_count 0).
- scan_platforms / the scan socket now accept platform_fs_slugs so a
folder can be scanned by slug; database platforms stay accepted by id.
Frontend (v2):
- Fetch filesystem folders, key the scan picker by fs_slug, include
zero-ROM database platforms, and tag never-scanned folders.
Fixes#3832
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
A self-hosted PLAYMATCH_API_URL on a LAN IP, localhost, or a Docker
service name is rejected by the shared HTTP client's SSRF defense before
connecting, so health checks and lookups fail. Add a narrowly scoped
allowlist, derived from the admin-configured provider URL, that both SSRF
gates (the static URL hook and the connect-time backend) honor. The
exception is matched by exact host and port, and the public default URL
is unaffected since public addresses already pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Disable 7zz wildcard matching (-spd) when extracting a named member: a
member literally named with "*" or "?" would otherwise act as a pattern,
matching other members and concatenating them into the -so stream, which
would hash plausible-but-wrong data. Applied to all three extraction
call sites, including the two pre-existing readers that share the
hazard. Verified against the production Alpine 7zz build.
Route extraction stderr to an unlinked temp file instead of a pipe: a
filled pipe blocks 7zz while the parent waits on stdout.read(), which
the chunk-based deadline never interrupts. A file-backed stderr applies
no backpressure and is still read back for the error log on failure.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The bundled Alpine 7zz build lacks the RAR codec: listing RAR members
works, but streaming their contents fails with "Unsupported Method"
(verified against the production image).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
RAHasher only decompresses .zip archives itself; any other container
(.7z, .rar, .gz, .bz2, .xz, .tar, ...) was hashed as its raw archive
bytes, silently storing a well-formed hash that matches nothing on
RetroAchievements (issue #3808).
Non-zip archives on buffer-hash platforms are now extracted to a temp
file via the bundled 7zz binary and the extracted ROM is hashed instead.
The new extract_largest_archive_member helper follows the existing 7zz
subprocess patterns, handles single-stream formats whose listings carry
no Attributes line (.gz/.xz), and unwraps one level of nesting so
compressed tarballs (.tgz) reach the ROM inside the inner tar.
Arcade is exempt: its RA hash is computed from the file's basename, so
any container format already hashes correctly and extraction (which
renames the file) would break it. Disc platforms keep their existing
archive skip.
When extraction fails (corrupt archive, or a codec the 7zz build lacks,
e.g. RAR) no hash is stored at all and the 7zz stderr reason is logged
at error level, so scan logs explain the missing hash instead of
silently storing a garbage one.
Fixes#3808
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Centralize the cache-hit-or-build-then-fallback flow into
resolve_cached_zip(), collapsing three near-identical endpoint
blocks; add ZipFileEntry.from_rom_file() factory.
- Use get_ttl_hours() (now size-based) in cleanup_stale_zips instead
of inlining the tier decision.
- Drop on-demand LRU eviction and the 2x space guard; a full disk now
falls back to mod_zip streaming via the existing build try/except.
- Replace the per-request importlib.reload(zipfile) with a one-time,
thread-safe shim that fixes zipfile_inflate64's _get_compressor
signature without a global module reload.
- Simplify get_cache_key by folding the empty-entries case into the
normal path (non-empty keys unchanged).
Generated-By: PostHog Code
Task-Id: e68b880f-34d8-4bf6-8cd0-886ef2caecb4
get_supported_platforms() resolved tgdb_id from the MobyGames and
Hasheous platform entries only, but MobyGames platforms never carry a
tgdb_id and the Hasheous platform list has no TGDB mappings, so the
explicit key always overrode the value spread from the TGDB handler
with None. Mirror the fallback chain used during scans in
scan_handler.py by falling back to the TGDB platform entry itself.
Co-Authored-By: Claude <noreply@anthropic.com>
Serving any .pdf/.md file inline by extension also flipped game/extra files
from downloads to inline. Gate the document check on RomFileCategory.MANUAL so
only manuals render inline; other files keep the attachment behavior.
Generated-By: PostHog Code
Task-Id: 73be371c-908a-4f9f-9748-7ddba2df71e2
Uploaded manual files (RomFile with category="manual") were served from the
content endpoint as application/octet-stream + attachment, so the in-page
manual viewer showed a blank area while nav buttons and download still worked.
Include .pdf and .md in is_allowed_media_file (with explicit MIME overrides)
so they are served inline, and set X-Content-Type-Options: nosniff on inline
responses so a Markdown manual can't be sniffed into HTML.
Fixes#3712
Generated-By: PostHog Code
Task-Id: 73be371c-908a-4f9f-9748-7ddba2df71e2
Restrict extracted audio cover bytes to JPEG/PNG via magic-byte sniffing
instead of trusting the declared MP4 imageformat, so a GIF (or missing
format) is no longer mislabeled and persisted as image/jpeg.
MP4Cover.FORMAT_PNG was referenced via a non-existent MP4.Cover attribute,
breaking cover extraction for m4a files. Add unit tests and guard
extract_embedded_cover so failures do not abort the upload path.
get_supported_platforms built a slug->platform map with a plain dict
comprehension. When a folder is mapped as a variant or alias of an
existing platform, scanning resolves it to the parent slug, so two
platform rows share the same slug. The comprehension let the later row
(the variant) overwrite the parent, renaming it in the platform picker
and Folder Mappings page.
Prefer the canonical platform (fs_slug == slug) when building the map so
a variant folder no longer shadows its parent.
Fixes#3157
Generated-By: PostHog Code
Task-Id: 571866ea-86a0-49c2-b62e-dbea077d0181
DNS64/NAT64 networks synthesize IPv6 answers that embed a public IPv4
in the RFC 6052 well-known prefix 64:ff9b::/96. The SSRF classifier
rejected these because the prefix is is_reserved, breaking all outbound
metadata and cover fetching on NAT64-only deployments.
is_forbidden_ip now unwraps a NAT64-wrapped address and evaluates the
embedded IPv4 instead, so a wrapped public IPv4 is allowed while a
wrapped private/internal IPv4 (e.g. 127.0.0.1, 10.0.0.1) stays blocked.
Fixes#3668
Generated-By: PostHog Code
Task-Id: 73b38615-966e-4955-9228-2cb6bbcda277
The decoded-group cache is now capped by a byte budget instead of an
entry count, so a crafted chunk_size can't pin gigabytes of decoded
groups in memory. The budget still fits the chunks covering one Wii
hash group, keeping the data and exception passes cached.
Also use the existing _MAX_EXCEPTIONS_PER_LIST and
_WII_SECTORS_PER_HASH_GROUP constants in the exception-list parser and
drop a redundant slice in the bad-magic error message.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Condense the rvz_hasher module docstring and hardening comments, and
drop three tests whose coverage was already provided elsewhere (the
container-compression transitivity check and the Wii duplicates of the
container-level magic/missing-file failure tests).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Catch zstandard.ZstdError so a corrupt zstd group returns no hash and
falls back to RAHasher instead of aborting the scan.
- Cap chunk_size at 64 MiB and tighten the group-count bound so crafted
headers can't force multi-GB allocations.
- Bound decompression output per group (bz2/lzma max_length, chunked
zstd stream reads) to defuse decompression bombs.
- Reject main.dol segments extending past the disc end; a corrupt size
field would otherwise stall the scan hashing zero-fill.
- Key the group cache on all decode parameters and size it to keep one
Wii hash group's chunks cached across the data and exception passes
(avoids double decompression with sub-128 KiB chunks).
Real-ROM hashes are unchanged (both still match RA's database).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Cast year to text in the /api/music years facet search so Postgres does
not error on lower(integer) (MariaDB/SQLite auto-cast, hiding it in CI)
- Escape LIKE wildcards in music search via new utils.database.escape_like
- Drop lazy="selectin" on RomFile.track_meta; eager-load only where the
metadata is serialized (get_rom already did; add the three soundtrack reads)
- Migration backfill uses a single query + fetchmany (repo idiom, see 0084)
instead of manual keyset paging, in both directions
- Guard the extensionless folder-conversion collision (stale row over a
directory the user already created on disk)
- Renumber migration 0093 -> 0094 after 0093_states_rom_user_index landed
RomM stores soundtracks but exposes no way to consume them as a music library: a
client has to enumerate ROMs and pull each one's tracks individually, and the
per-track metadata lives in the `rom_files.audio_meta` JSON blob, which is
unindexable on MariaDB, so any library-wide filter or sort degrades to a full
scan.
This adds a queryable, music-first API for soundtracks, backed by a typed and
indexed `track_meta` table migrated from that JSON.
It also lets users upload soundtracks, manuals, and screenshots to any ROM, not
only folder-based ones. When the target is a single-file ROM, the client warns
that the upload will migrate it to a multi-file (folder) structure, then performs
that migration in place automatically.
RAHasher can't read the block-compressed RVZ/WIA containers Dolphin
creates, so GameCube and Wii games stored as .rvz/.wia never matched on
RetroAchievements ("Not a Gamecube disc" / "Not a supported Wii file").
Add utils/rvz_hasher.py, which reconstructs only the disc byte ranges
the RA hash covers, mirroring rcheevos:
- An RVZ/WIA reader with random access over raw-data and partition
groups (NONE/bzip2/LZMA/LZMA2/Zstandard codecs, RVZ packing with the
lagged-Fibonacci junk PRNG, and stored hash exceptions).
- GameCube: MD5 of the boot header, apploader and main.dol segments.
- Wii: the hash additionally covers encrypted cluster bytes, so the
reader recalculates the H0/H1/H2 hash tree, applies the container's
hash exceptions and re-encrypts clusters with the embedded title key
(AES-128-CBC) to reproduce the exact retail disc bytes.
RAHasherService tries the native path for .rvz/.wia on the GameCube and
Wii platforms and falls back to RAHasher on any failure.
Verified against Mario Kart: Double Dash!! (USA) and Super Mario Galaxy
(USA) RVZ dumps: the computed hashes are present in the official RA
hash lists (games 7693 and 189), and RAHasher 1.8.3 produces identical
hashes when run on disc images reconstructed by the same reader.
Closes#3649Closes#3650
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
PSP games stored as .cso (and .ciso/.zso/.dax) never matched on
RetroAchievements because RomM hands these files to the external RAHasher
binary, which can't read CSO/ZISO/DAX compressed-ISO containers and fails
with "Could not open track". The game was then left without an RA link.
The PSP RA hash does not depend on the whole disc: rcheevos computes it as
MD5(PSP_GAME/PARAM.SFO + PSP_GAME/SYSDIR/EBOOT.BIN), each file capped at
64 MiB. Those containers are block-indexed, so we can decompress just the
blocks those two files occupy and hash them in-process, producing the
identical hash RA stores (and PPSSPP computes).
Add utils/psp_hasher.py: a seekable block-decoder for CISO/ZISO (deflate
and LZ4) and DAX containers, a minimal ISO9660 reader to locate the two
files, and calculate_psp_ra_hash(). RAHasherService now computes the hash
natively for PSP .cso/.ciso/.zso/.dax files, falling back to RAHasher on
any failure. Raw .iso PSP discs still go to RAHasher, which reads them fine.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KsyrT6n8WYWWxR2XGoEASs
- Added new permission handling in `backend/handler/auth/dependencies.py` to support fine-grained, DB-backed permission checks.
- Enhanced user role update logic in `backend/endpoints/user.py` to prevent demotion of the last admin.
- Introduced `hidden_platform_ids` and `hidden_rom_ids` parameters in various database handlers to manage visibility based on admin settings.
- Created new endpoints for managing permission groups, user memberships, and hidden entities in `backend/tests/endpoints/test_permissions_admin.py`.
- Added tests for permissions visibility and CRUD operations in `backend/tests/endpoints/test_permissions_visibility.py` and `backend/tests/endpoints/test_permissions_me.py`.
- Updated archive handling in `backend/utils/archives.py` to improve error logging and timeout management during extraction.
Use UPS members for the platform-slug keys instead of bare strings.
zxspectrum and windows now use their real UPS slugs (UPS.ZXS, UPS.WIN);
naomi, chip-8 and steam stay as raw strings since they have no UPS member
(platform.slug falls back to the folder name for those). Lookups by raw
slug string still resolve, since UPS is a StrEnum.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Relocate generate_test_data.py (from backend/scripts) and
generate_supported_platforms.py (from backend/utils) into backend/tools,
alongside the existing xml_diagnostics.py. Update their run-command
references and document backend/tools in CLAUDE.md.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- patcher.js resolves rom-patcher-js from both the relocated sibling
layout (docker/Dockerfile) and the plain node_modules layout (root
Dockerfile), so both build flows work without a manual copy
- apply_patch wraps the node subprocess in asyncio.wait_for with a
timeout and kills it on expiry; a semaphore bounds concurrency, and the
endpoint rejects oversized ROM/patch files to avoid OOM
- report the patch source-checksum validation result via an
X-Patch-Validated header; the patcher UI warns on a mismatch
- return a generic "Patching failed" detail to clients and log the real
error server-side, so node/RomPatcher.js paths don't leak
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Move default_category_for_non_nested validator onto RomFileSchema so
top-level files default to category "game" (the v2 patcher's base-file
filter relies on this).
- Use Annotated Body() in the patch endpoint; check patcher output via
anyio async Path.
- Drop the now-unused client-side rom-patcher and vite-plugin-static-copy
(patching is server-side); simplify the Storybook plugin filter.
- Regenerate frontend OpenAPI types.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>