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/resources/socket-badge.svg b/.github/resources/socket-badge.svg new file mode 100644 index 000000000..41952a2bd --- /dev/null +++ b/.github/resources/socket-badge.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + Secured by Socket + + + SUPPLY CHAIN SECURITY + + + diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2341a4b81..c118a5032 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -57,6 +57,8 @@ jobs: steps: - name: Checkout code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 @@ -112,8 +114,10 @@ jobs: org.opencontainers.image.licenses="AGPLv3" - name: Set version + env: + VERSION: ${{ steps.meta.outputs.version }} run: | - sed -i 's//${{ steps.meta.outputs.version }}/' backend/__version__.py + sed -i "s//$VERSION/" backend/__version__.py - name: Build and push slim image by digest id: build-slim @@ -125,6 +129,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 +152,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..eb2becdd1 100644 --- a/.github/workflows/copilot-setup-steps.yml +++ b/.github/workflows/copilot-setup-steps.yml @@ -25,9 +25,11 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - 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..6f14f508a 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: @@ -61,6 +62,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install mariadb connectors run: | @@ -68,7 +71,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 @@ -96,6 +99,9 @@ jobs: # assets/ under it), so copy the fixture library out of the repo rather # than scanning it in place. - name: Stage the library fixture + env: + MARIADB_PORT: ${{ job.services.mariadb.ports['3306'] }} + VALKEY_PORT: ${{ job.services.valkey.ports['6379'] }} run: | mkdir -p "$RUNNER_TEMP/romm/resources" "$RUNNER_TEMP/romm/assets" cp -R backend/romm_test/library "$RUNNER_TEMP/romm/library" @@ -103,8 +109,8 @@ jobs: # config.yml declares. cp -R backend/romm_test/config "$RUNNER_TEMP/romm/config" echo "ROMM_BASE_PATH=$RUNNER_TEMP/romm" >> "$GITHUB_ENV" - echo "DB_PORT=${{ job.services.mariadb.ports['3306'] }}" >> "$GITHUB_ENV" - echo "REDIS_PORT=${{ job.services.valkey.ports['6379'] }}" >> "$GITHUB_ENV" + echo "DB_PORT=$MARIADB_PORT" >> "$GITHUB_ENV" + echo "REDIS_PORT=$VALKEY_PORT" >> "$GITHUB_ENV" # A migration failure is its own red step rather than a confusing server-start failure. - name: Apply migrations diff --git a/.github/workflows/frontend-v1-frozen.yml b/.github/workflows/frontend-v1-frozen.yml index 9a7fb3593..b6fe5f61a 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: @@ -26,6 +27,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 + persist-credentials: false - name: Fail if v1 UI files changed env: diff --git a/.github/workflows/frontend.yml b/.github/workflows/frontend.yml index 30cb2af0e..bafb31752 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: @@ -18,6 +19,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 @@ -39,6 +42,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml index 6d3323820..60bd0b594 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: @@ -14,9 +15,11 @@ jobs: steps: - name: Checkout code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - 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..65fe28975 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 @@ -34,6 +32,8 @@ jobs: steps: - name: Checkout code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install mariadb connectors run: | @@ -41,7 +41,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 +68,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: @@ -91,6 +88,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install mariadb connectors run: | @@ -98,7 +97,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..93e3ef015 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: @@ -63,6 +61,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install mariadb connectors run: | @@ -70,7 +70,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: | @@ -82,12 +82,14 @@ jobs: - name: Initiate MariaDB database if: matrix.db == 'mariadb' + env: + MARIADB_PORT: ${{ job.services.mariadb.ports['3306'] }} run: | # Grant on the `romm_test%` namespace so the test user can create the # per-worker databases (romm_test_gw0, ...) used under pytest-xdist, # without granting it global privileges. The backticks are escaped so # the shell doesn't treat them as command substitution. - mysql --host 127.0.0.1 --port ${{ job.services.mariadb.ports['3306'] }} -uroot -ppasswd -e "GRANT ALL PRIVILEGES ON \`romm\_test%\`.* TO 'romm_test'@'%' WITH GRANT OPTION; FLUSH PRIVILEGES;" + mysql --host 127.0.0.1 --port "$MARIADB_PORT" -uroot -ppasswd -e "GRANT ALL PRIVILEGES ON \`romm\_test%\`.* TO 'romm_test'@'%' WITH GRANT OPTION; FLUSH PRIVILEGES;" - name: Run python tests env: diff --git a/.github/workflows/test-build.yml b/.github/workflows/test-build.yml index 1640e87a8..7be278d57 100644 --- a/.github/workflows/test-build.yml +++ b/.github/workflows/test-build.yml @@ -76,6 +76,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.branch || github.head_ref }} + persist-credentials: false - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 diff --git a/.github/workflows/trunk-check.yml b/.github/workflows/trunk-check.yml index 7f21098cb..961e33b9b 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: @@ -21,5 +22,7 @@ jobs: steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Trunk Check uses: trunk-io/trunk-action@e1234e67a86010d61ddac8d8ebf4b783e2ffd2fa # v2.0.0 diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml index aa505a17f..c6c1861c3 100644 --- a/.github/workflows/typecheck.yml +++ b/.github/workflows/typecheck.yml @@ -10,17 +10,17 @@ 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 + with: + persist-credentials: false - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 @@ -37,6 +37,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..df696f19c 100644 --- a/.github/workflows/update-hltb-api-url.yml +++ b/.github/workflows/update-hltb-api-url.yml @@ -8,18 +8,22 @@ 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 + with: + persist-credentials: false - 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/.trunk/configs/mypy.ini b/.trunk/configs/mypy.ini index 7043064c6..7ff97cd03 100644 --- a/.trunk/configs/mypy.ini +++ b/.trunk/configs/mypy.ini @@ -1,4 +1,5 @@ [mypy] check_untyped_defs = True disable_error_code = import-untyped -exclude = ["tests", "alembic"] +# INI configs take a regex here, not a TOML-style list. +exclude = (?x)(^|/)alembic/ diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 0d04ba83c..9f68fdb1a 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -22,6 +22,7 @@ lint: - oxipng - pyright enabled: + - zizmor@1.30.1 - grype@0.110.0 - pinact@4.0.0 - dotenv-linter@4.0.0 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..38b5591f5 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ These companies support us by providing their tools for free:
Greptile - Aikido + Socket
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/endpoints/user.py b/backend/endpoints/user.py index 246df940c..5da5ab38e 100644 --- a/backend/endpoints/user.py +++ b/backend/endpoints/user.py @@ -471,19 +471,26 @@ async def update_user( cleaned_data["avatar_path"] = file_location if cleaned_data: - db_user_handler.update_user(id, cleaned_data) + # Sessions are keyed by username, so the old one is what identifies + # them once the update has renamed the account. + previous_username = db_user.username + creds_updated = cleaned_data.get("username") or cleaned_data.get( + "hashed_password" + ) + + await auth_handler.apply_user_update( + id, + cleaned_data, + revoke_sessions_for=previous_username if creds_updated else None, + ) + + if creds_updated and request.user.id == id: + request.session.clear() # A role change alters the user's effective permissions; tell their UI. if "role" in cleaned_data: await emit_permissions_changed(id) - # Log out the current user if username or password changed - creds_updated = cleaned_data.get("username") or cleaned_data.get( - "hashed_password" - ) - if request.user.id == id and creds_updated: - request.session.clear() - db_user = db_user_handler.get_user(id) if not db_user: msg = f"Username with id {id} not found" diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index 6f8f1cd94..50e83b9d3 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -9,6 +9,7 @@ from joserfc import jwt from joserfc.errors import BadSignatureError, DecodeError from joserfc.jwk import OctKey from passlib.context import CryptContext +from redis.exceptions import RedisError from starlette.requests import HTTPConnection from config import ( @@ -205,6 +206,43 @@ class AuthHandler: return user + async def apply_user_update( + self, + user_id: int, + data: dict[str, Any], + revoke_sessions_for: str | None = None, + ) -> None: + """ + Write an update to a user, revoking that account's sessions around it. + Args: + user_id (int): The user the update applies to. + data (dict[str, Any]): The fields to write. + revoke_sessions_for (str | None): Username the sessions are keyed by, + or None to write without revoking. + """ + from handler.database import db_user_handler + + if revoke_sessions_for: + # Ahead of the write: an unreachable Redis then aborts the change + # rather than committing it with the account's sessions left live. + await RedisSessionMiddleware.clear_user_sessions(revoke_sessions_for) + + db_user_handler.update_user(user_id, data) + + if revoke_sessions_for: + # After it, for a login the old password was still good for. The + # write has committed, so a failure here is logged, not raised. + try: + await RedisSessionMiddleware.clear_user_sessions(revoke_sessions_for) + except RedisError, OSError: + log.error( + "Credentials for '%s' changed, but revoking its sessions " + "afterwards failed; a session created during the update may " + "still be live", + hl(revoke_sessions_for, color=CYAN), + exc_info=True, + ) + async def set_user_new_password(self, user: Any, new_password: str) -> None: """ Set the new password for the user. @@ -212,12 +250,11 @@ class AuthHandler: user (Any): The user object. new_password (str): The new password to set. """ - from handler.database import db_user_handler - - db_user_handler.update_user( - user.id, {"hashed_password": self.get_password_hash(new_password)} + await self.apply_user_update( + user.id, + {"hashed_password": self.get_password_hash(new_password)}, + revoke_sessions_for=user.username, ) - await RedisSessionMiddleware.clear_user_sessions(user.username) def generate_invite_link_token( self, user: Any, role: str, expiration: int | None = None diff --git a/backend/handler/auth/middleware/redis_session_middleware.py b/backend/handler/auth/middleware/redis_session_middleware.py index d575d2de2..5dad19921 100644 --- a/backend/handler/auth/middleware/redis_session_middleware.py +++ b/backend/handler/auth/middleware/redis_session_middleware.py @@ -31,10 +31,16 @@ class RedisSessionMiddleware: Clears all active sessions for a given user. """ session_ids = await async_cache.smembers(f"user_sessions:{user_id}") - if session_ids: - for session_id in session_ids: - await async_cache.delete(f"session:{session_id}") - await async_cache.delete(f"user_sessions:{user_id}") + if not session_ids: + return + + # A member arrives as bytes from a client that does not decode, and its + # repr in a key name would miss the session and leave it live. + keys = [ + f"session:{sid.decode() if isinstance(sid, bytes) else sid}" + for sid in session_ids + ] + await async_cache.delete(*keys, f"user_sessions:{user_id}") async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] not in ("http", "websocket"): @@ -66,19 +72,29 @@ class RedisSessionMiddleware: user_id = scope["session"].get("sub") if scope["session"]: - session_id = scope["session"].pop("session_id", None) or str( - uuid.uuid4() - ) # Retrieve or create session_id + existing_id = scope["session"].pop("session_id", None) + session_id = existing_id or str(uuid.uuid4()) session_data_json = json.dumps(scope["session"]) - await async_cache.set( - f"session:{session_id}", session_data_json, ex=self.max_age + # Refreshed only while its record is still there, so a + # session revoked mid-request is not written back. + stored = await async_cache.set( + f"session:{session_id}", + session_data_json, + ex=self.max_age, + xx=existing_id is not None, ) - # Add session_id to user set of sessions - if user_id: - await async_cache.sadd(f"user_sessions:{user_id}", session_id) + if stored: + # Add session_id to user set of sessions + if user_id: + await async_cache.sadd( + f"user_sessions:{user_id}", session_id + ) + + header_value = f"{self.session_cookie}={session_id}; path=/; Max-Age={self.max_age}; {self.security_flags}" + else: + header_value = f"{self.session_cookie}=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; {self.security_flags}" - header_value = f"{self.session_cookie}={session_id}; path=/; Max-Age={self.max_age}; {self.security_flags}" headers.append("Set-Cookie", header_value) elif session_id: await async_cache.delete(f"session:{session_id}") 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_identity.py b/backend/tests/endpoints/test_identity.py index 4cf6374c4..3f0684dc2 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -2,6 +2,7 @@ import base64 import json from datetime import timedelta from http import HTTPStatus +from typing import Any from unittest import mock import pytest @@ -260,6 +261,136 @@ def test_delete_user(client, access_token: str, editor_user: User): assert response.status_code == HTTPStatus.OK +@pytest.mark.asyncio +async def test_admin_password_reset_invalidates_the_target_user_sessions( + client, access_token: str, editor_user: User +): + """The reason the revocation is not scoped to the caller: an admin resetting + a compromised account has to end that account's sessions, not their own.""" + basic_auth = base64.b64encode( + f"{editor_user.username}:test_editor_password".encode("ascii") + ).decode("ascii") + response = client.post( + "/api/login", headers={"Authorization": f"Basic {basic_auth}"} + ) + assert response.status_code == HTTPStatus.OK + target_session = response.cookies.get("romm_session") + assert target_session is not None + + target_cookie = {"Cookie": f"romm_session={target_session}"} + assert client.get("/api/users/me", headers=target_cookie).status_code == ( + HTTPStatus.OK + ) + + client.cookies.clear() + + response = client.put( + f"/api/users/{editor_user.id}", + data={"password": "reset_by_admin_password"}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == HTTPStatus.OK + + response = client.get("/api/users/me", headers=target_cookie) + assert response.status_code in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN) + + # The admin's own credentials still work. + response = client.get( + "/api/users", headers={"Authorization": f"Bearer {access_token}"} + ) + assert response.status_code == HTTPStatus.OK + + +@pytest.mark.asyncio +async def test_a_failed_revocation_leaves_the_password_unchanged( + client, access_token: str, editor_user: User +): + """An unreachable Redis aborts the change instead of committing it.""" + original_hash = editor_user.hashed_password + + with mock.patch.object( + RedisSessionMiddleware, + "clear_user_sessions", + side_effect=ConnectionError("redis is down"), + ): + with pytest.raises(ConnectionError): + client.put( + f"/api/users/{editor_user.id}", + data={"password": "reset_while_redis_is_down"}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + db_user = DBUsersHandler().get_user(editor_user.id) + assert db_user is not None + assert db_user.hashed_password == original_hash + + +@pytest.mark.asyncio +async def test_a_failed_post_write_revocation_does_not_fail_the_change( + client, access_token: str, editor_user: User +): + """The write has committed by the second pass, so its failure is logged.""" + original_hash = editor_user.hashed_password + calls: list[str] = [] + + async def revoke_then_fail(user_id: str) -> None: + calls.append(user_id) + if len(calls) == 2: + raise ConnectionError("redis went down mid-update") + + with mock.patch.object( + RedisSessionMiddleware, "clear_user_sessions", side_effect=revoke_then_fail + ): + response = client.put( + f"/api/users/{editor_user.id}", + data={"password": "reset_with_redis_failing_late"}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == HTTPStatus.OK + assert len(calls) == 2 + + db_user = DBUsersHandler().get_user(editor_user.id) + assert db_user is not None + assert db_user.hashed_password != original_hash + + +@pytest.mark.asyncio +async def test_sessions_are_revoked_on_both_sides_of_the_write( + client, access_token: str, editor_user: User +): + """The second pass catches a login the old password was still good for.""" + calls: list[str] = [] + real_update = DBUsersHandler.update_user + + def record_update( + self: DBUsersHandler, id: int, data: dict, *args: Any, **kwargs: Any + ) -> User: + # `set_last_active` writes on every authenticated request; only the + # credential write is being ordered here. + if "hashed_password" in data: + calls.append("write") + return real_update(self, id, data, *args, **kwargs) + + async def record_revoke(user_id: str) -> None: + calls.append("revoke") + + with ( + mock.patch.object(DBUsersHandler, "update_user", record_update), + mock.patch.object( + RedisSessionMiddleware, "clear_user_sessions", side_effect=record_revoke + ), + ): + response = client.put( + f"/api/users/{editor_user.id}", + data={"password": "another_reset_password"}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == HTTPStatus.OK + assert calls == ["revoke", "write", "revoke"] + + @pytest.mark.asyncio async def test_password_change_invalidates_sessions(client, admin_user: User): # Get the user's session cookie 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_redis_session_middleware.py b/backend/tests/handler/auth/test_redis_session_middleware.py new file mode 100644 index 000000000..62e4f274c --- /dev/null +++ b/backend/tests/handler/auth/test_redis_session_middleware.py @@ -0,0 +1,69 @@ +"""Test suite for RedisSessionMiddleware's Redis-backed session persistence.""" + +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.requests import Request +from starlette.responses import JSONResponse +from starlette.routing import Route +from starlette.testclient import TestClient + +from handler.auth.constants import SESSION_COOKIE_NAME +from handler.auth.middleware.redis_session_middleware import RedisSessionMiddleware + +USERNAME = "user_1" + + +def create_test_app() -> Starlette: + async def login(request: Request) -> JSONResponse: + request.session["iss"] = "romm:auth" + request.session["sub"] = USERNAME + return JSONResponse({"ok": True}) + + async def revoke(request: Request) -> JSONResponse: + """Revoke the caller's sessions while their own request is in flight.""" + await RedisSessionMiddleware.clear_user_sessions(USERNAME) + return JSONResponse({"ok": True}) + + async def whoami(request: Request) -> JSONResponse: + return JSONResponse({"sub": request.session.get("sub")}) + + return Starlette( + routes=[ + Route("/login", login, methods=["POST"]), + Route("/revoke", revoke, methods=["POST"]), + Route("/whoami", whoami, methods=["GET"]), + ], + middleware=[ + Middleware( + RedisSessionMiddleware, + session_cookie=SESSION_COOKIE_NAME, + same_site="strict", + https_only=False, + ) + ], + ) + + +class TestRedisSessionMiddleware: + def test_session_survives_across_requests(self) -> None: + client = TestClient(create_test_app()) + + assert client.post("/login").status_code == 200 + assert client.get("/whoami").json()["sub"] == USERNAME + + def test_revoked_session_is_not_restored_by_an_in_flight_request(self) -> None: + """A session revoked mid-flight must not be written back.""" + client = TestClient(create_test_app()) + client.post("/login") + + client.post("/revoke") + + assert client.get("/whoami").json()["sub"] is None + + def test_a_cookie_for_an_unknown_session_gets_a_fresh_id(self) -> None: + client = TestClient(create_test_app()) + client.cookies.set(SESSION_COOKIE_NAME, "not-a-real-session") + + response = client.post("/login") + + assert response.cookies[SESSION_COOKIE_NAME] != "not-a-real-session" 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 8a1c05560..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` | TypeScript validation | -| `generate` | `openapi-typescript-codegen` | Generate types from backend OpenAPI | -| `lint` | `eslint` | Lint `.vue`, `.js`, `.ts` files | +| 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/eslint.config.js b/frontend/eslint.config.js index b43b8ec1b..55903d52b 100644 --- a/frontend/eslint.config.js +++ b/frontend/eslint.config.js @@ -1,5 +1,7 @@ import eslint from "@eslint/js"; import prettierConfig from "eslint-config-prettier/flat"; +import { createTypeScriptImportResolver } from "eslint-import-resolver-typescript"; +import importX from "eslint-plugin-import-x"; import vue from "eslint-plugin-vue"; import vuea11y from "eslint-plugin-vuejs-accessibility"; import globals from "globals"; @@ -10,6 +12,21 @@ export default tseslint.config( ...tseslint.configs.recommended, ...vue.configs["flat/recommended"], ...vuea11y.configs["flat/recommended"], + importX.flatConfigs.recommended, + importX.flatConfigs.typescript, + { + // Only the cycle rule below earns its keep; the rest of the preset + // re-reports what vue-tsc already catches, at a module graph per rule. + rules: { + "import-x/no-unresolved": "off", + "import-x/named": "off", + "import-x/namespace": "off", + "import-x/default": "off", + "import-x/export": "off", + "import-x/no-named-as-default": "off", + "import-x/no-named-as-default-member": "off", + }, + }, // Global ignore (object with only `ignores` = applies everywhere). // Storybook config files live outside `src/` and aren't part of the // app tsconfig, so type-aware linting can't resolve them. @@ -75,6 +92,33 @@ export default tseslint.config( ], }, }, + // Import cycles. The resolver has to be the one that reads tsconfig `paths`, + // or `@/*` and `@v2/*` go unresolved and the rule silently passes. + { + files: ["src/**/*.ts", "src/**/*.vue"], + settings: { + "import-x/resolver-next": [ + createTypeScriptImportResolver({ + project: "./tsconfig.json", + extensions: [".ts", ".tsx", ".vue", ".js", ".mjs", ".json"], + }), + ], + }, + rules: { + // Lazy route components make the router reachable from the views it + // renders; that edge is resolved at runtime, so it is not a real cycle. + "import-x/no-cycle": [ + "error", + { maxDepth: 15, allowUnsafeDynamicCyclicDependency: true }, + ], + }, + }, + { + // Frozen v1: two cycles between the console theme helpers predate the + // rule and cannot be refactored under the freeze. + files: ["src/console/**"], + rules: { "import-x/no-cycle": "off" }, + }, // Keep last: Prettier owns formatting, so this switches off every // stylistic rule the two tools would otherwise fight over. prettierConfig, diff --git a/frontend/package-lock.json b/frontend/package-lock.json index e53e7ae49..71473dc1f 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -52,9 +52,10 @@ "@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", + "eslint-plugin-import-x": "^4.17.1", "eslint-plugin-vue": "^10.8.0", "eslint-plugin-vuejs-accessibility": "^2.5.0", "globals": "^16.0.0", @@ -5374,6 +5375,349 @@ "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@unrs/resolver-binding-android-arm-eabi": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.12.2.tgz", + "integrity": "sha512-g5T90pqg1bo/7mytQx6F4iBNC0Wsh9cu+z9veDbFjc7HjpesJFWD7QMS0NGStXM075+7dJPPVvBbpZlnrdpi/w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@unrs/resolver-binding-android-arm64": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.12.2.tgz", + "integrity": "sha512-YGCRZv/9GLhwmz6mYDeTsm/92BAyR28l6c2ReweVW5pWgfsitWLY8upvfRlGdoyD8HjeTHSYJWyZGD4KJA/nFQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@unrs/resolver-binding-darwin-arm64": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.12.2.tgz", + "integrity": "sha512-u9DiNT1auQMO20A9SyTuG3wUgQWB9Z7KjAg0uFuCDR1FsAY8A0CG2S6JpHS1xwm/w1G08bjXZDcyOCjv1WAm2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@unrs/resolver-binding-darwin-x64": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.12.2.tgz", + "integrity": "sha512-f7rPLi/T1HVKZu/u6t87lroib16n8vrSzcyxI7lg4BGO9UF26KhQL44sd9eOUgrTYhvRXtWOIZT5PejdPyJfUA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@unrs/resolver-binding-freebsd-x64": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.12.2.tgz", + "integrity": "sha512-BpcOjWCJub6nRZUS2zA20pmLvjtqAtGejETaIyRLiZiQf++cbrjltLA5NN/xaXfqeOBOSlMFbemIl5/S5tljmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.12.2.tgz", + "integrity": "sha512-vZTDvdSISZjJx66OzJqtsOhzifbqRjbmI1Mnu49fQDwog5GtDI4QidRiEAYbZCRj9C8YZEW+3ZjqsyS9GR4k2A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.12.2.tgz", + "integrity": "sha512-BiPI+IrIlwcW4nLLMM21+B1dFPzd55yAVgVGrdgDjNef+ch03GdxrcyaIz8X9SsQirh/kCQ7mviyWlMxdh2D7g==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm64-gnu": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.12.2.tgz", + "integrity": "sha512-zJc0H99FEPoFfSrNpa91HYfxzfAJCr502oxNK1cfdC9hlaFI43RT+JFCann9JUgZmLzzntChHyn13Sgn9ljHNg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm64-musl": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.12.2.tgz", + "integrity": "sha512-KQ3Lki6l+Pz1k/eBipN41ES+YUK30beLGb9YqcB1O542cyLCNE6GaxrfcY3T6EezmGGk84wb5XyO9loTM9tkcA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-loong64-gnu": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-loong64-gnu/-/resolver-binding-linux-loong64-gnu-1.12.2.tgz", + "integrity": "sha512-3SJGEh1DborhG6pyxvhPzCT4bbSIVihsvgJc13P1bHG7KLdNDaF9T3gsTwFc7Jw/5Y5/iWOjkEx7Zy0NvCGX3Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-loong64-musl": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-loong64-musl/-/resolver-binding-linux-loong64-musl-1.12.2.tgz", + "integrity": "sha512-jiuG/Obbel7uw1PwHNFfrkiKhLAF6mnyZ6aWlOAVN9WqKm8v0OFGnciJIHu8+CMvXLQ8AD51LPzAoUfT21D5Ew==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.12.2.tgz", + "integrity": "sha512-q7xRvVpmcfeL+LlZg8Pbbo6QaTZwDU5BaGZbwfhkEsXJn3Was8xYfE0RBH266xZt0rM6B7i8xAYIvjthuUIWHg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.12.2.tgz", + "integrity": "sha512-0CVdx6lcnT3Q9inOH8tsMIOJ6ImndllMjqJHg8RLVdB7Vq4SfkEXl9mCSsVNuNA4MCYycRicCUxPCabVHJRr6A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-riscv64-musl": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.12.2.tgz", + "integrity": "sha512-iOwlRo9vnp6R6ohHQS11n0NnfdXx/omhkocmIfaPRpQhKZ+3BDMkkdRVh53qjkFkpPddf+FETA28NwGN7l5l+w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-s390x-gnu": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.12.2.tgz", + "integrity": "sha512-HYJtLfXq94q8iZNFT1lknx258wlkkWhZeUXJRqzKBBUJ00CvZ+N33zgbCqimLjsyw5Va6uUxhVa12mI+kaveEw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-x64-gnu": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.12.2.tgz", + "integrity": "sha512-mPsUhunKKDih5O96Y6enDQyHc1SqBPlY1E/SfMWDM3EdJ95Z9CArPeCVwCCqbP45ljvivdEk8Fxn+SIb1rDAJQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-x64-musl": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.12.2.tgz", + "integrity": "sha512-azrt6+5ydLd8Vt210AAFis/lZevSfPw93EJRIJG+xPu4WCJ8K0kppCTpMyLPcKT7H15M4Jnt2tMp5bOvCkRC6A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-openharmony-arm64": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-openharmony-arm64/-/resolver-binding-openharmony-arm64-1.12.2.tgz", + "integrity": "sha512-YZ9hP4O0X9PQb8eO980qmLNGH4zT3I9+SZTdt0Pr0YyuGQhYKoOZkV02VzrzyOZJ5xIJ3UFIenKkUkGg8GjgWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@unrs/resolver-binding-wasm32-wasi": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.12.2.tgz", + "integrity": "sha512-tYFDIkMxSflfEc/h92ZWNsZlHSwgimbNHSO3PL2JWQHfCuC2q316jMyYU9TIWZsFK2bQwyK5VAdYgn8ygPj69A==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "1.10.0", + "@emnapi/runtime": "1.10.0", + "@napi-rs/wasm-runtime": "^1.1.4" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@unrs/resolver-binding-win32-arm64-msvc": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.12.2.tgz", + "integrity": "sha512-qzNyg3xL0VPQmCaUh+N5jSitce6k+uCBfMDesWRnlULOZaqUkaJ0ybdT+UqlAWJoQjuqfIU/0Ptx9bteN4D82g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@unrs/resolver-binding-win32-ia32-msvc": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.12.2.tgz", + "integrity": "sha512-WD9sY00OfpHVGfsnHZoA8jVT+esS/Bg8z8jzxp5BnDCjjwsuKsPQrzswwpFy4J1AUJbXPRfkpcX0mXrzeXW79g==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@unrs/resolver-binding-win32-x64-msvc": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.12.2.tgz", + "integrity": "sha512-nAB74NfSNKknqQ1RrYj6uz8FcXEomu/MATJZxh/x+BArzN2U3JbOYC0APYzUIGhVY3m5hRxA8VPNdPBoG8txlA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@vavt/copy2clipboard": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@vavt/copy2clipboard/-/copy2clipboard-1.0.3.tgz", @@ -6615,6 +6959,16 @@ "node": ">=18" } }, + "node_modules/comment-parser": { + "version": "1.4.9", + "resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.4.9.tgz", + "integrity": "sha512-+2AvZKjJaNq9GQljm3tr0utwrig5BL+jgJGvz5rDpGKNIp+ojcRXWUwBbh/sGIi1QCprR6PsKFakub+w1v+4hQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 12.0.0" + } + }, "node_modules/common-tags": { "version": "1.8.2", "resolved": "https://registry.npmjs.org/common-tags/-/common-tags-1.8.2.tgz", @@ -7445,6 +7799,103 @@ "eslint": ">=7.0.0" } }, + "node_modules/eslint-import-context": { + "version": "0.1.9", + "resolved": "https://registry.npmjs.org/eslint-import-context/-/eslint-import-context-0.1.9.tgz", + "integrity": "sha512-K9Hb+yRaGAGUbwjhFNHvSmmkZs9+zbuoe3kFQ4V1wYjrepUFYM2dZAfNtjbbj3qsPfUfsA68Bx/ICWQMi+C8Eg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-tsconfig": "^4.10.1", + "stable-hash-x": "^0.2.0" + }, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-import-context" + }, + "peerDependencies": { + "unrs-resolver": "^1.0.0" + }, + "peerDependenciesMeta": { + "unrs-resolver": { + "optional": true + } + } + }, + "node_modules/eslint-import-resolver-typescript": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-4.4.5.tgz", + "integrity": "sha512-nbE5XLph6TLtGYcu/U6e6ZVXyKBhbDWK5cLGk76eJ7NdZpwf1P9EFkpt1Z01mNZNrrilsAYWKH6zUkL4reoXbw==", + "dev": true, + "license": "ISC", + "dependencies": { + "debug": "^4.4.1", + "eslint-import-context": "^0.1.8", + "get-tsconfig": "^4.10.1", + "is-bun-module": "^2.0.0", + "stable-hash-x": "^0.2.0", + "tinyglobby": "^0.2.14", + "unrs-resolver": "^1.7.11" + }, + "engines": { + "node": "^16.17.0 || >=18.6.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-import-resolver-typescript" + }, + "peerDependencies": { + "eslint": "*", + "eslint-plugin-import": "*", + "eslint-plugin-import-x": "*" + }, + "peerDependenciesMeta": { + "eslint-plugin-import": { + "optional": true + }, + "eslint-plugin-import-x": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-import-x": { + "version": "4.17.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-import-x/-/eslint-plugin-import-x-4.17.1.tgz", + "integrity": "sha512-4cdstYkKCyjumM2Q9NSI03K8D2a9F4Ssz33K2lv2hQa4KmR9jPLwk3uWGtNvclfqBrPGfGuMBwsGMbe6dMRbfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "^8.56.0", + "comment-parser": "^1.4.1", + "debug": "^4.4.1", + "eslint-import-context": "^0.1.9", + "is-glob": "^4.0.3", + "minimatch": "^9.0.3 || ^10.1.2", + "semver": "^7.7.2", + "stable-hash-x": "^0.2.0", + "unrs-resolver": "^1.9.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-plugin-import-x" + }, + "peerDependencies": { + "@typescript-eslint/utils": "^8.56.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "eslint-import-resolver-node": "*" + }, + "peerDependenciesMeta": { + "@typescript-eslint/utils": { + "optional": true + }, + "eslint-import-resolver-node": { + "optional": true + } + } + }, "node_modules/eslint-plugin-vue": { "version": "10.8.0", "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-10.8.0.tgz", @@ -8024,6 +8475,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-tsconfig": { + "version": "4.14.3", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.14.3.tgz", + "integrity": "sha512-++QEw4DIY7WGoukz+/+A/8dGYPT9l9yIadnmSgZ8Rjr3YVSVDipQSO9CdnJo9ePqFqUUqh+wk9uIaoiAwsiPkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, "node_modules/glob": { "version": "11.1.0", "resolved": "https://registry.npmjs.org/glob/-/glob-11.1.0.tgz", @@ -8412,6 +8876,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-bun-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-bun-module/-/is-bun-module-2.0.0.tgz", + "integrity": "sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.7.1" + } + }, "node_modules/is-callable": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", @@ -9872,6 +10346,22 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/napi-postinstall": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz", + "integrity": "sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==", + "dev": true, + "license": "MIT", + "bin": { + "napi-postinstall": "lib/cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/napi-postinstall" + } + }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", @@ -10874,6 +11364,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, "node_modules/rfdc": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", @@ -11288,6 +11788,16 @@ "node": ">=0.10.0" } }, + "node_modules/stable-hash-x": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/stable-hash-x/-/stable-hash-x-0.2.0.tgz", + "integrity": "sha512-o3yWv49B/o4QZk5ZcsALc6t0+eCelPc44zZsLtCQnZPDwFpDYSWcDnrv2TtMmMbQ7uKo3J0HTURCqckw23czNQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -12087,6 +12597,44 @@ "node": ">=18.12.0" } }, + "node_modules/unrs-resolver": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.12.2.tgz", + "integrity": "sha512-dmlRxBJJayXjqTwC+JtF1HhJmgf3ftQ3YejFcZrf4+KKtJv0qDsK1pjqaaVjG7wJ5NJ6UVP1OqRMQ71Z4C3rxQ==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "napi-postinstall": "^0.3.4" + }, + "funding": { + "url": "https://opencollective.com/unrs-resolver" + }, + "optionalDependencies": { + "@unrs/resolver-binding-android-arm-eabi": "1.12.2", + "@unrs/resolver-binding-android-arm64": "1.12.2", + "@unrs/resolver-binding-darwin-arm64": "1.12.2", + "@unrs/resolver-binding-darwin-x64": "1.12.2", + "@unrs/resolver-binding-freebsd-x64": "1.12.2", + "@unrs/resolver-binding-linux-arm-gnueabihf": "1.12.2", + "@unrs/resolver-binding-linux-arm-musleabihf": "1.12.2", + "@unrs/resolver-binding-linux-arm64-gnu": "1.12.2", + "@unrs/resolver-binding-linux-arm64-musl": "1.12.2", + "@unrs/resolver-binding-linux-loong64-gnu": "1.12.2", + "@unrs/resolver-binding-linux-loong64-musl": "1.12.2", + "@unrs/resolver-binding-linux-ppc64-gnu": "1.12.2", + "@unrs/resolver-binding-linux-riscv64-gnu": "1.12.2", + "@unrs/resolver-binding-linux-riscv64-musl": "1.12.2", + "@unrs/resolver-binding-linux-s390x-gnu": "1.12.2", + "@unrs/resolver-binding-linux-x64-gnu": "1.12.2", + "@unrs/resolver-binding-linux-x64-musl": "1.12.2", + "@unrs/resolver-binding-openharmony-arm64": "1.12.2", + "@unrs/resolver-binding-wasm32-wasi": "1.12.2", + "@unrs/resolver-binding-win32-arm64-msvc": "1.12.2", + "@unrs/resolver-binding-win32-ia32-msvc": "1.12.2", + "@unrs/resolver-binding-win32-x64-msvc": "1.12.2" + } + }, "node_modules/upath": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/upath/-/upath-2.0.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index fbf0d8184..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,9 +82,10 @@ "@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", + "eslint-plugin-import-x": "^4.17.1", "eslint-plugin-vue": "^10.8.0", "eslint-plugin-vuejs-accessibility": "^2.5.0", "globals": "^16.0.0", diff --git a/frontend/scripts/build-tokens.ts b/frontend/scripts/build-tokens.ts index 14b801a90..3c67d368d 100644 --- a/frontend/scripts/build-tokens.ts +++ b/frontend/scripts/build-tokens.ts @@ -175,10 +175,16 @@ const SHARED: Entry[] = [ ...entriesFor(zIndex, "zIndex", "--r-z-index"), ]; -const DARK: Entry[] = entriesFor(colorDark, "colorDark", "--r-color"); +// Native `color-scheme` rides with the palette so UA-drawn chrome (scrollbars, +// form controls, embedded viewers) follows the theme instead of staying light. +const DARK: Entry[] = [ + ["color-scheme", "dark"], + ...entriesFor(colorDark, "colorDark", "--r-color"), +]; // Light theme: the surface palette, then the brand overrides that re-tune // primary/secondary/accent for the off-white page (deeper for contrast). const LIGHT: Entry[] = [ + ["color-scheme", "light"], ...entriesFor(colorLight, "colorLight", "--r-color"), ...entriesFor(colorStatusLight, "colorStatusLight", "--r-color"), ...entriesFor(colorBrandLight, "colorBrandLight", "--r-color-brand"), 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 @@