* feat(auth): use the OIDC picture claim as the user's avatar
On each OIDC sign-in, a user with no avatar, or one synced from the
provider earlier, gets the picture claim stored as their avatar. An
uploaded avatar is never replaced. The download goes through the
SSRF-guarded client (the configured provider's origin may reach a LAN
address), is capped at 5 MB, must sniff as a supported image, and any
failure is logged without blocking the sign-in.
Closes#4297
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(auth): address review on the OIDC avatar sync
Addresses Greptile's review on #5730:
- ask the UserInfo endpoint when the ID token has no picture claim
- keep an avatar uploaded while the picture downloaded
- allow only the OIDC provider's origins to reach private addresses
- trim docstrings and narrow await_args in the callback test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(auth): type the OIDC avatar test helpers for mypy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* pr-ready: code-review
Bound the OIDC picture download with an overall deadline, trust the
OIDC CA bundle, catch hostname encoding errors so sign-in never 500s,
and set the synced avatar with a conditional update so a concurrent
upload wins.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* pr-ready: simplify
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* pr-ready: review-polish
Type the pytest fixtures and helpers in the OIDC avatar tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* pr-ready: prose
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(auth): remove the synced OIDC avatar when the user uploads one
Once avatar_path points at the uploaded avatar.<ext>, the sync never
touches the user's avatar again, so the old oidc-avatar.<ext> file
would otherwise stay on disk for good.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(auth): check a dummy hash when the username is unknown
Password sign-in skipped bcrypt for usernames with no account, so a
failed login answered far faster for an unknown name than for a real one.
Verify against a throwaway hash in that case so both take the same time.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(auth): run the dummy bcrypt check for accounts without a usable hash
OIDC-provisioned and empty-hash accounts skipped bcrypt, so a failed
password sign-in for them answered faster than for an unknown username.
verify_password now falls back to the dummy hash whenever the stored one
is unusable, and the tests assert bcrypt ran on a valid hash.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* 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>
* fix(play-sessions): filter rom_id and device_id on PlaySession after the visibility join
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat(auth): require the current password to change your own password
PUT /api/users/{id} set a new password or email for the caller with
nothing more than a me.write credential, so a leaked client token or a
hijacked session could take the account over for good.
A self-edit that changes the password or the email now needs
current_password, checked with bcrypt off the event loop (400 when
missing, 403 when wrong). Admins editing another user and the
forgot/reset-password flow are unchanged. Accounts with no local
password (OIDC-provisioned placeholders) can set a first one only from a
sign-in session, not from a bearer or client token.
UserSchema gains has_password so the UI asks for the current password
only when the backend will: the change-password dialog, the profile
email field, and the edit-user dialog when editing yourself.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(user): shorten _verify_account_holder docstring
Addresses Greptile review on #5351.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(user): treat a case-only email edit as no change (code-review)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* refactor(user): simplify current-password checks and tests (simplify)
Hash the new password off the event loop, reuse errorMessage and the
viewer token fixture, and table-drive the needsCurrentPassword tests.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(user): require the current password to change your own username
Login is by username and a rename revokes every session, so a stolen
me.write token could lock the owner out without touching the password.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(user): lock the email of OIDC accounts to the identity provider
The provider overwrites a linked account's email at every sign-in, and
finds an unlinked password-less account by it, so a self-edit is either
lost or breaks SSO sign-in. Admins can still change it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(RTextField): give read-only fields a muted style
Dashed chrome, no fill and muted text, with no hover or pointer-focus
halo, so a locked value no longer looks editable. Keyboard and gamepad
focus keep their outline.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
When SMTP is off or sending fails, the reset link is logged so an admin
can read it from stdout and pass it on. LogStreamHandler copied that
record into the Redis buffer behind GET /api/logs and the log socket,
which any logs.read holder can see, and logs.read is not admin-only.
Records logged with extra=STDOUT_ONLY now skip LogStreamHandler, and the
reset link uses it. The invite flow already logs only the token id.
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(oidc): match any of the comma-separated groups in OIDC_ROLE_*
OIDC_ROLE_ADMIN/EDITOR/VIEWER were read as one raw string and checked
for membership in the roles claim, so a value like
"romm-admin,platform-admins" never matched and the login was rejected
with 403. Parse each variable into a set of stripped, non-empty values
and grant the role when it intersects the claim. A single-valued string
claim is matched whole rather than by substring.
Fixes#4302
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(oidc): reject a string role claim that only contains a mapped group
Addresses Greptile's review on #5203: the string-claim case only covered a
match, which the old substring check would also have passed.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Importing any handler.auth submodule ran the package __init__, which
built the auth handlers and so loaded authlib, joserfc and Socket.IO.
models.user imports handler.auth.constants, so every process that
touched the models paid for the whole auth stack. The handler
instances now live next to their classes in handler.auth.base_handler.
utils.context imported fastapi only for annotations; that import now
sits under TYPE_CHECKING.
An idle RQ worker drops from about 118 MB to 89 MB RSS. Each job's
forked work horse now imports a little more on its own, about 0.2s
on an x86 host.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gh1SRMfuK7BZmf6YxMqSyT
- Match on (issuer, sub) with exact collation, so subjects from another
provider or differing only in case never match.
- Refuse a login whose email is linked to another subject at the same
issuer instead of rebinding the account; relink only across issuers.
- Check the account is enabled before saving identity changes.
- Keep the old email when it is claimed between the check and the write.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Store the provider's `sub` on a new nullable users.oidc_sub column, look users
up by it first and fall back to email, backfilling the sub on the next login. A
user matched by sub gets their stored email updated, unless another account
already holds it.
Fixes#1690
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Keep email_verified tied to the email it came with, and fall back to the
ID token claims when provider discovery fails as well.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Providers like Authelia follow OIDC Core 5.4 and return scope claims
(email, preferred_username, groups) only from the UserInfo endpoint.
When any claim RomM reads is absent from the ID token, fetch UserInfo
with the access token, check that its sub matches, and merge it under
the ID token claims.
Fixes#1927
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* chore(deps): bump redis to 8.1 and fakeredis to 2.38
redis-py 6.2.0 -> 8.1.0 and fakeredis 2.30.1 -> 2.38.0. RQ 2.12
(redis!=6,>=3.5) and fakeredis (redis>=4.3) both accept redis 8.
fakeredis 2.38 types FakeServer's version argument as a tuple, so pass
(7,) instead of 7. Behaviour is unchanged since fakeredis normalises an
int to a one-element tuple.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wzuPg8vDEjsQ8xqvZgFwx
* chore(deps): drop types-redis in favour of redis-py's own types
types-redis only covers redis 4.6 and shadowed the inline types that
redis 8 ships, so mypy was checking calls against a stale API. Removing
it also drops its transitive stub packages (types-cffi, types-pyopenssl,
types-setuptools), which nothing else uses.
redis-py's types differ from the stubs in three ways:
- Redis, AsyncRedis and Pipeline are not generic, so drop the [str] and
[bytes] parameters.
- Responses are typed bytes | str regardless of decode_responses, so cast
at the few call sites that rely on the decoded (or raw) type.
- watch, unwatch, multi, aclose and execute_command are unannotated, so
add redis to untyped_calls_exclude, as is done for rq and apprise.
Also replace setex, deprecated in redis 8, with set(..., ex=...).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wzuPg8vDEjsQ8xqvZgFwx
* fix(device-auth): replace deprecated GETSET with SET ... GET
code-review step. GETSET is deprecated since Redis 6.2 in favour of
SET with GET. Using it with ex= also sets the poll key's TTL in the same
command, instead of a separate EXPIRE that a crash could skip.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wzuPg8vDEjsQ8xqvZgFwx
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* chore(mypy): switch to strict mode with listed exceptions
Replace the hand-picked flags with `strict = True`, turning off only the
four flags that aren't clean yet (disallow_any_generics,
warn_return_any, disallow_untyped_calls, disallow_untyped_decorators).
Any other strict flag, including those future mypy releases add to the
preset, is on by default.
That turns on no_implicit_reexport, strict_equality and extra_checks:
- Import each name from the module that defines it. About 240 test
sites patched a dependency through the module that imported it
(`scan_module.fs_rom_handler`); they now import the same object from
its source, so every patch targets what it did before. Tests that
replace a module attribute are unchanged.
- handler.streaming.memory_cards re-exports store_memory_card_version
explicitly, since endpoints call it there and tests patch it there.
- mutagen gets implicit_reexport, as it re-exports without __all__.
- Test comparisons build typed values (CoverResult, a typed expected
dict, enum .value) and the CORS lookup casts for its identity check.
- One ss_handler ** spread keeps a coded ignore: extra_checks wants its
NotRequired dump_* keys spelled out, and the media dict never has them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G
* chore(mypy): give every generic its type arguments
Drop disallow_any_generics from the strict-mode exceptions and fix the
347 bare generics it reports, 230 of them in app code.
- Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider
JSON and endpoint bodies map string keys to mixed values, so the Any is
real and now written down. The OpenAPI document is unchanged.
- Rom query filters take and return RomSelect; _music_facet_joins and
_exclude_hidden are generic over the Select they're given, and
_build_hash_selects returns id-only selects.
- Redis clients are typed by what they return: the decoding caches are
Redis[str], the RQ connection and binary cache Redis[bytes].
- The rest get explicit parameters: Row, Pattern, ColumnElement,
QueryableAttribute, SpooledTemporaryFile, Task, Future and friends.
Precise types reached callers that had been getting Any, which surfaced:
- The LaunchBox cache writer is fed binary-cache pipelines.
- The flashpoint and IGDB request helpers return raw JSON of varying
shape, not always a dict.
- The rom search endpoint returned dicts under a list[SearchRomSchema]
annotation; it now validates them into that schema.
- The audit filter's id subquery selects strings.
- In tests the binary cache is the non-decoding fake shared with
async_cache, so it is cast to Redis[bytes] rather than changed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G
* test(upload): assert cleanup against the patched upload directory
The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches
the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G
* chore(mypy): keep the row type through the ROM filter helpers
filter_roms and its helpers also receive select(Rom.id) membership queries,
so they now take and return the caller's Select type instead of narrowing to
RomSelect. merged_ra_metadata mixes scalar and list values.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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>
- A channel's min_level is its own enum (info, warning, error), so the
API refuses `success` and neither the list nor the dialog maps it.
- One home each for the admin-reaches-the-LAN rule (the DB handler now
returns the owner's role) and for describing a failed delivery.
- One webhook config builder for create and update, which drops the
secret of a Discord webhook on both.
- SMTP_SECURITY outside starttls/tls/none leaves email off, so the
heartbeat says so, with a warning at startup.
- The attempts counter gets its TTL in the same round trip as INCR.
- Deliveries group channels by user and serialize a notification only
when a channel wants it.
- The v2 side reuses errorMessage (now with a fallback) instead of its
own detail parsing, mirrors the backend length limits as constants,
shares one channel test factory, and derives `created` on save from
the list instead of carrying it on the event.
- Drop RBadge's inline override, which nothing needs now that an inline
badge gets no anchor class, and trim docstrings to one sentence.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Bound a webhook delivery: 15 s in all, and only the first KiB of a
refusal's body is read, so a hostile endpoint can't hold the API or a
worker with an endless or slow reply.
- Key the confirmation-code cooldown per user and per address instead of
per channel, which a delete and re-create reset, so a user can't mail
an address without limit.
- Don't carry a stored secret to another origin or format: it has to be
given again (Discord, which uses none, drops it), so a changed URL
can't be used to read an ntfy token or HMAC key.
- Refuse a webhook URL whose port isn't a number; one got saved and then
broke the channel list with a 500.
- Refuse an unknown SMTP_SECURITY instead of logging in over plaintext.
- Tell the reset form whether reset links are really emailed, which also
needs a shareable ROMM_BASE_URL (heartbeat NOTIFICATIONS.EMAILS_RESET_LINKS).
- Say a code went out only when the address is new to the channel.
- Match a channel's address whole, so a trailing newline isn't kept.
- Test that forgot-password answers alike and sends the link afterwards,
and document the new cache keys.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The previous commit carried only the renames of this change, when staging
the rest failed on a path the rename had already moved. This is the change
itself.
A reset link only ever went to the server log, for an admin to pass on. It
now goes to the user's email address when SMTP is set up, the user has one
and ROMM_BASE_URL is shareable, falling back to the log otherwise or when the
server refuses the message. The link is built from ROMM_BASE_URL alone, never
the request's Host, so a forged header can't aim it at another server; it
goes out after the response, so its timing doesn't reveal whether the
username exists; and a user's inbox gets at most one a minute.
The SMTP sender moves from the notification channels to
handler/email_handler.py now that it has a second caller. The v2 reset form
says the link is on its way when the server sends email.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* 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>
Registration ran the username and email uniqueness checks ahead of the
token, so an anonymous caller with any garbage token could enumerate
accounts one guess at a time. The token is now verified first, without
consuming it, so a registration rejected on a duplicate keeps the invite.
Consumption moves from a GET followed by a DELETE to a single GETDEL, so
two registrations racing on one invite cannot both see it as valid and
both create an account. The invite link itself is no longer written to
the log, only its id; the link is already in the response.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
OIDC-provisioned accounts hold a placeholder rather than a bcrypt hash.
passlib raises on one it cannot identify, so a login against such an
account turned a 401 into a 500 that marked it as OIDC-backed.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Addresses the two open review findings on the credential-change path.
The endpoint was sequencing two Redis revocations around the database
write itself, reaching past the handler layer into the session
middleware. The whole sequence now lives in `auth_handler`, so the
endpoint validates, calls a handler and serializes, as the rest of the
backend does.
The second revocation runs after the write has committed, so raising
from it reported a failed change that had in fact succeeded, and an
operator could not tell the two apart. It is now logged instead, naming
the account and warning that a session created during the update may
still be live. The first revocation still raises, because it has a write
to abort.
`set_user_new_password` (the forgot-password path) goes through the same
helper, which gives it the pre-write pass it did not have: an
unreachable Redis there used to change the password and leave the
account's sessions live.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp
Registering `a-user-2` when `a-user` exists silently hands the provider's
user a name they did not choose. Fail the login with a 409 instead.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A provider name already at the column's length left no room to append
`-2` to, and the log said the name was invalid even when all that happened
was a collision. Both now come from the one helper that knows which it was.
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>
Collapse the Role enum from viewer/editor/admin to two kinds (admin/user);
non-admin access now comes entirely from permission groups + overrides.
Backend:
- Role -> StrEnum {USER, ADMIN}, VARCHAR-backed (native_enum=False); Role.coerce
maps legacy/unknown strings (incl. in-flight invites) to USER.
- Resolver: group-less users fall back to the default group (dropped the
role-based legacy fallback); kiosk caps all non-admins to read-only.
- OIDC editor/viewer claims both map to USER (env var names unchanged).
- Migration 0092 converts the native enum to VARCHAR and normalizes
ADMIN->admin, VIEWER/EDITOR->user.
- Updated endpoints, conftest fixtures, role/oidc/parity/db-handler tests, tools.
Frontend:
- v2 + v1 user management now use admin/user (dropdowns, defaults, getRoleIcon).
- Regenerated types (Role = 'user' | 'admin'); added role-user i18n to all locales.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Gate automatic account creation on OIDC login behind a new OIDC_ALLOW_REGISTRATION environment variable. Defaults to true, preserving the current auto-provisioning behavior; set it to false to run OIDC in an "existing users only" mode, where a login from an email without an existing RomM account is rejected with a 403 instead of silently creating one. Existing users are unaffected either way.
Adds the config constant, env.template and docs entries, and tests covering the enabled/disabled and existing-user paths.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Use atomic getdel for pairing code exchange
- Add cascade="all, delete-orphan" to User.client_tokens
- Move generate/hash_client_token into AuthHandler as static methods
- Extract endpoint helpers to utils/client_tokens.py
Three tests were also implemented to check initial implementation that now invalidates expired access and refresh tokens and also rotating refresh tokens.
Since I introduced wrapper functions for create_oauth_token to distinguish between access and refresh token there is no need to set the token type in the data dict, since the type is now enforced in the wrapper functions create_access_token and create_refresh_token.
By convention I renamed create_oauth_token to _create_oauth_token as it is considered a private helper function now.