diff --git a/.claude/skills/draft-announcement/SKILL.md b/.claude/skills/draft-announcement/SKILL.md new file mode 100644 index 000000000..a8ff4af23 --- /dev/null +++ b/.claude/skills/draft-announcement/SKILL.md @@ -0,0 +1,156 @@ +--- +name: draft-announcement +description: Draft the Discord release announcement for a RomM release, from the release notes plus an interview about community news. Use when asked to "write the Discord announcement for 5.3.0", "draft the announcement post", "announce the beta in Discord", or to refresh an announcement draft. Interviews the user for the things no diff contains (new team members, third-party apps to spotlight, milestones, events, Discord housekeeping), writes in the house voice, and never posts to Discord. +argument-hint: "[version to announce, e.g. 5.3.0 | nothing to infer it]" +--- + +# Drafting a Discord announcement + +The release notes say what shipped. The announcement says why anyone should care, +in RomM's voice, in one Discord message. It is a short, warm, slightly unhinged +post: a hook, the few features worth naming, the community news, a pointer to the +notes, a sign-off. + +Half the content is not in the repository. **Interview the user for it.** Never +invent a contributor, an app, a milestone, a link or a handle. + +Write the draft to the session scratchpad and print it. **Never** post to Discord, +and never write into the maintainer's announcement archive (see section 1). + +--- + +## 1. Read before you write + +`$ARGUMENTS` is the version. If empty, take the newest tag and confirm it. + +The release notes are the feature source. + +```bash +TAG=5.3.0 +gh release view "$TAG" --json body --jq .body # the notes for this release +# for a release not yet published, use the draft in the scratchpad +``` + +Past announcements are the voice source, and a Discord post is not in the repo, so +they exist only wherever the maintainer archives them. Ask where that is if you do +not already know, and treat it as **read only**: drafts go to the scratchpad. + +Read the **two most recent** before drafting. They set the current voice, and they +tell you which third-party apps were already spotlighted. An app highlighted in +either one does not get spotlighted again. + +From the notes, pull: + +- the Highlights, as candidate features to name, +- every `> [!WARNING]` and `> [!CAUTION]`, which **must** survive into the + announcement (`4.1.0` led with the mandatory `config.yml`, `4.0.0` led with the + RCE advisory), +- a rough PR count and whether the release is mostly fixes, which decides the hook. + +## 2. Interview the user, one step at a time + +The community news is names, URLs and handles that only the user has, so it gets +**typed, not picked**. Ask **one question per message** and wait for the answer +before asking the next. Never send the whole questionnaire as a numbered list, and +never collect the content answers as checkbox options. + +Number every step and say how many there are ("Step 2 of 6"), so the user can see +where the interview ends. Each step states exactly which fields you need, and how +to skip it. Take "skip", "none" or "n/a" as an answer, move on without arguing, and +drop that item from the draft. + +| # | Step | Ask for | +| --- | ------------------ | --------------------------------------------------------------------------------------------------------------- | +| 1 | Features | print the Highlights you found as a numbered list, ask which get named prose; the rest become bullets | +| 2 | App spotlight | name, repo URL, author's handle, one line on what it does. List the apps already spotlighted so nothing repeats | +| 3 | Team or role news | handle, what they built or do, what changes now (joined the team, project gone official, new Experts) | +| 4 | Milestone or event | what it is, the number or date, and the link | +| 5 | Anything else | housekeeping, a call to action, a beta bug-report ask; the exact wording they want | +| 6 | Pings and shape | the only genuinely multiple-choice step, so one `AskUserQuestion` call: who gets pinged, and one message or two | + +Ask for a handle as it is written in Discord, since `@Covin` and `@Covin90` are not +interchangeable. Never offer a sample answer that could be mistaken for a real one: +no invented app names, no placeholder URLs, no guessed star counts. + +If steps 2 through 5 all come back empty, drop the Community news section. Several +releases (`4.3.0`, `4.4.0`) have none, and a padded one reads worse than none. + +Skip a step only when the answer is already on the table, and say so rather than +silently dropping it: a user who opened with "announce 5.3.0, spotlight ``" has +answered step 2 already. + +## 3. The shape + +Always, in this order: + +1. **Hook.** One or two sentences, opening on something _timely_. Check today's + date first and use it: the season, a holiday, the month, or a self-aware nod to + the last release. `3.6.0` served Thanksgiving turkey, `3.10.0` opened on the + summer heat, `3.7.0` on the new year, `4.9.0` on being the last `4.x`, `5.1.0` + on arriving sooner than anyone expected. Then `@everyone` (if pinging), the + version in backticks, and what the release is _about_. Never open cold with + "version X is out". Keep the reference light and skip a holiday that is not + widely shared, and do not assert a date you have not checked ("the equinox is + today") when "the days are getting shorter" carries the same warmth. +2. **Any upgrade warning**, immediately after the hook. Imperative, and what to do, + not why. +3. **The features**, in one of two shapes: + - **Bullet list** for a release carried by a long tail (`5.1.0`, `4.3.0`): one + sentence of setup, then five to nine bullets of three to six words each. + - **`###` section per feature** for a release with two to five real headliners + (`3.10.0`, `4.4.0`, `3.5.0`): a heading and two or three sentences, saying what + it does and the one thing needed to use it. Close with an `Other notable +features:` bullet list when there is a tail. +4. **`## Community news`** (`### Community updates` also appears; match the last + one). Team additions first, then app spotlights, then milestones and events, then + housekeeping and calls to action. +5. **The pointer.** "More details on each of these features, and a complete list of + changes, can be found in the [release notes](url)." Link the tag URL. +6. **Sign-off.** "See you soon!", optionally with `:mario_here_we_go:`. + +## 4. Voice + +- Second person, present tense, contractions. Talking to friends, not users. +- One idea per sentence, and short paragraphs. Nothing here is a manual. +- Enthusiasm is earned by specifics, not adjectives. Name the feature, don't call + it revolutionary. No claim the release notes do not support. +- Emphasis is _italics_ on a single word, sparingly. Bold is for the thing that + will break someone's install. +- Backticks for versions, env vars, config keys, filenames. +- Credit by name every time: the contributor for a feature, the author for an app. +- No em-dashes. No AI throat-clearing, no "we're excited to announce" twice in one + post, no bullet list of benefits. + +## 5. Discord mechanics + +- **2000 characters**, hard. Past announcements run 1300 to 2100; treat 1800 as the + target and count before handing over (`wc -m`). +- Over the limit, pick one: split at a section boundary into message 1 (hook plus + features) and message 2 (community news plus sign-off), marking the split in the + draft; or do what `3.7.0` did and post a three-line teaser pointing at the GitHub + notes. Say which you did and why. +- `##`, `###`, `**bold**`, `*italics*`, `` `code` ``, `> quote`, `-`/`*` bullets and + `[text](url)` all render. Tables, images and HTML do not. +- `@everyone` goes in the first sentence or not at all. +- Custom emoji only from ones this server is known to have: + `:mario_here_we_go:` (the usual sign-off), `:linkEz:`, `:linkLove:`, `:peepoAlert:`, + `:snakeSalute:`, `:excuseme:`, `:okay:`, `:linuxNootNoot:`. Anything else renders as + literal text, so use plain unicode (🎊 👉 ⚠️ 🔥) instead of guessing a shortcode. +- Role pings (`@Expert`, `@Alpha Tester`, `@Beta Tester`) only when the user asked + for them, spelled as they gave them. + +## 6. Before handing it over + +- Every feature named appears in the release notes. +- The hook opens on something timely, and the reference matches today's date. +- Every warning and caution in the notes appears in the announcement. +- Every handle, repo URL and number came from the user or from the notes, never + from you, and every URL is one you have actually seen. +- No app spotlighted in either of the last two announcements. +- The release notes link ends in the tag being announced. +- Under 2000 characters, or split deliberately. +- No em-dashes, no invented emoji shortcodes. + +Write to `/-announcement.md`, print it, and say what still needs a +human: a screenshot or GIF to attach, a link the user has not given you, a name you +could not confirm. diff --git a/.claude/skills/draft-announcement/template.md b/.claude/skills/draft-announcement/template.md new file mode 100644 index 000000000..72aea51a2 --- /dev/null +++ b/.claude/skills/draft-announcement/template.md @@ -0,0 +1,69 @@ +# Discord announcement skeletons + +Pick a shape by how many real headliners the release has, drop any section with no +content, and stay under 2000 characters. Bare URLs and loose headings inside the +skeletons are deliberate: Discord renders them, not GitHub. + +## Bullet shape (a long tail of changes) + +```text +@everyone + + +⚠️ + + + +- +- +- +- +- + +## Community news + + + + + + + +More details on each of these features, and a complete list of changes, can be +found in the [release notes](https://github.com/rommapp/romm/releases/tag/X.Y.Z). + +See you soon! :mario_here_we_go: +``` + +## Section shape (two to five real headliners) + +```text +@everyone + + +⚠️ + +### + + + +### + + + +Other notable features: + +- +- + +## Community news + + + +More details on each of these features, and a complete list of changes, can be +found in the [release notes](https://github.com/rommapp/romm/releases/tag/X.Y.Z). + +See you soon! :mario_here_we_go: +``` diff --git a/.claude/skills/review-polish/SKILL.md b/.claude/skills/review-polish/SKILL.md index afa27d2cb..d62988f0b 100644 --- a/.claude/skills/review-polish/SKILL.md +++ b/.claude/skills/review-polish/SKILL.md @@ -142,10 +142,11 @@ mypy wanting explicit annotations on `__init__` attributes Run from `frontend/`: -1. `npm run typecheck` — zero errors (`vue-tsc --noEmit`). -2. `npm run lint` _(if present)_ / ESLint clean. Trunk also runs ESLint + Prettier in CI. -3. `npm run test` — zero failures (Vitest + happy-dom; runs unit tests **and** every `/lib` story's `play()` via `composeStories`). -4. `npm run build` — zero failures (CI sanity check). +1. `npm run typecheck`: zero errors (`vue-tsc --noEmit`). +2. `npm run typecheck:scripts`: zero errors (`tsc -p tsconfig.node.json`, covers `scripts/`). +3. `npm run lint` _(if present)_ / ESLint clean. Trunk also runs ESLint + Prettier in CI. +4. `npm run test`: zero failures (Vitest + happy-dom; runs unit tests **and** every `/lib` story's `play()` via `composeStories`). +5. `npm run build`: zero failures (CI sanity check). **If you touched the backend API:** start the backend, run `npm run generate`, then re-`typecheck`. diff --git a/.github/resources/aikido-badge.svg b/.github/resources/aikido-badge.svg deleted file mode 100644 index 343c746d7..000000000 --- a/.github/resources/aikido-badge.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - Secured with Aikido - - - OPEN SOURCE SECURITY - - - diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2341a4b81..70e480857 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -125,6 +125,10 @@ jobs: labels: ${{ steps.meta-slim.outputs.labels }} target: slim-image outputs: type=image,name=${{ env.DIGEST_IMAGE }},push-by-digest=true,name-canonical=true,push=true + # Both stages run `apk upgrade` off a fixed base digest, so nothing in + # them changes between releases and the cache would serve the package + # set of whenever the layer was first built. + no-cache-filters: python-runtime,production-stage # Deliberately not seeded from the preview cache: those layers are # built from PR head content and must not reach a release image. cache-from: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }} @@ -144,6 +148,7 @@ jobs: labels: ${{ steps.meta.outputs.labels }} target: full-image outputs: type=image,name=${{ env.DIGEST_IMAGE }},push-by-digest=true,name-canonical=true,push=true + no-cache-filters: python-runtime,production-stage cache-from: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }} cache-to: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }},mode=max build-args: | diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml index 8636222a2..9ff713112 100644 --- a/.github/workflows/copilot-setup-steps.yml +++ b/.github/workflows/copilot-setup-steps.yml @@ -27,7 +27,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install Python run: uv python install diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 82f4f7785..684f5c3e4 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -22,7 +22,8 @@ on: - uv.lock - .python-version -permissions: read-all +permissions: + contents: read jobs: e2e: @@ -68,7 +69,7 @@ jobs: sudo apt-get install -y libmariadb3 libmariadb-dev - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: uv python install diff --git a/.github/workflows/frontend-v1-frozen.yml b/.github/workflows/frontend-v1-frozen.yml index 9a7fb3593..abe0b50f8 100644 --- a/.github/workflows/frontend-v1-frozen.yml +++ b/.github/workflows/frontend-v1-frozen.yml @@ -16,7 +16,8 @@ on: - "frontend/src/console/**" - "frontend/src/layouts/**" -permissions: read-all +permissions: + contents: read jobs: check-v1-frozen: diff --git a/.github/workflows/frontend.yml b/.github/workflows/frontend.yml index 30cb2af0e..f6369f515 100644 --- a/.github/workflows/frontend.yml +++ b/.github/workflows/frontend.yml @@ -10,7 +10,8 @@ on: paths: - "frontend/**" -permissions: read-all +permissions: + contents: read jobs: test: diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml index 6d3323820..0de50a7e9 100644 --- a/.github/workflows/i18n.yml +++ b/.github/workflows/i18n.yml @@ -5,7 +5,8 @@ on: paths: - "frontend/src/locales/**/*.json" -permissions: read-all +permissions: + contents: read jobs: check-translations: @@ -16,7 +17,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: uv python install diff --git a/.github/workflows/migrations.yml b/.github/workflows/migrations.yml index 1d603225a..06a181a4c 100644 --- a/.github/workflows/migrations.yml +++ b/.github/workflows/migrations.yml @@ -9,14 +9,12 @@ on: - uv.lock - .python-version -permissions: read-all +permissions: + contents: read jobs: migrate-postgres: runs-on: ubuntu-latest - permissions: - checks: write - pull-requests: write services: postgres: image: postgres:18 @@ -41,7 +39,7 @@ jobs: sudo apt-get install -y libmariadb3 libmariadb-dev - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: uv python install @@ -68,9 +66,6 @@ jobs: # migration SQL that a default utf8mb4 server accepts (issue #4350). name: migrate-mariadb (${{ matrix.mariadb }}, ${{ matrix.collation }}) runs-on: ubuntu-latest - permissions: - checks: write - pull-requests: write strategy: fail-fast: false matrix: @@ -98,7 +93,7 @@ jobs: sudo apt-get install -y libmariadb3 libmariadb-dev - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: uv python install diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index c127fc30f..a17ddd193 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -22,14 +22,12 @@ on: - Dockerfile - docker/Dockerfile -permissions: read-all +permissions: + contents: read jobs: pytest: runs-on: ubuntu-latest - permissions: - checks: write - pull-requests: write strategy: fail-fast: false matrix: @@ -70,7 +68,7 @@ jobs: sudo apt-get install -y libmariadb3 libmariadb-dev 7zip - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: | diff --git a/.github/workflows/trunk-check.yml b/.github/workflows/trunk-check.yml index 7f21098cb..443778ff8 100644 --- a/.github/workflows/trunk-check.yml +++ b/.github/workflows/trunk-check.yml @@ -10,7 +10,8 @@ concurrency: group: ${{ github.head_ref || github.run_id }} cancel-in-progress: true -permissions: read-all +permissions: + contents: read jobs: trunk_check: diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml index aa505a17f..da0d15d95 100644 --- a/.github/workflows/typecheck.yml +++ b/.github/workflows/typecheck.yml @@ -10,14 +10,12 @@ on: paths: - "frontend/**" -permissions: read-all +permissions: + contents: read jobs: typecheck: runs-on: ubuntu-latest - permissions: - checks: write - pull-requests: write steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -37,6 +35,10 @@ jobs: run: npm run typecheck working-directory: frontend + - name: Run scripts typecheck + run: npm run typecheck:scripts + working-directory: frontend + - name: Lockfile lint run: | [ -z "$(jq -r '.packages | to_entries[] | select((.key | contains("node_modules")) and (.value.resolved | contains("git+ssh") | not) and (.value | has("resolved") and has("integrity") | not)) | .key' < package-lock.json)" ] diff --git a/.github/workflows/update-hltb-api-url.yml b/.github/workflows/update-hltb-api-url.yml index 9b45293c3..f6b38fd4d 100644 --- a/.github/workflows/update-hltb-api-url.yml +++ b/.github/workflows/update-hltb-api-url.yml @@ -8,18 +8,20 @@ on: - cron: "0 6 * * 1" permissions: - contents: write - pull-requests: write + contents: read jobs: update-hltb-api-url: runs-on: ubuntu-latest + permissions: + contents: write # For create-pull-request to push the branch + pull-requests: write # For create-pull-request to open the PR steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - name: Install python run: | diff --git a/CLAUDE.md b/CLAUDE.md index d59075454..771b337a5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,6 +53,7 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha | `pr-ready` | Before opening a PR - the four passes in order: `security-audit`, `code-review xhigh --fix`, `simplify`, `review-polish`. Not auto-invoked. | | `address-bot-reviews` | After Greptile and Copilot review a PR - triage each finding, fix what holds up, reply with the fix or the reason, and resolve the threads. Not auto-invoked. | | `draft-release-notes` | Drafting the GitHub release notes for a release, stable or alpha/beta, from the diff since the previous stable tag. | +| `draft-announcement` | Drafting the Discord announcement for a release, from the release notes plus an interview about community news. Not auto-invoked. | --- @@ -99,6 +100,7 @@ uv run alembic upgrade head # apply migrations npm install # install (Node 24) npm run dev # dev server :3000 npm run typecheck # vue-tsc +npm run typecheck:scripts # tsc on the Node/Vite tooling in scripts/ npm run test # vitest (+ Storybook play() tests) npm run test:e2e # playwright (needs a running app + seeded e2e users) npm run build # production build diff --git a/README.md b/README.md index a3718343e..b38827e9b 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,6 @@ These companies support us by providing their tools for free: diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 043f07b37..b32ff1b4f 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -919,7 +919,17 @@ class ConfigManager: f"Invalid config.yml: {config_key}.{key} must be a non-empty string" ) sys.exit(3) - normalized[str(key).lower()] = value + folded = str(key).lower() + # One key covers `PSX` and `psx` alike, so a second spelling of the + # same folder silently replaces the first. + if folded in normalized and normalized[folded] != value: + log.warning( + f"{config_key}.{key} replaces a case variant of the same " + f"folder name: {hl(normalized[folded])} is dropped for " + f"{hl(value)}, since folder names are matched " + "case-insensitively" + ) + normalized[folded] = value return normalized @@ -1401,9 +1411,11 @@ class ConfigManager: def add_platform_binding(self, fs_slug: str, slug: str) -> None: fs_slug = fs_slug.lower() platform_bindings = self.config.PLATFORMS_BINDING - if fs_slug in platform_bindings: - log.warning(f"Binding for {hl(fs_slug)} already exists") + bound = platform_bindings.get(fs_slug) + if bound == slug: return None + if bound: + log.info(f"Rebinding {hl(fs_slug)} from {hl(bound)} to {hl(slug)}") platform_bindings[fs_slug] = slug self.config.PLATFORMS_BINDING = platform_bindings @@ -1423,9 +1435,11 @@ class ConfigManager: def add_platform_version(self, fs_slug: str, slug: str) -> None: fs_slug = fs_slug.lower() platform_versions = self.config.PLATFORMS_VERSIONS - if fs_slug in platform_versions: - log.warning(f"Version for {hl(fs_slug)} already exists") + parent = platform_versions.get(fs_slug) + if parent == slug: return None + if parent: + log.info(f"Reparenting {hl(fs_slug)} from {hl(parent)} to {hl(slug)}") platform_versions[fs_slug] = slug self.config.PLATFORMS_VERSIONS = platform_versions diff --git a/backend/endpoints/configs.py b/backend/endpoints/configs.py index bd081063c..418125b17 100644 --- a/backend/endpoints/configs.py +++ b/backend/endpoints/configs.py @@ -18,6 +18,7 @@ from endpoints.responses.config import ConfigResponse from exceptions.config_exceptions import ConfigNotWritableException from handler.auth.constants import Scope from handler.database import db_rom_handler +from handler.filesystem import fs_platform_handler from logger.logger import log from utils.router import APIRouter @@ -169,6 +170,19 @@ def get_config(request: Request) -> ConfigResponse: ) +async def _reject_ambiguous_folder(fs_slug: str) -> None: + """Refuse a mapping that several folders on disk would share.""" + ambiguous = await fs_platform_handler.find_ambiguous_folders(fs_slug) + if ambiguous: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=( + f"Folders {', '.join(ambiguous)} differ only by case and share a " + "single mapping. Rename one to map them to different platforms." + ), + ) + + @protected_route(router.post, "/system/platforms", [Scope.PLATFORMS_WRITE]) async def add_platform_binding( request: Request, payload: PlatformBindingPayload @@ -177,6 +191,7 @@ async def add_platform_binding( fs_slug = payload.fs_slug slug = payload.slug + await _reject_ambiguous_folder(fs_slug) try: cm.add_platform_binding(fs_slug, slug) @@ -208,6 +223,7 @@ async def add_platform_version( fs_slug = payload.fs_slug slug = payload.slug + await _reject_ambiguous_folder(fs_slug) try: cm.add_platform_version(fs_slug, slug) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index cc0749ffb..968749cee 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -192,10 +192,15 @@ def _swappable_disc_file_ids(rom: Rom) -> set[int]: return {f.id for f in playlist_files(rom.files)} -async def _session_status(platform: str, request: Request) -> dict[str, Any]: - """Whether the caller still holds this platform's session, and if not, why - it ended. Read-only, so it is safe to poll.""" - candidates = containers_for_platform(platform) +async def _session_status( + platform: str, + request: Request, + candidates: list[ResolvedContainer] | None = None, +) -> dict[str, Any]: + """Whether the caller holds a session among `candidates` (the platform's first + pool by default), and if not, why it ended. Read-only, so it is safe to poll.""" + if candidates is None: + candidates = containers_for_platform(platform) if not candidates: raise HTTPException( status_code=404, @@ -648,7 +653,7 @@ async def claim_session( The ROM's filesystem path is derived server-side from its database row - the client only supplies a ROM id, never a path. Returns 404 if the ROM doesn't exist or no container serves its platform. - Returns 409 if every container serving the platform is occupied. + Returns 409 if every container in the platform's first pool is occupied. Returns 428 if the container's pre-existing memory card needs a decision. """ rom = db_rom_handler.get_rom(req.rom_id) @@ -668,9 +673,8 @@ async def claim_session( detail=f"No streaming container configured for platform '{platform}'", ) - # Pool members are interchangeable on emulator and card sync (enforced by - # containers_for_platform), so the pre-claim validation below holds for - # whichever one the walk ends up winning. + # Pool members are interchangeable (`ResolvedContainer.interchangeable_with`), + # so the pre-claim validation below holds for whichever one the walk wins. reference = candidates[0] # Validate the resume pick before claiming so a bad state_id cannot @@ -933,7 +937,11 @@ async def save_and_exit_session( @protected_route(router.post, "/sessions/{platform}/heartbeat", [Scope.ROMS_USER_WRITE]) -async def heartbeat_session(request: Request, platform: str) -> SessionStatusSchema: +async def heartbeat_session( + request: Request, + platform: str, + container_key: str | None = Query(default=None, alias="container", max_length=300), +) -> SessionStatusSchema: """Refresh the session's liveness stamp and report whether it still exists. The frontend calls this every ~30s while a session is active. A session @@ -943,28 +951,32 @@ async def heartbeat_session(request: Request, platform: str) -> SessionStatusSch Reports `ended` rather than raising 404 when the caller no longer holds the session, so a force-released player learns why on the poll they are already making rather than watching a dead stream. + + `container` names the claim to refresh, needed for a desktop on a container + outside the platform's first pool. """ - candidates = containers_for_platform(platform) - if not candidates: - raise HTTPException( - status_code=404, - detail=f"No streaming container configured for platform '{platform}'", - ) - found = await access.find_session_for_user(candidates, request.user.id) + user_id = request.user.id + # A named claim answers for itself: another session the caller holds on the + # platform is not the one this client is beating. + candidates = ( + [access.named_container(platform, container_key)] + if container_key is not None + else containers_for_platform(platform) + ) + found = await access.find_session_for_user(candidates, user_id) if found is None: - return SessionStatusSchema(**await _session_status(platform, request)) + return SessionStatusSchema( + **await _session_status(platform, request, candidates) + ) _, session_key, _ = found - # Merging rather than writing the copy read above keeps a swap that landed - # in between; refusing a draining session keeps a heartbeat from making a - # container that is already being torn down look live. Either returns None, - # meaning the claim is gone and reporting "active" would leave the client - # beating a session it no longer holds. + # Merging keeps a swap that landed since the read. Refusing a draining or + # re-claimed session returns None, so the client stops beating a dead claim. try: refreshed = await mutate_session( session_key, {"last_seen": datetime.now(timezone.utc).isoformat()}, - require=lambda s: not s.get("draining"), + require=lambda s: not s.get("draining") and s.get("user_id") == user_id, ) except StreamingSessionContended: # A key too busy to write is a key that exists, so the session is live @@ -972,7 +984,9 @@ async def heartbeat_session(request: Request, platform: str) -> SessionStatusSch log.warning("heartbeat could not stamp contended session %s", session_key) return SessionStatusSchema(status="active", platform=platform) if refreshed is None: - return SessionStatusSchema(**await _session_status(platform, request)) + return SessionStatusSchema( + **await _session_status(platform, request, candidates) + ) await lifecycle.refresh_session_activity(session_key, refreshed) return SessionStatusSchema(status="active", platform=platform) diff --git a/backend/handler/auth/middleware/csrf_middleware.py b/backend/handler/auth/middleware/csrf_middleware.py index 83f2afc90..11a500645 100644 --- a/backend/handler/auth/middleware/csrf_middleware.py +++ b/backend/handler/auth/middleware/csrf_middleware.py @@ -16,6 +16,11 @@ from starlette.responses import PlainTextResponse, Response from starlette.types import ASGIApp, Message, Receive, Scope, Send +def _session_authenticated(request: Request) -> bool: + """Whether the session, resolved and maybe cleared upstream, names a user.""" + return bool((request.scope.get("session") or {}).get("sub")) + + class CSRFMiddleware: def __init__( self, @@ -60,9 +65,10 @@ class CSRFMiddleware: request = Request(scope, receive) - # Skip CSRF check if Authorization header is present + # HybridAuthBackend resolves the session before this header, so a + # session-authenticated request runs as the cookie's owner, not the bearer's. auth_scheme = request.headers.get("Authorization", "").split(" ", 1)[0].lower() - if auth_scheme == "bearer" or auth_scheme == "basic": + if auth_scheme in ("bearer", "basic") and not _session_authenticated(request): await self.app(scope, receive, send) return None diff --git a/backend/handler/database/platforms_handler.py b/backend/handler/database/platforms_handler.py index d19e383a6..d61da9ad7 100644 --- a/backend/handler/database/platforms_handler.py +++ b/backend/handler/database/platforms_handler.py @@ -2,7 +2,7 @@ import functools from collections.abc import Sequence from datetime import datetime -from sqlalchemy import delete, or_, select, update +from sqlalchemy import delete, func, or_, select, update from sqlalchemy.orm import Query, Session, selectinload from decorators.database import begin_session @@ -103,7 +103,15 @@ class DBPlatformsHandler(DBBaseHandler): query: Query = None, # type: ignore session: Session = None, # type: ignore ) -> Platform | None: - return session.scalar(query.filter_by(fs_slug=fs_slug).limit(1)) + platform = session.scalar(query.filter_by(fs_slug=fs_slug).limit(1)) + if platform: + return platform + + # Folder names are matched case-insensitively everywhere else, so a + # folder renamed only in case is the same platform, not a new one. + return session.scalar( + query.filter(func.lower(Platform.fs_slug) == fs_slug.lower()).limit(1) + ) @begin_session @with_firmware diff --git a/backend/handler/filesystem/platforms_handler.py b/backend/handler/filesystem/platforms_handler.py index 38ed64814..a138a32a5 100644 --- a/backend/handler/filesystem/platforms_handler.py +++ b/backend/handler/filesystem/platforms_handler.py @@ -77,3 +77,22 @@ class FSPlatformsHandler(FSHandler): platforms = self._exclude_platforms(platforms) return platforms + + async def find_ambiguous_folders(self, fs_slug: str) -> list[str]: + """The folders a single config mapping would cover, when it covers several. + + Folder names key the config case-insensitively, so siblings differing + only by case (which only a case-sensitive filesystem allows) share one + entry and cannot be mapped apart. + + Args: + fs_slug: The folder name a mapping is being written for. + + Returns: + The matching folders, sorted, or empty when the name is unambiguous. + """ + folded = fs_slug.lower() + matches = sorted( + folder for folder in await self.get_platforms() if folder.lower() == folded + ) + return matches if len(matches) > 1 else [] diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 410e13b12..4e8f958a1 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -80,7 +80,11 @@ from models.user import User from utils import emoji from utils.audio_tags import persist_embedded_cover, remove_persisted_cover from utils.filesystem import sanitize_filename -from utils.platform_aliases import resolve_fs_slug, resolve_platform_slug +from utils.platform_aliases import ( + resolve_fs_folder, + resolve_fs_slug, + resolve_platform_slug, +) LOGGER_MODULE_NAME = {"module_name": "scan"} @@ -292,7 +296,11 @@ async def scan_platform( if platform: known_fs_slug = resolve_fs_slug(platform.slug, cnfg) if known_fs_slug: - platform_attrs["fs_slug"] = known_fs_slug + # `resolve_fs_slug` answers with a lowercased config key, but + # every path is built from the folder's own casing. + platform_attrs["fs_slug"] = ( + resolve_fs_folder(known_fs_slug, fs_platforms) or known_fs_slug + ) platform_attrs["slug"] = resolve_platform_slug(fs_slug, cnfg) diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index c202c2a0a..fefb2cbe4 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -10,6 +10,7 @@ from handler.streaming.config import ( ResolvedContainer, containers_by_key, containers_for_platform, + entry_for_platform, ) from handler.streaming.session_store import get_live_session from models.rom import Rom @@ -106,30 +107,37 @@ async def find_session_for_user( return None +def named_container(platform: str, container_key: str) -> ResolvedContainer: + """A container serving a platform, found by key so one in a later pool stays + reachable. Raises 404 when the key names no such container.""" + candidate = entry_for_platform(containers_by_key().get(container_key, []), platform) + if candidate is None: + raise HTTPException( + status_code=404, + detail=f"No streaming container '{container_key}' for platform '{platform}'", + ) + return candidate + + async def resolve_named_container( platform: str, container_key: str ) -> tuple[ResolvedContainer, str, dict[str, Any] | None]: - """One named container serving a platform, plus whatever session it holds. + """A named container plus whatever session it holds. Returns (container, session_key, session), the session being None when the - container is free or draining. Raises 404 when the key names no container - serving this platform. + container is free or draining. """ - for candidate in containers_for_platform(platform): - session_key = candidate.key - if session_key != container_key: - continue - return candidate, session_key, await get_live_session(session_key) - raise HTTPException( - status_code=404, - detail=f"No streaming container '{container_key}' for platform '{platform}'", + return ( + named_container(platform, container_key), + container_key, + await get_live_session(container_key), ) async def resolve_owned_session( platform: str, request: Request ) -> tuple[ResolvedContainer, str, dict[str, Any]]: - """Find the caller's session among the platform's containers. + """Find the caller's session in the platform's first pool. Returns (container, session_key, session). Raises 404 when the platform has no configured container or nothing is active, 403 when every active session diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index 36ec1bbf3..c636cfabb 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -3,12 +3,15 @@ The raw YAML is loose: a container may serve one platform or a map of them, and may leave its broker host to be derived. Resolution is memoized until the config changes, so an unusable container is reported once rather than once per lookup. +A platform's containers form pools of interchangeable members, and a game claim +only walks the first. """ from __future__ import annotations import json import secrets +from collections.abc import Iterable, Sequence from dataclasses import dataclass from typing import Any from urllib.parse import urlparse, urlunparse @@ -517,38 +520,63 @@ def resolve_containers() -> tuple[ResolvedContainer, ...]: for row, platform in _platform_entries(dict(entry)): resolved.append(_resolve_one(row, platform, entry.get("label"))) + _warn_about_later_pools(resolved) _cache_fingerprint = fingerprint _cached = tuple(resolved) return _cached -def containers_for_platform(platform: str) -> list[ResolvedContainer]: - """Every container serving a platform, in config order. +def _pools(containers: Iterable[ResolvedContainer]) -> list[list[ResolvedContainer]]: + """Group containers into pools of interchangeable members. A pool sits at its + first member's config position, and members keep config order.""" + pools: list[list[ResolvedContainer]] = [] + for container in containers: + pool = next((p for p in pools if p[0].interchangeable_with(container)), None) + if pool is None: + pools.append([container]) + else: + pool.append(container) + return pools - More than one entry is a pool and the claim takes the first free one, so a - container that disagrees with the head on emulator or card sync is not a - pool member and is left out. - """ - lower = platform.lower() - candidates: list[ResolvedContainer] = [] - for container in resolve_containers(): - if container.platform.lower() != lower: - continue - if not container.key: - # Nothing to dial, so a claim would have nowhere to go. The fleet - # view still lists it, which is where the operator sees why. - continue - if candidates and not candidates[0].interchangeable_with(container): + +def _pools_by_platform( + resolved: Iterable[ResolvedContainer], +) -> dict[str, list[list[ResolvedContainer]]]: + """Every platform's pools, keyed by the lowercased platform.""" + by_platform: dict[str, list[ResolvedContainer]] = {} + for container in resolved: + # Nothing to dial, so a claim would have nowhere to go. The fleet view + # still lists it, which is where the operator sees why. + if container.key: + by_platform.setdefault(container.platform.lower(), []).append(container) + return {platform: _pools(members) for platform, members in by_platform.items()} + + +def _warn_about_later_pools(resolved: Sequence[ResolvedContainer]) -> None: + """Name every container a game claim can never reach, once per config.""" + for pools in _pools_by_platform(resolved).values(): + later = [c.key for pool in pools[1:] for c in pool] + if later: log.warning( - "container for platform '%s' disagrees with the first one on " - "emulator, memory card sync or protocol, so it is not a pool " - "member, skipping: %s", - platform, - container.key, + "containers for platform '%s' disagree on emulator, memory card " + "sync, save picker or protocol, so game claims only use the first " + "pool; never claimed for a game: %s", + pools[0][0].platform, + ", ".join(later), ) - continue - candidates.append(container) - return candidates + + +def pools_for_platform(platform: str) -> list[list[ResolvedContainer]]: + """Every container serving a platform, grouped into pools. A container that + matches no other is a pool of one.""" + return _pools_by_platform(resolve_containers()).get(platform.lower(), []) + + +def containers_for_platform(platform: str) -> list[ResolvedContainer]: + """The platform's first pool, which a game claim walks for the first free + container, in config order.""" + pools = pools_for_platform(platform) + return pools[0] if pools else [] def containers_by_key() -> dict[str, list[ResolvedContainer]]: @@ -560,6 +588,14 @@ def containers_by_key() -> dict[str, list[ResolvedContainer]]: return grouped +def entry_for_platform( + entries: Sequence[ResolvedContainer], platform: str +) -> ResolvedContainer | None: + """The record among one container's entries that serves this platform.""" + lower = platform.lower() + return next((e for e in entries if e.platform.lower() == lower), None) + + def container_for_session( grouped: dict[str, list[ResolvedContainer]], container_key: str, platform: Any ) -> ResolvedContainer | None: @@ -569,21 +605,14 @@ def container_for_session( entries = grouped.get(container_key) if not entries: return None - if isinstance(platform, str): - lower = platform.lower() - for entry in entries: - if entry.platform.lower() == lower: - return entry - return entries[0] + entry = entry_for_platform(entries, platform) if isinstance(platform, str) else None + return entry or entries[0] def configured_emulator(platform: str) -> str: """The emulator a configured container serves this platform with, if any.""" - lower = platform.lower() - for container in resolve_containers(): - if container.platform.lower() == lower: - return container.emulator - return "" + entry = entry_for_platform(resolve_containers(), platform) + return entry.emulator if entry else "" def streaming_enabled() -> bool: diff --git a/backend/tests/config/test_config_loader.py b/backend/tests/config/test_config_loader.py index 325741c33..4e93b35f9 100644 --- a/backend/tests/config/test_config_loader.py +++ b/backend/tests/config/test_config_loader.py @@ -1,5 +1,6 @@ import logging import os +from contextlib import contextmanager from pathlib import Path import pytest @@ -16,6 +17,22 @@ from config.config_manager import ( ) +@contextmanager +def capture_romm_logs(caplog, level=logging.WARNING): + """Capture the `romm` logger, whose records never reach caplog on their own. + + It sets `propagate = False`, so caplog's handler has to be attached to it + directly rather than to the root logger. + """ + romm_logger = logging.getLogger("romm") + romm_logger.addHandler(caplog.handler) + try: + with caplog.at_level(level, logger="romm"): + yield caplog + finally: + romm_logger.removeHandler(caplog.handler) + + def test_config_loader(): loader = ConfigManager( os.path.join(Path(__file__).resolve().parent, "fixtures", "config/config.yml") @@ -524,15 +541,8 @@ def test_legacy_streaming_container_logs_deprecation_warning(caplog, tmp_path): " broker_host: http://192.168.1.51:8000\n" " label: PCSX2\n" ) - # The "romm" logger has propagate=False, so caplog's handler must be - # added directly to it rather than relying on root-logger propagation. - romm_logger = logging.getLogger("romm") - romm_logger.addHandler(caplog.handler) - try: - with caplog.at_level(logging.WARNING, logger="romm"): - loader = ConfigManager(str(config_file)) - finally: - romm_logger.removeHandler(caplog.handler) + with capture_romm_logs(caplog): + loader = ConfigManager(str(config_file)) assert loader.config.STREAMING_CONTAINERS assert "deprecated" in caplog.text @@ -552,13 +562,8 @@ def test_webstation_streaming_container_does_not_warn(caplog, tmp_path): " platforms:\n" " ps2: pcsx2\n" ) - romm_logger = logging.getLogger("romm") - romm_logger.addHandler(caplog.handler) - try: - with caplog.at_level(logging.WARNING, logger="romm"): - ConfigManager(str(config_file)) - finally: - romm_logger.removeHandler(caplog.handler) + with capture_romm_logs(caplog): + ConfigManager(str(config_file)) assert "deprecated" not in caplog.text @@ -630,6 +635,48 @@ def test_platform_binding_lookup_ignores_case(tmp_path): assert loader.config.PLATFORMS_BINDING == {} +def test_case_variant_folder_keys_collapse_with_a_warning(caplog, tmp_path): + """One key covers both, so the dropped mapping must not vanish silently.""" + with capture_romm_logs(caplog): + loader = _write_config( + tmp_path, ' platforms:\n PSX: "ps2"\n psx: "psx"\n' + ) + + assert loader.config.PLATFORMS_BINDING == {"psx": "psx"} + assert "case variant" in caplog.text + assert "ps2" in caplog.text + + +def test_identical_case_variant_mappings_do_not_warn(caplog, tmp_path): + with capture_romm_logs(caplog): + loader = _write_config( + tmp_path, ' platforms:\n PSX: "psx"\n psx: "psx"\n' + ) + + assert loader.config.PLATFORMS_BINDING == {"psx": "psx"} + assert "case variant" not in caplog.text + + +def test_rebinding_a_folder_replaces_the_existing_platform(tmp_path): + loader = _write_config(tmp_path, ' platforms:\n GameCube: "ngc"\n') + + loader.add_platform_binding("GameCube", "wii") + + assert loader.config.PLATFORMS_BINDING == {"gamecube": "wii"} + reloaded = ConfigManager(loader.config_file) + assert reloaded.config.PLATFORMS_BINDING == {"gamecube": "wii"} + + +def test_reparenting_a_folder_replaces_the_existing_version(tmp_path): + loader = _write_config(tmp_path, ' versions:\n NAOMI: "arcade"\n') + + loader.add_platform_version("naomi", "dc") + + assert loader.config.PLATFORMS_VERSIONS == {"naomi": "dc"} + reloaded = ConfigManager(loader.config_file) + assert reloaded.config.PLATFORMS_VERSIONS == {"naomi": "dc"} + + def _write_emulatorjs_config(tmp_path: Path, emulatorjs_block: str) -> ConfigManager: config_file = tmp_path / "config.yml" config_file.write_text(f"emulatorjs:\n{emulatorjs_block}") diff --git a/backend/tests/endpoints/test_config.py b/backend/tests/endpoints/test_config.py index 4222c3aa6..8ea1ddf27 100644 --- a/backend/tests/endpoints/test_config.py +++ b/backend/tests/endpoints/test_config.py @@ -1,4 +1,4 @@ -from unittest.mock import patch +from unittest.mock import AsyncMock, patch from fastapi import status @@ -87,6 +87,46 @@ def test_add_platform_version_payload_shape(client, access_token: str): add_platform_version.assert_called_once_with("n64", "1.0") +def test_mapping_a_folder_with_a_case_variant_sibling_is_rejected( + client, access_token: str +): + """One config key covers both, so the write would remap the sibling too.""" + with ( + patch( + "endpoints.configs.fs_platform_handler.find_ambiguous_folders", + AsyncMock(return_value=["PSX", "psx"]), + ), + patch.object(cm, "add_platform_binding") as add_platform_binding, + ): + response = client.post( + "/api/config/system/platforms", + headers={"Authorization": f"Bearer {access_token}"}, + json={"fs_slug": "PSX", "slug": "ps2"}, + ) + + assert response.status_code == status.HTTP_409_CONFLICT + assert "differ only by case" in response.json()["detail"] + add_platform_binding.assert_not_called() + + +def test_mapping_a_folder_whose_name_is_unique_is_allowed(client, access_token: str): + with ( + patch( + "endpoints.configs.fs_platform_handler.find_ambiguous_folders", + AsyncMock(return_value=[]), + ), + patch.object(cm, "add_platform_binding") as add_platform_binding, + ): + response = client.post( + "/api/config/system/platforms", + headers={"Authorization": f"Bearer {access_token}"}, + json={"fs_slug": "Nintendo 64", "slug": "n64"}, + ) + + assert response.status_code == status.HTTP_200_OK + add_platform_binding.assert_called_once_with("Nintendo 64", "n64") + + def test_add_exclusion_payload_shape(client, access_token: str): with patch.object(cm, "add_exclusion") as add_exclusion: response = client.post( diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 9b0a2761f..6b1f06f1d 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -54,6 +54,7 @@ from handler.streaming.config import ( ResolvedContainer, _derive_broker_host, emulator_display_label, + pools_for_platform, reset_cache, resolve_entry, ) @@ -536,7 +537,7 @@ def test_clears_stale_saves_has_no_picker_to_gate_on_a_legacy_container(caplog): assert "clears_stale_saves" in caplog.text -def test_a_container_that_disagrees_on_clearing_saves_is_not_a_pool_member(caplog): +def test_a_container_that_disagrees_on_clearing_saves_is_a_pool_of_its_own(caplog): """The picker is advertised from the head of the pool, so a member that keeps its own newer files would take the pick and silently discard it.""" first = { @@ -562,7 +563,7 @@ def test_a_container_that_disagrees_on_clearing_saves_is_not_a_pool_member(caplo finally: romm_logger.removeHandler(caplog.handler) assert [c.clears_stale_saves for c in candidates] == [True] - assert "not a pool" in caplog.text + assert "never claimed for a game" in caplog.text def test_legacy_containers_still_pool_under_an_inert_clearing_flag(): @@ -1223,6 +1224,22 @@ def test_pool_409s_only_once_every_container_is_held( assert "2 containers" in r3.json()["detail"]["message"] +def test_a_claim_never_lands_in_a_later_pool( + client, access_token, viewer_access_token, rom: Rom +): + """Only the first pool matches the settings a claim is validated against, + so a later pool stays out of reach even when it is the only one free.""" + later = {**_pool_member(rom, 1), "emulator": "other"} + with _streaming(_pool_member(rom, 0), later): + r1 = _claim_ok(client, access_token, rom.id) + r2 = _claim_ok(client, viewer_access_token, rom.id) + assert _session_raw(later) is None + assert len(pools_for_platform(rom.platform_slug)) == 2 + assert r1.status_code == 202 + assert r1.json()["container"] == _key_of(_pool_member(rom, 0)) + assert r2.status_code == 409 + + def test_a_pool_does_not_roll_its_own_holder_onto_a_second_container( client, access_token, rom: Rom ): @@ -1405,6 +1422,103 @@ def test_admin_release_rejects_a_container_that_serves_another_platform( assert r.status_code == 404 +def _in_a_later_ps2_pool() -> dict: + """A second webstation that disagrees with `_webstation()` on the ps2 + emulator, so it forms a later ps2 pool.""" + return _webstation( + host="http://192.168.1.11:3000", + broker_host="http://192.168.1.11:8000", + platforms={"ps2": "play", "ngc": "dolphin"}, + ) + + +def test_admin_release_ends_a_session_on_a_container_in_a_later_pool( + client, access_token +): + """A game claim never reaches a later pool, but an admin can still end a + session there by naming the container.""" + later = _in_a_later_ps2_pool() + with _streaming(_webstation(), later): + key = _key_of(later) + assert key not in [c.key for c in streaming.containers_for_platform("ps2")] + assert _desktop(client, access_token, key)[0].status_code == 200 + with patch("handler.streaming.commands.stop", return_value=None): + r = client.delete( + "/api/streaming/sessions/ps2", + params={"container": key}, + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "released" + assert _session_raw(later) is None + + +def test_heartbeat_naming_the_container_refreshes_a_desktop_in_a_later_pool( + client, access_token +): + """The platform's lookup only walks the first pool, so only the named key + keeps this desktop claim fresh.""" + later = _in_a_later_ps2_pool() + with _streaming(_webstation(), later): + key = _key_of(later) + assert _desktop(client, access_token, key)[0].status_code == 200 + _age_session_on(later, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", + params={"container": key}, + headers=_auth(access_token), + ) + session = json.loads(_session_raw(later)) + assert r.status_code == 200 + assert r.json()["status"] == "active" + assert not session_store.session_is_stale(session) + + +def test_heartbeat_naming_a_released_container_reports_ended(client, access_token): + """A session the caller holds on another of the platform's containers must + not answer for the named one.""" + later = _in_a_later_ps2_pool() + with _streaming(_webstation(), later): + key = _key_of(later) + assert ( + _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 + ) + assert _desktop(client, access_token, key)[0].status_code == 200 + with patch("handler.streaming.commands.stop", return_value=None): + released = client.delete( + "/api/streaming/sessions/ps2", + params={"container": key}, + headers=_auth(access_token), + ) + assert released.status_code == 200 + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", + params={"container": key}, + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + + +def test_heartbeat_naming_a_container_leaves_another_users_session_alone( + client, access_token, viewer_access_token +): + later = _in_a_later_ps2_pool() + with _streaming(_webstation(), later): + key = _key_of(later) + assert _desktop(client, access_token, key)[0].status_code == 200 + _age_session_on(later, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", + params={"container": key}, + headers=_auth(viewer_access_token), + ) + session = json.loads(_session_raw(later)) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert session_store.session_is_stale(session) + + def test_status_finds_the_termination_on_whichever_container_held_it( client, access_token, viewer_access_token, rom: Rom ): @@ -1445,9 +1559,9 @@ def test_heartbeat_refreshes_the_session_on_the_container_that_holds_it( assert after > before -def test_a_container_that_disagrees_on_the_emulator_is_not_a_pool_member(caplog): +def test_a_container_that_disagrees_on_the_emulator_is_a_later_pool(caplog): """Pool members file states and cards in one place, so an entry naming a - different emulator is a separate setup rather than a spare container.""" + different emulator is a pool of its own rather than a spare container.""" first = { "platform": "ps2", "host": "http://192.168.1.10:3000", @@ -1457,16 +1571,35 @@ def test_a_container_that_disagrees_on_the_emulator_is_not_a_pool_member(caplog) second = {**first, "host": "http://192.168.1.11:3000"} second["broker_host"] = "http://192.168.1.11:8000" second["emulator"] = "play" + third = { + **first, + "host": "http://192.168.1.12:3000", + "broker_host": "http://192.168.1.12:8000", + } romm_logger = logging.getLogger("romm") romm_logger.addHandler(caplog.handler) try: - with _streaming(first, second): + with _streaming(first, second, third): with caplog.at_level(logging.WARNING, logger="romm"): + pools = pools_for_platform("ps2") candidates = streaming.containers_for_platform("ps2") finally: romm_logger.removeHandler(caplog.handler) - assert [c.emulator for c in candidates] == ["pcsx2"] - assert "not a pool" in caplog.text + assert [[c.emulator for c in pool] for pool in pools] == [ + ["pcsx2", "pcsx2"], + ["play"], + ] + assert candidates == pools[0] + # Once per config, not once per lookup. + assert caplog.text.count("never claimed for a game") == 1 + assert _key_of(second) in caplog.text + + +def test_a_lone_container_is_a_pool_of_one(rom: Rom): + member = _pool_member(rom, 0) + with _streaming(member): + pools = pools_for_platform(rom.platform_slug) + assert [[c.key for c in pool] for pool in pools] == [[_key_of(member)]] def test_webstation_pool_members_at_different_subfolders_are_still_a_pool(caplog): @@ -1498,7 +1631,7 @@ def test_webstation_pool_members_at_different_subfolders_are_still_a_pool(caplog "http://192.168.1.10:8000", "http://192.168.1.11:8000", ] - assert "not a pool" not in caplog.text + assert "never claimed for a game" not in caplog.text def test_a_proxied_host_disagreeing_with_its_subfolder_cannot_be_claimed(caplog): diff --git a/backend/tests/handler/auth/test_csrf_middleware.py b/backend/tests/handler/auth/test_csrf_middleware.py index 1d59e12b0..066a3aaa9 100644 --- a/backend/tests/handler/auth/test_csrf_middleware.py +++ b/backend/tests/handler/auth/test_csrf_middleware.py @@ -1,5 +1,6 @@ import asyncio import re +from typing import Any from itsdangerous import URLSafeSerializer from starlette.applications import Starlette @@ -10,9 +11,10 @@ from starlette.requests import Request from starlette.responses import JSONResponse, PlainTextResponse from starlette.routing import Route from starlette.testclient import TestClient +from starlette.types import ASGIApp, Receive, Scope, Send from config import ROMM_AUTH_SECRET_KEY -from handler.auth.constants import ALGORITHM +from handler.auth.constants import ALGORITHM, SESSION_COOKIE_NAME from handler.auth.middleware.csrf_middleware import CSRFMiddleware from handler.auth.middleware.session_middleware import SessionMiddleware from models.user import User @@ -58,6 +60,30 @@ def create_test_app(**csrf_kwargs) -> Starlette: return Starlette(routes=routes, middleware=middleware) +def create_session_app(session: dict[str, Any]) -> Starlette: + """A CSRF app behind a resolved session, as `main.py` orders them.""" + + class StubSessionMiddleware: + def __init__(self, app: ASGIApp) -> None: + self.app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + scope["session"] = dict(session) + await self.app(scope, receive, send) + + async def post_handler(request: Request) -> JSONResponse: + return JSONResponse({"status": "success"}) + + return Starlette( + routes=[Route("/post", post_handler, methods=["POST"])], + middleware=[ + Middleware(StubSessionMiddleware), + Middleware(AuthenticationMiddleware, backend=BasicAuthBackend()), + Middleware(CSRFMiddleware, secret="test-secret"), + ], + ) + + class TestCSRFMiddleware: def test_csrf_cookie_set_on_first_get(self) -> None: """A GET request should set the CSRF cookie if none exists.""" @@ -203,6 +229,22 @@ class TestCSRFMiddleware: resp = client.post("/post", headers={"Authorization": "Bearer token"}) assert resp.status_code == 200 + def test_authenticated_session_keeps_csrf_on_despite_auth_header(self) -> None: + """The session authenticates first, so the header must not exempt it.""" + client = TestClient(create_session_app({"iss": "romm:auth", "sub": "victim"})) + client.cookies.set(SESSION_COOKIE_NAME, "live-session-id") + + resp = client.post("/post", headers={"Authorization": "Bearer anything"}) + assert resp.status_code == 403 + + def test_stale_session_still_lets_the_auth_header_through(self) -> None: + """A cookie the session store rejected leaves the header as the credential.""" + client = TestClient(create_session_app({})) + client.cookies.set(SESSION_COOKIE_NAME, "expired-session-id") + + resp = client.post("/post", headers={"Authorization": "Bearer token"}) + assert resp.status_code == 200 + def test_non_http_scope_bypass(self) -> None: """WebSocket (or other non-HTTP) scopes should pass through.""" # Manual ASGI call; TestClient doesn't expose WebSocket easily diff --git a/backend/tests/handler/database/test_platforms_handler.py b/backend/tests/handler/database/test_platforms_handler.py index 195264373..6ede30241 100644 --- a/backend/tests/handler/database/test_platforms_handler.py +++ b/backend/tests/handler/database/test_platforms_handler.py @@ -2,6 +2,32 @@ from handler.database import db_platform_handler from models.platform import Platform +def test_lookup_finds_a_folder_renamed_only_in_case(): + """A rescan must reuse the row, not add a second platform beside it.""" + stored = db_platform_handler.add_platform( + Platform(name="N64", slug="n64", fs_slug="nintendo 64") + ) + + found = db_platform_handler.get_platform_by_fs_slug("Nintendo 64") + + assert found is not None + assert found.id == stored.id + + +def test_lookup_returns_the_exactly_named_folder_when_one_exists(): + """The exact spelling is tried first, for backends that can tell them apart. + + MariaDB and MySQL match case-insensitively by collation, so only the + exactly-named row is asserted here; PostgreSQL additionally distinguishes + the sibling. + """ + exact = db_platform_handler.add_platform( + Platform(name="PlayStation", slug="psx", fs_slug="psx") + ) + + assert db_platform_handler.get_platform_by_fs_slug("psx").id == exact.id + + def test_rescan_preserves_user_authored_fields(platform): """A rescan merges a freshly built Platform over the existing row. diff --git a/backend/tests/handler/filesystem/test_platforms_handler.py b/backend/tests/handler/filesystem/test_platforms_handler.py index 58448f70d..dffef35ad 100644 --- a/backend/tests/handler/filesystem/test_platforms_handler.py +++ b/backend/tests/handler/filesystem/test_platforms_handler.py @@ -205,6 +205,24 @@ class TestFSPlatformsHandler: assert "n64" in result assert "psx" not in result + async def test_find_ambiguous_folders_reports_case_variant_siblings( + self, handler: FSPlatformsHandler + ): + """One config key covers both, so they cannot be mapped apart.""" + with patch.object(handler, "get_platforms", return_value=["PSX", "n64", "psx"]): + assert await handler.find_ambiguous_folders("psx") == ["PSX", "psx"] + assert await handler.find_ambiguous_folders("PSX") == ["PSX", "psx"] + + async def test_find_ambiguous_folders_ignores_an_unshared_name( + self, handler: FSPlatformsHandler + ): + with patch.object( + handler, "get_platforms", return_value=["Nintendo 64", "psx"] + ): + assert await handler.find_ambiguous_folders("Nintendo 64") == [] + assert await handler.find_ambiguous_folders("nintendo 64") == [] + assert await handler.find_ambiguous_folders("absent") == [] + async def test_get_platforms_calls_list_directories_with_correct_path( self, handler: FSPlatformsHandler, config ): diff --git a/backend/tests/test_web_server_config.py b/backend/tests/test_web_server_config.py index d125b3957..59c2c2d1d 100644 --- a/backend/tests/test_web_server_config.py +++ b/backend/tests/test_web_server_config.py @@ -18,6 +18,11 @@ NGINX_UPSTREAM_IDLE_TIMEOUT = 60 # pool is off entirely and the timeout invariant stops meaning anything. NGINX_UPSTREAM_KEEPALIVE_SINCE = (1, 29, 7) +# njs 0.9.7 dropped the "js vm init njs" notice it logged on every start. nginx +# 1.30.0 also shipped builds bundling njs 0.9.6, so 1.30.1 is the first release +# that never logs it. +NJS_QUIET_STARTUP_SINCE = (1, 30, 1) + REQUIRED_GZIP_TYPES = [ "application/wasm", # EmulatorJS, js-dos and FAKE-08 cores "image/svg+xml", # player logos and favicons @@ -47,16 +52,32 @@ def test_compressible_types_are_gzipped(gzip_types: set[str], media_type: str) - assert media_type in gzip_types, f"{media_type} would be served uncompressed" -def test_nginx_defaults_upstream_keepalive_on() -> None: +def _format(version: tuple[int, ...]) -> str: + return ".".join(str(part) for part in version) + + +def _nginx_version() -> tuple[int, ...]: match = re.search(r"^ARG NGINX_VERSION=(\S+)", DOCKERFILE.read_text(), re.M) assert match, "docker/Dockerfile is missing an ARG NGINX_VERSION pin" - version = tuple(int(part) for part in match.group(1).split(".")) + return tuple(int(part) for part in match.group(1).split(".")) + + +def test_nginx_defaults_upstream_keepalive_on() -> None: + version = _nginx_version() assert version >= NGINX_UPSTREAM_KEEPALIVE_SINCE, ( - f"nginx {match.group(1)} does not pool upstream connections by default, " + f"nginx {_format(version)} does not pool upstream connections by default, " f"so every API request opens a new one" ) +def test_nginx_starts_without_the_njs_notice() -> None: + version = _nginx_version() + assert version >= NJS_QUIET_STARTUP_SINCE, ( + f"nginx {_format(version)} bundles an njs that logs a 'js vm init njs' " + f"notice on every start, because the config imports a VM at the http level" + ) + + def test_gunicorn_outlives_nginx_upstream_idle_timeout() -> None: assert _init_script_keepalive() > NGINX_UPSTREAM_IDLE_TIMEOUT diff --git a/backend/tests/utils/test_platform_aliases.py b/backend/tests/utils/test_platform_aliases.py index 7d2c25c82..d1b0924e8 100644 --- a/backend/tests/utils/test_platform_aliases.py +++ b/backend/tests/utils/test_platform_aliases.py @@ -7,6 +7,7 @@ from config.config_manager import Config from utils.platform_aliases import ( PLATFORM_FS_ALIASES, PLATFORM_SLUG_FOLDERS, + resolve_fs_folder, resolve_fs_slug, resolve_platform_slug, ) @@ -85,6 +86,23 @@ def test_slug_reached_by_several_folders_has_no_reverse(): assert resolve_fs_slug("my-custom-slug", _config()) is None +def test_resolves_a_config_key_to_the_folder_on_disk(): + """Config keys are lowercased; paths need the folder's own casing.""" + assert resolve_fs_folder("nintendo 64", ["Nintendo 64", "psx"]) == "Nintendo 64" + + +def test_resolves_a_folder_that_is_not_on_disk_to_nothing(): + assert resolve_fs_folder("nintendo 64", ["psx"]) is None + + +def test_two_folders_differing_only_by_case_each_resolve_to_themselves(): + """A case-sensitive filesystem allows both; neither may claim the other.""" + folders = ["PSX", "psx"] + + assert resolve_fs_folder("psx", folders) == "psx" + assert resolve_fs_folder("PSX", folders) == "PSX" + + def test_reverse_map_agrees_with_alias_table(): for slug, fs_slug in PLATFORM_SLUG_FOLDERS.items(): assert PLATFORM_FS_ALIASES[fs_slug].value == slug diff --git a/backend/utils/platform_aliases.py b/backend/utils/platform_aliases.py index 4833a44ae..1f030c425 100644 --- a/backend/utils/platform_aliases.py +++ b/backend/utils/platform_aliases.py @@ -1,5 +1,6 @@ from __future__ import annotations +from collections.abc import Iterable from typing import TYPE_CHECKING, Final from utils.platform_slugs import UniversalPlatformSlug as UPS @@ -190,3 +191,23 @@ def resolve_fs_slug(slug: str, config: Config) -> str | None: if bound == slug: return fs_slug return PLATFORM_SLUG_FOLDERS.get(slug) + + +def resolve_fs_folder(fs_slug: str, fs_platforms: Iterable[str]) -> str | None: + """Resolve a folder name to the one on disk it names, ignoring case. + + Config keys are lowercased, but paths are built from the folder's own + casing. An exact match wins, so on a case-sensitive filesystem two folders + differing only by case each still resolve to themselves. + + Returns: + The folder as it is spelled on disk, or None when none matches. + """ + folded = fs_slug.lower() + fallback: str | None = None + for folder in fs_platforms: + if folder == fs_slug: + return folder + if fallback is None and folder.lower() == folded: + fallback = folder + return fallback diff --git a/docker/Dockerfile b/docker/Dockerfile index cb113bb7e..2f9178397 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,4 +1,5 @@ # Stages: +# - python-runtime: Patch the Python image's libraries before they ship # - frontend-build: Build frontend # - backend-build: Build backend environment # - backend-dev-build: Similar to `backend-build`, but also compiles and installs development dependencies @@ -14,15 +15,15 @@ # ARGUMENT DECLARATIONS -ARG ALPINE_VERSION=3.23 -ARG ALPINE_SHA256=25109184c71bdad752c8312a8623239686a9a2071e8825f20acb8f2198c3f659 +ARG ALPINE_VERSION=3.24 +ARG ALPINE_SHA256=294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6 # Pins the base image tag, so it cannot read ../.python-version; keep the two in sync. ARG PYTHON_VERSION=3.14 -ARG PYTHON_ALPINE_SHA256=8caa2adfeb414dfe68d8b257f7aea9e205a400521c2b13b2d2e5e731fb8e70e5 +ARG PYTHON_ALPINE_SHA256=9e9fde4d32eedce0b661d9ab91e826b62dddf28e928c230ec55f1866cac66b01 ARG NODE_VERSION=24.16 -ARG NODE_ALPINE_SHA256=2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 -ARG NGINX_VERSION=1.29.8 -ARG NGINX_SHA256=5616878291a2eed594aee8db4dade5878cf7edcb475e59193904b198d9b830de +ARG NODE_ALPINE_SHA256=21f403ab171f2dc89bad4dd69d7721bfd15f084ccb46cdd225f31f2bc59b5c9a +ARG NGINX_VERSION=1.30.5 +ARG NGINX_SHA256=a5f2157a0302eb0c5e300415effb63a9e70ed1eb9c107283819bf6d149ab607c ARG UV_VERSION=0.12.13 ARG UV_SHA256=eb47c391d3a252d9d912270dd2b5e234af5493e92039fedb483f1dd1cb5659ce @@ -30,6 +31,15 @@ ARG UV_SHA256=eb47c391d3a252d9d912270dd2b5e234af5493e92039fedb483f1dd1cb5659ce FROM python:${PYTHON_VERSION}-alpine${ALPINE_VERSION}@sha256:${PYTHON_ALPINE_SHA256} AS python-alias +# PATCHED PYTHON RUNTIME +# production-stage copies /usr/lib from here over its own, so these libraries +# need the same patches, or the stale ones land in the final image. Kept apart +# from python-alias so that busting this layer's cache (see `no-cache-filters` +# in build.yml) does not also rebuild the venv and the sigil bindings. +FROM python-alias AS python-runtime +RUN apk upgrade --no-cache + + # FRONTEND BUILD # Built on the native build platform: the output (/front/dist) is static JS/CSS, # fully architecture-independent, so there is no need to emulate the target arch. @@ -217,7 +227,9 @@ RUN git clone https://github.com/evanmiller/mod_zip.git && \ FROM nginx:${NGINX_VERSION}-alpine${ALPINE_VERSION}@sha256:${NGINX_SHA256} AS production-stage ARG WEBSERVER_FOLDER=/var/www/html -RUN apk add --no-cache \ +# Alpine backports security fixes to its repo faster than the base image is +# rebuilt, so the digest pin alone leaves known-vulnerable packages in the image. +RUN apk upgrade --no-cache && apk add --no-cache \ bash \ libarchive-tools \ libmagic \ @@ -234,11 +246,11 @@ RUN apk add --no-cache \ # TODO: Replace with a bundled installation of Python using `uv`, when it is supported. # Related issue: https://github.com/astral-sh/uv/issues/7865 ARG PYTHON_VERSION -COPY --from=python-alias /usr/lib/* /usr/lib/ -COPY --from=python-alias /usr/local/bin/* /usr/local/bin/ -COPY --from=python-alias /usr/local/include/python${PYTHON_VERSION} /usr/local/include/python${PYTHON_VERSION} -COPY --from=python-alias /usr/local/lib/libpython* /usr/local/lib/ -COPY --from=python-alias /usr/local/lib/python${PYTHON_VERSION} /usr/local/lib/python${PYTHON_VERSION} +COPY --from=python-runtime /usr/lib/* /usr/lib/ +COPY --from=python-runtime /usr/local/bin/* /usr/local/bin/ +COPY --from=python-runtime /usr/local/include/python${PYTHON_VERSION} /usr/local/include/python${PYTHON_VERSION} +COPY --from=python-runtime /usr/local/lib/libpython* /usr/local/lib/ +COPY --from=python-runtime /usr/local/lib/python${PYTHON_VERSION} /usr/local/lib/python${PYTHON_VERSION} COPY --from=rahasher-build /RALibretro/bin64/RAHasher /usr/bin/RAHasher COPY --from=nginx-build ./nginx/objs/ngx_http_zip_module.so /usr/lib/nginx/modules/ diff --git a/docs/FRONTEND_ARCHITECTURE.md b/docs/FRONTEND_ARCHITECTURE.md index 758484892..79693ba45 100644 --- a/docs/FRONTEND_ARCHITECTURE.md +++ b/docs/FRONTEND_ARCHITECTURE.md @@ -123,7 +123,8 @@ frontend/ ├── index.html # HTML entry point (
) ├── package.json # Dependencies & scripts ├── vite.config.js # Vite build config with plugins -├── tsconfig.json # TypeScript configuration +├── tsconfig.json # Vue app TypeScript (vue-tsc) +├── tsconfig.node.json # Node/Vite tooling TypeScript (tsc -p) ├── eslint.config.js # ESLint flat config ├── .nvmrc # Node 24 │ @@ -1099,14 +1100,15 @@ Procedural SVG generation for: ### Scripts -| Script | Command | Purpose | -| ----------- | ---------------------------- | ---------------------------------------- | -| `dev` | `vite --host` | Development server | -| `build` | `vite build` | Production build | -| `preview` | `vite preview` | Preview production build | -| `typecheck` | `vue-tsc --noEmit` | TypeScript validation | -| `generate` | `openapi-typescript-codegen` | Generate types from backend OpenAPI | -| `lint` | `eslint` | Lint `.vue`, `.js`, `.ts`; import cycles | +| Script | Command | Purpose | +| ------------------- | ------------------------------------ | ------------------------------------------------------ | +| `dev` | `vite --host` | Development server | +| `build` | `vite build` | Production build | +| `preview` | `vite preview` | Preview production build | +| `typecheck` | `vue-tsc --noEmit` | App SFCs (`tsconfig.json`) | +| `typecheck:scripts` | `tsc --noEmit -p tsconfig.node.json` | Node/Vite tooling in `scripts/` (`tsconfig.node.json`) | +| `generate` | `openapi-typescript-codegen` | Generate types from backend OpenAPI | +| `lint` | `eslint` | Lint `.vue`, `.js`, `.ts`; import cycles | ### OpenAPI Code Generation diff --git a/frontend/.browserslistrc b/frontend/.browserslistrc deleted file mode 100644 index e8391d6f3..000000000 --- a/frontend/.browserslistrc +++ /dev/null @@ -1,11 +0,0 @@ -# Browser support baseline for the RomM frontend. Matches Tailwind v4's -# minimum targets. This is the single source of truth for browser support: -# vite.config.js derives Lightning CSS's `build.cssTarget` from it (so the -# production build prefixes/down-levels CSS for exactly these browsers), and -# any other tooling reads the same file. Expressed as floors, not pinned -# versions, and the actual version data comes from caniuse-lite. -chrome >= 111 -edge >= 111 -firefox >= 128 -safari >= 16.4 -ios_saf >= 16.4 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f63fc5d70..71473dc1f 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -52,7 +52,6 @@ "@vue/test-utils": "^2.4.9", "@vue/tsconfig": "^0.9.1", "axe-core": "^4.12.1", - "browserslist": "^4.28.8", "eslint": "^10.0.3", "eslint-config-prettier": "^10.1.8", "eslint-import-resolver-typescript": "^4.4.5", diff --git a/frontend/package.json b/frontend/package.json index b2f0de5d2..17850c5be 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -27,6 +27,7 @@ "build": "vite build", "preview": "vite preview", "typecheck": "vue-tsc --noEmit", + "typecheck:scripts": "tsc --noEmit -p tsconfig.node.json", "generate": "openapi --input http://127.0.0.1:3000/openapi.json --output ./src/__generated__ --client axios --useOptions --useUnionTypes --exportServices false --exportSchemas false --exportCore false", "test": "vitest run", "test:watch": "vitest", @@ -81,7 +82,6 @@ "@vue/test-utils": "^2.4.9", "@vue/tsconfig": "^0.9.1", "axe-core": "^4.12.1", - "browserslist": "^4.28.8", "eslint": "^10.0.3", "eslint-config-prettier": "^10.1.8", "eslint-import-resolver-typescript": "^4.4.5", diff --git a/frontend/src/components/Settings/LibraryManagement/Config/Dialog/CreateFolderMapping.vue b/frontend/src/components/Settings/LibraryManagement/Config/Dialog/CreateFolderMapping.vue index d17d97a75..0dad195f2 100644 --- a/frontend/src/components/Settings/LibraryManagement/Config/Dialog/CreateFolderMapping.vue +++ b/frontend/src/components/Settings/LibraryManagement/Config/Dialog/CreateFolderMapping.vue @@ -36,13 +36,10 @@ const availableFolders = computed(() => { } // Exclude folders that are already mapped as either an alias or a variant. - const isBound = Object.keys(configStore.config.PLATFORMS_BINDING).includes( - folder, + return ( + !configStore.getPlatformBinding(folder) && + !configStore.getPlatformVersion(folder) ); - const isVersion = Object.keys( - configStore.config.PLATFORMS_VERSIONS, - ).includes(folder); - return !isBound && !isVersion; }); }); diff --git a/frontend/src/components/Settings/LibraryManagement/Config/FolderMappings.vue b/frontend/src/components/Settings/LibraryManagement/Config/FolderMappings.vue index 47bde87a6..4a2bcb27c 100644 --- a/frontend/src/components/Settings/LibraryManagement/Config/FolderMappings.vue +++ b/frontend/src/components/Settings/LibraryManagement/Config/FolderMappings.vue @@ -1,4 +1,5 @@