From 9ecad406357f80980370c136817b15bc94b111d8 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 9 Nov 2026 10:22:41 -0600 Subject: [PATCH 01/28] docs: v2-contract - install_java, MineUI-managed Java (2.13.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Beginner-friendly Scope B: a server on this computer with no suitable Java should not send a kid to install a JDK by hand. MineUI downloads the Eclipse Temurin JRE of the major the Minecraft version needs into its own app-wide folder and uses it. - New scoped command install_java { major } -> JavaCheck (§3.1). - JavaCheck gains managed; java_check resolution order is now override, then MineUI-managed Java of a compatible major, then JAVA_HOME / PATH / well-known roots, so a Java MineUI installed is the one it runs. - DownloadKind gains "java"; progress events carry the requesting server's id (§4.3). - §6.3a fixes the download rules: Adoptium API v3 only, https, redirect hops limited to the observed host chain (api.adoptium.net, github.com, release-assets.githubusercontent.com), 300 MB cap, sha256 from the API response, traversal-safe extraction into a temp dir renamed into place, and java -version must report the requested major. - Audit action java.install (§3.11), §5 mode row, §8 javainstall module. - §7 re-synced with app/lib/ipc.ts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- app/lib/ipc.ts | 7 ++- docs/v2-contract.md | 113 ++++++++++++++++++++++++++++++++++++++------ 2 files changed, 105 insertions(+), 15 deletions(-) diff --git a/app/lib/ipc.ts b/app/lib/ipc.ts index 3630279..1bcbb05 100644 --- a/app/lib/ipc.ts +++ b/app/lib/ipc.ts @@ -171,6 +171,8 @@ export type JavaCheck = { majorVersion: number | null; requiredMajor: number | null; compatible: boolean | null; + /** 2.13.0 - the Java found is one MineUI downloaded (installJava). */ + managed: boolean; }; export const getSettings = () => scoped("get_settings"); @@ -178,6 +180,9 @@ export const setSettings = (settings: Settings) => scoped("set_settings", { settings }); export const detectRuntimes = () => scoped("detect_runtimes"); export const javaCheck = () => scoped("java_check"); +/** 2.13.0 - download Temurin JRE `major` into MineUI's own folder (app-wide); + * resolves with this server's Java check after the install. */ +export const installJava = (major: number) => scoped("install_java", { major }); /* ---------- server state / lifecycle / status ---------- */ @@ -661,7 +666,7 @@ export type ServerStateEvent = { exitCode: number | null; }; -export type DownloadKind = "server-jar" | "mod"; +export type DownloadKind = "server-jar" | "mod" | "java"; export type DownloadProgressEvent = { serverId: string; downloadId: string; diff --git a/docs/v2-contract.md b/docs/v2-contract.md index a8d4425..a1cf6ff 100644 --- a/docs/v2-contract.md +++ b/docs/v2-contract.md @@ -61,11 +61,11 @@ type ErrorCode = | "EULA_NOT_ACCEPTED" // simple-mode start/create without EULA acceptance | "INSTANCE_NOT_FOUND" // simple-mode instance dir missing/uninitialized | "INSTANCE_EXISTS" // create_instance over an existing instance - | "DOWNLOAD_FAILED" // network failure fetching manifest/jar/mod - | "CHECKSUM_MISMATCH" // downloaded jar failed sha1 verification + | "DOWNLOAD_FAILED" // network failure fetching manifest/jar/mod/Java; unsafe Java archive (§6.3a) + | "CHECKSUM_MISMATCH" // downloaded jar failed sha1 verification, Java archive sha256 (2.13.0) | "SERVER_UTILS_UNAVAILABLE" // serverUtilsUrl set but unreachable/non-OK | "PATH_NOT_ALLOWED" // config-editor path rejected by validation (§6) - | "FILE_TOO_LARGE" // config write > 1.5 MB, upload > 256 MB + | "FILE_TOO_LARGE" // config write > 1.5 MB, upload > 256 MB, Java archive > 300 MB | "WRONG_MODE" // command not available in active mode (§5) | "INVALID_INPUT" // failed argument validation | "SETTINGS_INVALID" // set_settings payload failed validation @@ -393,6 +393,7 @@ the current target, §7); the null fallback exists for robustness, not for use. | `set_settings` | `{ settings: Settings }` | `Settings` (normalized) | both | `settings::save` | POST /api/settings | | `detect_runtimes` | - | `RuntimeProbe` | both | `runtime::detect` | - (new) | | `java_check` | - | `JavaCheck` | both | `java::check` | - (new) | +| `install_java` (2.13.0) | `{ major: number }` | `JavaCheck` | both (only servers on this computer use it) | `javainstall::install` | - (new) | Notes: @@ -432,10 +433,38 @@ Notes: Windows/macOS, "start the Docker service" on Linux; Podman → "run `podman machine start`" on Windows/macOS, "check the Podman service/socket" on Linux (no machine there). -- `java_check` resolves `simple.javaPath` override → `JAVA_HOME/bin/java` → `java` on - PATH; parses `java -version` stderr. `requiredMajor` comes from the current instance - metadata (`mineui-instance.json`, §3.6) when present, else `null` and - `compatible: null`. +- `java_check` resolves, in order (2.13.0): the `simple.javaPath` override (used as + is, never substituted); then **MineUI-managed Java** (below) of a compatible + major - the exact `requiredMajor` first, else the smallest managed major above it + (with `requiredMajor` unknown, the highest managed major); then `JAVA_HOME/bin/java`, + every `java` on PATH and the well-known install roots (`/usr/lib/jvm`, sdkman, + `/Library/Java/JavaVirtualMachines`, `Program Files\Eclipse Adoptium`, ...), the + best of those winning (a compatible one, else the highest major). It parses + `java -version` stderr. `requiredMajor` comes from the current instance metadata + (`mineui-instance.json`, §3.6) when present, else `null` and `compatible: null`. + Simple-mode start, `create_instance` and `change_instance_version` use the same + resolution, so a Java MineUI installed is the one they run. `managed` is true when + the Java found lies inside the managed Java folder. +- **MineUI-managed Java (2.13.0)** lives at `/java/temurin--jre/`, + where `` is the data root the shell injects (`app_data_dir`, the + `default` profile's data dir) - never a `servers//` folder: one download serves + every server profile. Inside it is the archive's tree as extracted (e.g. + `jdk-21.0.13+9-jre/bin/java`); the binary is located, not assumed (§6.3a rule 7). +- `install_java` (2.13.0) downloads the Eclipse Temurin JRE of `major` from Adoptium + into the managed folder (§6.3a), then returns this server's `java_check` result. + When the server has no instance yet, that check runs with `requiredMajor = major` + so `compatible` says whether the install fixed it. If a working managed Java of + `major` is already there nothing is downloaded. It is a host-side install for + servers that run on this computer (Simple mode); it works the same whatever the + targeted profile's mode, but a container server never uses it (its image brings + its own Java). Progress: `mineui://download-progress` with `kind: "java"`, carrying + the requesting server's id (§4.3). One install per major at a time, app-wide: a + second request for the same major (from any server) waits for the first and then + reuses what it installed, or tries again if it failed. `major` outside `8..=30` → + `INVALID_INPUT`; no Temurin JRE for this OS/architecture, a network failure, an + unsafe archive or a binary that does not report `major` → `DOWNLOAD_FAILED`; a + sha256 mismatch → `CHECKSUM_MISMATCH`; an archive over 300 MB → `FILE_TOO_LARGE`. + Every message is plain enough to show as is. Audited as `java.install` (§3.11). ```ts type RuntimeProbe = { @@ -453,6 +482,8 @@ type JavaCheck = { majorVersion: number | null; // e.g. 21 requiredMajor: number | null; // from instance metadata, if an instance exists compatible: boolean | null; // null when requiredMajor unknown + /** 2.13.0 - the Java found is one MineUI downloaded (install_java). */ + managed: boolean; }; ``` @@ -1113,7 +1144,9 @@ type AuditEntry = { `scheduler.restart`, `scheduler.backup`, `scheduler.broadcast`, `server.add`, `server.rename`, `server.remove` (§3.12), `container.create`, `container.delete`, `container.ports` (§3.13), `container.update` (§3.2 start - fallback, 2.11.1). + fallback, 2.11.1), `java.install` (§3.1, 2.13.0: target `temurin--jre`, + detail e.g. `Temurin JRE 21.0.13+9`; written when a download was attempted, not + when an existing install was reused). ### 3.12 Server profiles (2.6.0) @@ -1749,12 +1782,13 @@ full detail. Frontend pattern: fetch state on mount, subscribe for invalidation. ### 4.3 `mineui://download-progress` -Emitted for server-jar downloads (`create_instance`) and mod downloads -(`download_mod`). Throttled to ≥ 150 ms between progress events per download; the +Emitted for server-jar downloads (`create_instance`), mod downloads +(`download_mod`) and the Java runtime download (`install_java`, 2.13.0 - carrying +the requesting server's id although the install is app-wide). Throttled to ≥ 150 ms between progress events per download; the terminal event (`done` or `error`) is always emitted. ```ts -type DownloadKind = "server-jar" | "mod"; +type DownloadKind = "server-jar" | "mod" | "java"; // "java": 2.13.0 type DownloadProgressEvent = { downloadId: string; // uuid, unique per download @@ -1771,7 +1805,10 @@ type DownloadProgressEvent = { `download_mod` returns its `downloadId`; `create_instance` does not (its jar download is identified by `kind: "server-jar"` - only one can run at a time, enforced by -`INSTANCE_EXISTS`). +`INSTANCE_EXISTS`). `install_java` does not either: its download is identified by +`kind: "java"`, `filename` being the Adoptium archive name (e.g. +`OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz`); a request that waits for +another server's install of the same major sees no events. Subscription lifecycle (all events): `listen()` returns an unlisten fn; every page/hook that subscribes MUST unlisten on unmount. Events carry no secrets. @@ -1799,6 +1836,7 @@ that subscribes MUST unlisten on unmount. Events carry no secrets. | Instance commands (§3.6) | full | `WRONG_MODE` | | `open_app_dir` `"server"` (§3.15, 2.10.0) | opens `instanceDir` | `WRONG_MODE` (no host folder) | | `detect_runtimes`, `java_check` | available (java relevant) | available (runtime relevant) | +| `install_java` (§3.1, 2.13.0) | downloads Temurin JRE into the app-wide managed folder; start/create/change version then use it | available but unused (the container image brings its own Java) | | Container create/pull | - | `create_container` makes an itzg/minecraft-server container (§3.13); attaching to an existing one still works; `delete_container` removes one, and its data volume only when asked, on explicit confirmation | | Ports and joining (§3.16, 2.11.0) | `get_join_info`: `serverPort`, reach from `server-ip`, nothing to publish | `get_join_info` from the container's bindings; `update_container_ports` rebuilds a stopped MineUI container with other ports, on explicit confirmation | @@ -1883,6 +1921,47 @@ jar, ≤ 2 GiB in total. Encrypted or unreadable archives → `INVALID_INPUT`. server-jar downloads always use the strict client (their URLs come from the HTTPS manifest and content is SHA-1 pinned). +### 6.3a Java downloads (`install_java`, 2.13.0) + +Fixed hosts, no user-supplied URL. Error codes as listed in §3.1. + +1. `major` is an integer in `8..=30` (`INVALID_INPUT`). +2. OS and architecture come from the build (`cfg!`): `linux` / `mac` / `windows`; + `x86_64` → `x64`, `aarch64` → `aarch64`. Any other target → `DOWNLOAD_FAILED` + ("no Temurin build for this computer"). +3. One GET of `https://api.adoptium.net/v3/assets/latest//hotspot?architecture=&image_type=jre&os=&vendor=eclipse`. + The first asset whose `binary.image_type` is `jre`, `binary.os`/`architecture` + match and `version.major` is `major` is used; none → `DOWNLOAD_FAILED` + ("Adoptium has no Java runtime for this computer"). From it: + `binary.package.link` (the archive), `binary.package.checksum` (sha256, 64 hex + chars), `binary.package.size`, `binary.package.name` (ends `.tar.gz` or `.zip`, + else `DOWNLOAD_FAILED`) and `version.openjdk_version` (for the audit detail). +4. https only. The API URL and the archive link must be on the host allowlist, and + every redirect hop is re-checked against it (≤ 5 hops, https, allowlisted host): + `api.adoptium.net`, `github.com`, `release-assets.githubusercontent.com`. Observed + chain on 2026-11-09: the API answers 200 itself; the archive link is + `https://github.com/adoptium/temurin-binaries/releases/download/...`, which + 302-redirects once to `release-assets.githubusercontent.com` (200). A hop anywhere + else fails the download (`DOWNLOAD_FAILED`). +5. Size cap 300 MB: an announced `size` or `Content-Length` over it is refused before + streaming, and the stream is cut at the cap (`FILE_TOO_LARGE`). The streamed + bytes' sha256 must equal `checksum` (`CHECKSUM_MISMATCH`). 60 s idle timeout as §6.3. +6. Extraction (off the async runtime) into `/java/.tmp-temurin--jre-/`, + beside the target: `.tar.gz` (Linux, macOS) with `tar` + `flate2`, `.zip` + (Windows) with `zip`. The whole install is refused (`DOWNLOAD_FAILED`) when any + entry path is absolute, has a drive/root prefix or a `..` component (zip: no + `enclosed_name`); when a symlink target is absolute or resolves outside the + extraction dir; when a hard link names a path outside it. Other entry types + (devices, fifos) are skipped. At most 20 000 entries and 1 GiB written. File modes + are kept (`bin/java` stays executable). +7. The binary is located, not assumed: `bin/java` (`bin/java.exe` on Windows) or + `Contents/Home/bin/java` (macOS bundle) at most three folders below the + extraction dir (Temurin's top folder is `jdk--jre`). `java -version` run + on it must report `major` (`DOWNLOAD_FAILED` otherwise). +8. Then the temp dir is renamed to `/java/temurin--jre/`. A + previous folder there (one that failed the reuse check) is renamed aside first + and removed after. On every failure the archive and the temp dir are removed. + ### 6.4 RCON commands See §3.4: trim, strip one leading `/`, ≤ 200 chars, first token lowercased ∈ @@ -2071,6 +2150,8 @@ export type JavaCheck = { majorVersion: number | null; requiredMajor: number | null; compatible: boolean | null; + /** 2.13.0 - the Java found is one MineUI downloaded (installJava). */ + managed: boolean; }; export const getSettings = () => scoped("get_settings"); @@ -2078,6 +2159,9 @@ export const setSettings = (settings: Settings) => scoped("set_settings", { settings }); export const detectRuntimes = () => scoped("detect_runtimes"); export const javaCheck = () => scoped("java_check"); +/** 2.13.0 - download Temurin JRE `major` into MineUI's own folder (app-wide); + * resolves with this server's Java check after the install. */ +export const installJava = (major: number) => scoped("install_java", { major }); /* ---------- server state / lifecycle / status ---------- */ @@ -2561,7 +2645,7 @@ export type ServerStateEvent = { exitCode: number | null; }; -export type DownloadKind = "server-jar" | "mod"; +export type DownloadKind = "server-jar" | "mod" | "java"; export type DownloadProgressEvent = { serverId: string; downloadId: string; @@ -2643,7 +2727,8 @@ Frontend rules: | `rcon` | RCON client (connect/auth/send/close) + allowlist enforcement | | `query` | Minecraft server-list-ping client (handshake + status packet, 3 s timeout) | | `mojang` | version manifest fetch/cache, per-version json, jar download + sha1 verify, progress callback | -| `java` | java discovery + `-version` parsing | +| `java` | java discovery + `-version` parsing; the managed-Java lookup and resolution order (§3.1, 2.13.0) | +| `javainstall` | `install_java` (§3.1, §6.3a, 2.13.0): Adoptium API query, the host-allowlisted client, sha256-verified download, safe tar.gz/zip extraction, locate + probe, rename into place, per-major install lock, `java.install` audit | | `instance` | create/delete/status, change version in place (2.10.0), `mineui-instance.json`, eula.txt, server.properties RCON assertion (preserving user keys) | | `mods` | list/upload/download/delete over `Runtime` or host fs (§3.5, §6.2–6.3) | | `mod_archive` | `unpack_mod_archive`: entry selection, bounded host-side extraction, placement (§3.5, §6.2a) | From 7b38fab96a3343c7dca8be39ed06414eac495874 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 9 Nov 2026 10:30:55 -0600 Subject: [PATCH 02/28] docs: v2-contract - required_java_major (2.13.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Start here needs to know which Java a Minecraft version wants before create_instance runs, so it can offer "Get Java for me" up front instead of parsing a JAVA_NOT_FOUND message. - New app-wide command required_java_major { mcVersion } -> number | null (§3.6): Mojang's javaVersion.majorVersion for the version, "LATEST" resolving to the latest release first; null when it cannot be resolved. - The same function picks create_container's image tag (§3.13), now shared from mojang (§8); §5 row; §7 re-synced with app/lib/ipc.ts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- app/lib/ipc.ts | 4 ++++ docs/v2-contract.md | 19 ++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/app/lib/ipc.ts b/app/lib/ipc.ts index 1bcbb05..8863898 100644 --- a/app/lib/ipc.ts +++ b/app/lib/ipc.ts @@ -509,6 +509,10 @@ export type InstanceStatus = { export const listMcVersions = (includeSnapshots?: boolean) => scoped("list_mc_versions", { includeSnapshots }); +/** 2.13.0, app-wide - the Java major a version ("LATEST" allowed) needs; + * null when it cannot be resolved (offline, unknown version). */ +export const requiredJavaMajor = (mcVersion: string) => + call("required_java_major", { mcVersion }); export const createInstance = (args: CreateInstanceArgs) => scoped("create_instance", { args }); export const deleteInstance = () => diff --git a/docs/v2-contract.md b/docs/v2-contract.md index a1cf6ff..79cd85e 100644 --- a/docs/v2-contract.md +++ b/docs/v2-contract.md @@ -791,6 +791,18 @@ Semantics: | `delete_instance` | `{ confirm: true }` | `void` | simple | `instance::delete` | - (new) | | `instance_status` | - | `InstanceStatus` | simple | `instance::status` | - (new) | | `change_instance_version` | `{ mcVersion: string; allowDowngrade?: boolean }` | `ChangedInstanceVersion` (2.10.0) | simple | `instance::change_version` | - (new) | +| `required_java_major` (2.13.0) | `{ mcVersion: string }` | `number \| null` | both, app-wide (no `serverId`) | `Hub::required_java_major` → `mojang::required_java_major` | - (new) | + +`required_java_major` (2.13.0) is app-wide: like §3.12 and §3.15 it takes **no** +`serverId` (an exception to §3.0) and uses the active profile's Mojang manifest cache. +It answers which Java major a Minecraft version needs before anything is created, so +the UI can offer `install_java` (§3.1) up front. `mcVersion` is a Mojang version id, +or `"LATEST"` (any case, or empty), which resolves to the manifest's latest release +first. The answer is `javaVersion.majorVersion` from that version's detail JSON +(`mojang::version_detail`, same cache and client as `create_instance`). It never +rejects: offline with no cached manifest, an unknown version, or a detail without +`javaVersion` (very old versions) all resolve to `null`. Not audited. +`create_container` (§3.13) picks its image tag with the same function. ```ts type McVersion = { @@ -1836,6 +1848,7 @@ that subscribes MUST unlisten on unmount. Events carry no secrets. | Instance commands (§3.6) | full | `WRONG_MODE` | | `open_app_dir` `"server"` (§3.15, 2.10.0) | opens `instanceDir` | `WRONG_MODE` (no host folder) | | `detect_runtimes`, `java_check` | available (java relevant) | available (runtime relevant) | +| `required_java_major` (§3.6, 2.13.0) | app-wide: the Java major a version needs, before `install_java` | app-wide: the same answer picks the image's Java tag (§3.13) | | `install_java` (§3.1, 2.13.0) | downloads Temurin JRE into the app-wide managed folder; start/create/change version then use it | available but unused (the container image brings its own Java) | | Container create/pull | - | `create_container` makes an itzg/minecraft-server container (§3.13); attaching to an existing one still works; `delete_container` removes one, and its data volume only when asked, on explicit confirmation | | Ports and joining (§3.16, 2.11.0) | `get_join_info`: `serverPort`, reach from `server-ip`, nothing to publish | `get_join_info` from the container's bindings; `update_container_ports` rebuilds a stopped MineUI container with other ports, on explicit confirmation | @@ -2488,6 +2501,10 @@ export type InstanceStatus = { export const listMcVersions = (includeSnapshots?: boolean) => scoped("list_mc_versions", { includeSnapshots }); +/** 2.13.0, app-wide - the Java major a version ("LATEST" allowed) needs; + * null when it cannot be resolved (offline, unknown version). */ +export const requiredJavaMajor = (mcVersion: string) => + call("required_java_major", { mcVersion }); export const createInstance = (args: CreateInstanceArgs) => scoped("create_instance", { args }); export const deleteInstance = () => @@ -2726,7 +2743,7 @@ Frontend rules: | `machine` | Podman machine facts (provider, rootful, WSL address), cached 60 s; the rootful-WSL note (§3.2); the Windows build, once per process (§3.16, 2.11.1) | | `rcon` | RCON client (connect/auth/send/close) + allowlist enforcement | | `query` | Minecraft server-list-ping client (handshake + status packet, 3 s timeout) | -| `mojang` | version manifest fetch/cache, per-version json, jar download + sha1 verify, progress callback | +| `mojang` | version manifest fetch/cache, per-version json, jar download + sha1 verify, progress callback; `required_java_major` (§3.6, 2.13.0, shared with `provision`) | | `java` | java discovery + `-version` parsing; the managed-Java lookup and resolution order (§3.1, 2.13.0) | | `javainstall` | `install_java` (§3.1, §6.3a, 2.13.0): Adoptium API query, the host-allowlisted client, sha256-verified download, safe tar.gz/zip extraction, locate + probe, rename into place, per-major install lock, `java.install` audit | | `instance` | create/delete/status, change version in place (2.10.0), `mineui-instance.json`, eula.txt, server.properties RCON assertion (preserving user keys) | From 0c44c02152667651c54fd88e3a67c831cb939d0c Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 9 Nov 2026 10:49:04 -0600 Subject: [PATCH 03/28] feat(core): MineUI downloads Java for servers on this computer install_java fetches the Eclipse Temurin JRE of the requested major from the Adoptium API v3 into /java/temurin--jre/, shared by every server profile: https only, redirects only to api.adoptium.net, github.com and release-assets.githubusercontent.com, 300 MB cap, sha256 from the API response, tar/zip entries with absolute paths, .. or links leaving the target refused, extracted beside the target and renamed into place, and the result must report the requested major. One install per major at a time. Progress uses the download-progress event with kind "java"; audited as java.install. java_check now looks for MineUI-managed Java after an explicit override and before JAVA_HOME / PATH, preferring the exact major. required_java_major (moved to mojang) gives the screens the Java a Minecraft version needs before a server exists. 273 unit tests; the live test downloaded Temurin 21.0.13+9 once for two concurrent requests and reused it. Windows and macOS layouts are covered by unit tests on synthetic archives only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- Cargo.lock | 16 +- crates/mineui-core/Cargo.toml | 1 + crates/mineui-core/src/download.rs | 24 +- crates/mineui-core/src/hub.rs | 17 +- crates/mineui-core/src/instance.rs | 11 +- crates/mineui-core/src/java.rs | 222 +++- crates/mineui-core/src/javainstall.rs | 1055 +++++++++++++++++ crates/mineui-core/src/lib.rs | 36 +- crates/mineui-core/src/lifecycle.rs | 2 + crates/mineui-core/src/mod_archive.rs | 2 + crates/mineui-core/src/model.rs | 8 + crates/mineui-core/src/mods.rs | 2 + crates/mineui-core/src/mojang.rs | 94 ++ crates/mineui-core/src/provision.rs | 19 +- .../fixtures/adoptium-jre-21-linux-x64.json | 33 + crates/mineui-core/tests/live_java.rs | 158 +++ src-tauri/src/commands.rs | 26 +- src-tauri/src/lib.rs | 2 + 18 files changed, 1681 insertions(+), 47 deletions(-) create mode 100644 crates/mineui-core/src/javainstall.rs create mode 100644 crates/mineui-core/tests/fixtures/adoptium-jre-21-linux-x64.json create mode 100644 crates/mineui-core/tests/live_java.rs diff --git a/Cargo.lock b/Cargo.lock index 13c5c52..460106b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1833,6 +1833,7 @@ dependencies = [ "serde", "serde_json", "sha1", + "sha2 0.11.1", "sysinfo", "tar", "tempfile", @@ -3133,6 +3134,17 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + [[package]] name = "shlex" version = "2.0.1" @@ -3521,7 +3533,7 @@ dependencies = [ "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "syn 2.0.119", "tauri-utils", "thiserror 2.0.21", @@ -4783,7 +4795,7 @@ dependencies = [ "once_cell", "percent-encoding", "raw-window-handle", - "sha2", + "sha2 0.10.9", "soup3", "tao-macros", "thiserror 2.0.21", diff --git a/crates/mineui-core/Cargo.toml b/crates/mineui-core/Cargo.toml index d2a45c9..02e2bc3 100644 --- a/crates/mineui-core/Cargo.toml +++ b/crates/mineui-core/Cargo.toml @@ -27,6 +27,7 @@ async-trait = "0.1" regex = "1" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } sha1 = "0.11" +sha2 = "0.11" hex = "0.4" rand = "0.10" uuid = { version = "1", features = ["v4"] } diff --git a/crates/mineui-core/src/download.rs b/crates/mineui-core/src/download.rs index d43f2e0..e53a95f 100644 --- a/crates/mineui-core/src/download.rs +++ b/crates/mineui-core/src/download.rs @@ -28,6 +28,12 @@ pub struct DownloadRequest { pub max_bytes: Option, /// Expected SHA-1 (lowercase hex); mismatch → CHECKSUM_MISMATCH. pub expected_sha1: Option, + /// Expected SHA-256 (hex); mismatch → CHECKSUM_MISMATCH (Java runtime + /// archives, §6.3a). + pub expected_sha256: Option, + /// A client with its own redirect policy (the host-allowlisted Java + /// client, §6.3a). Takes precedence over `allow_private_hosts`. + pub client: Option, /// When false (§6.3 rule 5) the download uses `core.http_public`, whose /// redirect policy re-validates every hop against private/loopback /// ranges. True only when the user enabled @@ -116,7 +122,9 @@ async fn run(core: &crate::Core, req: &DownloadRequest) -> Result Result Result Result Option { + let core = self.core(None).await.ok()?; + crate::mojang::required_java_major(&core, mc_version).await + } + /// `get_public_address` (§3.16, 2.11.0): explicit user action only. pub async fn public_address(&self) -> Result { let core = self.core(None).await?; @@ -423,7 +431,12 @@ impl Hub { settings.advanced.query_port = game_port; settings.advanced.rcon_port = rcon_port; crate::settings::save(&paths.config_dir, settings).await?; - let core = Core::init(paths.config_dir.clone(), paths.data_dir.clone()).await?; + let core = Core::init_in_app( + paths.config_dir.clone(), + paths.data_dir.clone(), + self.root.data_dir.clone(), + ) + .await?; index.servers.push(ServerProfile { id: id.clone(), diff --git a/crates/mineui-core/src/instance.rs b/crates/mineui-core/src/instance.rs index bb26dfd..3e3248c 100644 --- a/crates/mineui-core/src/instance.rs +++ b/crates/mineui-core/src/instance.rs @@ -205,7 +205,13 @@ async fn create_inner(core: &crate::Core, args: &CreateInstanceArgs) -> Result Vec { } /// All java binaries worth probing, most-authoritative first: -/// JAVA_HOME, then every PATH hit, then well-known install roots. +/// JAVA_HOME, then every PATH hit, then well-known install roots, then +/// `extra` (managed installs that did not win the managed step). /// Deduplicated by canonical path (PATH symlinks often point into jvm dirs). -fn collect_candidates() -> Vec { +fn collect_candidates(extra: Vec) -> Vec { let mut out: Vec = Vec::new(); let mut seen: Vec = Vec::new(); let push = |candidate: PathBuf, out: &mut Vec, seen: &mut Vec| { @@ -139,10 +141,64 @@ fn collect_candidates() -> Vec { for candidate in well_known_candidates() { push(candidate, &mut out, &mut seen); } + for candidate in extra { + push(candidate, &mut out, &mut seen); + } out } -fn java_exe_name() -> &'static str { +/// Managed installs under `managed_root` (`/java`): every +/// `temurin--jre` folder with a locatable java binary, as +/// `(major, binary)`. Temp and set-aside folders (leading `.`) are ignored. +pub fn managed_installs(managed_root: &Path) -> Vec<(u32, PathBuf)> { + let mut out = Vec::new(); + let Ok(entries) = std::fs::read_dir(managed_root) else { + return out; + }; + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + let Some(major) = name + .strip_prefix("temurin-") + .and_then(|rest| rest.strip_suffix("-jre")) + .and_then(|m| m.parse::().ok()) + else { + continue; + }; + if !entry.file_type().is_ok_and(|t| t.is_dir()) { + continue; + } + if let Some(binary) = crate::javainstall::locate_java(&entry.path()) { + out.push((major, binary)); + } + } + out.sort(); + out +} + +/// Order in which managed majors are tried (§3.1): the exact required major, +/// then the smallest major above it; majors below it never. With no +/// requirement known, the highest major first. +pub fn managed_preference(majors: &[u32], required_major: Option) -> Vec { + let mut out: Vec = majors.to_vec(); + out.sort_unstable(); + out.dedup(); + match required_major { + Some(required) => { + out.retain(|m| *m >= required); + out + } + None => { + out.reverse(); + out + } + } +} + +fn is_managed(path: &Path, managed_root: Option<&Path>) -> bool { + managed_root.is_some_and(|root| path.starts_with(root)) +} + +pub(crate) fn java_exe_name() -> &'static str { if cfg!(windows) { "java.exe" } else { @@ -177,25 +233,50 @@ pub async fn probe(binary: &Path) -> Option<(String, u32)> { /// install root is pathologically full. const MAX_PROBES: usize = 16; -/// `java_check` command (§3.1): discover installs, probe them, and pick the -/// best - a compatible one when `required_major` is known, else the highest -/// major. An explicit override is authoritative: it is never silently -/// substituted with a discovered install. +/// `java_check` resolution for one server (§3.1): its `simple.javaPath` +/// override and the app-wide managed Java folder. +pub async fn check_for(core: &crate::Core, required_major: Option) -> Result { + let java_path = core.settings().await.simple.java_path.clone(); + let managed_root = crate::javainstall::managed_root(core); + check(java_path.as_deref(), Some(&managed_root), required_major).await +} + +/// `java_check` command (§3.1): the override when set; else MineUI-managed +/// Java of a compatible major (`managed_root`, 2.13.0); else discover +/// installs, probe them, and pick the best - a compatible one when +/// `required_major` is known, else the highest major. An explicit override +/// is authoritative: it is never silently substituted with a discovered +/// install. pub async fn check( java_path_override: Option<&Path>, + managed_root: Option<&Path>, required_major: Option, ) -> Result { if let Some(path) = java_path_override { if !path.is_file() { return Ok(not_found(None, required_major)); } + let managed = is_managed(path, managed_root); return Ok(match probe(path).await { - Some((version, major)) => found(path, version, major, required_major), + Some((version, major)) => found(path, version, major, required_major, managed), None => not_found(Some(path), required_major), }); } - let candidates = collect_candidates(); + let managed = managed_root.map(managed_installs).unwrap_or_default(); + let majors: Vec = managed.iter().map(|(m, _)| *m).collect(); + for wanted in managed_preference(&majors, required_major) { + for (major, binary) in managed.iter().filter(|(m, _)| *m == wanted) { + // The folder name is a claim; the probe is the truth. + if let Some((version, probed)) = probe(binary).await { + if probed == *major && required_major.is_none_or(|r| probed >= r) { + return Ok(found(binary, version, probed, required_major, true)); + } + } + } + } + + let candidates = collect_candidates(managed.into_iter().map(|(_, b)| b).collect()); let mut best: Option<(PathBuf, String, u32)> = None; for candidate in candidates.iter().take(MAX_PROBES) { let Some((version, major)) = probe(candidate).await else { @@ -214,12 +295,21 @@ pub async fn check( } } Ok(match best { - Some((path, version, major)) => found(&path, version, major, required_major), + Some((path, version, major)) => { + let managed = is_managed(&path, managed_root); + found(&path, version, major, required_major, managed) + } None => not_found(candidates.first().map(PathBuf::as_path), required_major), }) } -fn found(path: &Path, version: String, major: u32, required_major: Option) -> JavaCheck { +fn found( + path: &Path, + version: String, + major: u32, + required_major: Option, + managed: bool, +) -> JavaCheck { JavaCheck { found: true, path: Some(path.to_string_lossy().to_string()), @@ -227,6 +317,7 @@ fn found(path: &Path, version: String, major: u32, required_major: Option) major_version: Some(major), required_major, compatible: required_major.map(|required| major >= required), + managed, } } @@ -238,6 +329,7 @@ fn not_found(path: Option<&Path>, required_major: Option) -> JavaCheck { major_version: None, required_major, compatible: None, + managed: false, } } @@ -320,6 +412,112 @@ mod tests { assert_eq!(scan_install_root(tmp.path(), &[], None), vec![exe]); } + #[test] + fn managed_preference_exact_then_smallest_above() { + assert_eq!(managed_preference(&[25, 17, 21], Some(21)), vec![21, 25]); + assert_eq!(managed_preference(&[25, 17, 21], Some(18)), vec![21, 25]); + assert_eq!(managed_preference(&[17], Some(21)), Vec::::new()); + assert_eq!(managed_preference(&[17, 25, 21], None), vec![25, 21, 17]); + assert_eq!(managed_preference(&[], Some(8)), Vec::::new()); + } + + /// A fake `java` script reporting `version` (unix only: needs /bin/sh). + #[cfg(unix)] + fn fake_managed(root: &Path, major: u32, version: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let bin = root + .join(format!("temurin-{major}-jre")) + .join(format!("jdk-{version}-jre")) + .join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let exe = bin.join("java"); + std::fs::write( + &exe, + format!("#!/bin/sh\necho 'openjdk version \"{version}\" 2026-10-21' >&2\n"), + ) + .unwrap(); + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); + exe + } + + /// Exec of a just-written script can fail with ETXTBSY while another + /// test thread's fork still holds the write fd; wait until each runs. + #[cfg(unix)] + async fn wait_runnable(paths: &[&PathBuf]) { + for path in paths { + for _ in 0..50 { + if probe(path).await.is_some() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + } + } + + #[cfg(unix)] + #[tokio::test] + async fn check_prefers_exact_managed_major_then_smallest_above() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("java"); + let j17 = fake_managed(&root, 17, "17.0.17"); + let j21 = fake_managed(&root, 21, "21.0.13"); + let j25 = fake_managed(&root, 25, "25.0.1"); + wait_runnable(&[&j17, &j21, &j25]).await; + // Temp/aside folders and non-matching names are ignored. + std::fs::create_dir_all(root.join(".tmp-temurin-21-jre-x/bin")).unwrap(); + assert_eq!(managed_installs(&root).len(), 3); + + let pick = |required| { + let root = root.clone(); + async move { check(None, Some(&root), required).await.unwrap() } + }; + let exact = pick(Some(21)).await; + assert_eq!(exact.path.as_deref(), Some(j21.to_str().unwrap())); + assert_eq!(exact.major_version, Some(21)); + assert_eq!(exact.compatible, Some(true)); + assert!(exact.managed); + + assert_eq!( + pick(Some(17)).await.path.as_deref(), + Some(j17.to_str().unwrap()) + ); + let above = pick(Some(18)).await; + assert_eq!(above.path.as_deref(), Some(j21.to_str().unwrap())); + assert!(above.managed); + let newest = pick(None).await; + assert_eq!(newest.path.as_deref(), Some(j25.to_str().unwrap())); + assert_eq!(newest.compatible, None); + + // Nothing managed is new enough: discovery decides, and a managed + // Java that is too old is never reported compatible. + let too_new = pick(Some(26)).await; + if too_new.managed { + assert_eq!(too_new.compatible, Some(false)); + } + + // The override still wins, and is flagged managed only when it lies + // inside the managed folder. + let over = check(Some(&j17), Some(&root), Some(21)).await.unwrap(); + assert_eq!(over.path.as_deref(), Some(j17.to_str().unwrap())); + assert_eq!(over.compatible, Some(false)); + assert!(over.managed); + } + + #[cfg(unix)] + #[tokio::test] + async fn managed_folder_name_is_checked_against_the_probe() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("java"); + // A folder claiming 21 whose java reports 17 is not used as 21. + let liar = fake_managed(&root, 21, "17.0.17"); + wait_runnable(&[&liar]).await; + let res = check(None, Some(&root), Some(21)).await.unwrap(); + assert_ne!( + (res.path.as_deref(), res.compatible), + (Some(liar.to_str().unwrap()), Some(true)) + ); + } + #[test] fn missing_root_yields_empty() { assert!(scan_install_root(Path::new("/nonexistent-mineui-test"), &[], None).is_empty()); diff --git a/crates/mineui-core/src/javainstall.rs b/crates/mineui-core/src/javainstall.rs new file mode 100644 index 0000000..8057c13 --- /dev/null +++ b/crates/mineui-core/src/javainstall.rs @@ -0,0 +1,1055 @@ +//! MineUI-managed Java: `install_java` (contract §3.1, §6.3a, 2.13.0). +//! +//! Downloads the Eclipse Temurin JRE of one major from Adoptium into +//! `/java/temurin--jre/`, shared by every server profile. +//! Fixed hosts only, sha256-verified, extracted into a temp dir beside the +//! target with traversal-safe rules, probed, then renamed into place. + +use std::collections::HashMap; +use std::io::Read; +use std::path::{Component, Path, PathBuf}; +use std::sync::{Arc, LazyLock}; +use std::time::Duration; + +use serde::Deserialize; + +use crate::error::{Error, Result}; +use crate::model::{AuditSource, DownloadKind, JavaCheck}; + +/// §6.3a rule 1. +pub const MIN_MAJOR: i64 = 8; +pub const MAX_MAJOR: i64 = 30; +/// §6.3a rule 5: archive cap. +pub const MAX_ARCHIVE_BYTES: u64 = 300 * 1024 * 1024; +/// §6.3a rule 6: extraction limits. +const MAX_ENTRIES: usize = 20_000; +const MAX_EXTRACTED_BYTES: u64 = 1024 * 1024 * 1024; +/// §6.3a rule 7: how deep below the extraction dir the binary may sit. +const MAX_LOCATE_DEPTH: usize = 3; +/// §6.3a rule 4: the only hosts a Java download may touch, redirects +/// included. Observed chain (2026-11-09): api.adoptium.net answers itself; +/// the archive link is on github.com, which 302s once to +/// release-assets.githubusercontent.com. +pub const ALLOWED_HOSTS: &[&str] = &[ + "api.adoptium.net", + "github.com", + "release-assets.githubusercontent.com", +]; +const MAX_REDIRECTS: usize = 5; +const API_BASE: &str = "https://api.adoptium.net/v3/assets/latest"; + +/// `/java`: the managed Java folder, app-wide. +pub fn managed_root(core: &crate::Core) -> PathBuf { + core.app_data_dir().join("java") +} + +/// The folder one major is installed in. +pub fn install_dir_name(major: u32) -> String { + format!("temurin-{major}-jre") +} + +/// §6.3a rule 2: Adoptium's `os` / `architecture` names for a Rust +/// `std::env::consts::{OS, ARCH}` pair. +pub fn adoptium_platform(os: &str, arch: &str) -> Option<(&'static str, &'static str)> { + let os = match os { + "linux" => "linux", + "macos" => "mac", + "windows" => "windows", + _ => return None, + }; + let arch = match arch { + "x86_64" => "x64", + "aarch64" => "aarch64", + _ => return None, + }; + Some((os, arch)) +} + +/// This build's platform, or None where Temurin has no build we fetch. +pub fn this_platform() -> Option<(&'static str, &'static str)> { + adoptium_platform(std::env::consts::OS, std::env::consts::ARCH) +} + +/// §6.3a rule 3: the Adoptium API v3 query for one major. +pub fn api_url(major: u32, os: &str, arch: &str) -> String { + format!("{API_BASE}/{major}/hotspot?architecture={arch}&image_type=jre&os={os}&vendor=eclipse") +} + +/// §6.3a rule 4: https, no credentials, default port, allowlisted host. +pub fn url_allowed(url: &reqwest::Url) -> bool { + url.scheme() == "https" + && url.username().is_empty() + && url.password().is_none() + && url.port().is_none() + && url + .host_str() + .is_some_and(|h| ALLOWED_HOSTS.iter().any(|a| a.eq_ignore_ascii_case(h))) +} + +/// The client every Java request goes through: each redirect hop must stay +/// https on an allowlisted host. +fn build_client() -> reqwest::Client { + let policy = reqwest::redirect::Policy::custom(|attempt| { + if attempt.previous().len() > MAX_REDIRECTS { + return attempt.error("too many redirects"); + } + if !url_allowed(attempt.url()) { + let host = attempt.url().host_str().unwrap_or("?").to_string(); + return attempt.error(format!("redirect to a host MineUI does not trust ({host})")); + } + attempt.follow() + }); + reqwest::Client::builder() + .redirect(policy) + .connect_timeout(Duration::from_secs(15)) + .read_timeout(Duration::from_secs(60)) + .user_agent(concat!("MineUI/", env!("CARGO_PKG_VERSION"))) + .build() + .expect("reqwest client construction cannot fail with static config") +} + +/* ---------- Adoptium response ---------- */ + +#[derive(Debug, Deserialize)] +struct Asset { + binary: Binary, + version: AssetVersion, +} + +#[derive(Debug, Deserialize)] +struct Binary { + os: String, + architecture: String, + image_type: String, + package: Package, +} + +#[derive(Debug, Deserialize)] +struct Package { + link: String, + checksum: String, + size: u64, + name: String, +} + +#[derive(Debug, Deserialize)] +struct AssetVersion { + major: u32, + #[serde(default)] + openjdk_version: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ArchiveKind { + TarGz, + Zip, +} + +/// What `select_asset` takes from the API response. +#[derive(Debug, Clone)] +pub struct SelectedAsset { + pub link: reqwest::Url, + pub sha256: String, + pub size: u64, + pub name: String, + /// e.g. `21.0.13+9` (from `openjdk_version`, `-LTS` dropped). + pub version: String, + pub kind: ArchiveKind, +} + +/// §6.3a rules 3-5: pick the asset from an API response body and check +/// everything the download relies on. +pub fn select_asset(body: &str, major: u32, os: &str, arch: &str) -> Result { + let assets: Vec = serde_json::from_str(body).map_err(|e| { + Error::DownloadFailed(format!("Adoptium sent an answer MineUI cannot read: {e}")) + })?; + let asset = assets + .into_iter() + .find(|a| { + a.binary.image_type == "jre" + && a.binary.os == os + && a.binary.architecture == arch + && a.version.major == major + }) + .ok_or_else(|| { + Error::DownloadFailed(format!( + "Adoptium has no Java {major} runtime for this computer ({os} {arch})" + )) + })?; + let package = asset.binary.package; + let link = reqwest::Url::parse(&package.link).map_err(|_| { + Error::DownloadFailed("Adoptium sent a download link MineUI cannot read".into()) + })?; + if !url_allowed(&link) { + return Err(Error::DownloadFailed(format!( + "the Java download link points to a host MineUI does not trust ({})", + link.host_str().unwrap_or("?") + ))); + } + let checksum = package.checksum.to_ascii_lowercase(); + if checksum.len() != 64 || !checksum.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(Error::DownloadFailed( + "Adoptium sent no usable sha256 checksum for the Java download".into(), + )); + } + if package.size > MAX_ARCHIVE_BYTES { + return Err(Error::FileTooLarge(format!( + "the Java download is {} bytes; the limit is {MAX_ARCHIVE_BYTES}", + package.size + ))); + } + let lower = package.name.to_ascii_lowercase(); + let kind = if lower.ends_with(".tar.gz") { + ArchiveKind::TarGz + } else if lower.ends_with(".zip") { + ArchiveKind::Zip + } else { + return Err(Error::DownloadFailed(format!( + "the Java download is not a .tar.gz or .zip ({})", + package.name + ))); + }; + let version = asset + .version + .openjdk_version + .trim_end_matches("-LTS") + .to_string(); + Ok(SelectedAsset { + link, + sha256: checksum, + size: package.size, + name: package.name, + version: if version.is_empty() { + major.to_string() + } else { + version + }, + kind, + }) +} + +/* ---------- extraction (blocking; run off the async runtime) ---------- */ + +fn unsafe_archive(why: impl std::fmt::Display) -> Error { + Error::DownloadFailed(format!("the Java download was refused: {why}")) +} + +/// An entry path made only of normal components (`.` ignored). Absolute +/// paths, drive/root prefixes and `..` are refused. +fn safe_relative(path: &Path) -> Result { + let mut out = PathBuf::new(); + for component in path.components() { + match component { + Component::Normal(part) => out.push(part), + Component::CurDir => {} + Component::ParentDir => { + return Err(unsafe_archive(format!( + "an entry climbs out of its folder ({})", + path.display() + ))) + } + Component::RootDir | Component::Prefix(_) => { + return Err(unsafe_archive(format!( + "an entry has an absolute path ({})", + path.display() + ))) + } + } + } + Ok(out) +} + +/// A symlink at `entry` (relative to the extraction dir) pointing at +/// `target` must be relative and resolve inside the extraction dir. +fn check_symlink_target(entry: &Path, target: &Path) -> Result<()> { + let refuse = || { + unsafe_archive(format!( + "a link points outside the Java folder ({} -> {})", + entry.display(), + target.display() + )) + }; + let mut depth: i64 = entry + .parent() + .map(|p| { + p.components() + .filter(|c| matches!(c, Component::Normal(_))) + .count() as i64 + }) + .unwrap_or(0); + for component in target.components() { + match component { + Component::Normal(_) => depth += 1, + Component::CurDir => {} + Component::ParentDir => { + depth -= 1; + if depth < 0 { + return Err(refuse()); + } + } + Component::RootDir | Component::Prefix(_) => return Err(refuse()), + } + } + Ok(()) +} + +/// Extract a `.tar.gz` stream into `dest` (which must exist). +pub fn extract_tar_gz(reader: R, dest: &Path) -> Result<()> { + let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(reader)); + // Keep the rwx bits (`bin/java` must stay executable); never setuid etc. + archive.set_preserve_permissions(false); + archive.set_overwrite(false); + let entries = archive + .entries() + .map_err(|e| unsafe_archive(format!("unreadable archive: {e}")))?; + let mut count = 0usize; + let mut written = 0u64; + for entry in entries { + let mut entry = entry.map_err(|e| unsafe_archive(format!("unreadable archive: {e}")))?; + count += 1; + if count > MAX_ENTRIES { + return Err(unsafe_archive("too many entries")); + } + let raw = entry + .path() + .map_err(|e| unsafe_archive(format!("unreadable entry name: {e}")))? + .into_owned(); + let rel = safe_relative(&raw)?; + if rel.as_os_str().is_empty() { + continue; + } + let kind = entry.header().entry_type(); + if kind.is_dir() { + // Created by unpack_in below. + } else if kind.is_file() || kind == tar::EntryType::Continuous { + written = written.saturating_add(entry.size()); + if written > MAX_EXTRACTED_BYTES { + return Err(unsafe_archive("it unpacks to more than 1 GiB")); + } + } else if kind.is_symlink() { + let target = entry + .link_name() + .map_err(|e| unsafe_archive(format!("unreadable link: {e}")))? + .ok_or_else(|| unsafe_archive("a link without a target"))? + .into_owned(); + check_symlink_target(&rel, &target)?; + } else if kind.is_hard_link() { + let target = entry + .link_name() + .map_err(|e| unsafe_archive(format!("unreadable link: {e}")))? + .ok_or_else(|| unsafe_archive("a link without a target"))? + .into_owned(); + safe_relative(&target)?; + } else { + // Devices, fifos, pax/GNU metadata the iterator did not fold in. + continue; + } + let unpacked = entry + .unpack_in(dest) + .map_err(|e| unsafe_archive(format!("could not unpack {}: {e}", rel.display())))?; + if !unpacked { + return Err(unsafe_archive(format!( + "an entry climbs out of its folder ({})", + raw.display() + ))); + } + } + Ok(()) +} + +/// The raw zip entry name, `\\` read as `/`: no leading root, no drive +/// letter, no `..` segment (stricter than `enclosed_name`, which strips a +/// leading `/` and allows `a/../b`). +fn check_zip_name(name: &str) -> Result<()> { + let name = name.replace('\\', "/"); + let bytes = name.as_bytes(); + if name.starts_with('/') || (bytes.len() >= 2 && bytes[1] == b':') { + return Err(unsafe_archive(format!( + "an entry has an absolute path ({name})" + ))); + } + if name.split('/').any(|segment| segment == "..") { + return Err(unsafe_archive(format!( + "an entry climbs out of its folder ({name})" + ))); + } + Ok(()) +} + +/// Extract a `.zip` file into `dest` (which must exist). Links inside the +/// folder are skipped (Windows JRE zips have none); links leaving it refuse +/// the archive. +pub fn extract_zip(file: std::fs::File, dest: &Path) -> Result<()> { + let mut zip = zip::ZipArchive::new(file) + .map_err(|e| unsafe_archive(format!("unreadable archive: {e}")))?; + if zip.len() > MAX_ENTRIES { + return Err(unsafe_archive("too many entries")); + } + let mut written = 0u64; + for index in 0..zip.len() { + let mut entry = zip + .by_index(index) + .map_err(|e| unsafe_archive(format!("unreadable archive: {e}")))?; + let name = entry.name().to_string(); + check_zip_name(&name)?; + let rel = entry + .enclosed_name() + .ok_or_else(|| unsafe_archive(format!("an entry has an unsafe path ({name})")))?; + let rel = safe_relative(&rel)?; + if rel.as_os_str().is_empty() { + continue; + } + if entry.is_symlink() { + let mut target = String::new(); + entry + .by_ref() + .take(4096) + .read_to_string(&mut target) + .map_err(|e| unsafe_archive(format!("unreadable link: {e}")))?; + check_symlink_target(&rel, Path::new(&target))?; + continue; + } + let out = dest.join(&rel); + if entry.is_dir() { + std::fs::create_dir_all(&out) + .map_err(|e| Error::Io(format!("could not create {}: {e}", out.display())))?; + continue; + } + if let Some(parent) = out.parent() { + std::fs::create_dir_all(parent) + .map_err(|e| Error::Io(format!("could not create {}: {e}", parent.display())))?; + } + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&out) + .map_err(|e| unsafe_archive(format!("could not write {}: {e}", rel.display())))?; + let remaining = MAX_EXTRACTED_BYTES - written; + let copied = std::io::copy(&mut entry.by_ref().take(remaining + 1), &mut file) + .map_err(|e| unsafe_archive(format!("could not unpack {}: {e}", rel.display())))?; + written += copied; + if written > MAX_EXTRACTED_BYTES { + return Err(unsafe_archive("it unpacks to more than 1 GiB")); + } + #[cfg(unix)] + if let Some(mode) = entry.unix_mode() { + use std::os::unix::fs::PermissionsExt; + let _ = file.set_permissions(std::fs::Permissions::from_mode(mode & 0o777)); + } + } + Ok(()) +} + +/* ---------- locating the binary ---------- */ + +/// §6.3a rule 7: `bin/` or `Contents/Home/bin/` in `dir` or a +/// folder at most three levels below it. Symlinked folders are not +/// followed. Breadth-first, names sorted, so the shallowest hit wins. +pub fn locate_java_with(dir: &Path, exe: &str) -> Option { + let mut level = vec![dir.to_path_buf()]; + for depth in 0..=MAX_LOCATE_DEPTH { + let mut next = Vec::new(); + for folder in &level { + for candidate in [ + folder.join("bin").join(exe), + folder.join("Contents").join("Home").join("bin").join(exe), + ] { + if candidate.is_file() { + return Some(candidate); + } + } + if depth == MAX_LOCATE_DEPTH { + continue; + } + let Ok(entries) = std::fs::read_dir(folder) else { + continue; + }; + let mut children: Vec = entries + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) + .map(|e| e.path()) + .collect(); + children.sort(); + next.extend(children); + } + level = next; + } + None +} + +/// `locate_java_with` for this OS's executable name. +pub fn locate_java(dir: &Path) -> Option { + locate_java_with(dir, crate::java::java_exe_name()) +} + +/* ---------- install ---------- */ + +/// One install per target folder at a time (§3.1): a second request waits +/// on the same lock and then finds the first one's result on disk. +static INSTALL_LOCKS: LazyLock>>>> = + LazyLock::new(|| std::sync::Mutex::new(HashMap::new())); + +fn install_lock(target: &Path) -> Arc> { + let mut map = INSTALL_LOCKS.lock().unwrap_or_else(|p| p.into_inner()); + map.entry(target.to_path_buf()).or_default().clone() +} + +/// `Some(binary)` when `target` holds a java that reports `major`. +async fn working_install(target: &Path, major: u32) -> Option { + let binary = locate_java(target)?; + match crate::java::probe(&binary).await { + Some((_, probed)) if probed == major => Some(binary), + _ => None, + } +} + +pub fn validate_major(major: i64) -> Result { + if !(MIN_MAJOR..=MAX_MAJOR).contains(&major) { + return Err(Error::InvalidInput(format!( + "Java version must be between {MIN_MAJOR} and {MAX_MAJOR}, not {major}" + ))); + } + Ok(major as u32) +} + +/// `install_java` (§3.1): make sure Temurin JRE `major` is in the managed +/// folder, then return this server's Java check. +pub async fn install(core: &crate::Core, major: i64) -> Result { + let major = validate_major(major)?; + ensure_installed(core, &managed_root(core), major).await?; + let instance = crate::instance::probe(core).await?; + let required = instance.required_java_major.or(Some(major)); + crate::java::check_for(core, required).await +} + +/// Install `major` under `root` unless a working copy is there. Returns the +/// java binary. +pub async fn ensure_installed(core: &crate::Core, root: &Path, major: u32) -> Result { + let dir_name = install_dir_name(major); + let target = root.join(&dir_name); + let lock = install_lock(&target); + let _guard = lock.lock().await; + if let Some(binary) = working_install(&target, major).await { + return Ok(binary); + } + let mut version: Option = None; + let result = download_and_install(core, root, &target, major, &mut version).await; + let detail = version.map(|v| format!("Temurin JRE {v}")); + crate::audit::record( + core, + AuditSource::User, + "java.install", + Some(&dir_name), + detail.as_deref(), + result.as_ref().err(), + ) + .await; + result +} + +async fn download_and_install( + core: &crate::Core, + root: &Path, + target: &Path, + major: u32, + version_out: &mut Option, +) -> Result { + let (os, arch) = this_platform().ok_or_else(|| { + Error::DownloadFailed("there is no Temurin Java build for this computer".into()) + })?; + let client = build_client(); + + // 1. Ask Adoptium which archive to fetch. + let api = reqwest::Url::parse(&api_url(major, os, arch)) + .map_err(|e| Error::Internal(format!("bad Adoptium URL: {e}")))?; + let response = client.get(api).send().await.map_err(|e| { + Error::DownloadFailed(format!("could not reach Adoptium to download Java: {e}")) + })?; + if !response.status().is_success() { + return Err(Error::DownloadFailed(format!( + "Adoptium answered HTTP {} when asked for Java {major}", + response.status().as_u16() + ))); + } + let body = response + .text() + .await + .map_err(|e| Error::DownloadFailed(format!("could not read Adoptium's answer: {e}")))?; + let asset = select_asset(&body, major, os, arch)?; + *version_out = Some(asset.version.clone()); + + // 2. Download it (progress events, cap, sha256). + let req = crate::download::DownloadRequest { + url: asset.link.clone(), + kind: DownloadKind::Java, + filename: asset.name.clone(), + download_id: uuid::Uuid::new_v4().to_string(), + max_bytes: Some(MAX_ARCHIVE_BYTES), + expected_sha1: None, + expected_sha256: Some(asset.sha256.clone()), + allow_private_hosts: false, + client: Some(client), + }; + let downloaded = crate::download::to_temp_file(core, &req).await?; + let archive = downloaded.temp_path; + + // 3. Extract beside the target, probe, rename into place. + let result = unpack_and_place(root, target, major, &archive, asset.kind).await; + let _ = tokio::fs::remove_file(&archive).await; + result +} + +async fn unpack_and_place( + root: &Path, + target: &Path, + major: u32, + archive: &Path, + kind: ArchiveKind, +) -> Result { + tokio::fs::create_dir_all(root) + .await + .map_err(|e| Error::Io(format!("could not create {}: {e}", root.display())))?; + let dir_name = install_dir_name(major); + let tmp = root.join(format!(".tmp-{dir_name}-{}", uuid::Uuid::new_v4())); + let placed = async { + tokio::fs::create_dir(&tmp) + .await + .map_err(|e| Error::Io(format!("could not create {}: {e}", tmp.display())))?; + let (archive_path, tmp_dir) = (archive.to_path_buf(), tmp.clone()); + let binary = tokio::task::spawn_blocking(move || -> Result { + let file = std::fs::File::open(&archive_path) + .map_err(|e| Error::Io(format!("could not open the Java download: {e}")))?; + match kind { + ArchiveKind::TarGz => extract_tar_gz(std::io::BufReader::new(file), &tmp_dir)?, + ArchiveKind::Zip => extract_zip(file, &tmp_dir)?, + } + locate_java(&tmp_dir).ok_or_else(|| { + Error::DownloadFailed("the Java download has no java program in it".into()) + }) + }) + .await + .map_err(|e| Error::Internal(format!("Java extraction task failed: {e}")))??; + + match crate::java::probe(&binary).await { + Some((_, probed)) if probed == major => {} + Some((version, _)) => { + return Err(Error::DownloadFailed(format!( + "the downloaded Java reports version {version}, not {major}" + ))) + } + None => { + return Err(Error::DownloadFailed( + "the downloaded Java does not run on this computer".into(), + )) + } + } + let relative = binary + .strip_prefix(&tmp) + .map_err(|_| Error::Internal("located java outside the temp dir".into()))? + .to_path_buf(); + place(root, &tmp, target, &dir_name).await?; + Ok(target.join(relative)) + } + .await; + if placed.is_err() { + let _ = tokio::fs::remove_dir_all(&tmp).await; + } + placed +} + +/// §6.3a rule 8: rename `tmp` to `target`, moving a previous (broken) +/// folder aside first and removing it after. +async fn place(root: &Path, tmp: &Path, target: &Path, dir_name: &str) -> Result<()> { + let aside = root.join(format!(".old-{dir_name}-{}", uuid::Uuid::new_v4())); + let had_old = tokio::fs::symlink_metadata(target).await.is_ok(); + if had_old { + tokio::fs::rename(target, &aside).await.map_err(|e| { + Error::Io(format!( + "could not move the old Java folder aside ({}): {e}", + target.display() + )) + })?; + } + if let Err(e) = tokio::fs::rename(tmp, target).await { + if had_old { + let _ = tokio::fs::rename(&aside, target).await; + } + return Err(Error::Io(format!( + "could not move Java into place ({}): {e}", + target.display() + ))); + } + if had_old { + let _ = tokio::fs::remove_dir_all(&aside).await; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const FIXTURE: &str = include_str!("../tests/fixtures/adoptium-jre-21-linux-x64.json"); + + #[test] + fn maps_platforms() { + assert_eq!(adoptium_platform("linux", "x86_64"), Some(("linux", "x64"))); + assert_eq!( + adoptium_platform("macos", "aarch64"), + Some(("mac", "aarch64")) + ); + assert_eq!( + adoptium_platform("windows", "x86_64"), + Some(("windows", "x64")) + ); + assert_eq!(adoptium_platform("linux", "riscv64"), None); + assert_eq!(adoptium_platform("freebsd", "x86_64"), None); + } + + #[test] + fn api_url_per_platform() { + assert_eq!( + api_url(21, "linux", "x64"), + "https://api.adoptium.net/v3/assets/latest/21/hotspot?architecture=x64&image_type=jre&os=linux&vendor=eclipse" + ); + assert_eq!( + api_url(17, "mac", "aarch64"), + "https://api.adoptium.net/v3/assets/latest/17/hotspot?architecture=aarch64&image_type=jre&os=mac&vendor=eclipse" + ); + assert_eq!( + api_url(8, "windows", "x64"), + "https://api.adoptium.net/v3/assets/latest/8/hotspot?architecture=x64&image_type=jre&os=windows&vendor=eclipse" + ); + let url = reqwest::Url::parse(&api_url(21, "linux", "x64")).unwrap(); + assert!(url_allowed(&url)); + } + + #[test] + fn major_range() { + assert!(validate_major(7).is_err()); + assert_eq!(validate_major(7).unwrap_err().code(), "INVALID_INPUT"); + assert_eq!(validate_major(31).unwrap_err().code(), "INVALID_INPUT"); + assert_eq!(validate_major(-21).unwrap_err().code(), "INVALID_INPUT"); + assert_eq!(validate_major(8).unwrap(), 8); + assert_eq!(validate_major(30).unwrap(), 30); + } + + #[test] + fn host_allowlist() { + let ok = |u: &str| url_allowed(&reqwest::Url::parse(u).unwrap()); + assert!(ok("https://github.com/adoptium/x.tar.gz")); + assert!(ok("https://release-assets.githubusercontent.com/a?b=c")); + assert!(!ok("http://github.com/adoptium/x.tar.gz")); + assert!(!ok("https://objects.githubusercontent.com/x")); + assert!(!ok("https://github.com.evil.example/x")); + assert!(!ok("https://user:pw@github.com/x")); + assert!(!ok("https://github.com:8443/x")); + } + + #[test] + fn parses_real_response() { + let asset = select_asset(FIXTURE, 21, "linux", "x64").unwrap(); + assert_eq!(asset.kind, ArchiveKind::TarGz); + assert_eq!(asset.version, "21.0.13+9"); + assert_eq!( + asset.name, + "OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz" + ); + assert_eq!( + asset.sha256, + "a535a1df9c6284d9618872984e026ae0352d1f7e9e0605425c0e6114f47351dd" + ); + assert_eq!(asset.link.host_str(), Some("github.com")); + assert_eq!(asset.size, 52_181_297); + } + + #[test] + fn refuses_mismatched_or_unsafe_assets() { + // Wrong major / platform: nothing matches. + assert_eq!( + select_asset(FIXTURE, 17, "linux", "x64") + .unwrap_err() + .code(), + "DOWNLOAD_FAILED" + ); + assert_eq!( + select_asset(FIXTURE, 21, "mac", "x64").unwrap_err().code(), + "DOWNLOAD_FAILED" + ); + assert_eq!( + select_asset("[]", 21, "linux", "x64").unwrap_err().code(), + "DOWNLOAD_FAILED" + ); + // A link off the allowlist. + let evil = FIXTURE.replace("https://github.com/", "https://evil.example/"); + assert_eq!( + select_asset(&evil, 21, "linux", "x64").unwrap_err().code(), + "DOWNLOAD_FAILED" + ); + // Plain http. + let http = FIXTURE.replace("\"link\": \"https://", "\"link\": \"http://"); + assert_eq!( + select_asset(&http, 21, "linux", "x64").unwrap_err().code(), + "DOWNLOAD_FAILED" + ); + // No usable checksum. + let nosum = FIXTURE.replace( + "a535a1df9c6284d9618872984e026ae0352d1f7e9e0605425c0e6114f47351dd", + "nope", + ); + assert_eq!( + select_asset(&nosum, 21, "linux", "x64").unwrap_err().code(), + "DOWNLOAD_FAILED" + ); + // Over the size cap. + let big = FIXTURE.replace("\"size\": 52181297", "\"size\": 999999999"); + assert_eq!( + select_asset(&big, 21, "linux", "x64").unwrap_err().code(), + "FILE_TOO_LARGE" + ); + } + + /* ----- archive builders ----- */ + + fn tar_gz(build: impl FnOnce(&mut tar::Builder>>)) -> Vec { + let enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + let mut builder = tar::Builder::new(enc); + build(&mut builder); + builder.into_inner().unwrap().finish().unwrap() + } + + fn add_file(b: &mut tar::Builder>>, path: &str, mode: u32) { + let data = b"#!/bin/sh\n"; + let mut header = tar::Header::new_gnu(); + header.set_size(data.len() as u64); + header.set_mode(mode); + header.set_entry_type(tar::EntryType::Regular); + b.append_data(&mut header, path, &data[..]).unwrap(); + } + + /// Writes a raw name into the header, bypassing tar-rs's own path + /// checks (an attacker's archive is not built with tar-rs). + fn add_raw( + b: &mut tar::Builder>>, + name: &str, + kind: tar::EntryType, + link: Option<&str>, + ) { + let mut header = tar::Header::new_old(); + { + let raw = header.as_old_mut(); + raw.name[..name.len()].copy_from_slice(name.as_bytes()); + if let Some(link) = link { + raw.linkname[..link.len()].copy_from_slice(link.as_bytes()); + } + } + header.set_entry_type(kind); + header.set_mode(0o644); + header.set_size(0); + header.set_cksum(); + b.append(&header, std::io::empty()).unwrap(); + } + + fn untar(bytes: &[u8]) -> (tempfile::TempDir, Result<()>) { + let dir = tempfile::tempdir().unwrap(); + let res = extract_tar_gz(bytes, dir.path()); + (dir, res) + } + + #[test] + fn tar_extracts_and_keeps_exec_bit() { + let bytes = tar_gz(|b| { + add_file(b, "jdk-21.0.13+9-jre/bin/java", 0o755); + add_file(b, "jdk-21.0.13+9-jre/lib/modules", 0o644); + add_raw( + b, + "jdk-21.0.13+9-jre/legal/java.sql/LICENSE", + tar::EntryType::Symlink, + Some("../java.base/LICENSE"), + ); + }); + let (dir, res) = untar(&bytes); + res.unwrap(); + let java = dir.path().join("jdk-21.0.13+9-jre/bin/java"); + assert!(java.is_file()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&java).unwrap().permissions().mode(); + assert_eq!(mode & 0o111, 0o111, "bin/java must stay executable"); + } + assert_eq!(locate_java_with(dir.path(), "java"), Some(java)); + } + + #[test] + fn tar_refuses_parent_dir_entry() { + let bytes = tar_gz(|b| add_raw(b, "../x", tar::EntryType::Regular, None)); + let (dir, res) = untar(&bytes); + assert_eq!(res.unwrap_err().code(), "DOWNLOAD_FAILED"); + assert!(!dir.path().parent().unwrap().join("x").exists()); + } + + #[test] + fn tar_refuses_absolute_entry() { + let bytes = tar_gz(|b| add_raw(b, "/abs", tar::EntryType::Regular, None)); + let (_dir, res) = untar(&bytes); + assert_eq!(res.unwrap_err().code(), "DOWNLOAD_FAILED"); + } + + #[test] + fn tar_refuses_outside_symlinks() { + for target in ["../../outside", "/etc/passwd", "a/../../.."] { + let bytes = tar_gz(|b| add_raw(b, "jre/link", tar::EntryType::Symlink, Some(target))); + let (dir, res) = untar(&bytes); + assert_eq!(res.unwrap_err().code(), "DOWNLOAD_FAILED", "{target}"); + assert!(std::fs::symlink_metadata(dir.path().join("jre/link")).is_err()); + } + // A hard link naming a path outside. + let bytes = tar_gz(|b| add_raw(b, "jre/hard", tar::EntryType::Link, Some("../x"))); + assert_eq!(untar(&bytes).1.unwrap_err().code(), "DOWNLOAD_FAILED"); + } + + #[test] + fn symlink_target_rules() { + let p = Path::new; + assert!(check_symlink_target(p("a/b/link"), p("../c")).is_ok()); + assert!(check_symlink_target(p("a/b/link"), p("../../c")).is_ok()); + assert!(check_symlink_target(p("a/b/link"), p("../../../c")).is_err()); + assert!(check_symlink_target(p("link"), p("..")).is_err()); + assert!(check_symlink_target(p("a/link"), p("/abs")).is_err()); + } + + fn zip_bytes(entries: &[(&str, &[u8])]) -> Vec { + let mut out = std::io::Cursor::new(Vec::new()); + { + let mut w = zip::ZipWriter::new(&mut out); + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Stored); + for (name, data) in entries { + w.start_file(*name, opts).unwrap(); + std::io::Write::write_all(&mut w, data).unwrap(); + } + w.finish().unwrap(); + } + out.into_inner() + } + + fn unzip(bytes: &[u8]) -> (tempfile::TempDir, Result<()>) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("a.zip"); + std::fs::write(&path, bytes).unwrap(); + let dest = dir.path().join("out"); + std::fs::create_dir(&dest).unwrap(); + let res = extract_zip(std::fs::File::open(&path).unwrap(), &dest); + (dir, res) + } + + #[test] + fn zip_extracts_windows_layout() { + let bytes = zip_bytes(&[ + ("jdk-21.0.13+9-jre/bin/java.exe", b"MZ"), + ("jdk-21.0.13+9-jre/release", b"JAVA_VERSION=21"), + ]); + let (dir, res) = unzip(&bytes); + res.unwrap(); + let out = dir.path().join("out"); + assert_eq!( + locate_java_with(&out, "java.exe"), + Some(out.join("jdk-21.0.13+9-jre/bin/java.exe")) + ); + } + + #[test] + fn zip_refuses_traversal_and_absolute() { + for name in ["../x", "/abs", "a/../../x", "a/../b", "C:/x", "..\\x"] { + let bytes = zip_bytes(&[(name, b"x")]); + let (dir, res) = unzip(&bytes); + assert_eq!(res.unwrap_err().code(), "DOWNLOAD_FAILED", "{name}"); + assert!(!dir.path().join("x").exists()); + } + } + + #[test] + fn locates_java_in_each_layout() { + let tmp = tempfile::tempdir().unwrap(); + let mk = |rel: &str| { + let p = tmp.path().join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, b"").unwrap(); + p + }; + let linux = mk("linux/jdk-21.0.13+9-jre/bin/java"); + let mac = mk("mac/jdk-21.0.13+9-jre/Contents/Home/bin/java"); + let win = mk("win/jdk-21.0.13+9-jre/bin/java.exe"); + assert_eq!( + locate_java_with(&tmp.path().join("linux"), "java"), + Some(linux) + ); + assert_eq!(locate_java_with(&tmp.path().join("mac"), "java"), Some(mac)); + assert_eq!( + locate_java_with(&tmp.path().join("win"), "java.exe"), + Some(win) + ); + // Too deep: four folders below. + mk("deep/a/b/c/d/bin/java"); + assert_eq!(locate_java_with(&tmp.path().join("deep"), "java"), None); + assert_eq!(locate_java_with(&tmp.path().join("missing"), "java"), None); + } + + #[tokio::test] + async fn sha256_mismatch_is_refused() { + // Serve a body from a local socket and verify through the real + // download path with a wrong expected sha256. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let (mut sock, _) = listener.accept().await.unwrap(); + let mut buf = [0u8; 1024]; + let _ = sock.read(&mut buf).await; + let body = b"not really a jre"; + let head = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + sock.write_all(head.as_bytes()).await.unwrap(); + sock.write_all(body).await.unwrap(); + sock.flush().await.unwrap(); + }); + let tmp = tempfile::tempdir().unwrap(); + let core = crate::Core::init(tmp.path().join("config"), tmp.path().join("data")) + .await + .unwrap(); + let mut events = core.subscribe_events(); + let req = crate::download::DownloadRequest { + url: reqwest::Url::parse(&format!("http://{addr}/jre.tar.gz")).unwrap(), + kind: DownloadKind::Java, + filename: "jre.tar.gz".into(), + download_id: "t".into(), + max_bytes: Some(MAX_ARCHIVE_BYTES), + expected_sha1: None, + expected_sha256: Some("0".repeat(64)), + allow_private_hosts: true, + client: Some(reqwest::Client::new()), + }; + let Err(err) = crate::download::to_temp_file(&core, &req).await else { + panic!("a sha256 mismatch must fail the download"); + }; + assert_eq!(err.code(), "CHECKSUM_MISMATCH"); + // The terminal event carries the same code, kind "java". + let mut last = None; + while let Ok(ev) = events.try_recv() { + if let crate::model::CoreEvent::DownloadProgress(p) = ev { + last = Some(p); + } + } + let last = last.expect("a terminal progress event"); + assert_eq!(last.kind, DownloadKind::Java); + assert_eq!(last.error.unwrap().code, "CHECKSUM_MISMATCH"); + // Nothing left behind in the temp dir. + let leftovers = std::fs::read_dir(tmp.path().join("data/tmp")) + .unwrap() + .count(); + assert_eq!(leftovers, 0); + } +} diff --git a/crates/mineui-core/src/lib.rs b/crates/mineui-core/src/lib.rs index 2b75a44..6a0206c 100644 --- a/crates/mineui-core/src/lib.rs +++ b/crates/mineui-core/src/lib.rs @@ -19,6 +19,7 @@ pub mod hub; pub mod identity; pub mod instance; pub mod java; +pub mod javainstall; pub mod joininfo; pub mod lifecycle; pub mod logs; @@ -62,6 +63,11 @@ pub struct Paths { /// Shared application core. One instance per app, wrapped in `Arc`. pub struct Core { pub paths: Paths, + /// The app-level data root the shell injected (`app_data_dir`): equal to + /// `paths.data_dir` for the `default` profile, the parent of + /// `servers//` for the others. App-wide state lives here, e.g. + /// MineUI-managed Java (§3.1, 2.13.0). + app_data_dir: PathBuf, pub http: reqwest::Client, /// Strict variant of `http` for user-supplied download URLs: its /// redirect policy blocks hops onto private/loopback hosts (§6.3). @@ -91,7 +97,19 @@ impl Core { /// `/settings.json`. Must be called on a Tokio runtime. pub async fn init(config_dir: PathBuf, data_dir: PathBuf) -> Result> { let loaded = settings::load(&config_dir, &data_dir).await?; - Ok(Self::build(config_dir, data_dir, loaded)) + let app_data_dir = data_dir.clone(); + Ok(Self::build(config_dir, data_dir, app_data_dir, loaded)) + } + + /// `init` for a server profile whose dirs sit under the app roots + /// (§2.5): `app_data_dir` is the shell-injected data root. + pub async fn init_in_app( + config_dir: PathBuf, + data_dir: PathBuf, + app_data_dir: PathBuf, + ) -> Result> { + let loaded = settings::load(&config_dir, &data_dir).await?; + Ok(Self::build(config_dir, data_dir, app_data_dir, loaded)) } /// Test/embedding constructor: skips disk I/O for settings. @@ -100,10 +118,16 @@ impl Core { data_dir: PathBuf, settings: Settings, ) -> Arc { - Self::build(config_dir, data_dir, settings) + let app_data_dir = data_dir.clone(); + Self::build(config_dir, data_dir, app_data_dir, settings) } - fn build(config_dir: PathBuf, data_dir: PathBuf, loaded: Settings) -> Arc { + fn build( + config_dir: PathBuf, + data_dir: PathBuf, + app_data_dir: PathBuf, + loaded: Settings, + ) -> Arc { let (events, _keepalive) = tokio::sync::broadcast::channel::(512); let logs = logs::Manager::new(events.clone()); let supervisor = supervisor::Supervisor::new(events.clone(), logs.sink()); @@ -112,6 +136,7 @@ impl Core { config_dir, data_dir, }, + app_data_dir, http: download::build_client(), http_public: download::build_public_client(), supervisor, @@ -128,6 +153,11 @@ impl Core { }) } + /// The app-level data root (see the field). + pub fn app_data_dir(&self) -> &std::path::Path { + &self.app_data_dir + } + /// Snapshot of the current settings. pub async fn settings(&self) -> Settings { self.settings.read().await.clone() diff --git a/crates/mineui-core/src/lifecycle.rs b/crates/mineui-core/src/lifecycle.rs index 224ed1c..ed9f50e 100644 --- a/crates/mineui-core/src/lifecycle.rs +++ b/crates/mineui-core/src/lifecycle.rs @@ -187,8 +187,10 @@ async fn start_inner(core: &crate::Core) -> Result<()> { "accept the Minecraft EULA in settings before starting".into(), )); } + let managed_root = crate::javainstall::managed_root(core); let java = crate::java::check( settings.simple.java_path.as_deref(), + Some(&managed_root), instance.required_java_major, ) .await?; diff --git a/crates/mineui-core/src/mod_archive.rs b/crates/mineui-core/src/mod_archive.rs index 76c742e..cedb256 100644 --- a/crates/mineui-core/src/mod_archive.rs +++ b/crates/mineui-core/src/mod_archive.rs @@ -304,6 +304,8 @@ async fn acquire( download_id: download_id.clone(), max_bytes: Some(ARCHIVE_MAX_BYTES), expected_sha1: None, + expected_sha256: None, + client: None, allow_private_hosts: allow_private, }; let result = crate::download::to_temp_file(core, &request).await?; diff --git a/crates/mineui-core/src/model.rs b/crates/mineui-core/src/model.rs index 40387dd..e483383 100644 --- a/crates/mineui-core/src/model.rs +++ b/crates/mineui-core/src/model.rs @@ -31,6 +31,8 @@ pub struct JavaCheck { pub major_version: Option, pub required_major: Option, pub compatible: Option, + /// 2.13.0: the Java found lies in MineUI's managed folder (§3.1). + pub managed: bool, } /* ---------- §3.2 server state / status ---------- */ @@ -487,6 +489,8 @@ pub struct ServerStateEvent { pub enum DownloadKind { ServerJar, Mod, + /// 2.13.0: `install_java` (§4.3). + Java, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -855,6 +859,10 @@ mod tests { serde_json::to_string(&DownloadKind::ServerJar).unwrap(), "\"server-jar\"" ); + assert_eq!( + serde_json::to_string(&DownloadKind::Java).unwrap(), + "\"java\"" + ); } #[test] diff --git a/crates/mineui-core/src/mods.rs b/crates/mineui-core/src/mods.rs index 838a2a9..6960c3d 100644 --- a/crates/mineui-core/src/mods.rs +++ b/crates/mineui-core/src/mods.rs @@ -270,6 +270,8 @@ async fn download_inner( download_id: download_id.clone(), max_bytes: Some(MOD_MAX_BYTES), expected_sha1: None, + expected_sha256: None, + client: None, allow_private_hosts: allow_private, }; let result = crate::download::to_temp_file(core, &request).await?; diff --git a/crates/mineui-core/src/mojang.rs b/crates/mineui-core/src/mojang.rs index 26f1974..3603ff0 100644 --- a/crates/mineui-core/src/mojang.rs +++ b/crates/mineui-core/src/mojang.rs @@ -174,6 +174,27 @@ pub async fn version_detail(core: &crate::Core, version_id: &str) -> Result Option { + let version = version.trim(); + let id = if version.is_empty() || version.eq_ignore_ascii_case("LATEST") { + list_versions(core, false) + .await + .ok()? + .into_iter() + .find(|v| v.latest)? + .id + } else { + version.to_string() + }; + let detail = version_detail(core, &id).await.ok()?; + detail.java_version.map(|j| j.major_version) +} + /// `releaseTime` of one version from the cached manifest (§3.6 /// `change_instance_version` step 3). `None` when no manifest is cached or /// the version is not listed. Call after `version_detail`, which warms it. @@ -203,6 +224,8 @@ pub async fn download_server_jar( download_id: uuid::Uuid::new_v4().to_string(), max_bytes: None, expected_sha1: Some(download.sha1.clone()), + expected_sha256: None, + client: None, // Server-jar URLs come from Mojang's HTTPS manifest and the content // is SHA-1 pinned; still use the strict client - piston-data has no // business redirecting to private hosts. @@ -280,6 +303,77 @@ mod tests { assert_eq!(detail.java_version.unwrap().major_version, 21); } + /// Serves version detail JSON per path from a local socket. + async fn detail_server() -> std::net::SocketAddr { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = listener.accept().await else { + return; + }; + let mut buf = vec![0u8; 2048]; + let n = sock.read(&mut buf).await.unwrap_or(0); + let req = String::from_utf8_lossy(&buf[..n]).to_string(); + let body = if req.starts_with("GET /new ") { + DETAIL_FIXTURE.to_string() + } else if req.starts_with("GET /old ") { + r#"{"id":"1.16.5","javaVersion":{"component":"jre-legacy","majorVersion":8}}"# + .to_string() + } else { + r#"{"id":"a1.0.4"}"#.to_string() + }; + let head = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + let _ = sock.write_all(head.as_bytes()).await; + let _ = sock.write_all(body.as_bytes()).await; + let _ = sock.flush().await; + } + }); + addr + } + + #[tokio::test] + async fn required_java_major_from_detail() { + let addr = detail_server().await; + let tmp = tempfile::tempdir().unwrap(); + let core = crate::Core::init(tmp.path().join("config"), tmp.path().join("data")) + .await + .unwrap(); + let v = |id: &str, path: &str| ManifestVersion { + id: id.into(), + version_type: "release".into(), + url: format!("http://{addr}/{path}"), + release_time: "2026-01-01T00:00:00+00:00".into(), + }; + // A warm cache: no request ever reaches Mojang. + *core.mojang_cache.lock().await = Some(ManifestCache { + fetched_at: Instant::now(), + manifest: VersionManifest { + latest: ManifestLatest { + release: "1.21.6".into(), + snapshot: "1.21.6".into(), + }, + versions: vec![ + v("1.21.6", "new"), + v("1.16.5", "old"), + v("a1.0.4", "ancient"), + ], + }, + }); + assert_eq!(required_java_major(&core, "1.21.6").await, Some(21)); + assert_eq!(required_java_major(&core, "1.16.5").await, Some(8)); + assert_eq!(required_java_major(&core, "LATEST").await, Some(21)); + assert_eq!(required_java_major(&core, "latest").await, Some(21)); + assert_eq!(required_java_major(&core, "").await, Some(21)); + // No javaVersion in the detail, or not in the manifest: null. + assert_eq!(required_java_major(&core, "a1.0.4").await, None); + assert_eq!(required_java_major(&core, "9.9.9").await, None); + } + #[test] fn mc_version_wire_shape() { let v = McVersion { diff --git a/crates/mineui-core/src/provision.rs b/crates/mineui-core/src/provision.rs index f80b62d..ed1c1f7 100644 --- a/crates/mineui-core/src/provision.rs +++ b/crates/mineui-core/src/provision.rs @@ -247,23 +247,6 @@ pub fn image_tag_for_java(major: Option) -> &'static str { } } -/// Java major the version needs, per Mojang's version detail; `None` when -/// it cannot be resolved (offline, or a version Mojang does not list). -async fn required_java_major(core: &crate::Core, version: &str) -> Option { - let id = if version == LATEST { - crate::mojang::list_versions(core, false) - .await - .ok()? - .into_iter() - .find(|v| v.latest)? - .id - } else { - version.to_string() - }; - let detail = crate::mojang::version_detail(core, &id).await.ok()?; - detail.java_version.map(|j| j.major_version) -} - /// The env file body (§3.13 step 7). Every value is either a constant or /// validated to a charset without newlines. pub fn env_file_body(plan: &Plan, memory_mb: u32, rcon_password: &str) -> String { @@ -400,7 +383,7 @@ async fn create_inner(core: &crate::Core, args: &CreateContainerArgs) -> Result< ensure_port_free(game_bind, args.game_port)?; ensure_port_free(Ipv4Addr::LOCALHOST, args.rcon_port)?; - let java_major = required_java_major(core, &plan.version).await; + let java_major = crate::mojang::required_java_major(core, &plan.version).await; if zip.is_some() && matches!(java_major, Some(0..=8)) { // The java8 image carries no CurseForge API key (image docs), and // MineUI does not take one. diff --git a/crates/mineui-core/tests/fixtures/adoptium-jre-21-linux-x64.json b/crates/mineui-core/tests/fixtures/adoptium-jre-21-linux-x64.json new file mode 100644 index 0000000..e087a62 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/adoptium-jre-21-linux-x64.json @@ -0,0 +1,33 @@ +[ + { + "binary": { + "architecture": "x64", + "heap_size": "normal", + "image_type": "jre", + "jvm_impl": "hotspot", + "os": "linux", + "package": { + "checksum": "a535a1df9c6284d9618872984e026ae0352d1f7e9e0605425c0e6114f47351dd", + "checksum_link": "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.13%2B9/OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz.sha256.txt", + "link": "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.13%2B9/OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz", + "name": "OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz", + "size": 52181297 + }, + "project": "jdk", + "scm_ref": "jdk-21.0.13+9_adopt", + "updated_at": "2026-10-22T12:08:16Z" + }, + "release_link": "https://github.com/adoptium/temurin21-binaries/releases/tag/jdk-21.0.13%2B9", + "release_name": "jdk-21.0.13+9", + "vendor": "eclipse", + "version": { + "build": 9, + "major": 21, + "minor": 0, + "openjdk_version": "21.0.13+9-LTS", + "optional": "LTS", + "security": 13, + "semver": "21.0.13+9.0.LTS" + } + } +] diff --git a/crates/mineui-core/tests/live_java.rs b/crates/mineui-core/tests/live_java.rs new file mode 100644 index 0000000..2c1b073 --- /dev/null +++ b/crates/mineui-core/tests/live_java.rs @@ -0,0 +1,158 @@ +//! Live test for `install_java` (contract §3.1, §6.3a, 2.13.0). **Opt-in** - +//! `#[ignore]`; CI never runs it. Needs the network: it downloads the real +//! Temurin JRE 21 for this computer from Adoptium (about 50 MB) into a temp +//! app data dir, which is removed afterwards. +//! +//! ```sh +//! cargo test -p mineui-core --test live_java -- --ignored --nocapture +//! ``` + +use std::collections::HashSet; +use std::sync::Arc; + +use mineui_core::model::{CoreEvent, DownloadKind}; +use mineui_core::Core; + +/// The download ids of every `kind: "java"` progress event seen so far. +fn java_downloads(rx: &mut tokio::sync::broadcast::Receiver) -> HashSet { + let mut ids = HashSet::new(); + loop { + match rx.try_recv() { + Ok(CoreEvent::DownloadProgress(p)) if p.kind == DownloadKind::Java => { + assert!(p.error.is_none(), "download error: {:?}", p.error); + ids.insert(p.download_id); + } + Ok(_) => {} + Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => {} + Err(_) => break, + } + } + ids +} + +async fn profile(app_data: &std::path::Path, config: &std::path::Path, id: &str) -> Arc { + Core::init_in_app( + config.join("servers").join(id), + app_data.join("servers").join(id), + app_data.to_path_buf(), + ) + .await + .unwrap() +} + +#[tokio::test] +#[ignore] +async fn live_install_temurin_21_once_for_every_profile() { + let tmp = tempfile::tempdir().unwrap(); + let app_data = tmp.path().join("data"); + let config = tmp.path().join("config"); + let a = profile(&app_data, &config, "a1b2c3d4").await; + let b = profile(&app_data, &config, "e5f6a7b8").await; + let mut rx_a = a.subscribe_events(); + let mut rx_b = b.subscribe_events(); + + // Two servers ask at once: one download, both get the same Java. + let started = std::time::Instant::now(); + let (ra, rb) = tokio::join!( + mineui_core::javainstall::install(&a, 21), + mineui_core::javainstall::install(&b, 21) + ); + let (ra, rb) = (ra.unwrap(), rb.unwrap()); + eprintln!("installed in {:?}: {ra:?}", started.elapsed()); + let downloads: HashSet = java_downloads(&mut rx_a) + .union(&java_downloads(&mut rx_b)) + .cloned() + .collect(); + assert_eq!(downloads.len(), 1, "exactly one download for two requests"); + + for r in [&ra, &rb] { + assert!(r.found && r.managed, "{r:?}"); + assert_eq!(r.major_version, Some(21)); + assert_eq!(r.required_major, Some(21)); + assert_eq!(r.compatible, Some(true)); + } + assert_eq!(ra.path, rb.path); + let java = std::path::PathBuf::from(ra.path.clone().unwrap()); + assert!( + java.starts_with(app_data.join("java").join("temurin-21-jre")), + "app-wide folder, not a server folder: {}", + java.display() + ); + + // The binary really runs and reports 21. + let out = std::process::Command::new(&java) + .arg("-version") + .output() + .unwrap(); + assert!(out.status.success()); + let text = String::from_utf8_lossy(&out.stderr); + eprintln!("{text}"); + assert!(text.contains("version \"21."), "{text}"); + assert!(text.contains("Temurin"), "{text}"); + + // No temp or aside folders left behind. + let leftovers: Vec<_> = std::fs::read_dir(app_data.join("java")) + .unwrap() + .flatten() + .map(|e| e.file_name().to_string_lossy().to_string()) + .collect(); + assert_eq!(leftovers, vec!["temurin-21-jre".to_string()]); + + // A later call reuses it without downloading again. + let again = mineui_core::javainstall::install(&a, 21).await.unwrap(); + assert_eq!(again.path, ra.path); + assert!(java_downloads(&mut rx_a).is_empty(), "no second download"); + + // java_check on a server finds it too (managed first). + let check = mineui_core::java::check_for(&b, Some(21)).await.unwrap(); + assert_eq!(check.path, ra.path); + assert!(check.managed); + + // Exactly one java.install audit entry, on the profile that downloaded. + let mut audited = 0; + for core in [&a, &b] { + let log = mineui_core::audit::recent(core, Some(50)).await.unwrap(); + for entry in log.entries.iter().filter(|e| e.action == "java.install") { + assert!(entry.ok); + assert_eq!(entry.target.as_deref(), Some("temurin-21-jre")); + let detail = entry.detail.as_deref().unwrap_or(""); + assert!(detail.starts_with("Temurin JRE 21."), "{detail}"); + eprintln!("audit: {detail}"); + audited += 1; + } + } + assert_eq!(audited, 1); +} + +/// `required_java_major` (§3.6) against the real Mojang manifest. +#[tokio::test] +#[ignore] +async fn live_required_java_major_from_mojang() { + let tmp = tempfile::tempdir().unwrap(); + let core = Core::init(tmp.path().join("config"), tmp.path().join("data")) + .await + .unwrap(); + let latest = mineui_core::mojang::list_versions(&core, false) + .await + .unwrap() + .into_iter() + .find(|v| v.latest) + .unwrap(); + let for_latest = mineui_core::mojang::required_java_major(&core, "LATEST").await; + let for_id = mineui_core::mojang::required_java_major(&core, &latest.id).await; + eprintln!("latest release {} needs Java {for_latest:?}", latest.id); + assert_eq!(for_latest, for_id); + assert!(for_latest.is_some_and(|m| m >= 21)); + assert_eq!( + mineui_core::mojang::required_java_major(&core, "1.20.4").await, + Some(17) + ); + assert_eq!( + mineui_core::mojang::required_java_major(&core, "1.16.5").await, + Some(8) + ); + assert_eq!( + mineui_core::mojang::required_java_major(&core, "no-such-version").await, + None + ); +} diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 480f00b..e5636ef 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -59,15 +59,23 @@ pub async fn detect_runtimes( #[tauri::command] pub async fn java_check(hub: HubState<'_>, server_id: Option) -> CmdResult { let core = core_for(&hub, server_id).await?; - let settings = core.settings().await; // Ungated probe: java_check is available in both modes and reads the // instance metadata only when present (§3.1). let instance = mineui_core::instance::probe(&core).await?; - mineui_core::java::check( - settings.simple.java_path.as_deref(), - instance.required_java_major, - ) - .await + mineui_core::java::check_for(&core, instance.required_java_major).await +} + +/// 2.13.0: download Temurin JRE `major` into the app-wide managed folder. +/// `major` arrives as i64 so an out-of-range number reaches core's +/// validation (`INVALID_INPUT`) instead of failing deserialization. +#[tauri::command] +pub async fn install_java( + hub: HubState<'_>, + server_id: Option, + major: i64, +) -> CmdResult { + let core = core_for(&hub, server_id).await?; + mineui_core::javainstall::install(&core, major).await } /* ---------- §3.2 server state / lifecycle / status ---------- */ @@ -523,6 +531,12 @@ pub async fn get_app_info(hub: HubState<'_>) -> CmdResult { Ok(hub.app_info()) } +/// 2.13.0, app-wide (§3.6): the Java major a Minecraft version needs. +#[tauri::command] +pub async fn required_java_major(hub: HubState<'_>, mc_version: String) -> CmdResult> { + Ok(hub.required_java_major(&mc_version).await) +} + #[tauri::command] pub async fn check_for_update(hub: HubState<'_>) -> CmdResult { hub.check_for_update().await diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9daf56a..037e0de 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -107,6 +107,7 @@ pub fn run() { commands::set_settings, commands::detect_runtimes, commands::java_check, + commands::install_java, // §3.2 server state / lifecycle / status commands::get_server_state, commands::start_server, @@ -133,6 +134,7 @@ pub fn run() { commands::delete_instance, commands::instance_status, commands::change_instance_version, + commands::required_java_major, // §3.7 config files commands::list_config_files, commands::read_config_file, From 20e4fdb494679c261c424d1f8dc04c302fa095a4 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 9 Nov 2026 10:30:47 -0600 Subject: [PATCH 04/28] feat(ui): Simple / Advanced view level, plain server-kind labels, What's this? A labelled Simple / Advanced switch in the header (and in App Settings, Appearance) sets how much MineUI shows. It is a view setting only, kept in localStorage (mineui-view-level, default simple), and calls no IPC: the 2.9.0 header toggle was removed because it re-pointed a server between running on this computer and in a container. Simple hides Status, Console and Config (opening one shows a notice with Show Advanced), Scheduled tasks, Network and ports and the Advanced section of Server Settings, and on the Dashboard the metric readings and trend lines, with the live log behind a disclosure. The two server kinds read "On this computer" and "In a container" on screen so the words Simple and Advanced only name the view. The IPC Mode enum is unchanged. What's this?: a glossary of 25 terms written for kids and teens and a Term component (popover, keyboard and touch) used on the settings, status, console, config, players and mods pages. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- app/components/AdvancedOnly.tsx | 55 ++++++++++++ app/components/AppearanceCard.tsx | 7 ++ app/components/Navbar.tsx | 39 ++++++--- app/components/RuntimeInstallHelp.tsx | 3 +- app/components/ServerProvider.tsx | 2 +- app/components/ServersOverview.tsx | 2 +- app/components/Term.tsx | 52 ++++++++++++ app/components/ViewLevelProvider.tsx | 98 +++++++++++++++++++++ app/components/ViewLevelSwitch.tsx | 57 +++++++++++++ app/config/page.tsx | 22 ++++- app/layout.tsx | 21 +++-- app/lib/glossary.ts | 118 ++++++++++++++++++++++++++ app/mods/page.tsx | 9 +- app/page.tsx | 67 +++++++++++---- app/players/page.tsx | 14 ++- app/rcon/page.tsx | 20 ++++- app/settings/page.tsx | 86 ++++++++++++++----- app/status/page.tsx | 34 ++++++-- 18 files changed, 624 insertions(+), 82 deletions(-) create mode 100644 app/components/AdvancedOnly.tsx create mode 100644 app/components/Term.tsx create mode 100644 app/components/ViewLevelProvider.tsx create mode 100644 app/components/ViewLevelSwitch.tsx create mode 100644 app/lib/glossary.ts diff --git a/app/components/AdvancedOnly.tsx b/app/components/AdvancedOnly.tsx new file mode 100644 index 0000000..c76477c --- /dev/null +++ b/app/components/AdvancedOnly.tsx @@ -0,0 +1,55 @@ +"use client"; + +// Guard for pages that only exist in Advanced view (Status, Console, +// Config). In Simple view the page is not rendered at all - so its own +// hooks never run - and a short notice offers the way in instead. +import { Button, Card } from "@heroui/react"; +import { Eye } from "lucide-react"; +import { useViewLevel } from "@/app/components/ViewLevelProvider"; +import { useUISound } from "@/app/hooks/useUISound"; + +export default function AdvancedOnly({ + name, + what, + children, +}: { + /** Page name, e.g. "Console". */ + name: string; + /** One sentence: what the page is for. */ + what: string; + children: React.ReactNode; +}) { + const { level, setLevel } = useViewLevel(); + const { play } = useUISound(); + + if (level === "advanced") return <>{children}; + + return ( +
+ + +
+ + {name} is in Advanced view +
+ {what} +
+ +

+ You do not need it to run a server with friends. Switching only + changes what MineUI shows. Your servers stay exactly as they are. +

+ +
+
+
+ ); +} diff --git a/app/components/AppearanceCard.tsx b/app/components/AppearanceCard.tsx index 56f65db..f1b431d 100644 --- a/app/components/AppearanceCard.tsx +++ b/app/components/AppearanceCard.tsx @@ -18,6 +18,7 @@ import { Label, } from "@heroui/react"; import { Segment } from "@heroui-pro/react"; +import ViewLevelSwitch from "@/app/components/ViewLevelSwitch"; import ChoiceCards from "@/app/components/ChoiceCards"; import { firstKey } from "@/app/lib/keys"; import { useUISound } from "@/app/hooks/useUISound"; @@ -76,6 +77,12 @@ export default function AppearanceCard() { + + +

+ Simple shows what you need to run a server with friends. Advanced + shows everything. It does not change any server. +

level === "advanced" || !item.advancedOnly, + ); const priorityItems = navItems.slice(0, PRIORITY_COUNT); const overflowItems = navItems.slice(PRIORITY_COUNT); // T4 (640-699px) folds ALL eight items into "More"; T3 (700-899px) folds @@ -396,7 +403,7 @@ export default function Navbar() { - + {moreHasActive && ( @@ -414,9 +421,13 @@ export default function Navbar() { {/* Controls zone - fixed, shrink-0 (§9.1). */}
- {/* This server: which one the pages show (§9.1). How it is run - (Simple / Advanced) is changed in Server Settings only - a - one-click header toggle made a server look deleted. */} + {/* View level: how much MineUI shows. A view setting only - it + never touches a server (the 2.9.0 header toggle did, and made + a server look deleted). How a server is run is changed in + Server Settings only. */} + + + {/* This server: which one the pages show (§9.1). */} {/* The app: sound, app-wide settings, Ko-fi. */} diff --git a/app/components/RuntimeInstallHelp.tsx b/app/components/RuntimeInstallHelp.tsx index bff426c..f68e8ff 100644 --- a/app/components/RuntimeInstallHelp.tsx +++ b/app/components/RuntimeInstallHelp.tsx @@ -213,7 +213,8 @@ export default function RuntimeInstallHelp({ onRecheck, checking = false }: Runt launcher can have a shorter PATH than your terminal. Put the full path to podman or{" "} docker in this server's Settings → - Advanced → Runtime binary override, save, then check again. + Advanced (in Advanced view) → Runtime binary override, save, then + check again.
- {isOpen ? "Open" : entry?.mode === "simple" ? "Simple" : "Advanced"} + {isOpen ? "Open" : entry?.mode === "simple" ? "On this computer" : "In a container"} diff --git a/app/components/Term.tsx b/app/components/Term.tsx new file mode 100644 index 0000000..9d0dfca --- /dev/null +++ b/app/components/Term.tsx @@ -0,0 +1,52 @@ +"use client"; + +// A word with a "What's this?" explanation. Click, tap, Enter or Space opens +// a small popover; Escape closes it. Tokens only, so it follows every style +// and light/dark. +import { Popover } from "@heroui/react"; +import { Pressable } from "react-aria-components"; +import { GLOSSARY, type GlossaryTerm } from "@/app/lib/glossary"; + +export default function Term({ + term, + children, +}: { + term: GlossaryTerm; + /** What to show in the text; defaults to the term itself. */ + children?: React.ReactNode; +}) { + const entry = GLOSSARY[term]; + return ( + + {/* A , not Popover.Trigger: that renders a
, which is not + allowed inside the

most Terms sit in. Pressable gives the span + the same press handling (click, tap, Enter, Space). */} + + + {children ?? term} + + ? + + + + + + + {entry.title} + +

{entry.body}

+ + + + ); +} diff --git a/app/components/ViewLevelProvider.tsx b/app/components/ViewLevelProvider.tsx new file mode 100644 index 0000000..d249948 --- /dev/null +++ b/app/components/ViewLevelProvider.tsx @@ -0,0 +1,98 @@ +"use client"; + +// App-wide view level: "simple" shows what you need to run a server with +// friends, "advanced" shows everything. This is a VIEW setting only - it is +// kept in localStorage on this machine and never calls any IPC, never +// changes a server or a setting. (The 2.9.0 header toggle switched a server +// between "On this computer" and "In a container" and looked like deleting +// it; the server's run kind still lives in Server Settings > Advanced.) +import { + createContext, + useCallback, + useContext, + useMemo, + useSyncExternalStore, +} from "react"; + +export type ViewLevel = "simple" | "advanced"; + +export const VIEW_LEVEL_KEY = "mineui-view-level"; +export const DEFAULT_VIEW_LEVEL: ViewLevel = "simple"; + +export const VIEW_LEVELS: { id: ViewLevel; label: string }[] = [ + { id: "simple", label: "Simple" }, + { id: "advanced", label: "Advanced" }, +]; + +export const VIEW_LEVEL_HINT = + "Simple shows what you need to run a server with friends. Advanced shows everything."; + +const isLevel = (value: unknown): value is ViewLevel => + value === "simple" || value === "advanced"; + +let cached: ViewLevel | undefined; +const listeners = new Set<() => void>(); + +function readStored(): ViewLevel { + if (cached !== undefined) return cached; + let level: ViewLevel = DEFAULT_VIEW_LEVEL; + try { + const stored = window.localStorage.getItem(VIEW_LEVEL_KEY); + if (isLevel(stored)) level = stored; + } catch { + // No storage (private window, blocked): the default holds. + } + cached = level; + return level; +} + +function writeStored(level: ViewLevel) { + cached = level; + try { + window.localStorage.setItem(VIEW_LEVEL_KEY, level); + } catch { + // Not remembered, still applied for this session. + } + listeners.forEach((listener) => listener()); +} + +function subscribe(callback: () => void) { + listeners.add(callback); + return () => { + listeners.delete(callback); + }; +} + +interface ViewLevelContextValue { + level: ViewLevel; + setLevel: (level: ViewLevel) => void; +} + +const ViewLevelContext = createContext(null); + +export default function ViewLevelProvider({ + children, +}: { + children: React.ReactNode; +}) { + const level = useSyncExternalStore( + subscribe, + readStored, + () => DEFAULT_VIEW_LEVEL, + ); + const setLevel = useCallback((next: ViewLevel) => writeStored(next), []); + const value = useMemo(() => ({ level, setLevel }), [level, setLevel]); + return ( + + {children} + + ); +} + +export function useViewLevel(): ViewLevelContextValue { + const ctx = useContext(ViewLevelContext); + if (!ctx) { + throw new Error("useViewLevel() must be used within a "); + } + return ctx; +} diff --git a/app/components/ViewLevelSwitch.tsx b/app/components/ViewLevelSwitch.tsx new file mode 100644 index 0000000..b9a5531 --- /dev/null +++ b/app/components/ViewLevelSwitch.tsx @@ -0,0 +1,57 @@ +"use client"; + +// The Simple / Advanced view switch (header and App Settings). View level +// only: it changes what MineUI shows, never a server or a setting. +import { Segment } from "@heroui-pro/react"; +import { Tooltip } from "@heroui/react"; +import { firstKey } from "@/app/lib/keys"; +import { useUISound } from "@/app/hooks/useUISound"; +import { + VIEW_LEVELS, + VIEW_LEVEL_HINT, + useViewLevel, + type ViewLevel, +} from "@/app/components/ViewLevelProvider"; + +export default function ViewLevelSwitch({ + withTooltip = false, +}: { + withTooltip?: boolean; +}) { + const { level, setLevel } = useViewLevel(); + const { play } = useUISound(); + + const segment = ( + { + const next = firstKey(key) as ViewLevel | null; + if (!next || next === level) return; + play(next === "advanced" ? "toggle_on" : "toggle_off"); + setLevel(next); + }} + > + {VIEW_LEVELS.map((option) => ( + play("hover")} + > + {option.label} + + ))} + + ); + + if (!withTooltip) return segment; + return ( + + {segment} + + {VIEW_LEVEL_HINT} + + + ); +} diff --git a/app/config/page.tsx b/app/config/page.tsx index df3f37d..44ed37c 100644 --- a/app/config/page.tsx +++ b/app/config/page.tsx @@ -1,5 +1,9 @@ "use client"; +import Term from "@/app/components/Term"; + +import AdvancedOnly from "@/app/components/AdvancedOnly"; + import { useCallback, useEffect, useRef, useState } from "react"; import { motion } from "motion/react"; import { FileCode2 } from "lucide-react"; @@ -25,7 +29,7 @@ import { // Contract §3.7: config paths are now relative, forward-slash // ("server.properties", "config/foo.toml") - display them as-is. -export default function ConfigPage() { +function ConfigPageInner() { const { containerMotion, cardMotion } = usePageMotion(); const [files, setFiles] = useState([]); const [loading, setLoading] = useState(true); @@ -167,6 +171,11 @@ export default function ConfigPage() { variants={containerMotion} > +

+ Edit the server's settings files. Start with{" "} + server.properties: game mode, + difficulty and how many players fit. +

); } + +export default function ConfigPage() { + return ( + + + + ); +} diff --git a/app/layout.tsx b/app/layout.tsx index fd3dacb..44afcca 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -22,6 +22,7 @@ import "./globals.css"; import Navbar from "@/app/components/Navbar"; import ModeProvider, { PageBoundary } from "@/app/components/ModeProvider"; import ServerProvider from "@/app/components/ServerProvider"; +import ViewLevelProvider from "@/app/components/ViewLevelProvider"; import PidsControllerHelp from "@/app/components/PidsControllerHelp"; export const metadata: Metadata = { @@ -50,16 +51,18 @@ export default function RootLayout({ every component needing its own useReducedMotion() branch. */} {/* Server profile (which server is open) wraps mode (that - server's Simple/Advanced). The header stays mounted across a + server's run kind). The header stays mounted across a server switch; only the page is remounted (PageBoundary). */} - - - - {children} - - - - + + + + + {children} + + + + + diff --git a/app/lib/glossary.ts b/app/lib/glossary.ts new file mode 100644 index 0000000..914cfe7 --- /dev/null +++ b/app/lib/glossary.ts @@ -0,0 +1,118 @@ +// "What's this?" explanations for the words a new player has never seen. +// Written for kids and teens: short sentences, "you", no networking jargon +// where it can be avoided. One map so the same word says the same thing on +// every screen. Rendered by app/components/Term.tsx. + +export interface GlossaryEntry { + title: string; + body: string; +} + +export const GLOSSARY = { + Vanilla: { + title: "Vanilla", + body: "The normal Minecraft server, exactly as Mojang makes it. No mods and no plugins. Everyone can join with plain Minecraft.", + }, + Paper: { + title: "Paper", + body: "A faster version of the Minecraft server. It runs plugins, which add things like home commands. Players still join with plain Minecraft.", + }, + Purpur: { + title: "Purpur", + body: "Paper with extra settings you can change. It runs plugins too. Players still join with plain Minecraft.", + }, + Fabric: { + title: "Fabric", + body: "A light way to run mods. Pick it when the mods you want say they need Fabric. Your friends need the same mods and Fabric to join.", + }, + Quilt: { + title: "Quilt", + body: "A mod loader that works with most Fabric mods. Pick it only if a mod asks for Quilt.", + }, + Forge: { + title: "Forge", + body: "The oldest and biggest way to run mods. Many big modpacks use it. Your friends need the same mods and Forge to join.", + }, + NeoForge: { + title: "NeoForge", + body: "The newer version of Forge. Newer mods and modpacks use it. Your friends need the same mods and NeoForge to join.", + }, + "mod loader": { + title: "Mod loader", + body: "A helper that lets Minecraft load mods. Fabric, Quilt, Forge and NeoForge are mod loaders. A mod only works with the loader it was made for.", + }, + mod: { + title: "Mod", + body: "A file that changes the game itself, like new blocks, creatures or machines. Your friends usually need the same mods on their own computer to join.", + }, + plugin: { + title: "Plugin", + body: "A file that adds features to the server, like home commands or protection. It only runs on the server, so your friends do not install anything.", + }, + modpack: { + title: "Modpack", + body: "A ready-made bundle of mods that work well together. Pick one and MineUI sets the whole thing up for you.", + }, + RCON: { + title: "RCON", + body: "A way to send commands to the server from outside the game. MineUI uses it for the Console and to read who is online.", + }, + TPS: { + title: "TPS", + body: "How many times per second the server updates the game. 20 is perfect. If it drops lower, the game feels laggy.", + }, + MSPT: { + title: "MSPT", + body: "How many milliseconds the server needs for one update. Lower is better. If it goes over 50, the server can not keep up.", + }, + whitelist: { + title: "Whitelist", + body: "A list of the only people allowed in. If it is on, anyone not on the list can not join, even if they know where your server is.", + }, + "op / admin": { + title: "Op (admin)", + body: "A player who can use powerful commands, like changing the weather or banning someone. Only give it to people you trust.", + }, + EULA: { + title: "EULA", + body: "Mojang's rules for running a server. Minecraft will not start a server until you say you agree.", + }, + container: { + title: "Container", + body: "A sealed box on your computer where the server runs on its own. It keeps the server away from your other files, and it is easy to move or reset.", + }, + Podman: { + title: "Podman", + body: "A free program that runs containers. MineUI uses it to run your server in a box. You install it once.", + }, + Docker: { + title: "Docker", + body: "A popular program that runs containers. MineUI can use it instead of Podman. You install it once.", + }, + port: { + title: "Port", + body: "A numbered door into your computer. The Minecraft server listens at one door, usually 25565. Your friends knock on that door to join.", + }, + Java: { + title: "Java", + body: "The program Minecraft servers run on. If your computer has no Java, the server can not start.", + }, + "server.properties": { + title: "server.properties", + body: "The file with the server's main settings, like the game mode, difficulty and how many players fit. MineUI can edit it for you.", + }, + backup: { + title: "Backup", + body: "A saved copy of your world. If something breaks or gets blown up, you can go back to the copy.", + }, + world: { + title: "World", + body: "Everything you built and explored. It is saved in a folder on the server.", + }, + server: { + title: "Server", + body: "A copy of Minecraft that stays running so your friends can join it. When the server is off, nobody can play on it.", + }, +} as const satisfies Record; + +export type GlossaryTerm = keyof typeof GLOSSARY; diff --git a/app/mods/page.tsx b/app/mods/page.tsx index c12713f..79091f8 100644 --- a/app/mods/page.tsx +++ b/app/mods/page.tsx @@ -35,6 +35,7 @@ import { SkeletonCard } from "@/app/components/Skeleton"; import { useUISound } from "@/app/hooks/useUISound"; import { useMode } from "@/app/components/ModeProvider"; import { usePageMotion } from "@/app/lib/motion"; +import Term from "@/app/components/Term"; import { deleteMod, listMods, @@ -241,9 +242,11 @@ export default function ModsPage() { - Simple mode runs a vanilla server, which does not load mods or - plugins. Files you manage here are kept in the instance folder - and picked up if you switch to a modded setup later. + A server On this computer runs{" "} + vanilla Minecraft, which does not load{" "} + mods or plugins. + Files you manage here are kept in the server folder and picked up + if you run a modded server in a container later. diff --git a/app/page.tsx b/app/page.tsx index f7ffe4d..5ab5c9b 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -24,6 +24,7 @@ import { KPI } from "@heroui-pro/react/kpi"; import { useUISound } from "@/app/hooks/useUISound"; import { reportLifecycleError } from "@/app/components/PidsControllerHelp"; import { useMode } from "@/app/components/ModeProvider"; +import { useViewLevel } from "@/app/components/ViewLevelProvider"; import { SkeletonCard } from "@/app/components/Skeleton"; import CreateContainerFlow from "@/app/components/CreateContainerFlow"; import CreateServerFlow from "@/app/components/CreateServerFlow"; @@ -140,6 +141,12 @@ export default function Home() { // CreateServerFlow's default). const { mode, loading: modeLoading } = useMode(); const { active: activeServer, activeId } = useServers(); + // View level: Simple leaves out the numbers, the trend line and the live + // log (kept one click away). Display only - nothing here changes a server. + const { level } = useViewLevel(); + const expertView = level === "advanced"; + const [logOpen, setLogOpen] = useState(false); + const logVisible = expertView || logOpen; const serverOnline = status?.online ?? false; const playerCount = status?.players.online ?? 0; @@ -278,7 +285,7 @@ export default function Home() { if (logsRef.current) { logsRef.current.scrollTop = logsRef.current.scrollHeight; } - }, [logLines]); + }, [logLines, logVisible]); // What each action says when the *request* went through - which for Start // and Restart is not yet "the server is up". @@ -377,7 +384,7 @@ export default function Home() { Podman nor Docker on this computer. Your other servers are unaffected. If you would rather not install anything, a plain Minecraft server needs no containers: switch how this server - is run under Advanced in its settings. + is run in its settings (in Advanced view). @@ -491,7 +498,7 @@ export default function Home() {
- {isSimple ? "Simple mode" : "Advanced mode"} + {isSimple ? "On this computer" : "In a container"} {!needsOnboarding && ( <> @@ -575,12 +582,31 @@ export default function Home() { only ever mounted at first paint or after a full-page setLoading(true) remount) - must drive its own enter animation per the same fix as commit 1090c51. */} + {!expertView && ( + + + + )} + {logVisible && ( - +
@@ -625,6 +651,7 @@ export default function Home() { + )} {/* Same late-mount rule as the Server Logs section above - this stagger container itself must re-fire its entrance so its @@ -653,17 +680,21 @@ export default function Home() { {condition === "online" && ( <>
Version: {status?.version ?? "unknown"}
-
MOTD: {status?.motd ?? "-"}
-
- Ping: {status?.pingMs != null ? `${status.pingMs}ms` : "-"} -
+ {expertView && ( + <> +
MOTD: {status?.motd ?? "-"}
+
+ Ping: {status?.pingMs != null ? `${status.pingMs}ms` : "-"} +
+ + )} )} {condition === "warming" && (

The server is running but not taking players yet. The first start of a modded server or modpack can take several minutes - - watch the log above; it is ready when a line says{" "} + watch the server log above; it is ready when a line says{" "} Done.

)} @@ -678,7 +709,7 @@ export default function Home() { )} {condition === "crashed" && (

- The server stopped unexpectedly. The last lines of the log + The server stopped unexpectedly. The last lines of the server log above usually say why; Start tries again.

)} @@ -737,7 +768,7 @@ export default function Home() { Players - {playerDelta !== null && ( + {expertView && playerDelta !== null && ( 0 ? "up" : playerDelta < 0 ? "down" : "neutral"} @@ -758,12 +789,14 @@ export default function Home() { )} -
- -
+ {expertView && ( +
+ +
+ )}
{playerCount === 0 ? ( diff --git a/app/players/page.tsx b/app/players/page.tsx index 310fa58..92b49d6 100644 --- a/app/players/page.tsx +++ b/app/players/page.tsx @@ -1,5 +1,7 @@ "use client"; +import Term from "@/app/components/Term"; + import { useEffect, useMemo, useState } from "react"; import { motion } from "motion/react"; import { @@ -344,10 +346,14 @@ export default function PlayersPage() {
Players

- Whitelist: only - whitelisted players can join when the whitelist is on.{" "} - Admin (op): can run any - command, including stopping the server. + + Whitelist + + : only whitelisted players can join when the whitelist is on.{" "} + + Admin (op) + + : can run any command, including stopping the server.

diff --git a/app/rcon/page.tsx b/app/rcon/page.tsx index 941db62..a55c9ae 100644 --- a/app/rcon/page.tsx +++ b/app/rcon/page.tsx @@ -1,5 +1,9 @@ "use client"; +import Term from "@/app/components/Term"; + +import AdvancedOnly from "@/app/components/AdvancedOnly"; + import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import Link from "next/link"; import { motion } from "motion/react"; @@ -26,7 +30,7 @@ const PRESETS: { label: string; command: string; needsArgument?: boolean }[] = [ const firstWord = (value: string) => value.trim().split(/\s+/)[0]?.toLowerCase() ?? ""; -export default function ConsolePage() { +function ConsolePageInner() { const { containerMotion, cardMotion } = usePageMotion(); const { activeId } = useServers(); const { play } = useUISound(); @@ -173,7 +177,8 @@ export default function ConsolePage() {

Send a command to the running server - the same as typing it in the server's - own console. No leading slash. + own console. No leading slash. MineUI sends it through{" "} + RCON, so the server must be running.

{allowlist && (
@@ -301,3 +306,14 @@ export default function ConsolePage() {
); } + +export default function ConsolePage() { + return ( + + + + ); +} diff --git a/app/settings/page.tsx b/app/settings/page.tsx index e97b72c..ab8e62c 100644 --- a/app/settings/page.tsx +++ b/app/settings/page.tsx @@ -51,6 +51,8 @@ import { identityLine, phaseText, useServers } from "@/app/components/ServerProv import { setLeaveGuard } from "@/app/lib/leaveGuard"; import { pickFile, pickFolder } from "@/app/lib/dialog"; import { usePageMotion } from "@/app/lib/motion"; +import Term from "@/app/components/Term"; +import { useViewLevel } from "@/app/components/ViewLevelProvider"; import { deleteInstance, detectRuntimes, @@ -173,14 +175,14 @@ const describeSchedule = (schedule: Schedule): string => { const MODE_OPTIONS = [ { id: "simple", - title: "Simple", + title: "On this computer", description: - "MineUI downloads and runs a plain (vanilla) Minecraft server on this computer. Nothing else to install.", + "MineUI downloads and runs a plain (vanilla) Minecraft server on this computer. You need Java, and nothing else.", icon: Sparkles, }, { id: "advanced", - title: "Advanced", + title: "In a container", description: "Runs in a container (Podman or Docker). MineUI can create it for you - with Fabric, Forge, Paper or a modpack - or use one you already have.", icon: Container, @@ -223,8 +225,8 @@ export default function SettingsPage() { const serverBusy = phase === "running" || phase === "starting" || phase === "stopping"; const { play } = useUISound(); // Shared app-wide mode (app/components/ModeProvider.tsx). Mode switching - // lives here now, not in the draft/Save flow below - clicking Simple/ - // Advanced persists instantly through the same path the navbar toggle + // lives here now, not in the draft/Save flow below - clicking On this + // computer / In a container persists instantly through the same path the navbar toggle // uses, so this section and the navbar always agree. const { mode, @@ -359,6 +361,9 @@ export default function SettingsPage() { }; const isSimpleNow = mode === "simple"; + // View level (not the server kind): Simple view leaves out the expert cards. + const { level, setLevel } = useViewLevel(); + const expertView = level === "advanced"; const dirty = draft !== null && baseline !== null && snapshotOf(draft, allowlistText) !== baseline; const problems = useMemo( @@ -572,9 +577,18 @@ export default function SettingsPage() { This server
- {isSimple - ? "A plain Minecraft server that MineUI runs on this computer." - : "A server in a container (Podman or Docker) that MineUI controls."} + {isSimple ? ( + <> + A plain Minecraft server that MineUI runs on + this computer. + + ) : ( + <> + A server in a container ( + Podman or Docker) + that MineUI controls. + + )} @@ -705,9 +719,10 @@ export default function SettingsPage() { - {/* 1b. Network and ports - Advanced only; has its own Apply because - changing ports rebuilds the container (not part of the draft). */} - {!isSimple && ( + {/* 1b. Network and ports - containers only, Advanced view only; has + its own Apply because changing ports rebuilds the container (not + part of the draft). */} + {!isSimple && expertView && ( @@ -783,8 +798,9 @@ export default function SettingsPage() { onFocus={() => play("hover")} /> - The port players connect to (Minecraft's default is 25565). If you - forward a port on your router, keep the two the same. + The port players connect to (Minecraft's + default is 25565). If you forward a port on your router, keep the two the + same. @@ -792,7 +808,8 @@ export default function SettingsPage() { )} - {/* 3. Scheduled tasks (contract §3.10) */} + {/* 3. Scheduled tasks (contract §3.10) - Advanced view only. */} + {expertView && ( @@ -1094,6 +1111,7 @@ export default function SettingsPage() { + )} {/* 4. Backups (contract §3.8) */} @@ -1154,14 +1172,16 @@ export default function SettingsPage() { A full folder path on this computer - another disk, a USB drive or a network share is the point: backups otherwise live with the server itself. The folder is created if missing; a failed copy is recorded in - the activity log on the Status page. + the activity log (Status page, Advanced view). - {/* 5. Advanced - everything a working server never needs touched. */} + {/* 5. Advanced - everything a working server never needs touched. + Advanced view only. */} + {expertView && (
- The full path to a java program, if - MineUI finds the wrong one or none. + The full path to a java{" "} + program, if MineUI finds the wrong one or none. @@ -1238,8 +1258,9 @@ export default function SettingsPage() { onFocus={() => play("hover")} /> - The local channel MineUI uses to send commands to the server. Change - it only if another program already uses this port. + The local channel (RCON) MineUI uses to send + commands to the server. Change it only if another program already + uses this port.
@@ -1570,6 +1591,7 @@ export default function SettingsPage() { )} + )} {/* 6. Danger zone */} @@ -1620,6 +1642,26 @@ export default function SettingsPage() { + {!expertView && ( + + More settings are in Advanced view + + + )} + {/* One Save for the whole page, visible exactly when there is something to save. */} {dirty && ( diff --git a/app/status/page.tsx b/app/status/page.tsx index f2ba97d..09b05f5 100644 --- a/app/status/page.tsx +++ b/app/status/page.tsx @@ -1,5 +1,9 @@ "use client"; +import Term from "@/app/components/Term"; + +import AdvancedOnly from "@/app/components/AdvancedOnly"; + import { useEffect, useMemo, useState } from "react"; import { motion } from "motion/react"; import { @@ -173,7 +177,7 @@ const AUDIT_PHRASES: Record = { const auditPhrase = (action: string) => AUDIT_PHRASES[action] ?? action; -export default function StatusPage() { +function StatusPageInner() { const { containerMotion, cardMotion } = usePageMotion(); const [status, setStatus] = useState(null); const [metrics, setMetrics] = useState(null); @@ -446,7 +450,9 @@ export default function StatusPage() {
- Game speed (TPS): + + Game speed (TPS): + {tpsDisplay} @@ -458,7 +464,9 @@ export default function StatusPage() {
- Time per tick (MSPT): + + Time per tick (MSPT): + {metrics?.mspt ? `${formatMspt(metrics.mspt.one)} / ${formatMspt(metrics.mspt.five)} / ${formatMspt(metrics.mspt.fifteen)}` @@ -553,7 +561,7 @@ export default function StatusPage() { ) : ( {isSimple - ? "Container network stats are available in Advanced mode." + ? "Network stats are only shown for servers In a container." : "-"} )} @@ -583,7 +591,7 @@ export default function StatusPage() { ) : ( {isSimple - ? "Container block-IO stats are available in Advanced mode." + ? "Disk stats are only shown for servers In a container." : "-"} )} @@ -659,8 +667,9 @@ export default function StatusPage() { items={audit} renderEmptyState={() => (
- Nothing recorded yet. Server control, player actions, - RCON commands, backups and config edits show up here. + Nothing recorded yet. Server control, player actions,{" "} + RCON commands, backups and config edits + show up here.
)} > @@ -696,3 +705,14 @@ export default function StatusPage() {
); } + +export default function StatusPage() { + return ( + + + + ); +} From 673bdb9fa7ddb043c7bf79befff8c7b110149a6f Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Mon, 9 Nov 2026 11:10:26 -0600 Subject: [PATCH 05/28] feat(ui): Start here, Get Java for me, More options, Getting started Start here replaces the empty Dashboard when the only server is not set up yet: two questions (normal Minecraft or with mods; just me, people at home, or friends in other places too), one sentence naming the setup MineUI picks and why, a check of what this computer needs (Java, or Podman / Docker with the install help and Check again), a name and the EULA, then the same create calls and defaults as the existing flows, Start, and the Dashboard with How players join (its internet steps open for friends elsewhere). "I know what I want" opens the existing flows. Get Java for me (install_java with progress) appears in Start here, in the server-on-this-computer flow's requirements step, and on the Dashboard when Start fails with JAVA_NOT_FOUND or JAVA_INCOMPATIBLE, followed by Start again. A Java MineUI downloaded is named as such. The create flows keep type, version, pack and EULA up front; container name, ports, memory, network and extra ports are under a collapsed More options with unchanged defaults, and a problem inside it is named next to Create. Getting started: five steps with live ticks from server state, the audit log, player history and backups, a Show me for each, dismissible per server. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- app/components/CreateContainerFlow.tsx | 341 +++++++------ app/components/CreateServerFlow.tsx | 337 ++++++++----- app/components/GetJavaForMe.tsx | 136 ++++++ app/components/GettingStartedCard.tsx | 238 +++++++++ app/components/JoinInfoCard.tsx | 11 +- app/components/StartHere.tsx | 650 +++++++++++++++++++++++++ app/page.tsx | 137 +++++- app/settings/page.tsx | 6 +- 8 files changed, 1583 insertions(+), 273 deletions(-) create mode 100644 app/components/GetJavaForMe.tsx create mode 100644 app/components/GettingStartedCard.tsx create mode 100644 app/components/StartHere.tsx diff --git a/app/components/CreateContainerFlow.tsx b/app/components/CreateContainerFlow.tsx index 27665d2..802755d 100644 --- a/app/components/CreateContainerFlow.tsx +++ b/app/components/CreateContainerFlow.tsx @@ -38,7 +38,9 @@ import PortsEditor, { portsProblems } from "@/app/components/PortsEditor"; import { exposeConsequence } from "@/app/components/NetworkPortsCard"; import RuntimeInstallHelp from "@/app/components/RuntimeInstallHelp"; import OutLink from "@/app/components/OutLink"; +import Term from "@/app/components/Term"; import { useUISound } from "@/app/hooks/useUISound"; +import type { GlossaryTerm } from "@/app/lib/glossary"; import ChoiceCards from "@/app/components/ChoiceCards"; import { fadeUp } from "@/app/lib/motion"; import { @@ -53,14 +55,14 @@ import { type Settings, } from "@/app/lib/ipc"; -const LATEST = "LATEST"; -const DEFAULT_CONTAINER_NAME = "minecraft-server"; +export const LATEST = "LATEST"; +export const DEFAULT_CONTAINER_NAME = "minecraft-server"; const MEMORY_MIN = 1024; const MEMORY_MAX = 16384; const MEMORY_STEP = 512; -const MEMORY_DEFAULT = 4096; +export const MEMORY_DEFAULT = 4096; /** Modpacks are heavier than a bare loader. */ -const MEMORY_DEFAULT_MODPACK = 6144; +export const MEMORY_DEFAULT_MODPACK = 6144; /** What the new container runs. */ type Kind = "type" | "modpack"; @@ -80,18 +82,18 @@ const KINDS: { id: Kind; title: string; description: string; icon: LucideIcon }[ }, ]; -const LOADERS: { id: ContainerLoader; label: string; hint: string }[] = [ - { id: "vanilla", label: "Vanilla", hint: "Mojang's own server. No mods or plugins." }, - { id: "paper", label: "Paper", hint: "Plugins (Bukkit/Spigot), tuned for performance." }, - { id: "purpur", label: "Purpur", hint: "Paper with extra gameplay switches." }, - { id: "fabric", label: "Fabric", hint: "Lightweight mod loader for Fabric mods." }, - { id: "quilt", label: "Quilt", hint: "Fabric-compatible mod loader." }, - { id: "forge", label: "Forge", hint: "The classic mod loader; most large modpacks." }, - { id: "neoforge", label: "NeoForge", hint: "Forge's successor, for 1.20.2 and newer." }, +const LOADERS: { id: ContainerLoader; label: string; term: GlossaryTerm; hint: string }[] = [ + { id: "vanilla", label: "Vanilla", term: "Vanilla", hint: "Mojang's own server. No mods or plugins." }, + { id: "paper", label: "Paper", term: "Paper", hint: "Plugins (Bukkit/Spigot), tuned for performance." }, + { id: "purpur", label: "Purpur", term: "Purpur", hint: "Paper with extra gameplay switches." }, + { id: "fabric", label: "Fabric", term: "Fabric", hint: "Lightweight mod loader for Fabric mods." }, + { id: "quilt", label: "Quilt", term: "Quilt", hint: "Fabric-compatible mod loader." }, + { id: "forge", label: "Forge", term: "Forge", hint: "The classic mod loader; most large modpacks." }, + { id: "neoforge", label: "NeoForge", term: "NeoForge", hint: "Forge's successor, for 1.20.2 and newer." }, ]; /** "Fabric survival" → "mc-fabric-survival" (container-name grammar). */ -const containerNameFor = (serverName: string) => { +export const containerNameFor = (serverName: string) => { const slug = serverName .toLowerCase() .replace(/[^a-z0-9]+/g, "-") @@ -137,6 +139,7 @@ export default function CreateContainerFlow({ const [exposeToNetwork, setExposeToNetwork] = useState(true); const [extraPorts, setExtraPorts] = useState([]); const [portsOpen, setPortsOpen] = useState(false); + const [moreOpen, setMoreOpen] = useState(false); const [eulaAccepted, setEulaAccepted] = useState(false); const [creating, setCreating] = useState(false); @@ -208,6 +211,16 @@ export default function CreateContainerFlow({ const workloadReady = kind === "type" || (modpack !== null && version !== "" && version !== LATEST); const portProblems = portsProblems(extraPorts, gamePort, rconPort); + // Problems with fields that live under "More options": named next to the + // Create button too, so a collapsed section never hides why it is disabled. + const moreProblem: string | null = + containerName.trim() === "" + ? "Give the container a name." + : gamePort <= 0 || rconPort <= 0 + ? "Check the ports." + : portProblems.length > 0 + ? `Extra ports: ${portProblems[0]}` + : null; const canCreate = eulaAccepted && portProblems.length === 0 && @@ -266,10 +279,11 @@ export default function CreateContainerFlow({
{serverName} is not set up yet. Pick what it should run and MineUI - creates the server in a container (the widely used{" "} - itzg/minecraft-server image) and - connects to it. Only want plain Minecraft with nothing to install? Add - a Plain Minecraft server in App Settings → Servers instead. + creates the server in a container (the + widely used itzg/minecraft-server{" "} + image) and connects to it. Only want plain Minecraft with nothing to + install? Add a Plain Minecraft server in App Settings → + Servers instead. @@ -324,7 +338,14 @@ export default function CreateContainerFlow({ - {loaderMeta?.hint} + + {loaderMeta && ( + <> + {loaderMeta.label}:{" "} + {loaderMeta.hint} + + )} +
)} @@ -368,124 +389,7 @@ export default function CreateContainerFlow({ {versionHint}
- - - - - -
- - - setGamePort(numberFrom(event))} - /> - - - - setRconPort(numberFrom(event))} - /> - -
- -
- - - Memory - - { - setMemoryTouched(true); - setMemoryMb(value as number); - }} - > - - - - - - - - - JVM heap. 2048 MB suits a small vanilla server; modded servers - usually want 4096 MB or more, large modpacks 6144–8192 MB. - -
- -
- { - play(selected ? "toggle_on" : "toggle_off"); - setExposeToNetwork(selected); - }} - > - - - - - - - - - {exposeConsequence(exposeToNetwork, gamePort)}{" "} - RCON - the channel MineUI itself uses to send commands - always stays - on this computer, with a password MineUI generates. - - - { - play(open ? "toggle_on" : "toggle_off"); - setPortsOpen(open); - }} - > - - - Extra ports for mods - {extraPorts.length > 0 && ` (${extraPorts.length})`} - - - - - - - - - - - - +
+
+ { + play(open ? "toggle_on" : "toggle_off"); + setMoreOpen(open); + }} + > + + + More options + {moreProblem !== null && ( + (needs a look) + )} + + + + + + + +
+ + + + + +
+ + + setGamePort(numberFrom(event))} + /> + + + + setRconPort(numberFrom(event))} + /> + +
+

+ The game port is the one players connect to. + The RCON port is only for MineUI. +

+
+ + + Memory + + { + setMemoryTouched(true); + setMemoryMb(value as number); + }} + > + + + + + + + + + JVM heap. 2048 MB suits a small vanilla server; modded servers + usually want 4096 MB or more, large modpacks 6144–8192 MB. + +
+ +
+ { + play(selected ? "toggle_on" : "toggle_off"); + setExposeToNetwork(selected); + }} + > + + + + + + + + + {exposeConsequence(exposeToNetwork, gamePort)}{" "} + RCON (the channel MineUI itself uses to send + commands) always stays on this computer, with a password MineUI + generates. + + + { + play(open ? "toggle_on" : "toggle_off"); + setPortsOpen(open); + }} + > + + + Extra ports for mods + {extraPorts.length > 0 && ` (${extraPorts.length})`} + + + + + + + + + + + +
+
+
+
+
+
+ {creating && (
@@ -551,13 +608,11 @@ export default function CreateContainerFlow({ ? kind === "modpack" && modpack === null ? "Pick a modpack." : "Pick the Minecraft version." - : containerName.trim() === "" - ? "Give the container a name." + : moreProblem !== null + ? `${moreProblem} (in More options)` : !eulaAccepted ? "Accept the EULA to continue." - : portProblems.length > 0 - ? `Extra ports: ${portProblems[0]}` - : "Check the ports."} + : "Check the options."} )}
- MineUI downloads the official (plain, “vanilla”) server for the version - you pick and runs it on this computer. Nothing else to install. Want - mods, plugins or a modpack instead? Add a Modded or modpack - server in App Settings → Servers. + MineUI downloads the official (plain,{" "} + vanilla) server for the version you pick + and runs it on this computer. If your computer has no{" "} + Java, MineUI can get it for you. Want mods, + plugins or a modpack instead? Add a{" "} + Modded or modpack server in App Settings → Servers. @@ -201,95 +236,117 @@ export default function CreateServerFlow({ {step === 0 && ( -
-
- - Minecraft version - - +
+
+
+ + Minecraft version + + +
+
- + + + + + + + + + How much of this computer's RAM the server may use. 2048 MB is a + good default for a small server. + +
+ + +
)} {step === 1 && ( -
- - - Memory - - setMemoryMb(value as number)} - > - - - - - - - - - How much of this computer's RAM the server may use. 2048 MB is a - good default for a small server. - -
- )} - - {step === 2 && (
- Java + Java
)} - {step === 3 && ( + {step === 2 && (
@@ -381,7 +478,11 @@ export default function CreateServerFlow({
Java - {java?.found ? `${java.version ?? "?"} found` : "not found"} + {java?.found + ? java.managed + ? `MineUI's own Java ${java.majorVersion ?? java.version ?? "?"}` + : `${java.version ?? "?"} found` + : "not found"}
diff --git a/app/components/GetJavaForMe.tsx b/app/components/GetJavaForMe.tsx new file mode 100644 index 0000000..cbd5779 --- /dev/null +++ b/app/components/GetJavaForMe.tsx @@ -0,0 +1,136 @@ +"use client"; + +// "Get Java for me": MineUI downloads the Java a Minecraft version needs into +// its own folder (install_java, contract 2.13.0) and shows the progress. Used +// by Start here, the Create server flow and a failed Start on the Dashboard. +// The caller decides when Java is "ready" from the JavaCheck handed back. +import { useState } from "react"; +import { CheckCircle2, Download, Loader2, RefreshCw } from "lucide-react"; +import { Button, ProgressBar } from "@heroui/react"; +import { useUISound } from "@/app/hooks/useUISound"; +import { formatBytes } from "@/app/lib/format"; +import { + installJava, + IpcError, + onDownloadProgress, + type DownloadProgressEvent, + type JavaCheck, +} from "@/app/lib/ipc"; + +interface GetJavaForMeProps { + /** The Java major the Minecraft version needs. */ + major: number; + /** Called with the Java check after a successful download. */ + onInstalled: (check: JavaCheck) => void; + isDisabled?: boolean; + /** Button text; defaults to "Get Java for me". */ + label?: string; +} + +export default function GetJavaForMe({ + major, + onInstalled, + isDisabled = false, + label = "Get Java for me", +}: GetJavaForMeProps) { + const { play } = useUISound(); + const [busy, setBusy] = useState(false); + const [progress, setProgress] = useState(null); + const [error, setError] = useState(null); + const [done, setDone] = useState(false); + + const run = async () => { + play("click_confirm"); + setBusy(true); + setError(null); + setProgress(null); + const unlisten = await onDownloadProgress((event) => { + if (event.kind === "java") setProgress(event); + }); + try { + const check = await installJava(major); + play("success"); + setDone(true); + onInstalled(check); + } catch (e) { + play("error"); + setError( + e instanceof IpcError + ? e.message + : "MineUI could not download Java. Check your internet and try again.", + ); + } finally { + unlisten(); + setBusy(false); + } + }; + + const percent = + progress && progress.totalBytes + ? Math.min(100, (progress.receivedBytes / progress.totalBytes) * 100) + : null; + + return ( +
+ {done ? ( + + + Java {major} is ready. + + ) : ( +
+ + {!busy && !error && ( + + Free download (about 50 MB). MineUI keeps it in its own folder. + + )} +
+ )} + + {busy && ( +
+
+ {progress ? `Downloading ${progress.filename}` : "Starting the download..."} + + {progress + ? progress.totalBytes + ? `${formatBytes(progress.receivedBytes)} / ${formatBytes(progress.totalBytes)}` + : formatBytes(progress.receivedBytes) + : ""} + +
+ + + + + +
+ )} + + {error && ( +

+ {error} +

+ )} +
+ ); +} diff --git a/app/components/GettingStartedCard.tsx b/app/components/GettingStartedCard.tsx new file mode 100644 index 0000000..696b3e5 --- /dev/null +++ b/app/components/GettingStartedCard.tsx @@ -0,0 +1,238 @@ +"use client"; + +// Getting started: five steps with live ticks, per server. Everything comes +// from calls that already exist (server state, audit log, player history, +// backups list, instance status). Each open step has a Show me that scrolls +// to the right control. Dismissible per server; gone once all five are done. +import { useCallback, useEffect, useMemo, useState } from "react"; +import { Check, Circle, X } from "lucide-react"; +import { Button, Card } from "@heroui/react"; +import { useServers } from "@/app/components/ServerProvider"; +import { useUISound } from "@/app/hooks/useUISound"; +import { + getAuditLog, + getPlayerHistory, + getServerState, + instanceStatus, + listBackups, + type Mode, + type ServerPhase, +} from "@/app/lib/ipc"; + +export const GETTING_STARTED_KEY = "mineui-getting-started-dismissed"; +const POLL_MS = 10000; + +/** Page element ids the Show me buttons point at. */ +export const TARGET_START = "start-server-button"; +export const TARGET_JOIN = "join-info"; +export const TARGET_BACKUP = "backup-button"; + +type Facts = { + started: boolean; + players: number; + backups: number; +}; + +const dismissedKey = (serverId: string) => `${GETTING_STARTED_KEY}:${serverId}`; + +function readDismissed(serverId: string): boolean { + try { + return window.localStorage.getItem(dismissedKey(serverId)) === "1"; + } catch { + return false; + } +} + +/** Scroll to an element on the Dashboard and give it the keyboard focus. */ +function showMe(id: string) { + const el = document.getElementById(id); + if (!el) return; + el.scrollIntoView({ behavior: "smooth", block: "center" }); + const focusable = el.matches("button, a, input, [tabindex]") + ? el + : el.querySelector("button, a, input, [tabindex]"); + (focusable ?? el).focus({ preventScroll: true }); +} + +interface GettingStartedCardProps { + mode: Mode; + /** The open server's phase; a change re-reads the facts. */ + phase: ServerPhase | undefined; +} + +export default function GettingStartedCard({ mode, phase }: GettingStartedCardProps) { + const { play } = useUISound(); + const { activeId } = useServers(); + const [dismissed, setDismissed] = useState(null); + const [facts, setFacts] = useState(null); + + useEffect(() => { + // eslint-disable-next-line react-hooks/set-state-in-effect -- localStorage exists only in the browser, so it is read after mount + setDismissed(readDismissed(activeId)); + }, [activeId]); + + const load = useCallback(async () => { + const [state, audit, history, backups, instance] = await Promise.allSettled([ + getServerState(), + getAuditLog(200), + getPlayerHistory(), + listBackups(), + mode === "simple" ? instanceStatus() : Promise.resolve(null), + ]); + setFacts((prev) => { + let started = prev?.started ?? false; + // "Started at least once": any sign the server has run - its phase, a + // start time on the container or process, an exit code, a start in the + // audit log, or a world folder on this computer. + if (state.status === "fulfilled") { + const s = state.value; + started = + started || + (s.phase !== "not-created" && s.phase !== "stopped") || + Boolean(s.container?.startedAt) || + Boolean(s.process?.startedAt) || + (s.process?.lastExitCode ?? null) !== null; + } + if (audit.status === "fulfilled") { + started = + started || + audit.value.entries.some((e) => e.action === "server.start" && e.ok); + } + if (instance.status === "fulfilled" && instance.value?.worldExists) started = true; + const names = + history.status === "fulfilled" + ? new Set(history.value.users.map((u) => u.username.toLowerCase())).size + : (prev?.players ?? 0); + const backupCount = + backups.status === "fulfilled" ? backups.value.length : (prev?.backups ?? 0); + return { started, players: names, backups: backupCount }; + }); + }, [mode]); + + useEffect(() => { + if (dismissed !== false) return; + // eslint-disable-next-line react-hooks/set-state-in-effect -- IPC fetch-on-mount: re-read on a phase change, then lightly poll + void load(); + const interval = setInterval(() => void load(), POLL_MS); + return () => clearInterval(interval); + }, [dismissed, load, phase]); + + const steps = useMemo( + () => [ + { + id: "made", + title: "Your server is made", + hint: "Done the moment it appears here.", + done: true, + target: null as string | null, + }, + { + id: "started", + title: "Start your server", + hint: "Press Start. The first start can take a minute or two.", + done: facts?.started ?? false, + target: TARGET_START, + }, + { + id: "joined", + title: "Join it yourself", + hint: "Open Minecraft and use the address under How players join.", + done: (facts?.players ?? 0) >= 1, + target: TARGET_JOIN, + }, + { + id: "friend", + title: "A friend joins", + hint: "Send a friend the address under How players join.", + done: (facts?.players ?? 0) >= 2, + target: TARGET_JOIN, + }, + { + id: "backup", + title: "Make your first backup", + hint: "A backup is a saved copy of your world, in case something goes wrong.", + done: (facts?.backups ?? 0) >= 1, + target: TARGET_BACKUP, + }, + ], + [facts], + ); + + if (dismissed !== false || facts === null) return null; + const doneCount = steps.filter((s) => s.done).length; + if (doneCount === steps.length) return null; + + const dismiss = () => { + play("click_back"); + try { + window.localStorage.setItem(dismissedKey(activeId), "1"); + } catch { + // Not remembered across restarts, still hidden for this session. + } + setDismissed(true); + }; + + return ( + + +
+ Getting started + + {doneCount} of {steps.length} done. A few things to try with a new server. + +
+ +
+ +
    + {steps.map((step) => ( +
  1. + + {step.done ? : } + + {step.done ? "Done: " : "Not done yet: "} +
    + + {step.title} + + {!step.done && {step.hint}} +
    + {!step.done && step.target !== null && ( + + )} +
  2. + ))} +
+
+
+ ); +} diff --git a/app/components/JoinInfoCard.tsx b/app/components/JoinInfoCard.tsx index bd25581..46cb946 100644 --- a/app/components/JoinInfoCard.tsx +++ b/app/components/JoinInfoCard.tsx @@ -237,7 +237,14 @@ function ForwardingSteps({ ); } -export default function JoinInfoCard({ online }: { online: boolean }) { +export default function JoinInfoCard({ + online, + startOpenInternet = false, +}: { + online: boolean; + /** Open "From the internet" at first (after Start here, friends elsewhere). */ + startOpenInternet?: boolean; +}) { const router = useRouter(); const { play } = useUISound(); const { activeId, overview } = useServers(); @@ -249,7 +256,7 @@ export default function JoinInfoCard({ online }: { online: boolean }) { ); const [info, setInfo] = useState(null); const [failure, setFailure] = useState(null); - const [internetOpen, setInternetOpen] = useState(false); + const [internetOpen, setInternetOpen] = useState(startOpenInternet); const [looking, setLooking] = useState(false); const [publicIp, setPublicIp] = useState(null); const [lookupError, setLookupError] = useState(null); diff --git a/app/components/StartHere.tsx b/app/components/StartHere.tsx new file mode 100644 index 0000000..e759d9b --- /dev/null +++ b/app/components/StartHere.tsx @@ -0,0 +1,650 @@ +"use client"; + +// Start here: the front door for a computer with no server yet. Two plain +// questions (what to play, who plays), one sentence about what MineUI will set +// up and why, a check of what this computer needs (Java, or a container +// program), then it creates and starts the server with the SAME calls and +// defaults as the two create flows. It is not a third creation path. +import { useCallback, useState } from "react"; +import { motion } from "motion/react"; +import { + CheckCircle2, + Loader2, + Package, + PackageOpen, + RefreshCw, + Rocket, + Sparkles, + Users, + Wifi, + Globe, + User, + Blocks, + Cuboid, + TriangleAlert, +} from "lucide-react"; +import { Button, Card, Input, Label, ProgressBar, TextField } from "@heroui/react"; +import ChoiceCards from "@/app/components/ChoiceCards"; +import { + containerNameFor, + DEFAULT_CONTAINER_NAME, + LATEST, + MEMORY_DEFAULT, + MEMORY_DEFAULT_MODPACK, +} from "@/app/components/CreateContainerFlow"; +import GetJavaForMe from "@/app/components/GetJavaForMe"; +import { useMode } from "@/app/components/ModeProvider"; +import ModpackPicker, { type ModpackChoice } from "@/app/components/ModpackPicker"; +import OutLink from "@/app/components/OutLink"; +import RuntimeInstallHelp from "@/app/components/RuntimeInstallHelp"; +import { useServers } from "@/app/components/ServerProvider"; +import Term from "@/app/components/Term"; +import { useUISound } from "@/app/hooks/useUISound"; +import { formatBytes } from "@/app/lib/format"; +import { fadeUp } from "@/app/lib/motion"; +import { + createContainer, + createInstance, + detectRuntimes, + getSettings, + javaCheck, + listMcVersions, + onDownloadProgress, + requiredJavaMajor, + setSettings, + startServer, + IpcError, + type DownloadProgressEvent, + type JavaCheck, + type Mode, + type RuntimeProbe, +} from "@/app/lib/ipc"; + +type Play = "normal" | "mods"; +type Who = "me" | "home" | "friends"; +type ModsPath = "pack" | "none"; + +const MEMORY_MIN = 512; +const MEMORY_MAX = 16384; +const SERVER_NAME_DEFAULT = "My server"; +const MAX_NAME = 40; + +const PLAY_OPTIONS = [ + { + id: "normal" as const, + title: "Normal Minecraft", + description: "The game as it comes. No mods.", + icon: Cuboid, + }, + { + id: "mods" as const, + title: "Minecraft with mods", + description: "Your own mods, or a ready-made pack of them.", + icon: Blocks, + }, +]; + +const WHO_OPTIONS = [ + { + id: "me" as const, + title: "Just me", + description: "Only this computer.", + icon: User, + }, + { + id: "home" as const, + title: "People at home", + description: "Same Wi-Fi.", + icon: Wifi, + }, + { + id: "friends" as const, + title: "Friends in other places too", + description: "Over the internet.", + icon: Globe, + }, +]; + +const MODS_OPTIONS = [ + { + id: "pack" as const, + title: "Pick a modpack", + description: "A ready-made bundle of mods.", + icon: Package, + }, + { + id: "none" as const, + title: "Start with no mods", + description: "Add them later. MineUI uses Fabric.", + icon: PackageOpen, + }, +]; + +type JavaState = + | { kind: "idle" } + | { kind: "checking" } + | { kind: "ready"; major: number; check: JavaCheck } + | { kind: "need"; major: number; check: JavaCheck | null } + | { kind: "offline" }; + +const javaIsEnough = (check: JavaCheck | null, major: number) => + check !== null && + check.found && + check.compatible !== false && + (check.majorVersion ?? 0) >= major; + +interface StartHereProps { + /** Called once Start here begins changing anything, so the page keeps it + * on screen while the server's kind and data load again behind it. */ + onActive: () => void; + /** The server is made and started: land on the Dashboard. */ + onDone: (options: { friends: boolean }) => void; + /** "I know what I want": show today's create flows instead. */ + onSkip: () => void; +} + +export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) { + const { play } = useUISound(); + const { active, rename } = useServers(); + const { refresh: refreshMode } = useMode(); + + const [what, setWhat] = useState(""); + const [who, setWho] = useState(""); + const [name, setName] = useState(SERVER_NAME_DEFAULT); + const [java, setJava] = useState({ kind: "idle" }); + const [runtime, setRuntime] = useState(null); + const [runtimeChecking, setRuntimeChecking] = useState(false); + const [modsPath, setModsPath] = useState(""); + const [modpack, setModpack] = useState(null); + const [eula, setEula] = useState(false); + const [busy, setBusy] = useState(false); + const [step, setStep] = useState<"idle" | "making" | "starting">("idle"); + const [progress, setProgress] = useState(null); + const [error, setError] = useState(null); + // The server exists but did not start: Try again only starts it. + const [made, setMade] = useState(false); + + const checkJava = useCallback(async () => { + setJava({ kind: "checking" }); + try { + const major = await requiredJavaMajor(LATEST); + if (major === null) { + setJava({ kind: "offline" }); + return; + } + const check = await javaCheck().catch(() => null); + setJava( + javaIsEnough(check, major) + ? { kind: "ready", major, check: check as JavaCheck } + : { kind: "need", major, check }, + ); + } catch { + setJava({ kind: "offline" }); + } + }, []); + + const checkRuntime = useCallback(() => { + setRuntimeChecking(true); + detectRuntimes() + .then(setRuntime) + .catch(() => setRuntime(null)) + .finally(() => setRuntimeChecking(false)); + }, []); + + const chooseWhat = (next: Play) => { + setWhat(next); + setError(null); + if (next === "normal") void checkJava(); + else checkRuntime(); + }; + + const noRuntime = runtime !== null && runtime.resolved === null; + const runtimeReady = runtime !== null && runtime.resolved !== null; + const packVersion = + modpack && modpack.gameVersions.length > 0 ? modpack.gameVersions[0] : ""; + + // Everything the Create button needs, in the order it is asked for. + const missing: string | null = (() => { + if (what === "" || who === "") return "Answer both questions."; + if (what === "normal") { + if (java.kind === "checking" || java.kind === "idle") return "Checking this computer..."; + if (java.kind === "offline") return "MineUI cannot check this computer right now."; + if (java.kind === "need") return "This computer needs Java first (see above)."; + } else { + if (runtime === null) return "Checking this computer..."; + if (noRuntime) return "This computer needs Podman or Docker first (see above)."; + if (modsPath === "") return "Choose a modpack or start with no mods."; + if (modsPath === "pack" && modpack === null) return "Pick a modpack."; + if (modsPath === "pack" && packVersion === "") { + return "MineUI cannot tell which Minecraft version this pack uses. Use \"I know what I want\" below to pick it."; + } + } + if (!eula) return "Agree to the Minecraft rules to continue."; + return null; + })(); + + const reasonSentence = ( + <> + {what === "normal" ? ( + <> + MineUI will run a normal Minecraft server on this computer, because it is the + simplest way to play with no mods. + + ) : ( + <> + MineUI will run a server with mods in a container (a + sealed box that keeps the server tidy), because mods need their own setup and the + box keeps it apart from your other files. + + )} + {what === "mods" && modsPath === "pack" && modpack && ( + <> It will start from {modpack.title}. + )} + {what === "mods" && modsPath === "none" && ( + <> + {" "} + It will start with no mods, on Fabric, so you can add + mods later. + + )} + {who === "me" && what === "mods" && <> Only this computer can join it.} + {who === "home" && what === "mods" && <> Other devices on your Wi-Fi can join it.} + {who === "friends" && what === "mods" && ( + <> Other devices can join it, and MineUI will show the steps for friends elsewhere. + )} + {who === "me" && what === "normal" && <> Only you will play, so there is nothing else to set up.} + {who === "home" && what === "normal" && ( + <> When it is ready, MineUI shows the address people at home type to join. + )} + {who === "friends" && what === "normal" && ( + <> When it is ready, MineUI shows the address and the steps for friends elsewhere. + )} + + ); + + const run = async () => { + if (missing !== null || busy || what === "" || who === "") return; + play("click_confirm"); + setBusy(true); + setError(null); + setProgress(null); + onActive(); + let unlisten: (() => void) | null = null; + try { + if (!made) { + setStep("making"); + const wanted = name.trim().slice(0, MAX_NAME); + let serverName = active.name; + if (wanted !== "" && wanted !== active.name) { + try { + await rename(active.id, wanted); + serverName = wanted; + } catch { + // A name that does not stick must not stop the server. + } + } + + // Normal Minecraft runs On this computer, mods run In a container. + const wantMode: Mode = what === "normal" ? "simple" : "advanced"; + const current = await getSettings(); + if (current.activeMode !== wantMode) { + await setSettings({ ...current, activeMode: wantMode }); + await refreshMode(); + } + + if (what === "normal") { + unlisten = await onDownloadProgress((event) => { + if (event.kind === "server-jar") setProgress(event); + }); + const versions = await listMcVersions(); + const latest = versions.find((v) => v.latest && v.type === "release")?.id; + if (!latest) { + throw new IpcError("DOWNLOAD_FAILED", "MineUI could not find the newest Minecraft version."); + } + const memoryMb = Math.min( + Math.max(current.simple.memoryMb || 2048, MEMORY_MIN), + MEMORY_MAX, + ); + await createInstance({ mcVersion: latest, acceptEula: true, memoryMb }); + } else { + const containerName = + current.advanced.containerName !== DEFAULT_CONTAINER_NAME + ? current.advanced.containerName + : containerNameFor(serverName); + const withPack = modsPath === "pack" && modpack !== null; + await createContainer({ + loader: "fabric", + mcVersion: withPack ? packVersion : LATEST, + containerName, + memoryMb: withPack ? MEMORY_DEFAULT_MODPACK : MEMORY_DEFAULT, + gamePort: current.advanced.queryPort, + rconPort: current.advanced.rconPort, + exposeToNetwork: who !== "me", + extraPorts: [], + acceptEula: true, + modpack: withPack ? { source: modpack.source, project: modpack.project } : null, + }); + } + setMade(true); + } + + setStep("starting"); + await startServer(); + play("success"); + onDone({ friends: who === "friends" }); + } catch (e) { + play("error"); + setError( + e instanceof IpcError + ? e.message + : "Something went wrong. Nothing was lost, you can try again.", + ); + setStep("idle"); + setBusy(false); + } finally { + unlisten?.(); + } + }; + + const percent = + progress && progress.totalBytes + ? Math.min(100, (progress.receivedBytes / progress.totalBytes) * 100) + : null; + + const needsPanel = what !== ""; + + return ( + + + +
+ + Start here +
+ Welcome to MineUI + + Let's make a Minecraft server for you and your friends. Answer two + questions and MineUI does the rest. + +
+ + +
+ 1. What do you want to play? + +
+ +
+ 2. Who will play? + { + setWho(next); + setError(null); + }} + /> +
+ + {what !== "" && who !== "" && ( + <> +
+ +

{reasonSentence}

+
+ + + + + + + )} + + {needsPanel && what === "normal" && ( +
+ + What this computer needs + + {(java.kind === "checking" || java.kind === "idle") && ( + + + Checking for Java... + + )} + {java.kind === "ready" && ( +
+ + + {java.check.managed + ? `Using Java MineUI downloaded (${java.check.majorVersion ?? java.major})` + : `Java ${java.check.version ?? java.major} is on this computer. You are good to go.`} + +
+ )} + {java.kind === "need" && ( +
+

+ The newest Minecraft needs Java {java.major}.{" "} + {java.check?.found + ? "The Java on this computer is too old." + : "This computer does not have it yet."}{" "} + MineUI can get it for you. +

+ + setJava( + javaIsEnough(check, java.major) + ? { kind: "ready", major: java.major, check } + : { kind: "need", major: java.major, check }, + ) + } + /> +
+ )} + {java.kind === "offline" && ( +
+

+ + MineUI cannot check what your computer needs right now. Check your + internet connection and try again. +

+
+ +
+
+ )} +
+ )} + + {needsPanel && what === "mods" && ( +
+ + What this computer needs + + {runtime === null && ( + + + Looking for a program that runs containers... + + )} + {noRuntime && ( +
+

+ Servers with mods run in a container, and a container needs a free + program called Podman or{" "} + Docker. This computer does not have one yet. +

+ +
+ )} + {runtimeReady && ( + <> +
+ + + {runtime.resolved === "podman" ? "Podman" : "Docker"} is ready. You are + good to go. + +
+
+ + Which mods do you want? + + { + setModsPath(next); + if (next === "none") setModpack(null); + }} + /> +
+ {modsPath === "pack" && ( + + )} + + )} +
+ )} + + {what !== "" && who !== "" && ( + + )} + + {busy && ( +
+ + + {step === "starting" + ? "Starting your server..." + : what === "mods" + ? "Making your server. The first time, MineUI downloads the server files (about 1 GB), which can take a few minutes." + : progress + ? `Downloading ${progress.filename}` + : "Making your server..."} + {step !== "starting" && what === "normal" && progress?.totalBytes + ? ` ${formatBytes(progress.receivedBytes)} / ${formatBytes(progress.totalBytes)}` + : ""} + + + + + + +
+ )} + + {error && ( +
+

That did not work.

+

{error}

+ {made && ( +

+ Your server was made. Only starting it failed, so Try again just starts it. +

+ )} +
+ )} +
+ + + +
+ {missing !== null && !busy && what !== "" && who !== "" && ( + {missing} + )} + {what !== "" && who !== "" && ( + + )} +
+
+
+
+ ); +} diff --git a/app/page.tsx b/app/page.tsx index 5ab5c9b..0a3b5d6 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -28,7 +28,13 @@ import { useViewLevel } from "@/app/components/ViewLevelProvider"; import { SkeletonCard } from "@/app/components/Skeleton"; import CreateContainerFlow from "@/app/components/CreateContainerFlow"; import CreateServerFlow from "@/app/components/CreateServerFlow"; +import GetJavaForMe from "@/app/components/GetJavaForMe"; +import GettingStartedCard, { + TARGET_BACKUP, + TARGET_START, +} from "@/app/components/GettingStartedCard"; import JoinInfoCard from "@/app/components/JoinInfoCard"; +import StartHere from "@/app/components/StartHere"; import RuntimeInstallHelp from "@/app/components/RuntimeInstallHelp"; import ServerIdentity from "@/app/components/ServerIdentity"; import ServersOverview from "@/app/components/ServersOverview"; @@ -44,6 +50,7 @@ import { listMods, onLogs, onServerState, + requiredJavaMajor, restartServer, startLogStream, startServer, @@ -61,6 +68,15 @@ import { const MAX_LOG_LINES = 1000; +/** A Start that failed because the Java is missing or too old. */ +type JavaProblem = { + message: string; + /** The Java major to download; null = could not be looked up (offline). */ + major: number | null; + /** Java was downloaded: the next step is Start again. */ + fixed: boolean; +}; + // One statement of how the server is doing, from the two facts the backend // gives: the process/container phase and whether the game answers a ping. // "running" without an answer is the minutes between Start and "Done" (a @@ -140,7 +156,15 @@ export default function Home() { // for fields useMode() doesn't carry (e.g. simple.memoryMb for // CreateServerFlow's default). const { mode, loading: modeLoading } = useMode(); - const { active: activeServer, activeId } = useServers(); + const { active: activeServer, activeId, servers } = useServers(); + // Start here (first server, nothing set up): "I know what I want" skips it, + // and once it begins it stays on screen while the server's kind changes. + const [skipStartHere, setSkipStartHere] = useState(false); + const [startHereActive, setStartHereActive] = useState(false); + // After Start here: open the internet steps in How players join. + const [joinInternet, setJoinInternet] = useState(false); + const [landed, setLanded] = useState(false); + const [javaProblem, setJavaProblem] = useState(null); // View level: Simple leaves out the numbers, the trend line and the live // log (kept one click away). Display only - nothing here changes a server. const { level } = useViewLevel(); @@ -165,7 +189,9 @@ export default function Home() { const needsContainer = !isSimple && settings !== null && serverState?.phase === "not-created"; const needsOnboarding = needsInstance || needsContainer; - const showDashboard = !loading && backendError === null && !needsOnboarding; + const showStartHere = + !skipStartHere && servers.length === 1 && (needsOnboarding || startHereActive); + const showDashboard = !loading && backendError === null && !needsOnboarding && !showStartHere; // Depends on `mode`/`modeLoading` so a live mode toggle (no remount) also // refetches the mode-dependent data below (instanceStatus is simple-mode @@ -203,6 +229,18 @@ export default function Home() { bootstrap(); }, [bootstrap]); + // Just made by Start here: bring How players join into view. + useEffect(() => { + if (!landed || !showDashboard) return; + const timer = setTimeout(() => { + document + .getElementById("join-info") + ?.scrollIntoView({ behavior: "smooth", block: "start" }); + setLanded(false); + }, 900); + return () => clearTimeout(timer); + }, [landed, showDashboard]); + // Pull data (status ping + mods list) - no events for these, poll lightly. const refreshPolled = useCallback(async () => { const [statusResult, modsResult] = await Promise.allSettled([ @@ -317,7 +355,17 @@ export default function Home() { } catch (error) { play("error"); const fallback = { start: "Could not start", stop: "Could not stop", restart: "Could not restart", backup: "Backup failed" }[kind]; - if (kind === "start" || kind === "restart") { + if ( + (kind === "start" || kind === "restart") && + isSimple && + error instanceof IpcError && + (error.code === "JAVA_NOT_FOUND" || error.code === "JAVA_INCOMPATIBLE") + ) { + // Not a toast: the dashboard offers to get the Java it needs. + const version = instance?.mcVersion ?? "LATEST"; + const major = await requiredJavaMajor(version).catch(() => null); + setJavaProblem({ message: error.message, major, fixed: false }); + } else if (kind === "start" || kind === "restart") { reportLifecycleError(error, fallback, name); } else { toast.danger(error instanceof IpcError ? error.message : fallback); @@ -497,10 +545,12 @@ export default function Home() {
- - {isSimple ? "On this computer" : "In a container"} - - {!needsOnboarding && ( + {!showStartHere && ( + + {isSimple ? "On this computer" : "In a container"} + + )} + {!needsOnboarding && !showStartHere && ( <> {/* One chip says how the server is doing. Signature moment: a brief scale/glow whenever the condition changes, @@ -536,6 +586,7 @@ export default function Home() { Refresh +
+ ) : javaProblem.major !== null ? ( + + setJavaProblem((p) => (p ? { ...p, fixed: true } : p)) + } + /> + ) : ( +

+ MineUI cannot check which Java this server needs right now. Check + your internet connection, then press Start again. +

+ )} + + + + )} {!expertView && ( {!busy && !error && ( diff --git a/app/components/GettingStartedCard.tsx b/app/components/GettingStartedCard.tsx index 696b3e5..2ddecd8 100644 --- a/app/components/GettingStartedCard.tsx +++ b/app/components/GettingStartedCard.tsx @@ -3,10 +3,22 @@ // Getting started: five steps with live ticks, per server. Everything comes // from calls that already exist (server state, audit log, player history, // backups list, instance status). Each open step has a Show me that scrolls -// to the right control. Dismissible per server; gone once all five are done. -import { useCallback, useEffect, useMemo, useState } from "react"; -import { Check, Circle, X } from "lucide-react"; -import { Button, Card } from "@heroui/react"; +// to the right control. Dismissible per server. Small celebrations: a step's +// check springs in and chimes when it turns done, and the fifth step brings an +// "All done" moment before the card goes away. Each one plays once per server +// (lib/milestones.ts), never again on a reload. Reduce-motion: Motion drops +// the transforms (MotionConfig) and the sparks are not rendered at all. +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { motion, useReducedMotion } from "motion/react"; +import { Check, Circle, PartyPopper, X } from "lucide-react"; +import { Button, Card, ProgressCircle } from "@heroui/react"; +import { + announceFriendJoined, + markCelebrated, + readCelebrated, + type Milestone, +} from "@/app/lib/milestones"; +import { scaleIn, transition } from "@/app/lib/motion"; import { useServers } from "@/app/components/ServerProvider"; import { useUISound } from "@/app/hooks/useUISound"; import { @@ -54,6 +66,22 @@ function showMe(id: string) { (focusable ?? el).focus({ preventScroll: true }); } +const ALL_DONE_MS = 8000; +const SPARK_COLORS = ["bg-success", "bg-accent", "bg-warning"] as const; +const SPARKS = Array.from({ length: 12 }, (_, i) => { + const angle = (i / 12) * Math.PI * 2; + return { + x: Math.round(Math.cos(angle) * (56 + (i % 3) * 14)), + y: Math.round(Math.sin(angle) * (36 + (i % 3) * 10)), + color: SPARK_COLORS[i % SPARK_COLORS.length], + }; +}); + +/** Phosphor never scales or springs (theme contract), so it gets neither the + * check spring nor the sparks; the rest of the moment is a fade. */ +const isPhosphor = () => + typeof document !== "undefined" && document.documentElement.dataset.theme === "phosphor"; + interface GettingStartedCardProps { mode: Mode; /** The open server's phase; a change re-reads the facts. */ @@ -65,6 +93,11 @@ export default function GettingStartedCard({ mode, phase }: GettingStartedCardPr const { activeId } = useServers(); const [dismissed, setDismissed] = useState(null); const [facts, setFacts] = useState(null); + const reduceMotion = useReducedMotion(); + // Steps that turned done while the app was open: only those spring in. + const [popped, setPopped] = useState>(new Set()); + const [allDone, setAllDone] = useState(false); + const prevDone = useRef | null>(null); useEffect(() => { // eslint-disable-next-line react-hooks/set-state-in-effect -- localStorage exists only in the browser, so it is read after mount @@ -158,9 +191,99 @@ export default function GettingStartedCard({ mode, phase }: GettingStartedCardPr [facts], ); + // Celebrate a step the first time it is seen turning done (per server). + const doneKey = steps.map((s) => (s.done ? "1" : "0")).join(""); + useEffect(() => { + if (dismissed !== false || facts === null) return; + const before = prevDone.current; + const now = new Map(steps.map((s) => [s.id, s.done])); + prevDone.current = now; + const seen = readCelebrated(activeId); + const fresh = steps.filter( + (s) => s.id !== "made" && s.done && !seen.has(s.id) && (before?.get(s.id) ?? true) === false, + ); + for (const s of fresh) markCelebrated(activeId, s.id as Milestone); + if (fresh.length > 0) { + setPopped((prev) => new Set([...prev, ...fresh.map((s) => s.id)])); + play("success"); + if (fresh.some((s) => s.id === "friend")) announceFriendJoined(); + } + if (now.size > 0 && [...now.values()].every(Boolean) && !seen.has("all")) { + markCelebrated(activeId, "all"); + setAllDone(true); + if (fresh.length === 0) play("success"); + } + // eslint-disable-next-line react-hooks/exhaustive-deps -- doneKey stands for the done flags + }, [doneKey, dismissed, facts, activeId, play]); + + useEffect(() => { + if (!allDone) return; + const timer = setTimeout(() => setAllDone(false), ALL_DONE_MS); + return () => clearTimeout(timer); + }, [allDone]); + + // A different server starts clean. + useEffect(() => { + prevDone.current = null; + // eslint-disable-next-line react-hooks/set-state-in-effect -- reset when the open server changes + setPopped(new Set()); + setAllDone(false); + }, [activeId]); + if (dismissed !== false || facts === null) return null; const doneCount = steps.filter((s) => s.done).length; - if (doneCount === steps.length) return null; + if (doneCount === steps.length) { + if (!allDone) return null; + return ( + + + {!reduceMotion && !isPhosphor() && ( + + {SPARKS.map((spark, i) => ( + + ))} + + )} + +
+ + + +
+ All done! + + You made a server, joined it, had a friend over and saved a backup. That is + a real server admin move. + +
+
+ +
+
+
+ ); + } const dismiss = () => { play("click_back"); @@ -175,11 +298,32 @@ export default function GettingStartedCard({ mode, phase }: GettingStartedCardPr return ( -
- Getting started - - {doneCount} of {steps.length} done. A few things to try with a new server. - +
+
+ + + + + + + + {doneCount} + +
+
+ Getting started + + {doneCount} of {steps.length} done. A few things to try with a new server. + +
@@ -162,6 +167,7 @@ export default function ServersOverview() { onPress={() => runLifecycle(server.id, server.name, startServerById, "started")} onMouseEnter={() => play("hover")} > + Start diff --git a/app/components/StartHere.tsx b/app/components/StartHere.tsx index e759d9b..d36a19d 100644 --- a/app/components/StartHere.tsx +++ b/app/components/StartHere.tsx @@ -24,6 +24,9 @@ import { TriangleAlert, } from "lucide-react"; import { Button, Card, Input, Label, ProgressBar, TextField } from "@heroui/react"; +import { TextShimmer } from "@heroui-pro/react"; +import PressRipple from "@/app/components/PressRipple"; +import { announceServerMade } from "@/app/lib/milestones"; import ChoiceCards from "@/app/components/ChoiceCards"; import { containerNameFor, @@ -331,6 +334,7 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) setStep("starting"); await startServer(); play("success"); + announceServerMade("It is starting now. Give it a minute."); onDone({ friends: who === "friends" }); } catch (e) { play("error"); @@ -372,6 +376,7 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps)
1. What do you want to play? 2. Who will play? - {step === "starting" - ? "Starting your server..." - : what === "mods" - ? "Making your server. The first time, MineUI downloads the server files (about 1 GB), which can take a few minutes." - : progress - ? `Downloading ${progress.filename}` - : "Making your server..."} + + {step === "starting" + ? "Starting your server..." + : what === "mods" + ? "Making your server. The first time, MineUI downloads the server files (about 1 GB), which can take a few minutes." + : progress + ? `Downloading ${progress.filename}` + : "Making your server..."} + {step !== "starting" && what === "normal" && progress?.totalBytes ? ` ${formatBytes(progress.receivedBytes)} / ${formatBytes(progress.totalBytes)}` : ""} @@ -629,10 +638,11 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) isPending={busy} onMouseEnter={() => play("hover")} > + {busy ? ( <> - Working... + Working... ) : ( <> diff --git a/app/components/StatusPulse.tsx b/app/components/StatusPulse.tsx new file mode 100644 index 0000000..9d3d0e3 --- /dev/null +++ b/app/components/StatusPulse.tsx @@ -0,0 +1,27 @@ +"use client"; + +// A server's state as a small dot. Running: a soft ring breathes out from a +// success-coloured dot. Starting or stopping: the same ring, faster, in the +// warning colour. Everything else: a plain still dot. The ring is a CSS +// animation (globals.css, .status-ring) that is switched off for +// reduce-motion, so a still dot is all that is left there. +import type { ServerPhase } from "@/app/lib/ipc"; +import { phaseDotClass } from "@/app/components/ServerProvider"; + +interface StatusPulseProps { + phase: ServerPhase | null | undefined; + /** Size utility for the dot. Defaults to size-2. */ + className?: string; +} + +export default function StatusPulse({ phase, className = "size-2" }: StatusPulseProps) { + const color = phaseDotClass(phase); + const rhythm = + phase === "running" ? "calm" : phase === "starting" || phase === "stopping" ? "busy" : null; + return ( + + {rhythm && } + + + ); +} diff --git a/app/globals.css b/app/globals.css index 8b13f17..faee59d 100644 --- a/app/globals.css +++ b/app/globals.css @@ -156,3 +156,49 @@ html { transition-duration: var(--motion-slow); } } + +/* Status ring (app/components/StatusPulse.tsx): a soft ring breathes out + from the state dot. Running is calm, starting/stopping is quicker. Phosphor + never scales (theme contract), so there it only fades. Reduce-motion: no + ring at all, the plain dot stays. */ +@keyframes status-ring-grow { + 0% { + transform: scale(1); + opacity: 0.55; + } + 100% { + transform: scale(2.8); + opacity: 0; + } +} + +@keyframes status-ring-fade { + 0%, + 100% { + opacity: 0.5; + } + 50% { + opacity: 0; + } +} + +.status-ring { + position: absolute; + inset: 0; + animation: status-ring-grow 2.4s ease-out infinite; +} + +.status-ring[data-rhythm="busy"] { + animation-duration: 1s; +} + +[data-theme="phosphor"] .status-ring { + animation-name: status-ring-fade; +} + +@media (prefers-reduced-motion: reduce) { + .status-ring { + display: none; + animation: none; + } +} diff --git a/app/lib/milestones.ts b/app/lib/milestones.ts new file mode 100644 index 0000000..d10bc93 --- /dev/null +++ b/app/lib/milestones.ts @@ -0,0 +1,42 @@ +// Small celebrations that must not repeat: which ones a server already had is +// kept in localStorage per server, so a reload never replays a sound or a +// banner. Storage can be missing or blocked, so every call is guarded. +import { toast } from "@heroui/react"; + +export const CELEBRATED_KEY = "mineui-getting-started-celebrated"; + +export type Milestone = "started" | "joined" | "friend" | "backup" | "all"; + +const key = (serverId: string) => `${CELEBRATED_KEY}:${serverId}`; + +export function readCelebrated(serverId: string): Set { + try { + const raw = window.localStorage.getItem(key(serverId)); + const parsed: unknown = raw ? JSON.parse(raw) : []; + return new Set(Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === "string") : []); + } catch { + return new Set(); + } +} + +export function markCelebrated(serverId: string, id: Milestone) { + try { + const next = readCelebrated(serverId); + next.add(id); + window.localStorage.setItem(key(serverId), JSON.stringify([...next])); + } catch { + // Not remembered across restarts; the session still will not replay it. + } +} + +/** The "your server is made" toast (the caller plays the success sound). */ +export function announceServerMade(detail: string) { + toast.success("Your server is made!", { description: detail }); +} + +/** The "a friend joined" toast (the caller plays the success sound). */ +export function announceFriendJoined() { + toast.success("A friend joined!", { + description: "Your server is not just yours anymore. Have fun.", + }); +} diff --git a/app/page.tsx b/app/page.tsx index 0a3b5d6..2162f77 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -17,7 +17,11 @@ import { Users, } from "lucide-react"; import { Button, Card, Chip, ScrollShadow, Separator, toast } from "@heroui/react"; -import { EmptyState, NumberValue, TrendChip } from "@heroui-pro/react"; +import { EmptyState, NumberValue, TextShimmer, TrendChip } from "@heroui-pro/react"; +import NumberFlow from "@number-flow/react"; +import Rolling from "@/app/components/Rolling"; +import PressRipple from "@/app/components/PressRipple"; +import StatusPulse from "@/app/components/StatusPulse"; import Sparkline from "@/app/components/Sparkline"; import { recordSample, seriesOf, useMetricHistory } from "@/app/lib/metricHistory"; import { KPI } from "@heroui-pro/react/kpi"; @@ -102,6 +106,10 @@ const conditionOf = (phase: ServerPhase | undefined, online: boolean): Condition } }; +/** Something is in progress: the label shimmers and the dot beats faster. */ +const isBusyCondition = (condition: Condition) => + condition === "warming" || condition === "starting" || condition === "stopping"; + const CONDITION_LABEL: Record = { online: "Online", warming: "Starting up…", @@ -566,12 +574,17 @@ export default function Home() { {condition === "online" ? ( - {/* The one sanctioned ambient loop on this screen - (docs/theme-contract.md §6); reduced-motion - guard in globals.css. */} - + {/* Breathing ring (StatusPulse): the one ambient + loop on this screen, switched off for + reduce-motion in globals.css. */} + Online + ) : isBusyCondition(condition) ? ( + + + {CONDITION_LABEL[condition]} + ) : ( CONDITION_LABEL[condition] )} @@ -785,7 +798,13 @@ export default function Home() {
-
{CONDITION_LABEL[condition]}
+
+ {isBusyCondition(condition) ? ( + {CONDITION_LABEL[condition]} + ) : ( + CONDITION_LABEL[condition] + )} +
{condition === "online" && ( <>
Version: {status?.version ?? "unknown"}
@@ -793,7 +812,12 @@ export default function Home() { <>
MOTD: {status?.motd ?? "-"}
- Ping: {status?.pingMs != null ? `${status.pingMs}ms` : "-"} + Ping:{" "} + {status?.pingMs != null ? ( + + ) : ( + "-" + )}
)} @@ -831,6 +855,7 @@ export default function Home() { isDisabled={busy || !canStart} onMouseEnter={() => play("hover")} > + {busyAction === "start" ? ( ) : ( @@ -844,6 +869,7 @@ export default function Home() { isDisabled={busy || !canStop} onMouseEnter={() => play("hover")} > + {busyAction === "stop" ? ( ) : ( @@ -857,6 +883,7 @@ export default function Home() { isDisabled={busy || !canRestart} onMouseEnter={() => play("hover")} > + {busyAction === "restart" ? ( ) : ( @@ -892,9 +919,9 @@ export default function Home() {
- {(formatted) => ( + {() => ( <> - {formatted} + /{maxPlayers || "?"} )} diff --git a/app/status/page.tsx b/app/status/page.tsx index 09b05f5..f172909 100644 --- a/app/status/page.tsx +++ b/app/status/page.tsx @@ -1,10 +1,11 @@ "use client"; +import Rolling from "@/app/components/Rolling"; import Term from "@/app/components/Term"; import AdvancedOnly from "@/app/components/AdvancedOnly"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useState, type ReactNode } from "react"; import { motion } from "motion/react"; import { Activity, @@ -90,12 +91,15 @@ const speedTone = (tps: number | null): RingTone => function MetricRing({ value, label, + display, title, tone, trend, }: { value: number; label: string; + /** What to draw in the middle instead of the plain label (rolling digits). */ + display?: ReactNode; /** Full caption under the ring. */ title: string; tone: RingTone; @@ -112,7 +116,7 @@ function MetricRing({
- {label} + {display ?? label}
{title} @@ -267,7 +271,13 @@ function StatusPageInner() { const tpsDisplay = useMemo(() => { if (!metrics?.tps) return metrics && serverState?.phase === "running" ? NOT_REPORTED : "-"; if (!Number.isFinite(metrics.tps.one)) return metrics.tps.raw; - return `${metrics.tps.one.toFixed(1)} / ${metrics.tps.five.toFixed(1)} / ${metrics.tps.fifteen.toFixed(1)}`; + return ( + <> + /{" "} + /{" "} + + + ); }, [metrics, serverState]); const dimensionsDisplay = useMemo(() => { @@ -378,6 +388,11 @@ function StatusPageInner() { + ) : undefined + } title="Game speed (TPS)" tone={ringsTone.tps} trend={{ data: seriesOf(history, "tps"), domain: [0, 20] }} @@ -416,12 +431,14 @@ function StatusPageInner() {
Players: - {status?.players.online ?? 0}/{status?.players.max ?? "?"} + /{status?.players.max ?? "?"}
Ping: - {status?.pingMs != null ? `${status.pingMs}ms` : "-"} + + {status?.pingMs != null ? : "-"} +
MOTD: From c446d3b3217b2006b8b61934a43742d770ef4fec Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 19:05:11 -0600 Subject: [PATCH 10/28] ci: sign and notarize the macOS builds Developer ID Application certificate plus notarization through the App Store Connect API key. The key is written to RUNNER_TEMP on the macOS jobs only and handed to tauri as APPLE_API_KEY_PATH. Secrets: APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD, APPLE_SIGNING_IDENTITY, APPLE_API_KEY, APPLE_API_ISSUER, APPLE_API_KEY_P8_B64. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- .github/workflows/release.yml | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e1ea279..165493a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -125,20 +125,31 @@ jobs: # here. If the generated icon looks soft, regenerate the whole icon set # from a >=1024px source via `pnpm tauri icon` (this also needs updating # tauri.conf.json's bundle.icon list) rather than hand-adding an .icns. + # Notarization key: tauri reads the .p8 from a file, so write it outside + # the checkout and point APPLE_API_KEY_PATH at it for the build step. + - name: Write the App Store Connect API key (macOS) + if: startsWith(matrix.platform, 'macos') + env: + APPLE_API_KEY_P8_B64: ${{ secrets.APPLE_API_KEY_P8_B64 }} + run: | + umask 077 + printf '%s' "$APPLE_API_KEY_P8_B64" | base64 --decode > "$RUNNER_TEMP/asc_api_key.p8" + echo "APPLE_API_KEY_PATH=$RUNNER_TEMP/asc_api_key.p8" >> "$GITHUB_ENV" + - name: Build and release uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} HEROUI_AUTH_TOKEN: ${{ secrets.HEROUI_AUTH_TOKEN }} - # --- Code signing: not configured yet, no certs exist. --- - # macOS notarization/signing - add these secrets and uncomment when - # an Apple Developer cert is available: - # APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} - # APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} - # APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} - # APPLE_ID: ${{ secrets.APPLE_ID }} - # APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} - # APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + # --- macOS: Developer ID signing + notarization (since 2.13.0). --- + # The certificate is a Developer ID Application .p12 (base64); + # notarization uses the App Store Connect API key written to + # APPLE_API_KEY_PATH by the step above. Ignored on Linux and Windows. + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} # Windows code signing - add when a cert is available: # WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }} # WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }} From 1aa894d2f9b9003363f2a6118c2826bbe279f5ba Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 19:07:03 -0600 Subject: [PATCH 11/28] docs: beginner-friendly, alive and macOS signing (Unreleased) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- CHANGELOG.md | 54 ++++++++++++++++++++++++++++++++++++++ CLAUDE.md | 2 +- README.md | 74 +++++++++++++++++++++++++++++++++++++++++++--------- SECURITY.md | 16 +++++++----- 4 files changed, 126 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 927f9a1..f3c5903 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,60 @@ All notable changes to MineUI are documented here. Format follows ## [Unreleased] +### Added + +- **Simple and Advanced view.** A switch in the header, Simple by default, + remembered between runs. Simple hides the Status, Console and Config + pages; Scheduled tasks, Network and ports and the Advanced section in + Server Settings; and the Dashboard's MOTD, ping, trend chip and + sparklines. The server log sits behind "Show the server log". Opening a + hidden page shows a notice with a "Show Advanced" button. It is a view + setting only and never changes a server. +- **Start here.** With no server set up, the Dashboard asks "What do you + want to play?" (Normal Minecraft or Minecraft with mods) and "Who will + play?" (Just me, People at home, Friends in other places too), says what + it will set up, then creates and starts the server and shows How players + join. "I know what I want" opens the full create forms. It appears only + when the one server you have is not set up yet. "Just me" on a server On + this computer only changes the wording; container servers are limited to + this computer. +- **MineUI gets Java.** A server On this computer with no suitable Java + offers "Get Java for me". MineUI downloads the Eclipse Temurin JRE of the + major the Minecraft version needs from Adoptium (api.adoptium.net and + GitHub release assets, https only), checks its sha256, refuses more than + 300 MB, and keeps it in MineUI's own data folder, shared by all servers. + Java already on the computer is still used when present. Tested on a real + download on Linux; the Windows and macOS archive layouts are covered by + tests on synthetic archives only. +- **What's this?** Short explanations for 25 terms, among them RCON, port, + whitelist, op, EULA, container, Java, the mod loaders, TPS and MSPT. +- **Getting started checklist** on the Dashboard, per server: server made, + started, you joined, a friend joined, first backup. Steps tick from real + data, each open step has a Show me link, the card can be hidden, shows a + progress ring, and ends with an "All done!" moment at 5 of 5. +- **Alive touches.** Player count, ping and TPS digits roll when they + change. A ring breathes around the status dot while the server runs (and + faster while it starts or stops). In-progress labels shimmer. Start, Stop, + Restart and the create buttons ripple when pressed. Toasts mark the first + server made and the first friend joining. The join address is shown as a + tilting "server pass" card with Copy. All of it stops under the system's + reduce-motion setting, and sounds follow the existing sound setting. +- IPC: `install_java` and `required_java_major`, `JavaCheck.managed`, and + `DownloadKind` gains `"java"` (see `docs/v2-contract.md`). + +### Changed + +- **The two server kinds are called On this computer and In a container** + on screen (they were called Simple and Advanced, which now names the view + above). +- **The create forms show less up front.** Server type, version, pack and + the Mojang agreement come first; the rest is under More options, with the + same defaults as before. +- **macOS builds are signed with a Developer ID and notarized** by the + release workflow from this release on. Windows builds are still unsigned. +- @heroui-pro/react 1.0.0-beta.11. The Java installer reads archive names + the way zip 9 returns them. + ## [2.12.1] - 2026-11-10 ### Security diff --git a/CLAUDE.md b/CLAUDE.md index 4ef0ca0..3caa32d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ contribution process; this file is conventions and constraints only. - `pnpm lint` - ESLint - `pnpm tauri dev` - full app (Next.js dev server + Tauri window) - `pnpm tauri build` - production desktop bundle -- `cargo test -p mineui-core` - Rust unit tests (254 tests, must stay green) +- `cargo test -p mineui-core` - Rust unit tests (273 tests, must stay green) - `cargo fmt` / `cargo clippy` - run before committing any Rust change pnpm only. Do not use npm/yarn/bun. diff --git a/README.md b/README.md index 417f8b7..9268e86 100644 --- a/README.md +++ b/README.md @@ -42,13 +42,13 @@ it) just to manage the one you actually care about. MineUI is a native desktop app, not a web panel: **Tauri v2** (Rust backend) driving a **Next.js** static-export frontend over Tauri IPC - no Electron, no bundled Chromium, no local HTTP server to expose or secure. It manages any -number of servers at once, and each one runs in one of two modes: +number of servers at once, and each one runs in one of two ways: -- **Simple mode (default)** - MineUI creates and runs a vanilla server for +- **On this computer** - MineUI creates and runs a vanilla server for you: pick a Minecraft version, set memory, accept the EULA, and MineUI downloads the official server jar (SHA-1 verified), configures RCON, and supervises the Java process. No containers required. -- **Advanced mode** - a Minecraft server container managed by **Docker or +- **In a container** - a Minecraft server container managed by **Docker or Podman** (auto-detected, Podman preferred): control, logs, players, RCON, mods/plugins, config editing, backups, and container metrics. MineUI can **create** the container for you from the `itzg/minecraft-server` image - @@ -69,8 +69,10 @@ Grab the build for your platform from the | macOS (Apple Silicon) | `MineUI_2.12.1_aarch64.dmg` | | macOS (Intel) | `MineUI_2.12.1_x64.dmg` | -Simple mode needs Java installed (MineUI version-checks it against the -Minecraft release you pick). Advanced mode needs Docker or Podman. +A server On this computer needs Java. If the computer has none that fits +the Minecraft version you pick, MineUI offers *Get Java for me* and downloads +it (see [MineUI gets Java](#mineui-gets-java)); Java already installed is +used as before. A server In a container needs Docker or Podman. ### Installing a container runtime @@ -98,6 +100,51 @@ Website & docs: [mineui.i4c.studio](https://mineui.i4c.studio) ## Features +### Start here, for a first server + +With no server set up, the Dashboard asks two questions - *What do you want +to play?* (Normal Minecraft or Minecraft with mods) and *Who will play?* +(Just me, People at home, Friends in other places too) - says what it will +set up, then creates and starts the server and ends on how players join. +*I know what I want* opens the full create forms instead. It shows only when +the one server you have is not set up yet. For a server On this computer, +*Just me* only changes the wording; container servers are limited to this +computer. The create forms keep server type, version, pack and the Mojang +agreement up front and put the rest under *More options*, with the same +defaults. About 25 terms (RCON, port, whitelist, op, EULA, container, Java, +the mod loaders, TPS, MSPT and more) have a *What's this?* explanation. + +### Simple and Advanced view + +A switch in the header, Simple by default and remembered. Simple hides the +Status, Console and Config pages; Scheduled tasks, Network and ports and the +Advanced section in Server Settings; and the Dashboard's MOTD, ping, trend +chip and sparklines. The server log sits behind *Show the server log*. A +hidden page opened directly shows a notice with a *Show Advanced* button. +It is a view setting only and never changes a server. + +### MineUI gets Java + +A server On this computer with no suitable Java offers *Get Java for me*. +MineUI downloads the Eclipse Temurin JRE of the major the Minecraft version +needs from Adoptium (`api.adoptium.net` and GitHub release assets, https +only), verifies its sha256, caps the download at 300 MB, and keeps it in +MineUI's own data folder, shared by all servers. Tested for real on Linux; +the Windows and macOS archive layouts are covered by tests on synthetic +archives only. + +### Getting started and a few signs of life + +Each server's Dashboard shows a checklist: server made, started, you +joined, a friend joined, first backup. Steps tick from real data, each open +one has a *Show me* link, the card can be hidden, and it ends with an *All +done!* moment at 5 of 5. Player count, ping and TPS digits roll when they +change, a ring breathes around the status dot while the server runs, Start, +Stop, Restart and the create buttons ripple on press, and the join address +is a tilting "server pass" card with *Copy*. All of it stops under the +system's reduce-motion setting, and sounds follow the sound setting in App +Settings. + ### Several servers at once Add as many servers as you run - a Forge pack, a Fabric pack, a managed @@ -115,7 +162,7 @@ MineUI forget it: its container, world and backups are never touched. ### Create a modded server without touching the command line Adding a server offers three routes: a **Modded or modpack server** (a new -container), a **Plain Minecraft server** (vanilla, run on this computer, no +container), a **Normal Minecraft, on this computer** server (vanilla, no containers), or **A container I already run**. For a new container MineUI creates an [`itzg/minecraft-server`](https://github.com/itzg/docker-minecraft-server) container for you - pick Vanilla, Paper, Purpur, Fabric, Quilt, Forge or @@ -151,9 +198,10 @@ appearance (dark / light mode, style, accent), sounds (volume and four sound sets) and an About card (version, where files live, a manual update check), which apply to MineUI as a whole. **Settings** in the navigation is always the open server's own: its name, performance, scheduled tasks, backups, and - under *Advanced* - -connection details, console command rules and how the server is run (Simple -or Advanced; there is no header toggle for that any more, it is changed there, -never while the server runs, and asks first). +connection details, console command rules and how the server is run (On this +computer or In a container; it is changed there, never while the server runs, +and asks first). The header's Simple / Advanced switch is separate: it only +hides or shows parts of the app. ### Ports and how players join @@ -226,7 +274,7 @@ system** and a style in App Settings → Appearance, and optionally override the accent color. The token system behind them is in [`docs/theme-contract.md`](docs/theme-contract.md). -### Enriched metrics via a companion mod (Advanced mode, optional) +### Enriched metrics via a companion mod (servers In a container, optional) Point a server's Settings → **Server utils URL** at an instance of [mineui_server_utils](https://github.com/I4cTime/mineui_server_utils) - a @@ -237,8 +285,8 @@ plus container/process metrics; everything else still works. ### Every backend call is typed and contract-bound -`crates/mineui-core` is pure Rust (no Tauri dependency, 254 unit tests); -`src-tauri` is a thin `#[tauri::command]` shell (55 IPC commands) that +`crates/mineui-core` is pure Rust (no Tauri dependency, 273 unit tests); +`src-tauri` is a thin `#[tauri::command]` shell (57 IPC commands) that delegates to it. The full command/error/event surface is specified in [`docs/v2-contract.md`](docs/v2-contract.md) - binding, not a suggestion; see [CONTRIBUTING.md](CONTRIBUTING.md). @@ -266,7 +314,7 @@ Other commands: - `pnpm build` - static export to `out/` (what Tauri bundles) - `pnpm lint` - ESLint - `pnpm tauri build` - production desktop bundle -- `cargo test -p mineui-core` - Rust unit tests (254 tests; must stay green) +- `cargo test -p mineui-core` - Rust unit tests (273 tests; must stay green) CI (`.github/workflows/ci.yml`) runs lint/typecheck/build on the frontend and `cargo fmt`/`clippy`/`test` plus a `cargo check` of the Tauri shell, on every diff --git a/SECURITY.md b/SECURITY.md index a1d41df..dfd25ff 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -30,7 +30,7 @@ When reporting, please provide: - **Description** of the vulnerability and its potential impact. - **Steps to reproduce** or a proof of concept. - **Affected version(s)** of MineUI. -- **Environment** details (OS, mode - Simple/Advanced, container runtime and version if applicable). +- **Environment** details (OS, server kind - on this computer or in a container, container runtime and version if applicable). - **Suggested fix**, if you have one. ## Response Timeline @@ -47,12 +47,16 @@ When reporting, please provide: The following areas are in scope for security reports: - **Subprocess execution** - command injection via Docker/Podman CLI calls, - the managed Java process (Simple mode), or any other shell-out. All + the managed Java process (servers On this computer), or any other shell-out. All subprocess calls must build an argv array; shell-string interpolation is a reportable bug (see `CONTRIBUTING.md` § Scope boundaries). - **Server jar download and verification** - bypass or weakening of the SHA-1 verification MineUI performs before running an official Minecraft - server jar in Simple mode. + server jar on a server On this computer. +- **Java download** - the Eclipse Temurin JRE MineUI fetches for servers On + this computer: a bypass of the fixed hosts (https only), the sha256 check + or the 300 MB cap, or an archive entry that unpacks outside MineUI's Java + folder. - **RCON console** - command injection or allowlist bypass in the RCON command panel. - **Mods & Plugins** - path traversal or unsafe file handling in upload, @@ -65,14 +69,14 @@ The following areas are in scope for security reports: bypasses intended capability/permission scoping in `src-tauri/capabilities/`, or a mismatch between `docs/v2-contract.md` and the actual IPC implementation that grants excess access. -- **Container attachment (Advanced mode)** - unauthorized access to a +- **Container attachment (servers In a container)** - unauthorized access to a container's filesystem or Docker/Podman socket beyond the attached server. -- **Container creation (Advanced mode)** - argument or environment +- **Container creation (servers In a container)** - argument or environment injection into the runtime `run` call, the generated RCON password reaching an argv or a log, or the create flow touching a container or volume it did not just create. -- **Container deletion (Advanced mode)** - a container or data volume +- **Container deletion (servers In a container)** - a container or data volume removed without the explicit confirmed request, a volume removed although only the container was to go, a host folder deleted, or deletion reaching a container other than the one the server points at. From ce07acd8d3ff37fe996b3d6d0a5fe0667263b9b1 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 19:07:49 -0600 Subject: [PATCH 12/28] fix(ui): Settings no longer says a server on this computer needs Java installed; glossary count Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- CHANGELOG.md | 2 +- README.md | 2 +- app/settings/page.tsx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f3c5903..7dc5f58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,7 +30,7 @@ All notable changes to MineUI are documented here. Format follows Java already on the computer is still used when present. Tested on a real download on Linux; the Windows and macOS archive layouts are covered by tests on synthetic archives only. -- **What's this?** Short explanations for 25 terms, among them RCON, port, +- **What's this?** Short explanations for 26 terms, among them RCON, port, whitelist, op, EULA, container, Java, the mod loaders, TPS and MSPT. - **Getting started checklist** on the Dashboard, per server: server made, started, you joined, a friend joined, first backup. Steps tick from real diff --git a/README.md b/README.md index 9268e86..deb6b27 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ the one server you have is not set up yet. For a server On this computer, *Just me* only changes the wording; container servers are limited to this computer. The create forms keep server type, version, pack and the Mojang agreement up front and put the rest under *More options*, with the same -defaults. About 25 terms (RCON, port, whitelist, op, EULA, container, Java, +defaults. 26 terms (RCON, port, whitelist, op, EULA, container, Java, the mod loaders, TPS, MSPT and more) have a *What's this?* explanation. ### Simple and Advanced view diff --git a/app/settings/page.tsx b/app/settings/page.tsx index 7c6f4f0..f5ae6af 100644 --- a/app/settings/page.tsx +++ b/app/settings/page.tsx @@ -177,7 +177,7 @@ const MODE_OPTIONS = [ id: "simple", title: "On this computer", description: - "MineUI downloads and runs a plain (vanilla) Minecraft server on this computer. You need Java, and nothing else.", + "MineUI downloads and runs a plain (vanilla) Minecraft server on this computer. If this computer has no Java, MineUI can get it for you.", icon: Sparkles, }, { From 9d2ced351dea2bfe0f625ed7d3acf196678cde84 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 19:08:05 -0600 Subject: [PATCH 13/28] docs: theme-contract - the header view level switch is not a mode toggle (2.13.0) Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- docs/theme-contract.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/theme-contract.md b/docs/theme-contract.md index 8994976..94cf1e8 100644 --- a/docs/theme-contract.md +++ b/docs/theme-contract.md @@ -326,6 +326,12 @@ Servers). It sits first. **There is no mode toggle in the header (2.9.0):** a one-click Simple/Advanced flip re-pointed the open server at the other kind, which looked like the server had been deleted; how a server is run is changed in Server Settings → Advanced only, never while it runs, and asks first. +The header does carry a **view level** switch (2.13.0, `ViewLevelSwitch`, +a Pro `Segment` labelled "How much MineUI shows": Simple / Advanced, default +Simple, kept in `localStorage` as `mineui-view-level`). It only shows or hides +parts of the app and never changes how a server is run, so it is not the mode +toggle this paragraph rules out. On screen the two server kinds read "On this +computer" and "In a container". Tiers: the name shows at T1–T2 (`header-mid:` and up, truncated at 7rem) and is CSS-hidden at T3–T4, leaving dot + chevron; the trigger itself is rendered at every tier, so no From 53c306e95795ced4aa072e0eaea0cdf410d28029 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 20:12:25 -0600 Subject: [PATCH 14/28] docs: v2-contract - Modrinth mod search and install, enable/disable (2.13.0) Beginner-friendly part G: find mods and plugins on Modrinth for the current server and install them with their required dependencies, every file checked against the sha512 Modrinth publishes. - New scoped commands (section 3.5a): get_mod_support (what the server can load, read from its own state: container TYPE/VERSION, vanilla on this computer), search_mods (Modrinth search with project type, loader, game version and server_side facets, installed flag from version_files) and install_mod (newest compatible version, release over beta over alpha, required dependencies resolved transitively with cycle guard, pinned versions, skip of installed ones and a 50-file cap; all files downloaded before any is placed; placed files rolled back on failure). - set_mod_enabled renames name.jar <-> name.jar.disabled in either server kind, never overwriting a file (section 3.5). - Section 6.3b: api.modrinth.com and cdn.modrinth.com only, https, every redirect hop re-checked, sha512 required and verified, 256 MB cap. - Error codes reused: WRONG_MODE for a server that cannot load mods or plugins, INVALID_INPUT, DOWNLOAD_FAILED, CHECKSUM_MISMATCH, FILE_TOO_LARGE. New audit actions mod.install, mod.enable, mod.disable. - Section 7 gains the matching ipc.ts types and wrappers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- docs/v2-contract.md | 327 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 321 insertions(+), 6 deletions(-) diff --git a/docs/v2-contract.md b/docs/v2-contract.md index 79cd85e..32fc5e0 100644 --- a/docs/v2-contract.md +++ b/docs/v2-contract.md @@ -61,12 +61,12 @@ type ErrorCode = | "EULA_NOT_ACCEPTED" // simple-mode start/create without EULA acceptance | "INSTANCE_NOT_FOUND" // simple-mode instance dir missing/uninitialized | "INSTANCE_EXISTS" // create_instance over an existing instance - | "DOWNLOAD_FAILED" // network failure fetching manifest/jar/mod/Java; unsafe Java archive (§6.3a) - | "CHECKSUM_MISMATCH" // downloaded jar failed sha1 verification, Java archive sha256 (2.13.0) + | "DOWNLOAD_FAILED" // network failure fetching manifest/jar/mod/Java; unsafe Java archive (§6.3a); Modrinth unreachable or a file off its hosts (§6.3b) + | "CHECKSUM_MISMATCH" // downloaded jar failed sha1 verification, Java archive sha256, Modrinth file sha512 (2.13.0) | "SERVER_UTILS_UNAVAILABLE" // serverUtilsUrl set but unreachable/non-OK | "PATH_NOT_ALLOWED" // config-editor path rejected by validation (§6) | "FILE_TOO_LARGE" // config write > 1.5 MB, upload > 256 MB, Java archive > 300 MB - | "WRONG_MODE" // command not available in active mode (§5) + | "WRONG_MODE" // command not available in active mode (§5); Find mods on a server that cannot load mods or plugins (§3.5a) | "INVALID_INPUT" // failed argument validation | "SETTINGS_INVALID" // set_settings payload failed validation | "SERVER_NOT_FOUND" // serverId names no server profile (§2.5, §3.0) @@ -702,6 +702,10 @@ Semantics: | `download_mod` | `{ url: string; filename?: string; target: ModTarget }` | `{ filename: string; downloadId: string }` | both | `mods::download` | POST /api/mods/download | | `delete_mod` | `{ filename: string; target: ModTarget }` | `void` | both | `mods::delete` | POST /api/mods/delete | | `unpack_mod_archive` | `{ sourcePath?: string; url?: string; filename?: string; target: ModTarget }` | `UnpackedMods` | both | `mod_archive::unpack` | - (new, 2.7.0) | +| `set_mod_enabled` (2.13.0) | `{ filename: string; target: ModTarget; enabled: boolean }` | `{ filename: string }` | both | `mods::set_enabled` | - (new) | +| `get_mod_support` (2.13.0) | - | `ModSupport` | both | `modrinth::support` | - (new, §3.5a) | +| `search_mods` (2.13.0) | `{ query: string; offset?: number; limit?: number }` | `ModSearchPage` | both (a server that can load mods or plugins, §3.5a) | `modrinth::search` | - (new, §3.5a) | +| `install_mod` (2.13.0) | `{ projectId: string }` | `ModInstall` | both (a server that can load mods or plugins, §3.5a) | `modrinth::install` | - (new, §3.5a) | ```ts type ModTarget = "mods" | "plugins"; @@ -781,6 +785,189 @@ Semantics: those list mods to download instead of containing them, and belong in §3.13. Config files and anything else in the archive are not installed. Audited as `mod.unpack` (target = archive name, detail = `: N installed, M skipped`). +- `set_mod_enabled` (2.13.0): turns a mod or plugin off and on by renaming it, the + convention every loader follows (a file ending `.disabled` is not loaded). + `enabled: false` renames `.jar` to `.jar.disabled`; `enabled: true` + renames `.jar.disabled` back to `.jar`. `filename` is the name + `list_mods` reported (which lists disabled files under their full name, so + `ModEntry.filename` ends `.jar.disabled` for a disabled mod). Validation + (`INVALID_INPUT`): bare filename as `delete_mod` (§6.2 rules 1, 3 and 4 applied to + `.jar`); with `enabled: false` it must end `.jar`, with `enabled: true` + `.jar.disabled` (case-insensitive; `.zip` mods cannot be switched). A missing + source file → `INVALID_INPUT` (` does not exist`); an existing file (or + link, or folder) at the new name → `INVALID_INPUT`, nothing is overwritten. + Advanced → one constant script through `run_in_container` (exec when running, + the stopped-container helper otherwise), the two paths passed as positional + arguments, never written into the script: + `sh -c '[ -f "$1" ] || exit 3; if [ -e "$2" ] || [ -L "$2" ]; then exit 4; fi; mv -- "$1" "$2"' sh / /` + (exit 3 → does not exist, 4 → already exists, any other failure → `IO`); simple → + the same checks then `std::fs::rename`. Returns the new filename. Works whatever + the server type (it is not gated on §3.5a). Audited as `mod.disable` / + `mod.enable` (target = the filename before, detail = ` → `). + +### 3.5a Find mods on Modrinth (2.13.0) + +Search Modrinth for mods or plugins this server can load, and install one with its +required dependencies. Every request goes to fixed Modrinth hosts and every file is +checked against the sha512 Modrinth publishes (§6.3b). Scope is deliberately small: +no update checks, no datapacks, no CurseForge / Hangar / Spiget, no `.mrpack` files. + +```ts +type ModSupport = { + /** False when this server cannot load mods or plugins (see `reason`). */ + supported: boolean; + /** Where installs go: "mods" (Fabric, Quilt, Forge, NeoForge) or + * "plugins" (Paper, Purpur); null when not supported. */ + target: ModTarget | null; + /** The server type MineUI read, lowercase ("fabric", "paper", "vanilla", + * "modrinth", ...); null when it could not tell. */ + serverType: string | null; + /** The Minecraft version results must have a build for; null when unknown. */ + mcVersion: string | null; + /** Modrinth loader tags a version must carry, preferred first; empty when + * not supported. */ + loaders: string[]; + /** Why not, in a plain sentence; null when supported. */ + reason: string | null; +}; + +/** Whether a mod's players need it too, as Modrinth reports it. */ +type ModClientSide = "required" | "optional" | "unsupported" | "unknown"; + +type ModSearchHit = { + projectId: string; + slug: string; + title: string; + description: string; + author: string; + iconUrl: string | null; + downloads: number; + /** "required": every player must install the mod too. */ + clientSide: ModClientSide; + /** Already in this server's folder (enabled or disabled). */ + installed: boolean; +}; + +type ModSearchPage = { + hits: ModSearchHit[]; + /** Echo of the request after clamping; the next page starts at + * offset + limit. */ + offset: number; + limit: number; + /** Modrinth's count of matches (client-only projects it still reports are + * dropped from `hits`, so a page can be shorter than `limit`). */ + totalHits: number; +}; + +type InstalledModFile = { + filename: string; + projectId: string; + slug: string; + title: string; + versionId: string; + versionNumber: string; + /** True when installed because another file needs it. */ + dependency: boolean; + /** The id its download-progress events carried. */ + downloadId: string; +}; + +type ModInstall = { + target: ModTarget; + /** The project asked for first, then its dependencies. */ + installed: InstalledModFile[]; + /** Titles of required dependencies that were already installed. */ + alreadyInstalled: string[]; +}; +``` + +**What the server can load.** Read from the server's own state, never from the +caller: a server on this computer (simple) runs the vanilla jar; a container's type +and version are its `TYPE` and `VERSION` env (the itzg convention, the same read as +the §3.12 overview identity; `VERSION` empty or `LATEST` = unknown). + +| `TYPE` | `target` | `loaders` (preferred first) | +| --- | --- | --- | +| `FABRIC` | `mods` | `fabric` | +| `QUILT` | `mods` | `quilt`, `fabric` | +| `FORGE` | `mods` | `forge` | +| `NEOFORGE` | `mods` | `neoforge` | +| `PAPER` | `plugins` | `paper`, `spigot`, `bukkit` | +| `PURPUR` | `plugins` | `purpur`, `paper`, `spigot`, `bukkit` | + +Anything else is not supported, with a `reason`: a simple server (vanilla on this +computer), `VANILLA`, a modpack container (`MODRINTH`, `AUTO_CURSEFORGE`: the pack +decides its mods and MineUI cannot tell its loader), any other or missing `TYPE`, or +a supported type whose Minecraft version is unknown. + +- `get_mod_support`: the table above for the targeted server, no network. Not + supported is a result, not an error. Rejects only when the server's state cannot + be read: `RUNTIME_NOT_FOUND`, `RUNTIME_UNAVAILABLE`, `CONTAINER_NOT_FOUND` (the + configured container does not exist). +- `search_mods`: one GET of `https://api.modrinth.com/v2/search` with + `query` (trimmed, ≤ 100 chars, else `INVALID_INPUT`), `offset` (default 0, clamped to + 0-10 000), `limit` (default 20, clamped to 1-50), `index` = `downloads` for an empty + query else `relevance`, and facets + `[["project_type:mod"|"project_type:plugin"], [<"categories:" for each loader>], ["versions:"], ["server_side:required","server_side:optional"]]` + (`project_type:mod` for target `mods`, `project_type:plugin` for `plugins`; inner + arrays are OR, outer AND). Modrinth's `server_side` facet still lets through a few + projects whose summary `server_side` is `unsupported`; those hits are dropped. `installed` + is true when the hit's project id is among the projects of the files already in the + target folder (below); when that lookup fails, every `installed` is false and the + search still answers. Not supported → `WRONG_MODE` (message = `reason`); network, + non-2xx or an unreadable answer → `DOWNLOAD_FAILED`. Read-only, not audited. +- **Installed projects** (used by `search_mods` and `install_mod`): the sha1 of + every file in the target folder (advanced: the constant script + `for f in /*; do [ -f "$f" ] || continue; sha1sum "$f"; done` through + `run_in_container`; simple: hashed host-side), sent in one + `POST https://api.modrinth.com/v2/version_files` `{ "hashes": [...], "algorithm": "sha1" }`; + (at most 1000 hashes; files past that are only matched by name), and + the answer maps each known hash to its version and so its `project_id`. A file + Modrinth does not know (an upload, a jar from elsewhere) is simply not a project. + The answer is cached on the server's core for the same set of hashes. +- `install_mod`: `projectId` is a Modrinth project id or slug, + `^[A-Za-z0-9_-]{1,64}$` (`INVALID_INPUT`). Steps: + 1. Not supported → `WRONG_MODE`. + 2. Version choice for a project: `GET /v2/project//version` with + `loaders=`, `game_versions=[""]`, + `include_changelog=false`. Of the versions whose `status` is `listed` (or + absent), whose `game_versions` contain `mcVersion`, whose `loaders` share a tag + with `loaders` and whose primary file (the `primary: true` one, else the first) + is a `.jar`: the best by version type (`release` over `beta` over `alpha`), + then by loader (earlier in `loaders` first), then the newest `date_published`. + None → `INVALID_INPUT` naming the project, the Minecraft version and the + server type. A project Modrinth does not know (404) → `INVALID_INPUT`. + 3. Dependencies, breadth first from the chosen version: only + `dependency_type: "required"` (`optional`, `embedded`, `incompatible` are not + followed). A dependency naming a `version_id` uses exactly that version + (`GET /v2/version/`); it must share a loader tag with `loaders` (its game + versions are the author's call and are not checked). Otherwise its + `project_id` goes through step 2. A dependency with neither (only a + `file_name`) cannot be resolved. A project already planned is not visited + again (cycles end there); a dependency whose project is already installed, or + whose chosen file name is already in the folder, is skipped and reported in + `alreadyInstalled`. A required dependency that cannot be resolved fails the + whole install with `INVALID_INPUT` naming it and the mod that needs it. More + than 50 files in total → `INVALID_INPUT`. + 4. The project asked for is refused when it is already installed (its project id + is in the folder, enabled or disabled) or its file name is already taken + (`INVALID_INPUT`): MineUI never overwrites a file here. + 5. Each planned file is downloaded host-side under §6.3b (progress events with + `kind: "mod"`, one `downloadId` per file), all of them before any is placed. + 6. Then all are placed like `unpack_mod_archive` (advanced: one + `runtime cp /. :`; simple: file copies). If placing fails, + the files this install placed are removed again (advanced: `rm -f -- ` + through `run_in_container`); nothing that was in the folder before is touched. + Any failure leaves nothing of this install behind (temp files, staging folder, + placed files) and its message names the mod it concerns. Errors: `WRONG_MODE`, + `INVALID_INPUT`, `DOWNLOAD_FAILED` (network, non-2xx, unreadable answer, a file + link or redirect off the Modrinth hosts, a file without a sha512), + `CHECKSUM_MISMATCH`, `FILE_TOO_LARGE` (over 256 MB), `IO` and the runtime errors + of `list_mods` while placing. The mod only loads after a restart; the server is + not restarted. Audited as `mod.install`, one entry per placed file (target = the + filename, detail = `: `, plus + `, needed by ` for a dependency), or one failed entry (target = `projectId`) + when the install fails. ### 3.6 Simple-mode instance management (`WRONG_MODE` outside simple, except `list_mc_versions`) @@ -1150,7 +1337,11 @@ type AuditEntry = { token, detail = full command), `player.` for `kick`/`ban`/`pardon`/`op`/ `deop`/`whitelist` issued through `run_rcon_command` (target = username), `backup.create`, `backup.restore`, `backup.delete`, `backup.prune`, `backup.copy`, - `config.write`, `mod.upload`, `mod.download`, `mod.delete`, `mod.unpack`, `settings.update`, + `config.write`, `mod.upload`, `mod.download`, `mod.delete`, `mod.unpack`, + `mod.install` (§3.5a, 2.13.0: one entry per placed file, target = filename, detail + `: [, needed by ]`; on failure one entry with + target = the `projectId` asked for), `mod.enable` / `mod.disable` (§3.5, 2.13.0: + target = the filename before, detail = ` → `), `settings.update`, `instance.create`, `instance.delete`, `instance.change-version` (2.10.0, §3.6), `note.set`, `note.clear`, `scheduler.restart`, `scheduler.backup`, `scheduler.broadcast`, @@ -1795,7 +1986,8 @@ full detail. Frontend pattern: fetch state on mount, subscribe for invalidation. ### 4.3 `mineui://download-progress` Emitted for server-jar downloads (`create_instance`), mod downloads -(`download_mod`) and the Java runtime download (`install_java`, 2.13.0 - carrying +(`download_mod`, `unpack_mod_archive` from a URL, and each file of `install_mod`, +2.13.0) and the Java runtime download (`install_java`, 2.13.0 - carrying the requesting server's id although the install is app-wide). Throttled to ≥ 150 ms between progress events per download; the terminal event (`done` or `error`) is always emitted. @@ -1821,6 +2013,9 @@ is identified by `kind: "server-jar"` - only one can run at a time, enforced by `kind: "java"`, `filename` being the Adoptium archive name (e.g. `OpenJDK21U-jre_x64_linux_hotspot_21.0.13_9.tar.gz`); a request that waits for another server's install of the same major sees no events. +`install_mod` (2.13.0) returns each file's `downloadId` in `ModInstall` once it is +done; while it runs, its files are the `kind: "mod"` events whose `filename` is a +Modrinth file name, one download after the other. Subscription lifecycle (all events): `listen()` returns an unlisten fn; every page/hook that subscribes MUST unlisten on unmount. Events carry no secrets. @@ -1840,6 +2035,7 @@ that subscribes MUST unlisten on unmount. Events carry no secrets. | RCON (players, history, commands) | full - auto-configured at create/start | full - user-supplied credentials | | Player history log source | `/logs/latest.log` | exec `tail` in container | | Mods/plugins management | file ops work; **vanilla jar loads none** (UI note) | full | +| Find mods (§3.5a, 2.13.0) | `get_mod_support` says not supported (vanilla); `search_mods` / `install_mod` → `WRONG_MODE` | by the container's `TYPE`: Fabric, Quilt, Forge, NeoForge (mods), Paper, Purpur (plugins); other types as simple | | Config editor | host fs under `instanceDir` | exec/cp in container | | Backups create/list/restore/delete | host-side tar | argv-exec tar in container | | Metrics base | process CPU/RSS via sysinfo | container stats via runtime | @@ -1975,6 +2171,37 @@ Fixed hosts, no user-supplied URL. Error codes as listed in §3.1. previous folder there (one that failed the reuse check) is renamed aside first and removed after. On every failure the archive and the temp dir are removed. +### 6.3b Modrinth requests and files (`search_mods`, `install_mod`, 2.13.0) + +Fixed hosts, no user-supplied URL. Error codes as listed in §3.5a. + +1. The caller supplies only search text, two numbers and a project id or slug. The + text and numbers travel as URL-encoded query parameters; the id or slug must match + `^[A-Za-z0-9_-]{1,64}$` (`INVALID_INPUT`) before it becomes a path segment. Version + and project ids taken from Modrinth's own answers are held to the same pattern + before they become path segments (`DOWNLOAD_FAILED` otherwise). +2. Every request and every file goes through one client whose hosts are + `api.modrinth.com` (search, project versions, a version, `version_files`, the + projects batch) and `cdn.modrinth.com` (files): https only, no credentials, the + default port. Every redirect hop is re-checked against the same rule (≤ 5 hops); + a hop anywhere else fails the request (`DOWNLOAD_FAILED`). A version file whose + `url` is not on `cdn.modrinth.com` is refused before any request + (`DOWNLOAD_FAILED`). Observed on 2026-11-10: files are served 200 by + `cdn.modrinth.com` directly. +3. API calls: 10 s timeout, the `User-Agent` `I4cTime/mineui/ + (mineui.i4c.studio)` that Modrinth's rules ask for (300 requests per minute per + IP; an install makes 2 + one per resolved project, at most about 55). +4. A file is used only with a 128-hex-digit `hashes.sha512` (`DOWNLOAD_FAILED` + otherwise). The streamed bytes' sha512 must equal it, and the sha1 too when + Modrinth gives one (`CHECKSUM_MISMATCH`, message naming the mod). Size cap 256 MB: + an announced `size` or `Content-Length` over it is refused before streaming and + the stream is cut at the cap (`FILE_TOO_LARGE`). 60 s idle timeout as §6.3. +5. The file name is Modrinth's `filename` after §6.2 sanitization; it must end + `.jar` (a version whose primary file is not a `.jar` is not a candidate, §3.5a). +6. Downloads land in `/tmp/` and are moved into a staging folder + `/tmp/modrinth-/` under their final names; the staging folder and + every temp file are removed whether the install succeeds or fails. + ### 6.4 RCON commands See §3.4: trim, strip one leading `/`, ≤ 200 chars, first token lowercased ∈ @@ -2472,6 +2699,93 @@ export type ModArchiveSource = export const unpackModArchive = (source: ModArchiveSource, target: ModTarget) => scoped("unpack_mod_archive", { ...source, target }); +/** Renames name.jar to name.jar.disabled (enabled false) or back + * (enabled true); returns the new filename (§3.5, 2.13.0). */ +export const setModEnabled = (filename: string, target: ModTarget, enabled: boolean) => + scoped<{ filename: string }>("set_mod_enabled", { filename, target, enabled }); + +/* ---------- find mods on Modrinth (§3.5a, 2.13.0) ---------- */ + +/** What Find mods can do for this server. */ +export type ModSupport = { + /** False when this server cannot load mods or plugins (see `reason`). */ + supported: boolean; + /** Where installs go: "mods" (Fabric, Quilt, Forge, NeoForge) or + * "plugins" (Paper, Purpur); null when not supported. */ + target: ModTarget | null; + /** The server type MineUI read, lowercase ("fabric", "paper", "vanilla", + * "modrinth", ...); null when it could not tell. */ + serverType: string | null; + /** The Minecraft version results must have a build for; null when unknown. */ + mcVersion: string | null; + /** Modrinth loader tags a version must carry, preferred first; empty when + * not supported. */ + loaders: string[]; + /** Why not, in a plain sentence; null when supported. */ + reason: string | null; +}; + +/** Whether a mod's players need it too, as Modrinth reports it. */ +export type ModClientSide = "required" | "optional" | "unsupported" | "unknown"; + +export type ModSearchHit = { + projectId: string; + slug: string; + title: string; + description: string; + author: string; + iconUrl: string | null; + downloads: number; + /** "required": every player must install the mod too. */ + clientSide: ModClientSide; + /** Already in this server's folder (enabled or disabled). */ + installed: boolean; +}; + +export type ModSearchPage = { + hits: ModSearchHit[]; + /** Echo of the request after clamping; the next page starts at + * offset + limit. */ + offset: number; + limit: number; + /** Modrinth's count of matches (client-only projects it still reports are + * dropped from `hits`, so a page can be shorter than `limit`). */ + totalHits: number; +}; + +export type InstalledModFile = { + filename: string; + projectId: string; + slug: string; + title: string; + versionId: string; + versionNumber: string; + /** True when installed because another file needs it. */ + dependency: boolean; + /** The id its download-progress events carried. */ + downloadId: string; +}; + +export type ModInstall = { + target: ModTarget; + /** The project asked for first, then its dependencies. */ + installed: InstalledModFile[]; + /** Titles of required dependencies that were already installed. */ + alreadyInstalled: string[]; +}; + +/** No network; "not supported" is a result with a reason, not an error. */ +export const getModSupport = () => scoped("get_mod_support"); +/** Modrinth mods or plugins this server can load. Empty query = most + * downloaded. Rejects WRONG_MODE when the server cannot load any. */ +export const searchMods = (query: string, offset?: number, limit?: number) => + scoped("search_mods", { query, offset, limit }); +/** Installs the newest compatible version of a Modrinth project (id or + * slug) with its required dependencies, each checked against Modrinth's + * sha512. Takes effect after a restart. */ +export const installMod = (projectId: string) => + scoped("install_mod", { projectId }); + /* ---------- instance (simple mode) ---------- */ export type McVersion = { @@ -2747,7 +3061,8 @@ Frontend rules: | `java` | java discovery + `-version` parsing; the managed-Java lookup and resolution order (§3.1, 2.13.0) | | `javainstall` | `install_java` (§3.1, §6.3a, 2.13.0): Adoptium API query, the host-allowlisted client, sha256-verified download, safe tar.gz/zip extraction, locate + probe, rename into place, per-major install lock, `java.install` audit | | `instance` | create/delete/status, change version in place (2.10.0), `mineui-instance.json`, eula.txt, server.properties RCON assertion (preserving user keys) | -| `mods` | list/upload/download/delete over `Runtime` or host fs (§3.5, §6.2–6.3) | +| `mods` | list/upload/download/delete over `Runtime` or host fs (§3.5, §6.2–6.3); `set_mod_enabled` renames (2.13.0) | +| `modrinth` | Find mods (§3.5a, §6.3b, 2.13.0): server type → target and loader tags, the Modrinth host-allowlisted client, search facets, installed projects from `version_files`, version choice, dependency resolution, sha512-checked downloads, staged placement with rollback, `mod.install` audit | | `mod_archive` | `unpack_mod_archive`: entry selection, bounded host-side extraction, placement (§3.5, §6.2a) | | `config_files` | list/read/write over `Runtime` or host fs (§3.7, §6.1) | | `backups` | create/list/restore/delete (§3.8) | From 660d2c7c9755b06a7a984a90e1499464aaa5019a Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 20:22:55 -0600 Subject: [PATCH 15/28] feat(core): find mods on Modrinth, install with dependencies, enable/disable Beginner-friendly part G backend (contract sections 3.5, 3.5a, 6.3b). - modrinth module: get_mod_support reads what the server can load from its own state (container TYPE/VERSION; vanilla on this computer, modpack containers and unknown types say why). search_mods queries Modrinth with project type, loader categories, game version and server_side facets, drops client-only hits, and marks installed projects from the sha1s of the files in the folder via POST /v2/version_files (cached per hash set). - install_mod picks the newest compatible version (release over beta over alpha, preferred loader, newest), resolves required dependencies breadth first with a cycle guard, pinned versions, skip of installed projects or file names and a 50-file cap, downloads every file through a client that only talks https to api.modrinth.com and cdn.modrinth.com (every redirect hop re-checked), verifies sha512 (and sha1), stages the files and places them in one step, removing what it placed if placing fails. Audited as mod.install per file. - DownloadRequest gains expected_sha512 (sha2 already a dependency). - set_mod_enabled renames name.jar <-> name.jar.disabled with a constant script whose paths arrive as positional arguments, refusing to overwrite; audited as mod.enable / mod.disable. - Tauri: get_mod_support, search_mods, install_mod, set_mod_enabled (thin delegation); ipc.ts equals contract section 7. 306 unit tests (was 273) on recorded Modrinth fixtures. Live tests: the real search, resolution of Chunky + Fabric API, download with sha512 and a version_files lookup pass; the full install, installed flag, re-install refusal and enable/disable (running and stopped) pass on a throwaway TYPE=FABRIC container on rootless Podman. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- app/lib/ipc.ts | 87 ++ crates/mineui-core/src/download.rs | 17 + crates/mineui-core/src/javainstall.rs | 2 + crates/mineui-core/src/lib.rs | 5 + crates/mineui-core/src/mod_archive.rs | 3 +- crates/mineui-core/src/model.rs | 76 + crates/mineui-core/src/modpacks.rs | 2 +- crates/mineui-core/src/modrinth.rs | 1331 +++++++++++++++++ crates/mineui-core/src/modrinth/tests.rs | 1017 +++++++++++++ crates/mineui-core/src/mods.rs | 264 +++- crates/mineui-core/src/mojang.rs | 1 + .../modrinth-search-chunky-fabric-1.21.1.json | 294 ++++ .../fixtures/modrinth-version-files-sha1.json | 84 ++ ...odrinth-versions-chunky-fabric-1.21.1.json | 90 ++ .../modrinth-versions-fabric-api-1.21.1.json | 110 ++ crates/mineui-core/tests/live_modrinth.rs | 303 ++++ src-tauri/src/commands.rs | 53 +- src-tauri/src/lib.rs | 5 + 18 files changed, 3737 insertions(+), 7 deletions(-) create mode 100644 crates/mineui-core/src/modrinth.rs create mode 100644 crates/mineui-core/src/modrinth/tests.rs create mode 100644 crates/mineui-core/tests/fixtures/modrinth-search-chunky-fabric-1.21.1.json create mode 100644 crates/mineui-core/tests/fixtures/modrinth-version-files-sha1.json create mode 100644 crates/mineui-core/tests/fixtures/modrinth-versions-chunky-fabric-1.21.1.json create mode 100644 crates/mineui-core/tests/fixtures/modrinth-versions-fabric-api-1.21.1.json create mode 100644 crates/mineui-core/tests/live_modrinth.rs diff --git a/app/lib/ipc.ts b/app/lib/ipc.ts index 8863898..4a0522e 100644 --- a/app/lib/ipc.ts +++ b/app/lib/ipc.ts @@ -480,6 +480,93 @@ export type ModArchiveSource = export const unpackModArchive = (source: ModArchiveSource, target: ModTarget) => scoped("unpack_mod_archive", { ...source, target }); +/** Renames name.jar to name.jar.disabled (enabled false) or back + * (enabled true); returns the new filename (§3.5, 2.13.0). */ +export const setModEnabled = (filename: string, target: ModTarget, enabled: boolean) => + scoped<{ filename: string }>("set_mod_enabled", { filename, target, enabled }); + +/* ---------- find mods on Modrinth (§3.5a, 2.13.0) ---------- */ + +/** What Find mods can do for this server. */ +export type ModSupport = { + /** False when this server cannot load mods or plugins (see `reason`). */ + supported: boolean; + /** Where installs go: "mods" (Fabric, Quilt, Forge, NeoForge) or + * "plugins" (Paper, Purpur); null when not supported. */ + target: ModTarget | null; + /** The server type MineUI read, lowercase ("fabric", "paper", "vanilla", + * "modrinth", ...); null when it could not tell. */ + serverType: string | null; + /** The Minecraft version results must have a build for; null when unknown. */ + mcVersion: string | null; + /** Modrinth loader tags a version must carry, preferred first; empty when + * not supported. */ + loaders: string[]; + /** Why not, in a plain sentence; null when supported. */ + reason: string | null; +}; + +/** Whether a mod's players need it too, as Modrinth reports it. */ +export type ModClientSide = "required" | "optional" | "unsupported" | "unknown"; + +export type ModSearchHit = { + projectId: string; + slug: string; + title: string; + description: string; + author: string; + iconUrl: string | null; + downloads: number; + /** "required": every player must install the mod too. */ + clientSide: ModClientSide; + /** Already in this server's folder (enabled or disabled). */ + installed: boolean; +}; + +export type ModSearchPage = { + hits: ModSearchHit[]; + /** Echo of the request after clamping; the next page starts at + * offset + limit. */ + offset: number; + limit: number; + /** Modrinth's count of matches (client-only projects it still reports are + * dropped from `hits`, so a page can be shorter than `limit`). */ + totalHits: number; +}; + +export type InstalledModFile = { + filename: string; + projectId: string; + slug: string; + title: string; + versionId: string; + versionNumber: string; + /** True when installed because another file needs it. */ + dependency: boolean; + /** The id its download-progress events carried. */ + downloadId: string; +}; + +export type ModInstall = { + target: ModTarget; + /** The project asked for first, then its dependencies. */ + installed: InstalledModFile[]; + /** Titles of required dependencies that were already installed. */ + alreadyInstalled: string[]; +}; + +/** No network; "not supported" is a result with a reason, not an error. */ +export const getModSupport = () => scoped("get_mod_support"); +/** Modrinth mods or plugins this server can load. Empty query = most + * downloaded. Rejects WRONG_MODE when the server cannot load any. */ +export const searchMods = (query: string, offset?: number, limit?: number) => + scoped("search_mods", { query, offset, limit }); +/** Installs the newest compatible version of a Modrinth project (id or + * slug) with its required dependencies, each checked against Modrinth's + * sha512. Takes effect after a restart. */ +export const installMod = (projectId: string) => + scoped("install_mod", { projectId }); + /* ---------- instance (simple mode) ---------- */ export type McVersion = { diff --git a/crates/mineui-core/src/download.rs b/crates/mineui-core/src/download.rs index e53a95f..716e0f9 100644 --- a/crates/mineui-core/src/download.rs +++ b/crates/mineui-core/src/download.rs @@ -31,6 +31,9 @@ pub struct DownloadRequest { /// Expected SHA-256 (hex); mismatch → CHECKSUM_MISMATCH (Java runtime /// archives, §6.3a). pub expected_sha256: Option, + /// Expected SHA-512 (hex); mismatch → CHECKSUM_MISMATCH (Modrinth files, + /// §6.3b). + pub expected_sha512: Option, /// A client with its own redirect policy (the host-allowlisted Java /// client, §6.3a). Takes precedence over `allow_private_hosts`. pub client: Option, @@ -154,6 +157,7 @@ async fn run(core: &crate::Core, req: &DownloadRequest) -> Result Result Result>, + /// Modrinth's answer for the sha1s of the files in the mods/plugins + /// folder (§3.5a installed projects), cached for the same set of hashes. + pub(crate) modrinth_hashes: std::sync::Mutex>, /// Podman machine facts, cached 60 s (§3.2 `machine::facts`). pub(crate) machine_facts: tokio::sync::Mutex>, @@ -145,6 +149,7 @@ impl Core { mojang_cache: tokio::sync::Mutex::new(None), last_advanced_phase: std::sync::Mutex::new(None), container_kind: std::sync::Mutex::new(None), + modrinth_hashes: std::sync::Mutex::new(None), machine_facts: tokio::sync::Mutex::new(None), audit_lock: tokio::sync::Mutex::new(()), notes_lock: tokio::sync::Mutex::new(()), diff --git a/crates/mineui-core/src/mod_archive.rs b/crates/mineui-core/src/mod_archive.rs index cedb256..5ac0b48 100644 --- a/crates/mineui-core/src/mod_archive.rs +++ b/crates/mineui-core/src/mod_archive.rs @@ -217,7 +217,7 @@ fn extract_with_limits( } /// Place every file of `dir` into the target root. -async fn place_dir( +pub(crate) async fn place_dir( core: &crate::Core, dir: &Path, target: ModTarget, @@ -305,6 +305,7 @@ async fn acquire( max_bytes: Some(ARCHIVE_MAX_BYTES), expected_sha1: None, expected_sha256: None, + expected_sha512: None, client: None, allow_private_hosts: allow_private, }; diff --git a/crates/mineui-core/src/model.rs b/crates/mineui-core/src/model.rs index e483383..58b3e43 100644 --- a/crates/mineui-core/src/model.rs +++ b/crates/mineui-core/src/model.rs @@ -218,6 +218,82 @@ pub struct UnpackedMods { pub download_id: Option, } +/// Result of `set_mod_enabled` (§3.5, 2.13.0): the file's new name. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RenamedMod { + pub filename: String, +} + +/* ---------- §3.5a find mods on Modrinth (2.13.0) ---------- */ + +/// What Find mods can do for one server (`get_mod_support`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModSupport { + pub supported: bool, + pub target: Option, + pub server_type: Option, + pub mc_version: Option, + pub loaders: Vec, + pub reason: Option, +} + +/// Modrinth's `client_side` of a project. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ModClientSide { + Required, + Optional, + Unsupported, + Unknown, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModSearchHit { + pub project_id: String, + pub slug: String, + pub title: String, + pub description: String, + pub author: String, + pub icon_url: Option, + pub downloads: u64, + pub client_side: ModClientSide, + pub installed: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModSearchPage { + pub hits: Vec, + pub offset: u32, + pub limit: u32, + pub total_hits: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InstalledModFile { + pub filename: String, + pub project_id: String, + pub slug: String, + pub title: String, + pub version_id: String, + pub version_number: String, + pub dependency: bool, + pub download_id: String, +} + +/// Result of `install_mod`. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModInstall { + pub target: ModTarget, + pub installed: Vec, + pub already_installed: Vec, +} + /* ---------- §3.6 instance ---------- */ #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/mineui-core/src/modpacks.rs b/crates/mineui-core/src/modpacks.rs index 66d4982..6ec9fd4 100644 --- a/crates/mineui-core/src/modpacks.rs +++ b/crates/mineui-core/src/modpacks.rs @@ -25,7 +25,7 @@ const CURSEFORGE_PAGE: &str = "https://www.curseforge.com/minecraft/modpacks/"; const KNOWN_LOADERS: [&str; 4] = ["forge", "neoforge", "fabric", "quilt"]; /// Modrinth asks every client to identify itself. -fn user_agent() -> String { +pub(crate) fn user_agent() -> String { format!( "I4cTime/mineui/{} (mineui.i4c.studio)", env!("CARGO_PKG_VERSION") diff --git a/crates/mineui-core/src/modrinth.rs b/crates/mineui-core/src/modrinth.rs new file mode 100644 index 0000000..031d9f5 --- /dev/null +++ b/crates/mineui-core/src/modrinth.rs @@ -0,0 +1,1331 @@ +//! Find mods on Modrinth (contract §3.5a, §6.3b, 2.13.0): what a server can +//! load, search filtered to it, and installs of the newest compatible version +//! with its required dependencies. +//! +//! Every request goes through one client that only talks https to +//! `api.modrinth.com` and `cdn.modrinth.com`, redirects included. Every file +//! is checked against the sha512 Modrinth publishes, all files are downloaded +//! before any is placed, and a failed placement removes what it placed. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::LazyLock; +use std::time::Duration; + +use async_trait::async_trait; +use serde::de::DeserializeOwned; +use serde::Deserialize; + +use crate::error::{Error, Result}; +use crate::model::{ + AuditSource, DownloadKind, InstalledModFile, ModClientSide, ModInstall, ModSearchHit, + ModSearchPage, ModSupport, ModTarget, ServerPhase, +}; +use crate::settings::Mode; + +/// §6.3b rule 2: the only hosts Find mods may touch, redirects included. +pub const ALLOWED_HOSTS: &[&str] = &["api.modrinth.com", "cdn.modrinth.com"]; +/// Where version files must live (§6.3b rule 2). +pub const CDN_HOST: &str = "cdn.modrinth.com"; +const API_BASE: &str = "https://api.modrinth.com/v2"; +const MAX_REDIRECTS: usize = 5; +const API_TIMEOUT: Duration = Duration::from_secs(10); + +pub const DEFAULT_LIMIT: u32 = 20; +pub const MAX_LIMIT: u32 = 50; +pub const MAX_OFFSET: u32 = 10_000; +pub const MAX_QUERY_CHARS: usize = 100; +/// §3.5a step 3: most files one install may bring in. +pub const MAX_FILES: usize = 50; +/// Most hashes sent to `version_files` in one lookup. +const MAX_HASHES: usize = 1000; + +/// Constant hashing scripts, zero interpolation (§3.5a installed projects). +const HASH_MODS: &str = r#"for f in /data/mods/*; do [ -f "$f" ] || continue; sha1sum "$f"; done"#; +const HASH_PLUGINS: &str = + r#"for f in /data/plugins/*; do [ -f "$f" ] || continue; sha1sum "$f"; done"#; + +/* ---------- what the server can load (§3.5a table) ---------- */ + +/// The facts Find mods works from, for a server that can load mods or +/// plugins. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ServerMods { + pub target: ModTarget, + pub mc_version: String, + /// Modrinth loader tags, preferred first. + pub loaders: Vec, + /// For messages: "Fabric", "NeoForge", "Paper", ... + pub type_name: String, +} + +/// `TYPE` (lowercase) → where files go and the loader tags it accepts. +pub fn loaders_for(server_type: &str) -> Option<(ModTarget, &'static [&'static str])> { + match server_type { + "fabric" => Some((ModTarget::Mods, &["fabric"])), + "quilt" => Some((ModTarget::Mods, &["quilt", "fabric"])), + "forge" => Some((ModTarget::Mods, &["forge"])), + "neoforge" => Some((ModTarget::Mods, &["neoforge"])), + "paper" => Some((ModTarget::Plugins, &["paper", "spigot", "bukkit"])), + "purpur" => Some((ModTarget::Plugins, &["purpur", "paper", "spigot", "bukkit"])), + _ => None, + } +} + +fn type_name(server_type: &str) -> String { + match server_type { + "fabric" => "Fabric".into(), + "quilt" => "Quilt".into(), + "forge" => "Forge".into(), + "neoforge" => "NeoForge".into(), + "paper" => "Paper".into(), + "purpur" => "Purpur".into(), + "vanilla" => "Vanilla".into(), + other => other.to_ascii_uppercase(), + } +} + +/// §3.5a: support from what the server is. `simple` = a server on this +/// computer (always the vanilla jar today). +pub fn support_for( + simple: bool, + server_type: Option<&str>, + mc_version: Option<&str>, +) -> ModSupport { + let server_type = server_type.map(|t| t.trim().to_ascii_lowercase()); + let mc_version = mc_version + .map(str::trim) + .filter(|v| !v.is_empty() && !v.eq_ignore_ascii_case("latest")) + .map(str::to_string); + let not = |reason: String| ModSupport { + supported: false, + target: None, + server_type: server_type.clone(), + mc_version: mc_version.clone(), + loaders: Vec::new(), + reason: Some(reason), + }; + if simple { + return not( + "This server runs plain Minecraft on this computer, which cannot load mods or \ + plugins. A server in a container can." + .into(), + ); + } + let Some(kind) = server_type.as_deref() else { + return not("MineUI cannot tell what type of server this container runs.".into()); + }; + let Some((target, loaders)) = loaders_for(kind) else { + return not(match kind { + "vanilla" => { + "This server runs plain Minecraft (Vanilla), which cannot load mods or plugins." + .into() + } + "modrinth" | "auto_curseforge" => "This server runs a modpack. The pack decides its \ + mods, and MineUI cannot tell which mod loader it uses." + .into(), + other => format!( + "MineUI cannot add mods to a {} server.", + other.to_ascii_uppercase() + ), + }); + }; + if mc_version.is_none() { + return not( + "MineUI cannot tell which Minecraft version this server runs, so it cannot pick \ + mods that fit." + .into(), + ); + } + ModSupport { + supported: true, + target: Some(target), + server_type: server_type.clone(), + mc_version: mc_version.clone(), + loaders: loaders.iter().map(|l| l.to_string()).collect(), + reason: None, + } +} + +/// `get_mod_support` (§3.5a): no network. +pub async fn support(core: &crate::Core) -> Result { + let settings = core.settings().await; + if settings.active_mode == Mode::Simple { + return Ok(support_for( + true, + Some("vanilla"), + Some(settings.simple.mc_version.as_str()), + )); + } + let (phase, identity) = crate::identity::probe(core).await; + if phase? == ServerPhase::NotCreated { + return Err(Error::ContainerNotFound(format!( + "container '{}' does not exist", + settings.advanced.container_name + ))); + } + Ok(support_for( + false, + identity.loader.as_deref(), + identity.mc_version.as_deref(), + )) +} + +/// The server's facts, or `WRONG_MODE` with the reason it cannot load any. +pub fn server_mods(support: &ModSupport) -> Result { + match (support.supported, support.target, &support.mc_version) { + (true, Some(target), Some(mc_version)) => Ok(ServerMods { + target, + mc_version: mc_version.clone(), + loaders: support.loaders.clone(), + type_name: type_name(support.server_type.as_deref().unwrap_or("")), + }), + _ => Err(Error::WrongMode(support.reason.clone().unwrap_or_else( + || "This server cannot load mods or plugins.".into(), + ))), + } +} + +/* ---------- the host-allowlisted client (§6.3b rule 2) ---------- */ + +/// https, no credentials, default port, allowlisted host. +pub fn url_allowed(url: &reqwest::Url) -> bool { + url.scheme() == "https" + && url.username().is_empty() + && url.password().is_none() + && url.port().is_none() + && url + .host_str() + .is_some_and(|h| ALLOWED_HOSTS.iter().any(|a| a.eq_ignore_ascii_case(h))) +} + +/// Every redirect hop must pass `url_allowed` too. +fn redirect_policy() -> reqwest::redirect::Policy { + reqwest::redirect::Policy::custom(|attempt| { + if attempt.previous().len() > MAX_REDIRECTS { + return attempt.error("too many redirects"); + } + if !url_allowed(attempt.url()) { + let host = attempt.url().host_str().unwrap_or("?").to_string(); + return attempt.error(format!("redirect to a host MineUI does not trust ({host})")); + } + attempt.follow() + }) +} + +/// The client every Modrinth request and file goes through. +pub fn build_client() -> reqwest::Client { + reqwest::Client::builder() + .redirect(redirect_policy()) + .connect_timeout(Duration::from_secs(15)) + .read_timeout(Duration::from_secs(60)) + .user_agent(crate::modpacks::user_agent()) + .build() + .expect("reqwest client construction cannot fail with static config") +} + +static CLIENT: LazyLock = LazyLock::new(build_client); + +/// §6.3b rule 1: a project or version id / slug before it becomes a path +/// segment. +pub fn valid_id(id: &str) -> bool { + (1..=64).contains(&id.len()) + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') +} + +fn api_url(segments: &[&str]) -> Result { + let mut url = reqwest::Url::parse(API_BASE) + .map_err(|e| Error::Internal(format!("bad Modrinth URL: {e}")))?; + url.path_segments_mut() + .map_err(|_| Error::Internal("bad Modrinth URL".into()))? + .extend(segments); + Ok(url) +} + +/// GET (or POST with a JSON body) one API URL. `Ok(None)` = 404. +async fn api_json( + client: &reqwest::Client, + url: reqwest::Url, + body: Option<&serde_json::Value>, + what: &str, +) -> Result> { + if !url_allowed(&url) { + return Err(Error::Internal(format!("not a Modrinth API URL: {url}"))); + } + let request = match body { + Some(body) => client.post(url).json(body), + None => client.get(url), + }; + let response = request + .timeout(API_TIMEOUT) + .send() + .await + .map_err(|e| Error::DownloadFailed(format!("could not reach Modrinth: {e}")))?; + if response.status() == reqwest::StatusCode::NOT_FOUND { + return Ok(None); + } + if !response.status().is_success() { + return Err(Error::DownloadFailed(format!( + "Modrinth answered HTTP {} when asked for {what}", + response.status().as_u16() + ))); + } + let text = response + .text() + .await + .map_err(|e| Error::DownloadFailed(format!("could not read Modrinth's answer: {e}")))?; + serde_json::from_str(&text).map(Some).map_err(|e| { + Error::DownloadFailed(format!( + "Modrinth sent an answer MineUI cannot read ({what}): {e}" + )) + }) +} + +/* ---------- Modrinth's shapes ---------- */ + +#[derive(Debug, Clone, Deserialize)] +pub struct Version { + pub id: String, + pub project_id: String, + #[serde(default)] + pub version_number: String, + #[serde(default)] + pub version_type: String, + #[serde(default)] + pub status: Option, + #[serde(default)] + pub date_published: String, + #[serde(default)] + pub game_versions: Vec, + #[serde(default)] + pub loaders: Vec, + #[serde(default)] + pub dependencies: Vec, + #[serde(default)] + pub files: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Dependency { + #[serde(default)] + pub version_id: Option, + #[serde(default)] + pub project_id: Option, + #[serde(default)] + pub file_name: Option, + pub dependency_type: String, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct VersionFile { + #[serde(default)] + pub hashes: Hashes, + pub url: String, + pub filename: String, + #[serde(default)] + pub primary: bool, + #[serde(default)] + pub size: u64, +} + +#[derive(Debug, Clone, Default, Deserialize)] +pub struct Hashes { + #[serde(default)] + pub sha512: Option, + #[serde(default)] + pub sha1: Option, +} + +/// Parse a `/project//version` body. +pub fn parse_versions(body: &str) -> Result> { + serde_json::from_str(body).map_err(|e| { + Error::DownloadFailed(format!("Modrinth sent versions MineUI cannot read: {e}")) + }) +} + +/* ---------- version choice (§3.5a step 2) ---------- */ + +/// The primary file: the one marked primary, else the first. +pub fn primary_file(version: &Version) -> Option<&VersionFile> { + version + .files + .iter() + .find(|f| f.primary) + .or_else(|| version.files.first()) +} + +fn is_jar(file: &VersionFile) -> bool { + file.filename.to_ascii_lowercase().ends_with(".jar") +} + +fn type_rank(version_type: &str) -> u8 { + match version_type { + "release" => 0, + "beta" => 1, + "alpha" => 2, + _ => 3, + } +} + +/// Position of the version's best loader in the server's preference list. +fn loader_rank(version: &Version, loaders: &[String]) -> Option { + loaders + .iter() + .position(|l| version.loaders.iter().any(|v| v.eq_ignore_ascii_case(l))) +} + +fn published(version: &Version) -> i64 { + chrono::DateTime::parse_from_rfc3339(&version.date_published) + .map(|d| d.timestamp_micros()) + .unwrap_or(i64::MIN) +} + +/// Best version for this Minecraft version and these loaders: release over +/// beta over alpha, then the preferred loader, then the newest. +pub fn choose_version<'a>( + versions: &'a [Version], + mc_version: &str, + loaders: &[String], +) -> Option<&'a Version> { + versions + .iter() + .filter(|v| matches!(v.status.as_deref(), None | Some("listed"))) + .filter(|v| v.game_versions.iter().any(|g| g == mc_version)) + .filter(|v| primary_file(v).is_some_and(is_jar)) + .filter_map(|v| loader_rank(v, loaders).map(|rank| (v, rank))) + .min_by(|(a, rank_a), (b, rank_b)| { + type_rank(&a.version_type) + .cmp(&type_rank(&b.version_type)) + .then(rank_a.cmp(rank_b)) + .then_with(|| published(b).cmp(&published(a))) + }) + .map(|(v, _)| v) +} + +/* ---------- what is installed (§3.5a installed projects) ---------- */ + +/// Files already in the target folder. +#[derive(Debug, Clone, Default)] +pub struct InstalledIndex { + /// Lowercased name of every file in the folder. + pub filenames: HashSet, + /// Project id → a file of that project in the folder. + pub projects: HashMap, +} + +impl InstalledIndex { + pub fn has_file(&self, name: &str) -> bool { + self.filenames.contains(&name.to_ascii_lowercase()) + } +} + +/// `version_files` answers for one set of hashes. +#[derive(Debug, Clone)] +pub struct HashCache { + hashes: Vec, + projects: HashMap, +} + +/// `sha1sum` lines (`<40 hex> /`) → (sha1, name). +pub fn parse_sha1sum(stdout: &str, root: &str) -> Vec<(String, String)> { + let prefix = format!("{root}/"); + stdout + .lines() + .filter_map(|line| { + let (hash, rest) = line.split_once(char::is_whitespace)?; + if hash.len() != 40 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let path = rest.trim_start_matches([' ', '*']); + let name = path.strip_prefix(&prefix)?; + (!name.is_empty() && !name.contains('/')) + .then(|| (hash.to_ascii_lowercase(), name.to_string())) + }) + .collect() +} + +fn sha1_of_file(path: &Path) -> std::io::Result { + use sha1::{Digest, Sha1}; + use std::io::Read; + let mut file = std::fs::File::open(path)?; + let mut hasher = Sha1::new(); + let mut buf = vec![0u8; 64 * 1024]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + } + Ok(hex::encode(hasher.finalize())) +} + +/// (sha1, filename) of every file in the target folder. +async fn file_hashes(core: &crate::Core, target: ModTarget) -> Result> { + let settings = core.settings().await; + match settings.active_mode { + Mode::Advanced => { + let runtime = crate::runtime::resolve(&settings.advanced).await?; + let script = match target { + ModTarget::Mods => HASH_MODS, + ModTarget::Plugins => HASH_PLUGINS, + }; + let out = crate::runtime::run_in_container( + runtime.as_ref(), + &settings.advanced.container_name, + &["sh", "-c", script], + ) + .await?; + if !out.success() { + return Err(Error::Io(format!( + "could not read the files in {}: {}", + crate::mods::container_root(target), + out.stderr.trim() + ))); + } + Ok(parse_sha1sum( + &out.stdout, + crate::mods::container_root(target), + )) + } + Mode::Simple => { + let dir = settings.simple.instance_dir.join(target.dir_name()); + tokio::task::spawn_blocking(move || { + let mut found = Vec::new(); + let Ok(entries) = std::fs::read_dir(&dir) else { + return found; + }; + for entry in entries.flatten() { + if !entry.file_type().is_ok_and(|t| t.is_file()) { + continue; + } + if let Ok(hash) = sha1_of_file(&entry.path()) { + found.push((hash, entry.file_name().to_string_lossy().to_string())); + } + } + found + }) + .await + .map_err(|e| Error::Internal(format!("hashing task failed: {e}"))) + } + } +} + +#[derive(Debug, Deserialize)] +struct VersionProject { + project_id: String, +} + +/// Hash → project id, from `POST /v2/version_files` (cached per hash set). +async fn projects_for_hashes( + core: &crate::Core, + client: &reqwest::Client, + hashes: &[String], +) -> Result> { + let mut key: Vec = hashes.to_vec(); + key.sort(); + if let Some(cache) = core.modrinth_hashes.lock().unwrap().as_ref() { + if cache.hashes == key { + return Ok(cache.projects.clone()); + } + } + let body = serde_json::json!({ "hashes": key, "algorithm": "sha1" }); + let answer: HashMap = api_json( + client, + api_url(&["version_files"])?, + Some(&body), + "the installed files", + ) + .await? + .unwrap_or_default(); + let projects: HashMap = answer + .into_iter() + .map(|(hash, v)| (hash.to_ascii_lowercase(), v.project_id)) + .collect(); + *core.modrinth_hashes.lock().unwrap() = Some(HashCache { + hashes: key, + projects: projects.clone(), + }); + Ok(projects) +} + +/// What is already in the target folder, by name and by Modrinth project. +pub async fn installed_index( + core: &crate::Core, + client: &reqwest::Client, + target: ModTarget, +) -> Result { + let files = file_hashes(core, target).await?; + let mut index = InstalledIndex::default(); + for (_, name) in &files { + index.filenames.insert(name.to_ascii_lowercase()); + } + let hashes: Vec = files + .iter() + .take(MAX_HASHES) + .map(|(h, _)| h.clone()) + .collect(); + if hashes.is_empty() { + return Ok(index); + } + let projects = projects_for_hashes(core, client, &hashes).await?; + for (hash, name) in &files { + if let Some(project) = projects.get(hash) { + index + .projects + .entry(project.clone()) + .or_insert_with(|| name.clone()); + } + } + Ok(index) +} + +/* ---------- search (§3.5a search_mods) ---------- */ + +/// The search facets for this server (inner arrays OR, outer AND). +pub fn facets(server: &ServerMods) -> String { + let project_type = match server.target { + ModTarget::Mods => "project_type:mod", + ModTarget::Plugins => "project_type:plugin", + }; + let loaders: Vec = server + .loaders + .iter() + .map(|l| format!("categories:{l}")) + .collect(); + serde_json::json!([ + [project_type], + loaders, + [format!("versions:{}", server.mc_version)], + ["server_side:required", "server_side:optional"], + ]) + .to_string() +} + +#[derive(Debug, Deserialize)] +struct SearchResponse { + #[serde(default)] + hits: Vec, + #[serde(default)] + total_hits: u64, +} + +#[derive(Debug, Deserialize)] +struct RawHit { + project_id: String, + #[serde(default)] + slug: Option, + title: String, + #[serde(default)] + description: String, + #[serde(default)] + author: String, + #[serde(default)] + icon_url: Option, + #[serde(default)] + downloads: u64, + #[serde(default)] + client_side: String, + #[serde(default)] + server_side: String, +} + +fn client_side(value: &str) -> ModClientSide { + match value { + "required" => ModClientSide::Required, + "optional" => ModClientSide::Optional, + "unsupported" => ModClientSide::Unsupported, + _ => ModClientSide::Unknown, + } +} + +/// Parse a `/v2/search` body; client-only hits are dropped. +pub fn parse_search(body: &str, offset: u32, limit: u32) -> Result { + let parsed: SearchResponse = serde_json::from_str(body) + .map_err(|e| Error::DownloadFailed(format!("unexpected Modrinth response: {e}")))?; + let hits = parsed + .hits + .into_iter() + .filter(|h| h.server_side != "unsupported") + .map(|h| ModSearchHit { + slug: h.slug.unwrap_or_else(|| h.project_id.clone()), + project_id: h.project_id, + title: h.title, + description: h.description, + author: h.author, + icon_url: h.icon_url.filter(|u| !u.is_empty()), + downloads: h.downloads, + client_side: client_side(&h.client_side), + installed: false, + }) + .collect(); + Ok(ModSearchPage { + hits, + offset, + limit, + total_hits: parsed.total_hits, + }) +} + +/// One search request (no installed flags). +pub async fn search_page( + client: &reqwest::Client, + server: &ServerMods, + query: &str, + offset: u32, + limit: u32, +) -> Result { + let index = if query.is_empty() { + "downloads" + } else { + "relevance" + }; + let mut url = api_url(&["search"])?; + url.query_pairs_mut() + .append_pair("query", query) + .append_pair("facets", &facets(server)) + .append_pair("index", index) + .append_pair("offset", &offset.to_string()) + .append_pair("limit", &limit.to_string()); + let response = client + .get(url) + .timeout(API_TIMEOUT) + .send() + .await + .map_err(|e| Error::DownloadFailed(format!("could not reach Modrinth: {e}")))?; + if !response.status().is_success() { + return Err(Error::DownloadFailed(format!( + "Modrinth search returned HTTP {}", + response.status().as_u16() + ))); + } + let body = response + .text() + .await + .map_err(|e| Error::DownloadFailed(format!("could not read Modrinth's response: {e}")))?; + parse_search(&body, offset, limit) +} + +/// `search_mods` (§3.5a). +pub async fn search( + core: &crate::Core, + query: &str, + offset: Option, + limit: Option, +) -> Result { + let query = query.trim(); + if query.chars().count() > MAX_QUERY_CHARS { + return Err(Error::InvalidInput(format!( + "search text must be at most {MAX_QUERY_CHARS} characters" + ))); + } + let server = server_mods(&support(core).await?)?; + let offset = offset.unwrap_or(0).min(MAX_OFFSET); + let limit = limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT); + let client = CLIENT.clone(); + let (page, installed) = tokio::join!( + search_page(&client, &server, query, offset, limit), + installed_index(core, &client, server.target) + ); + let mut page = page?; + // The installed flags are a nicety: a failed lookup leaves them false. + if let Ok(installed) = installed { + for hit in &mut page.hits { + hit.installed = installed.projects.contains_key(&hit.project_id); + } + } + Ok(page) +} + +/* ---------- dependency resolution (§3.5a step 3) ---------- */ + +/// The calls the resolver makes; `Ok(None)` = Modrinth has no such thing. +#[async_trait] +pub trait VersionSource: Send + Sync { + async fn project_versions( + &self, + project: &str, + loaders: &[String], + mc_version: &str, + ) -> Result>>; + async fn version(&self, id: &str) -> Result>; + /// A project's title, for messages (best effort). + async fn title(&self, project: &str) -> Option; +} + +/// The real Modrinth API. +pub struct LiveSource { + pub client: reqwest::Client, +} + +#[derive(Debug, Deserialize)] +struct ProjectInfo { + id: String, + #[serde(default)] + slug: Option, + #[serde(default)] + title: String, +} + +#[async_trait] +impl VersionSource for LiveSource { + async fn project_versions( + &self, + project: &str, + loaders: &[String], + mc_version: &str, + ) -> Result>> { + let mut url = api_url(&["project", project, "version"])?; + url.query_pairs_mut() + .append_pair("loaders", &serde_json::json!(loaders).to_string()) + .append_pair( + "game_versions", + &serde_json::json!([mc_version]).to_string(), + ) + .append_pair("include_changelog", "false"); + api_json(&self.client, url, None, "a mod's versions").await + } + + async fn version(&self, id: &str) -> Result> { + api_json(&self.client, api_url(&["version", id])?, None, "a version").await + } + + async fn title(&self, project: &str) -> Option { + let url = api_url(&["project", project]).ok()?; + let info: ProjectInfo = api_json(&self.client, url, None, "a project") + .await + .ok()??; + Some(info.title).filter(|t| !t.is_empty()) + } +} + +/// One file the install will place. +#[derive(Debug, Clone)] +pub struct PlannedFile { + pub project_id: String, + pub version_id: String, + pub version_number: String, + pub filename: String, + pub url: reqwest::Url, + pub sha512: String, + pub sha1: Option, + pub size: u64, + /// The project id that needed it; None for the one asked for. + pub needed_by: Option, +} + +impl PlannedFile { + pub fn dependency(&self) -> bool { + self.needed_by.is_some() + } +} + +#[derive(Debug, Clone, Default)] +pub struct Plan { + /// The project asked for first, then its dependencies (breadth first). + pub files: Vec, + /// Project ids of required dependencies that are already installed. + pub already_installed: Vec, +} + +enum Want { + Project(String), + Version(String), +} + +struct Item { + want: Want, + needed_by: Option, +} + +async fn name_of(source: &dyn VersionSource, project: &str) -> String { + source + .title(project) + .await + .unwrap_or_else(|| project.to_string()) +} + +fn is_hex(s: &str, len: usize) -> bool { + s.len() == len && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// Turn a chosen version into a `PlannedFile` (§6.3b rules 2, 4, 5). Errors +/// do not name the mod; the caller puts its name in front (`about`). +fn plan_file(version: &Version, needed_by: Option) -> Result { + let no_jar = || Error::InvalidInput("it has no .jar file to install".into()); + let file = primary_file(version) + .filter(|f| is_jar(f)) + .ok_or_else(no_jar)?; + let filename = crate::validate::mod_filename(&file.filename, true)?; + if !filename.to_ascii_lowercase().ends_with(".jar") { + return Err(no_jar()); + } + let url = reqwest::Url::parse(&file.url) + .ok() + .filter(|u| url_allowed(u) && u.host_str() == Some(CDN_HOST)) + .ok_or_else(|| { + Error::DownloadFailed(format!( + "the file is not on {CDN_HOST}, so MineUI will not download it" + )) + })?; + let sha512 = file + .hashes + .sha512 + .as_deref() + .map(str::to_ascii_lowercase) + .filter(|h| is_hex(h, 128)) + .ok_or_else(|| { + Error::DownloadFailed( + "Modrinth gives no sha512 checksum for the file, so MineUI cannot check it".into(), + ) + })?; + let sha1 = file + .hashes + .sha1 + .as_deref() + .map(str::to_ascii_lowercase) + .filter(|h| is_hex(h, 40)); + if file.size > crate::mods::MOD_MAX_BYTES { + return Err(Error::FileTooLarge(format!( + "the file is {} bytes; the limit is {}", + file.size, + crate::mods::MOD_MAX_BYTES + ))); + } + Ok(PlannedFile { + project_id: version.project_id.clone(), + version_id: version.id.clone(), + version_number: version.version_number.clone(), + filename, + url, + sha512, + sha1, + size: file.size, + needed_by, + }) +} + +/// §3.5a steps 2-4: the files one install needs, breadth first. +pub async fn plan_install( + source: &dyn VersionSource, + server: &ServerMods, + project: &str, + installed: &InstalledIndex, +) -> Result { + if !valid_id(project) { + return Err(Error::InvalidInput(format!( + "not a Modrinth project id: {project}" + ))); + } + let on = format!("Minecraft {} on {}", server.mc_version, server.type_name); + let mut queue = VecDeque::from([Item { + want: Want::Project(project.to_string()), + needed_by: None, + }]); + let mut visited: HashSet = HashSet::new(); + let mut seen_versions: HashSet = HashSet::new(); + let mut plan = Plan::default(); + + while let Some(item) = queue.pop_front() { + let is_root = item.needed_by.is_none(); + let version = match &item.want { + Want::Project(id) => { + if visited.contains(id) { + continue; + } + if !is_root && installed.projects.contains_key(id) { + visited.insert(id.clone()); + plan.already_installed.push(id.clone()); + continue; + } + let Some(versions) = source + .project_versions(id, &server.loaders, &server.mc_version) + .await? + else { + return Err(Error::InvalidInput(match &item.needed_by { + None => format!("Modrinth has no project called {id}"), + Some(p) => format!( + "{} needs a project Modrinth does not have ({id})", + name_of(source, p).await + ), + })); + }; + match choose_version(&versions, &server.mc_version, &server.loaders) { + Some(v) => v.clone(), + None => { + let name = name_of(source, id).await; + return Err(Error::InvalidInput(match &item.needed_by { + None => format!("{name} has no version for {on}"), + Some(p) => format!( + "{} needs {name}, which has no version for {on}", + name_of(source, p).await + ), + })); + } + } + } + Want::Version(vid) => { + if !seen_versions.insert(vid.clone()) { + continue; + } + let p = match &item.needed_by { + Some(p) => name_of(source, p).await, + None => String::new(), + }; + let Some(v) = source.version(vid).await? else { + return Err(Error::InvalidInput(format!( + "{p} needs a version of another mod that Modrinth does not have ({vid})" + ))); + }; + if loader_rank(&v, &server.loaders).is_none() { + let name = name_of(source, &v.project_id).await; + return Err(Error::InvalidInput(format!( + "{p} needs {name} {}, which is not made for {}", + v.version_number, server.type_name + ))); + } + v + } + }; + + let pid = version.project_id.clone(); + if !valid_id(&pid) || !valid_id(&version.id) { + return Err(Error::DownloadFailed( + "Modrinth sent an id MineUI cannot use".into(), + )); + } + if !visited.insert(pid.clone()) { + continue; + } + if is_root { + if let Some(file) = installed.projects.get(&pid) { + return Err(Error::InvalidInput(format!( + "{} is already installed ({file})", + name_of(source, &pid).await + ))); + } + } else if installed.projects.contains_key(&pid) { + plan.already_installed.push(pid); + continue; + } + let file = match plan_file(&version, item.needed_by.clone()) { + Ok(file) => file, + Err(err) => return Err(about(err, &name_of(source, &pid).await)), + }; + if installed.has_file(&file.filename) { + if is_root { + return Err(Error::InvalidInput(format!( + "there is already a file named {} in the {} folder", + file.filename, + server.target.dir_name() + ))); + } + plan.already_installed.push(pid); + continue; + } + if plan + .files + .iter() + .any(|f| f.filename.eq_ignore_ascii_case(&file.filename)) + { + return Err(Error::InvalidInput(format!( + "two of the files to install are both named {}", + file.filename + ))); + } + + for dep in version + .dependencies + .iter() + .filter(|d| d.dependency_type == "required") + { + let want = match (&dep.version_id, &dep.project_id) { + (Some(vid), _) if valid_id(vid) => Want::Version(vid.clone()), + (None, Some(dep_pid)) if valid_id(dep_pid) => Want::Project(dep_pid.clone()), + (Some(_), _) | (None, Some(_)) => { + return Err(Error::DownloadFailed( + "Modrinth sent an id MineUI cannot use".into(), + )) + } + (None, None) => { + return Err(Error::InvalidInput(format!( + "{} needs {}, which is not on Modrinth, so MineUI cannot install it", + name_of(source, &pid).await, + dep.file_name.as_deref().unwrap_or("a file") + ))) + } + }; + queue.push_back(Item { + want, + needed_by: Some(pid.clone()), + }); + } + plan.files.push(file); + if plan.files.len() > MAX_FILES { + let root = name_of(source, &plan.files[0].project_id).await; + return Err(Error::InvalidInput(format!( + "{root} needs more than {MAX_FILES} files, more than MineUI installs at once" + ))); + } + } + Ok(plan) +} + +/* ---------- download, stage, place (§3.5a steps 5-6) ---------- */ + +/// The same error with the mod's name in front. +fn about(err: Error, name: &str) -> Error { + match err { + Error::DownloadFailed(m) => Error::DownloadFailed(format!("{name}: {m}")), + Error::ChecksumMismatch(m) => Error::ChecksumMismatch(format!("{name}: {m}")), + Error::FileTooLarge(m) => Error::FileTooLarge(format!("{name}: {m}")), + Error::Io(m) => Error::Io(format!("{name}: {m}")), + Error::InvalidInput(m) => Error::InvalidInput(format!("{name}: {m}")), + other => other, + } +} + +/// Download every planned file to a temp file, each checked against its +/// sha512 (and sha1). On any failure every temp file is removed. Returns +/// (temp path, download id) per file, in order. +pub async fn download_plan( + core: &crate::Core, + client: &reqwest::Client, + files: &[PlannedFile], + names: &HashMap, +) -> Result> { + let mut done: Vec<(PathBuf, String)> = Vec::new(); + for file in files { + let download_id = uuid::Uuid::new_v4().to_string(); + let request = crate::download::DownloadRequest { + url: file.url.clone(), + kind: DownloadKind::Mod, + filename: file.filename.clone(), + download_id: download_id.clone(), + max_bytes: Some(crate::mods::MOD_MAX_BYTES), + expected_sha1: file.sha1.clone(), + expected_sha256: None, + expected_sha512: Some(file.sha512.clone()), + client: Some(client.clone()), + allow_private_hosts: false, + }; + match crate::download::to_temp_file(core, &request).await { + Ok(result) => done.push((result.temp_path, download_id)), + Err(err) => { + for (path, _) in &done { + let _ = tokio::fs::remove_file(path).await; + } + let name = names + .get(&file.project_id) + .map(String::as_str) + .unwrap_or(&file.filename); + return Err(about(err, name)); + } + } + } + Ok(done) +} + +/// Remove files this install placed (never one that was there before: name +/// collisions were refused while planning). +async fn remove_placed(core: &crate::Core, target: ModTarget, names: &[String]) { + let settings = core.settings().await; + match settings.active_mode { + Mode::Advanced => { + let Ok(runtime) = crate::runtime::resolve(&settings.advanced).await else { + return; + }; + let root = crate::mods::container_root(target); + let paths: Vec = names.iter().map(|n| format!("{root}/{n}")).collect(); + let mut argv: Vec<&str> = vec!["rm", "-f", "--"]; + argv.extend(paths.iter().map(String::as_str)); + let _ = crate::runtime::run_in_container( + runtime.as_ref(), + &settings.advanced.container_name, + &argv, + ) + .await; + } + Mode::Simple => { + let dir = settings.simple.instance_dir.join(target.dir_name()); + for name in names { + let _ = tokio::fs::remove_file(dir.join(name)).await; + } + } + } +} + +/// Move the downloads into a staging folder under their final names and +/// place them all; on failure remove what was placed. The staging folder and +/// temp files are always removed. +pub async fn stage_and_place( + core: &crate::Core, + target: ModTarget, + files: &[PlannedFile], + temps: &[(PathBuf, String)], +) -> Result<()> { + let staging = core + .paths + .data_dir + .join("tmp") + .join(format!("modrinth-{}", uuid::Uuid::new_v4().simple())); + let names: Vec = files.iter().map(|f| f.filename.clone()).collect(); + let result = async { + tokio::fs::create_dir_all(&staging) + .await + .map_err(|e| Error::Io(format!("could not create a staging folder: {e}")))?; + for (file, (temp, _)) in files.iter().zip(temps) { + tokio::fs::rename(temp, staging.join(&file.filename)) + .await + .map_err(|e| Error::Io(format!("could not stage {}: {e}", file.filename)))?; + } + if let Err(err) = crate::mod_archive::place_dir(core, &staging, target, &names).await { + remove_placed(core, target, &names).await; + return Err(err); + } + Ok(()) + } + .await; + let _ = tokio::fs::remove_dir_all(&staging).await; + for (temp, _) in temps { + let _ = tokio::fs::remove_file(temp).await; + } + result +} + +/* ---------- install_mod (§3.5a) ---------- */ + +#[derive(Debug, Clone)] +struct Named { + slug: String, + title: String, +} + +/// Slugs and titles of several projects in one call (best effort). +async fn project_names(client: &reqwest::Client, ids: &[String]) -> HashMap { + if ids.is_empty() { + return HashMap::new(); + } + let Ok(mut url) = api_url(&["projects"]) else { + return HashMap::new(); + }; + url.query_pairs_mut() + .append_pair("ids", &serde_json::json!(ids).to_string()); + let answer: Option> = api_json(client, url, None, "project names") + .await + .ok() + .flatten(); + answer + .unwrap_or_default() + .into_iter() + .map(|p| { + let slug = p.slug.unwrap_or_else(|| p.id.clone()); + let title = if p.title.is_empty() { + slug.clone() + } else { + p.title + }; + (p.id, Named { slug, title }) + }) + .collect() +} + +async fn install_inner(core: &crate::Core, project: &str) -> Result { + let project = project.trim(); + if !valid_id(project) { + return Err(Error::InvalidInput(format!( + "not a Modrinth project id: {project}" + ))); + } + let server = server_mods(&support(core).await?)?; + let client = CLIENT.clone(); + let installed = installed_index(core, &client, server.target).await?; + let source = LiveSource { + client: client.clone(), + }; + let plan = plan_install(&source, &server, project, &installed).await?; + + let ids: Vec = plan + .files + .iter() + .map(|f| f.project_id.clone()) + .chain(plan.already_installed.iter().cloned()) + .collect(); + let names = project_names(&client, &ids).await; + let named = |id: &str| { + names.get(id).cloned().unwrap_or_else(|| Named { + slug: id.to_string(), + title: id.to_string(), + }) + }; + let titles: HashMap = + ids.iter().map(|id| (id.clone(), named(id).title)).collect(); + + let temps = download_plan(core, &client, &plan.files, &titles).await?; + stage_and_place(core, server.target, &plan.files, &temps).await?; + + let mut result = ModInstall { + target: server.target, + installed: Vec::new(), + already_installed: plan + .already_installed + .iter() + .map(|id| named(id).title) + .collect(), + }; + for (file, (_, download_id)) in plan.files.iter().zip(&temps) { + let n = named(&file.project_id); + let mut detail = format!( + "{}: {} {}", + crate::mods::target_label(server.target), + n.slug, + file.version_number + ); + if let Some(parent) = &file.needed_by { + detail.push_str(&format!(", needed by {}", named(parent).slug)); + } + crate::audit::record( + core, + AuditSource::User, + "mod.install", + Some(&file.filename), + Some(&detail), + None, + ) + .await; + result.installed.push(InstalledModFile { + filename: file.filename.clone(), + project_id: file.project_id.clone(), + slug: n.slug, + title: n.title, + version_id: file.version_id.clone(), + version_number: file.version_number.clone(), + dependency: file.dependency(), + download_id: download_id.clone(), + }); + } + Ok(result) +} + +/// `install_mod` (§3.5a): audited as `mod.install` per placed file, or one +/// failed entry. +pub async fn install(core: &crate::Core, project_id: &str) -> Result { + let r = install_inner(core, project_id).await; + if let Err(err) = &r { + crate::audit::record( + core, + AuditSource::User, + "mod.install", + Some(project_id), + None, + Some(err), + ) + .await; + } + r +} + +#[cfg(test)] +mod tests; diff --git a/crates/mineui-core/src/modrinth/tests.rs b/crates/mineui-core/src/modrinth/tests.rs new file mode 100644 index 0000000..09b390d --- /dev/null +++ b/crates/mineui-core/src/modrinth/tests.rs @@ -0,0 +1,1017 @@ +//! Unit tests for Find mods (§3.5a, §6.3b). Network-free: Modrinth answers +//! come from recorded fixtures (`tests/fixtures/modrinth-*.json`, fetched +//! 2026-11-10) or are built here; downloads come from a local socket. + +use super::*; + +const SEARCH_FIXTURE: &str = + include_str!("../../tests/fixtures/modrinth-search-chunky-fabric-1.21.1.json"); +const CHUNKY_VERSIONS: &str = + include_str!("../../tests/fixtures/modrinth-versions-chunky-fabric-1.21.1.json"); +const FABRIC_API_VERSIONS: &str = + include_str!("../../tests/fixtures/modrinth-versions-fabric-api-1.21.1.json"); +const VERSION_FILES: &str = include_str!("../../tests/fixtures/modrinth-version-files-sha1.json"); + +const CHUNKY: &str = "fALzjamp"; +const FABRIC_API: &str = "P7dR8mSH"; + +fn fabric() -> ServerMods { + server_mods(&support_for(false, Some("fabric"), Some("1.21.1"))).unwrap() +} + +/* ---------- a scripted Modrinth ---------- */ + +#[derive(Default)] +struct FakeSource { + /// Project id or slug → its versions (already "filtered" by Modrinth). + projects: HashMap>, + versions: HashMap, + titles: HashMap, + calls: std::sync::Mutex>, +} + +impl FakeSource { + fn with(mut self, project: &str, title: &str, versions: Vec) -> Self { + for v in &versions { + self.versions.insert(v.id.clone(), v.clone()); + } + self.projects.insert(project.into(), versions); + self.titles.insert(project.into(), title.into()); + self + } + fn calls(&self) -> Vec { + self.calls.lock().unwrap().clone() + } +} + +#[async_trait] +impl VersionSource for FakeSource { + async fn project_versions( + &self, + project: &str, + _loaders: &[String], + _mc_version: &str, + ) -> Result>> { + self.calls + .lock() + .unwrap() + .push(format!("project {project}")); + Ok(self.projects.get(project).cloned()) + } + async fn version(&self, id: &str) -> Result> { + self.calls.lock().unwrap().push(format!("version {id}")); + Ok(self.versions.get(id).cloned()) + } + async fn title(&self, project: &str) -> Option { + self.titles.get(project).cloned() + } +} + +fn dep(project: Option<&str>, version: Option<&str>, kind: &str) -> Dependency { + Dependency { + version_id: version.map(str::to_string), + project_id: project.map(str::to_string), + file_name: None, + dependency_type: kind.into(), + } +} + +fn required(project: &str) -> Dependency { + dep(Some(project), None, "required") +} + +/// A version with one primary jar on the CDN. +fn ver(id: &str, project: &str, kind: &str, date: &str, deps: Vec) -> Version { + Version { + id: id.into(), + project_id: project.into(), + version_number: format!("{id}-number"), + version_type: kind.into(), + status: Some("listed".into()), + date_published: date.into(), + game_versions: vec!["1.21.1".into()], + loaders: vec!["fabric".into()], + dependencies: deps, + files: vec![VersionFile { + hashes: Hashes { + sha512: Some("a".repeat(128)), + sha1: None, + }, + url: format!( + "https://cdn.modrinth.com/data/{project}/versions/{id}/{project}-{id}.jar" + ), + filename: format!("{project}-{id}.jar"), + primary: true, + size: 10, + }], + } +} + +const D1: &str = "2025-01-01T00:00:00Z"; +const D2: &str = "2025-06-01T00:00:00Z"; +const D3: &str = "2026-01-01T00:00:00Z"; + +/* ---------- §3.5a table ---------- */ + +#[test] +fn loader_tags_per_server_type() { + let mods = ModTarget::Mods; + let plugins = ModTarget::Plugins; + for (kind, target, loaders) in [ + ("FABRIC", mods, vec!["fabric"]), + ("quilt", mods, vec!["quilt", "fabric"]), + ("Forge", mods, vec!["forge"]), + ("NEOFORGE", mods, vec!["neoforge"]), + ("PAPER", plugins, vec!["paper", "spigot", "bukkit"]), + ( + "PURPUR", + plugins, + vec!["purpur", "paper", "spigot", "bukkit"], + ), + ] { + let s = support_for(false, Some(kind), Some("1.21.1")); + assert!(s.supported, "{kind}"); + assert_eq!(s.target, Some(target), "{kind}"); + assert_eq!(s.loaders, loaders, "{kind}"); + assert_eq!(s.server_type.as_deref(), Some(kind.to_lowercase().as_str())); + assert_eq!(s.mc_version.as_deref(), Some("1.21.1")); + assert!(s.reason.is_none()); + } +} + +#[test] +fn servers_that_cannot_load_mods_say_why() { + for (simple, kind, version, says) in [ + (true, Some("vanilla"), Some("1.21.1"), "on this computer"), + (false, Some("VANILLA"), Some("1.21.1"), "Vanilla"), + (false, Some("MODRINTH"), Some("1.21.1"), "modpack"), + (false, Some("AUTO_CURSEFORGE"), None, "modpack"), + (false, Some("SPIGOT"), Some("1.21.1"), "SPIGOT"), + (false, None, Some("1.21.1"), "what type"), + (false, Some("FABRIC"), None, "which Minecraft version"), + ( + false, + Some("FABRIC"), + Some("LATEST"), + "which Minecraft version", + ), + ] { + let s = support_for(simple, kind, version); + assert!(!s.supported, "{kind:?}"); + assert!(s.target.is_none() && s.loaders.is_empty()); + let reason = s.reason.clone().unwrap(); + assert!(reason.contains(says), "{kind:?}: {reason}"); + let err = server_mods(&s).unwrap_err(); + assert_eq!(err.code(), "WRONG_MODE"); + assert_eq!(err.to_string(), reason); + } +} + +#[test] +fn support_serializes_camel_case() { + let v = serde_json::to_value(support_for(false, Some("PAPER"), Some("1.21.4"))).unwrap(); + assert_eq!(v["target"], "plugins"); + assert_eq!(v["serverType"], "paper"); + assert_eq!(v["mcVersion"], "1.21.4"); + assert!(v["reason"].is_null()); +} + +#[tokio::test] +async fn a_server_on_this_computer_is_not_supported_and_needs_no_network() { + let tmp = tempfile::tempdir().unwrap(); + let core = crate::Core::init(tmp.path().join("config"), tmp.path().join("data")) + .await + .unwrap(); + let s = support(&core).await.unwrap(); + assert!(!s.supported); + assert_eq!(s.server_type.as_deref(), Some("vanilla")); + assert_eq!( + search(&core, "sodium", None, None) + .await + .unwrap_err() + .code(), + "WRONG_MODE" + ); + assert_eq!( + install(&core, "sodium").await.unwrap_err().code(), + "WRONG_MODE" + ); + // Input checks come first. + let long = "x".repeat(MAX_QUERY_CHARS + 1); + assert_eq!( + search(&core, &long, None, None).await.unwrap_err().code(), + "INVALID_INPUT" + ); + assert_eq!( + install(&core, "../etc").await.unwrap_err().code(), + "INVALID_INPUT" + ); + let log = crate::audit::recent(&core, Some(5)).await.unwrap(); + assert!(log + .entries + .iter() + .any(|e| e.action == "mod.install" && !e.ok)); +} + +/* ---------- search ---------- */ + +#[test] +fn facets_per_target() { + let f: serde_json::Value = serde_json::from_str(&facets(&fabric())).unwrap(); + assert_eq!( + f, + serde_json::json!([ + ["project_type:mod"], + ["categories:fabric"], + ["versions:1.21.1"], + ["server_side:required", "server_side:optional"] + ]) + ); + let quilt = server_mods(&support_for(false, Some("quilt"), Some("1.20.1"))).unwrap(); + let f: serde_json::Value = serde_json::from_str(&facets(&quilt)).unwrap(); + assert_eq!( + f[1], + serde_json::json!(["categories:quilt", "categories:fabric"]) + ); + assert_eq!(f[2], serde_json::json!(["versions:1.20.1"])); + let purpur = server_mods(&support_for(false, Some("purpur"), Some("1.21.4"))).unwrap(); + let f: serde_json::Value = serde_json::from_str(&facets(&purpur)).unwrap(); + assert_eq!(f[0], serde_json::json!(["project_type:plugin"])); + assert_eq!( + f[1], + serde_json::json!([ + "categories:purpur", + "categories:paper", + "categories:spigot", + "categories:bukkit" + ]) + ); +} + +#[test] +fn parses_a_real_search_page() { + let page = parse_search(SEARCH_FIXTURE, 0, 3).unwrap(); + assert_eq!(page.total_hits, 5); + assert_eq!((page.offset, page.limit), (0, 3)); + let slugs: Vec<&str> = page.hits.iter().map(|h| h.slug.as_str()).collect(); + assert_eq!(slugs, ["chunky", "chunkyborder", "chunky-offline"]); + let chunky = &page.hits[0]; + assert_eq!(chunky.project_id, CHUNKY); + assert_eq!(chunky.title, "Chunky"); + assert_eq!(chunky.author, "pop4959"); + assert_eq!(chunky.client_side, ModClientSide::Optional); + assert!(chunky.icon_url.is_some() && chunky.downloads > 0); + assert!(!chunky.installed); + let v = serde_json::to_value(chunky).unwrap(); + assert_eq!(v["projectId"], CHUNKY); + assert_eq!(v["clientSide"], "optional"); +} + +#[test] +fn search_drops_client_only_hits_and_rejects_garbage() { + let body = r#"{"hits":[ + {"project_id":"aaaa","slug":"a","title":"A","server_side":"unsupported","client_side":"required"}, + {"project_id":"bbbb","title":"B","server_side":"optional","client_side":"required","icon_url":""} + ],"offset":0,"limit":2,"total_hits":2}"#; + let page = parse_search(body, 0, 2).unwrap(); + assert_eq!(page.hits.len(), 1); + let b = &page.hits[0]; + assert_eq!(b.slug, "bbbb", "a missing slug falls back to the id"); + assert_eq!(b.client_side, ModClientSide::Required); + assert!(b.icon_url.is_none()); + assert_eq!( + parse_search("rate limited", 0, 1) + .unwrap_err() + .code(), + "DOWNLOAD_FAILED" + ); +} + +#[test] +fn sha1sum_lines() { + let out = "6c8098fc0f124c7b6492de60db0108747f7f9821 /data/mods/Chunky-Fabric-1.4.23.jar\n\ +584D303F646287EE6BE059ECB2FC451255BE9EE9 /data/mods/fabric api+1.jar.disabled\n\ +\\0123 /data/mods/escaped\n\ +garbage\n\ +6c8098fc0f124c7b6492de60db0108747f7f9821 /data/plugins/x.jar\n\ +6c8098fc0f124c7b6492de60db0108747f7f9821 /data/mods/sub/x.jar\n"; + let parsed = parse_sha1sum(out, "/data/mods"); + assert_eq!( + parsed, + vec![ + ( + "6c8098fc0f124c7b6492de60db0108747f7f9821".to_string(), + "Chunky-Fabric-1.4.23.jar".to_string() + ), + ( + "584d303f646287ee6be059ecb2fc451255be9ee9".to_string(), + "fabric api+1.jar.disabled".to_string() + ), + ] + ); +} + +#[test] +fn version_files_fixture_maps_hashes_to_projects() { + let answer: HashMap = serde_json::from_str(VERSION_FILES).unwrap(); + assert_eq!( + answer["6c8098fc0f124c7b6492de60db0108747f7f9821"].project_id, + CHUNKY + ); + assert_eq!( + answer["584d303f646287ee6be059ecb2fc451255be9ee9"].project_id, + FABRIC_API + ); + assert_eq!(answer.len(), 2, "an unknown hash is simply absent"); +} + +/* ---------- version choice ---------- */ + +#[test] +fn chooses_newest_release_from_real_versions() { + let chunky = parse_versions(CHUNKY_VERSIONS).unwrap(); + let v = choose_version(&chunky, "1.21.1", &fabric().loaders).unwrap(); + assert_eq!(v.version_number, "1.4.23"); + let api = parse_versions(FABRIC_API_VERSIONS).unwrap(); + let v = choose_version(&api, "1.21.1", &fabric().loaders).unwrap(); + assert_eq!(v.version_number, "0.116.18+1.21.1"); + assert!(choose_version(&api, "1.20.1", &fabric().loaders).is_none()); + let forge = vec!["forge".to_string()]; + assert!(choose_version(&api, "1.21.1", &forge).is_none()); +} + +#[test] +fn release_beats_beta_beats_alpha_then_newest() { + let loaders = fabric().loaders; + let versions = vec![ + ver("alpha-new", "p", "alpha", D3, vec![]), + ver("beta-new", "p", "beta", D3, vec![]), + ver("release-old", "p", "release", D1, vec![]), + ver("release-mid", "p", "release", D2, vec![]), + ]; + assert_eq!( + choose_version(&versions, "1.21.1", &loaders).unwrap().id, + "release-mid" + ); + assert_eq!( + choose_version(&versions[..2], "1.21.1", &loaders) + .unwrap() + .id, + "beta-new" + ); + assert_eq!( + choose_version(&versions[..1], "1.21.1", &loaders) + .unwrap() + .id, + "alpha-new" + ); +} + +#[test] +fn incompatible_versions_are_ignored() { + let loaders = fabric().loaders; + let mut wrong_mc = ver("wrong-mc", "p", "release", D3, vec![]); + wrong_mc.game_versions = vec!["1.21".into()]; + let mut wrong_loader = ver("wrong-loader", "p", "release", D3, vec![]); + wrong_loader.loaders = vec!["forge".into()]; + let mut not_jar = ver("not-jar", "p", "release", D3, vec![]); + not_jar.files[0].filename = "pack.zip".into(); + let mut draft = ver("draft", "p", "release", D3, vec![]); + draft.status = Some("draft".into()); + let ok = ver("ok", "p", "beta", D1, vec![]); + let all = vec![wrong_mc, wrong_loader, not_jar, draft, ok]; + assert_eq!(choose_version(&all, "1.21.1", &loaders).unwrap().id, "ok"); + assert!(choose_version(&all[..4], "1.21.1", &loaders).is_none()); +} + +#[test] +fn preferred_loader_wins_among_releases() { + let quilt = server_mods(&support_for(false, Some("quilt"), Some("1.21.1"))).unwrap(); + let fabric_build = ver("fabric-build", "p", "release", D3, vec![]); + let mut quilt_build = ver("quilt-build", "p", "release", D1, vec![]); + quilt_build.loaders = vec!["quilt".into()]; + let all = vec![fabric_build.clone(), quilt_build]; + assert_eq!( + choose_version(&all, "1.21.1", &quilt.loaders).unwrap().id, + "quilt-build" + ); + // A Quilt server still takes a Fabric-only mod. + assert_eq!( + choose_version(&[fabric_build], "1.21.1", &quilt.loaders) + .unwrap() + .id, + "fabric-build" + ); +} + +/* ---------- dependency resolution ---------- */ + +#[tokio::test] +async fn real_chunky_needs_fabric_api() { + let source = FakeSource::default() + .with("chunky", "Chunky", parse_versions(CHUNKY_VERSIONS).unwrap()) + .with( + FABRIC_API, + "Fabric API", + parse_versions(FABRIC_API_VERSIONS).unwrap(), + ); + let plan = plan_install(&source, &fabric(), "chunky", &InstalledIndex::default()) + .await + .unwrap(); + let files: Vec<(&str, bool)> = plan + .files + .iter() + .map(|f| (f.filename.as_str(), f.dependency())) + .collect(); + assert_eq!( + files, + [ + ("Chunky-Fabric-1.4.23.jar", false), + ("fabric-api-0.116.18+1.21.1.jar", true) + ] + ); + let chunky = &plan.files[0]; + assert_eq!(chunky.project_id, CHUNKY); + assert_eq!(chunky.url.host_str(), Some("cdn.modrinth.com")); + assert_eq!(chunky.sha512.len(), 128); + assert_eq!( + chunky.sha1.as_deref(), + Some("6c8098fc0f124c7b6492de60db0108747f7f9821") + ); + assert_eq!(plan.files[1].needed_by.as_deref(), Some(CHUNKY)); + assert!(plan.already_installed.is_empty()); +} + +#[tokio::test] +async fn resolves_transitively_breadth_first() { + let source = FakeSource::default() + .with( + "a", + "A", + vec![ver( + "a1", + "a", + "release", + D1, + vec![required("b"), required("c")], + )], + ) + .with( + "b", + "B", + vec![ver("b1", "b", "release", D1, vec![required("d")])], + ) + .with( + "c", + "C", + vec![ver( + "c1", + "c", + "release", + D1, + vec![ + required("d"), + dep(Some("e"), None, "optional"), + dep(Some("f"), None, "incompatible"), + dep(Some("g"), None, "embedded"), + ], + )], + ) + .with("d", "D", vec![ver("d1", "d", "release", D1, vec![])]); + let plan = plan_install(&source, &fabric(), "a", &InstalledIndex::default()) + .await + .unwrap(); + let ids: Vec<&str> = plan.files.iter().map(|f| f.project_id.as_str()).collect(); + assert_eq!( + ids, + ["a", "b", "c", "d"], + "d once, optional ones not followed" + ); + assert_eq!(plan.files[3].needed_by.as_deref(), Some("b")); +} + +#[tokio::test] +async fn a_cycle_ends_where_it_started() { + let source = FakeSource::default() + .with( + "a", + "A", + vec![ver("a1", "a", "release", D1, vec![required("b")])], + ) + .with( + "b", + "B", + vec![ver("b1", "b", "release", D1, vec![required("a")])], + ); + let plan = plan_install(&source, &fabric(), "a", &InstalledIndex::default()) + .await + .unwrap(); + let ids: Vec<&str> = plan.files.iter().map(|f| f.project_id.as_str()).collect(); + assert_eq!(ids, ["a", "b"]); + let project_calls = source + .calls() + .iter() + .filter(|c| c.starts_with("project ")) + .count(); + assert_eq!(project_calls, 2); +} + +#[tokio::test] +async fn a_pinned_version_is_used_as_named() { + let old_b = ver("b-old", "b", "release", D1, vec![]); + let new_b = ver("b-new", "b", "release", D3, vec![]); + let source = FakeSource::default() + .with( + "a", + "A", + vec![ver( + "a1", + "a", + "release", + D1, + vec![dep(Some("b"), Some("b-old"), "required")], + )], + ) + .with("b", "B", vec![new_b, old_b]); + let plan = plan_install(&source, &fabric(), "a", &InstalledIndex::default()) + .await + .unwrap(); + assert_eq!(plan.files[1].version_id, "b-old"); + assert!(source.calls().contains(&"version b-old".to_string())); + + // A pinned version made for another loader is refused, naming it. + let mut forge_b = ver("b-forge", "b", "release", D1, vec![]); + forge_b.loaders = vec!["forge".into()]; + let source = FakeSource::default() + .with( + "a", + "A", + vec![ver( + "a1", + "a", + "release", + D1, + vec![dep(None, Some("b-forge"), "required")], + )], + ) + .with("b", "B", vec![forge_b]); + let err = plan_install(&source, &fabric(), "a", &InstalledIndex::default()) + .await + .unwrap_err(); + assert_eq!(err.code(), "INVALID_INPUT"); + assert!( + err.to_string().contains("A needs B b-forge-number"), + "{err}" + ); + assert!(err.to_string().contains("Fabric"), "{err}"); +} + +#[tokio::test] +async fn installed_dependencies_are_skipped() { + let source = FakeSource::default() + .with( + "a", + "A", + vec![ver( + "a1", + "a", + "release", + D1, + vec![required("b"), required("c")], + )], + ) + .with("b", "B", vec![ver("b1", "b", "release", D1, vec![])]) + .with("c", "C", vec![ver("c1", "c", "release", D1, vec![])]); + let mut installed = InstalledIndex::default(); + // b by project (any version, e.g. an older or disabled jar) ... + installed + .projects + .insert("b".into(), "b-older.jar.disabled".into()); + // ... c by the exact file name. + installed.filenames.insert("c-c1.jar".into()); + let plan = plan_install(&source, &fabric(), "a", &installed) + .await + .unwrap(); + let ids: Vec<&str> = plan.files.iter().map(|f| f.project_id.as_str()).collect(); + assert_eq!(ids, ["a"]); + assert_eq!(plan.already_installed, ["b", "c"]); + assert!( + !source.calls().contains(&"project b".to_string()), + "an installed project is not even looked up" + ); +} + +#[tokio::test] +async fn the_mod_asked_for_is_never_installed_twice() { + let source = FakeSource::default().with( + "a", + "Alpha Mod", + vec![ver("a1", "a", "release", D1, vec![])], + ); + let mut installed = InstalledIndex::default(); + installed.projects.insert("a".into(), "alpha.jar".into()); + let err = plan_install(&source, &fabric(), "a", &installed) + .await + .unwrap_err(); + assert_eq!(err.code(), "INVALID_INPUT"); + assert_eq!( + err.to_string(), + "Alpha Mod is already installed (alpha.jar)" + ); + + let mut installed = InstalledIndex::default(); + installed.filenames.insert("a-a1.jar".into()); + let err = plan_install(&source, &fabric(), "a", &installed) + .await + .unwrap_err(); + assert!( + err.to_string().contains("already a file named a-a1.jar"), + "{err}" + ); +} + +#[tokio::test] +async fn missing_dependencies_fail_naming_them() { + // Not on Modrinth at all. + let source = FakeSource::default().with( + "a", + "Alpha", + vec![ver("a1", "a", "release", D1, vec![required("gone")])], + ); + let err = plan_install(&source, &fabric(), "a", &InstalledIndex::default()) + .await + .unwrap_err(); + assert_eq!(err.code(), "INVALID_INPUT"); + assert!(err.to_string().contains("Alpha needs a project"), "{err}"); + assert!(err.to_string().contains("gone"), "{err}"); + + // On Modrinth, but not for this version / loader. + let mut forge_only = ver("b1", "b", "release", D1, vec![]); + forge_only.loaders = vec!["forge".into()]; + let source = FakeSource::default() + .with( + "a", + "Alpha", + vec![ver("a1", "a", "release", D1, vec![required("b")])], + ) + .with("b", "Beta Lib", vec![forge_only]); + let err = plan_install(&source, &fabric(), "a", &InstalledIndex::default()) + .await + .unwrap_err(); + assert_eq!( + err.to_string(), + "Alpha needs Beta Lib, which has no version for Minecraft 1.21.1 on Fabric" + ); + + // Only a file name, no project. + let mut file_only = dep(None, None, "required"); + file_only.file_name = Some("secret-lib.jar".into()); + let source = FakeSource::default().with( + "a", + "Alpha", + vec![ver("a1", "a", "release", D1, vec![file_only])], + ); + let err = plan_install(&source, &fabric(), "a", &InstalledIndex::default()) + .await + .unwrap_err(); + assert!(err.to_string().contains("secret-lib.jar"), "{err}"); + + // The mod itself. + let source = FakeSource::default(); + let err = plan_install(&source, &fabric(), "nothing", &InstalledIndex::default()) + .await + .unwrap_err(); + assert_eq!(err.to_string(), "Modrinth has no project called nothing"); + let mut old = ver("o1", "old", "release", D1, vec![]); + old.game_versions = vec!["1.12.2".into()]; + let source = FakeSource::default().with("old", "Old Mod", vec![old]); + let err = plan_install(&source, &fabric(), "old", &InstalledIndex::default()) + .await + .unwrap_err(); + assert_eq!( + err.to_string(), + "Old Mod has no version for Minecraft 1.21.1 on Fabric" + ); +} + +#[tokio::test] +async fn more_than_the_cap_is_refused() { + // p0 → p1 → ... → p50: 51 files. + let mut source = FakeSource::default(); + for i in 0..=MAX_FILES { + let deps = if i < MAX_FILES { + vec![required(&format!("p{}", i + 1))] + } else { + vec![] + }; + let id = format!("p{i}"); + source = source.with( + &id, + &format!("P{i}"), + vec![ver(&format!("v{i}"), &id, "release", D1, deps)], + ); + } + let err = plan_install(&source, &fabric(), "p0", &InstalledIndex::default()) + .await + .unwrap_err(); + assert_eq!(err.code(), "INVALID_INPUT"); + assert!(err.to_string().contains("more than 50 files"), "{err}"); + // Exactly at the cap is fine. + let plan = plan_install(&source, &fabric(), "p1", &InstalledIndex::default()) + .await + .unwrap(); + assert_eq!(plan.files.len(), MAX_FILES); +} + +#[tokio::test] +async fn bad_ids_are_refused_before_any_request() { + let source = FakeSource::default(); + for id in ["", "../x", "a/b", "a b", &"x".repeat(65), "sodium?x=1"] { + let err = plan_install(&source, &fabric(), id, &InstalledIndex::default()) + .await + .unwrap_err(); + assert_eq!(err.code(), "INVALID_INPUT", "{id:?}"); + } + assert!(source.calls().is_empty()); +} + +/* ---------- §6.3b hosts and files ---------- */ + +#[test] +fn host_allowlist() { + let ok = |u: &str| url_allowed(&reqwest::Url::parse(u).unwrap()); + assert!(ok("https://api.modrinth.com/v2/search")); + assert!(ok("https://cdn.modrinth.com/data/x/y.jar")); + assert!(!ok("http://cdn.modrinth.com/data/x/y.jar")); + assert!(!ok("https://cdn.modrinth.com:8443/x")); + assert!(!ok("https://user:pw@cdn.modrinth.com/x")); + assert!(!ok("https://modrinth.com/x")); + assert!(!ok("https://cdn.modrinth.com.evil.example/x")); + assert!(!ok("https://github.com/x")); +} + +#[test] +fn files_off_the_cdn_or_without_sha512_are_refused() { + let mut off_cdn = ver("v", "p", "release", D1, vec![]); + off_cdn.files[0].url = "https://evil.example/p.jar".into(); + assert_eq!( + plan_file(&off_cdn, None).unwrap_err().code(), + "DOWNLOAD_FAILED" + ); + // The API host is allowlisted for requests, but files come from the CDN. + let mut api_host = ver("v", "p", "release", D1, vec![]); + api_host.files[0].url = "https://api.modrinth.com/p.jar".into(); + assert_eq!( + plan_file(&api_host, None).unwrap_err().code(), + "DOWNLOAD_FAILED" + ); + let mut no_hash = ver("v", "p", "release", D1, vec![]); + no_hash.files[0].hashes.sha512 = None; + assert_eq!( + plan_file(&no_hash, None).unwrap_err().code(), + "DOWNLOAD_FAILED" + ); + let mut short_hash = ver("v", "p", "release", D1, vec![]); + short_hash.files[0].hashes.sha512 = Some("abc".into()); + assert_eq!( + plan_file(&short_hash, None).unwrap_err().code(), + "DOWNLOAD_FAILED" + ); + let mut huge = ver("v", "p", "release", D1, vec![]); + huge.files[0].size = crate::mods::MOD_MAX_BYTES + 1; + assert_eq!(plan_file(&huge, None).unwrap_err().code(), "FILE_TOO_LARGE"); + let mut odd_name = ver("v", "p", "release", D1, vec![]); + odd_name.files[0].filename = "My Mod (1).jar".into(); + assert_eq!( + plan_file(&odd_name, None).unwrap().filename, + "My_Mod_(1).jar" + ); +} + +/// Serve fixed responses from a local socket, one per connection, keyed by +/// the request path. +async fn serve(routes: Vec<(&'static str, Vec, &'static str)>) -> std::net::SocketAddr { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = listener.accept().await else { + return; + }; + let mut buf = vec![0u8; 4096]; + let n = sock.read(&mut buf).await.unwrap_or(0); + let request = String::from_utf8_lossy(&buf[..n]).to_string(); + let path = request.split_whitespace().nth(1).unwrap_or("/").to_string(); + let (body, head) = routes + .iter() + .find(|(p, _, _)| *p == path) + .map(|(_, b, h)| (b.clone(), *h)) + .unwrap_or((Vec::new(), "HTTP/1.1 404 Not Found")); + let response = format!( + "{head}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + let _ = sock.write_all(response.as_bytes()).await; + let _ = sock.write_all(&body).await; + let _ = sock.flush().await; + } + }); + addr +} + +#[tokio::test] +async fn redirects_off_the_modrinth_hosts_are_refused() { + let addr = serve(vec![ + ( + "/to-evil", + Vec::new(), + "HTTP/1.1 302 Found\r\nLocation: https://evil.example/x.jar", + ), + ( + "/to-http-cdn", + Vec::new(), + "HTTP/1.1 302 Found\r\nLocation: http://cdn.modrinth.com/x.jar", + ), + ]) + .await; + // The real policy on a client pointed at the local socket (the first + // hop is local only because this is a test; the policy judges hops). + let client = reqwest::Client::builder() + .redirect(redirect_policy()) + .build() + .unwrap(); + for path in ["/to-evil", "/to-http-cdn"] { + let err = client + .get(format!("http://{addr}{path}")) + .send() + .await + .unwrap_err(); + assert!(err.is_redirect(), "{path}: {err}"); + let text = format!("{err:?}"); + assert!(text.contains("does not trust"), "{path}: {text}"); + } +} + +fn planned(addr: std::net::SocketAddr, project: &str, name: &str, body: &[u8]) -> PlannedFile { + use sha2::Digest; + PlannedFile { + project_id: project.into(), + version_id: format!("{project}-v"), + version_number: "1.0".into(), + filename: name.into(), + url: reqwest::Url::parse(&format!("http://{addr}/{name}")).unwrap(), + sha512: hex::encode(sha2::Sha512::digest(body)), + sha1: None, + size: body.len() as u64, + needed_by: None, + } +} + +async fn test_core() -> (tempfile::TempDir, std::sync::Arc) { + let tmp = tempfile::tempdir().unwrap(); + let core = crate::Core::init(tmp.path().join("config"), tmp.path().join("data")) + .await + .unwrap(); + (tmp, core) +} + +#[tokio::test] +async fn a_sha512_mismatch_leaves_nothing_behind() { + let addr = serve(vec![ + ("/good.jar", b"good bytes".to_vec(), "HTTP/1.1 200 OK"), + ("/bad.jar", b"tampered bytes".to_vec(), "HTTP/1.1 200 OK"), + ]) + .await; + let (tmp, core) = test_core().await; + let mut events = core.subscribe_events(); + let good = planned(addr, "good", "good.jar", b"good bytes"); + let mut bad = planned(addr, "bad", "bad.jar", b"the published bytes"); + bad.needed_by = Some("good".into()); + let names = HashMap::from([("bad".to_string(), "Bad Lib".to_string())]); + let client = reqwest::Client::new(); + + let err = download_plan(&core, &client, &[good.clone(), bad], &names) + .await + .unwrap_err(); + assert_eq!(err.code(), "CHECKSUM_MISMATCH"); + assert!(err.to_string().starts_with("Bad Lib: "), "{err}"); + assert!(err.to_string().contains("sha512"), "{err}"); + let leftovers = std::fs::read_dir(tmp.path().join("data/tmp")) + .unwrap() + .count(); + assert_eq!(leftovers, 0, "the good file's temp copy is gone too"); + let mods = core.settings().await.simple.instance_dir.join("mods"); + assert!(!mods.exists(), "nothing was placed"); + + // Progress events: kind "mod", the failing one ends in the same code. + let mut last_error = None; + while let Ok(ev) = events.try_recv() { + if let crate::model::CoreEvent::DownloadProgress(p) = ev { + assert_eq!(p.kind, DownloadKind::Mod); + if let Some(e) = p.error { + last_error = Some(e.code); + } + } + } + assert_eq!(last_error.as_deref(), Some("CHECKSUM_MISMATCH")); + + // The same good file alone downloads and verifies. + let temps = download_plan(&core, &client, &[good], &names) + .await + .unwrap(); + assert_eq!(std::fs::read(&temps[0].0).unwrap(), b"good bytes"); +} + +#[tokio::test] +async fn placing_on_this_computer_and_rolling_back() { + let addr = serve(vec![ + ("/a.jar", b"aaa".to_vec(), "HTTP/1.1 200 OK"), + ("/b.jar", b"bbb".to_vec(), "HTTP/1.1 200 OK"), + ]) + .await; + let (tmp, core) = test_core().await; + let client = reqwest::Client::new(); + let files = vec![ + planned(addr, "a", "a.jar", b"aaa"), + planned(addr, "b", "b.jar", b"bbb"), + ]; + let mods = core.settings().await.simple.instance_dir.join("mods"); + + // Success: both placed, staging and temps gone. + let temps = download_plan(&core, &client, &files, &HashMap::new()) + .await + .unwrap(); + stage_and_place(&core, ModTarget::Mods, &files, &temps) + .await + .unwrap(); + assert_eq!(std::fs::read(mods.join("a.jar")).unwrap(), b"aaa"); + assert_eq!(std::fs::read(mods.join("b.jar")).unwrap(), b"bbb"); + assert_eq!( + std::fs::read_dir(tmp.path().join("data/tmp")) + .unwrap() + .count(), + 0 + ); + + // Failure half way: b.jar cannot be written (a folder has that name), so + // the a.jar this attempt placed is removed again and the folder stays. + std::fs::remove_file(mods.join("a.jar")).unwrap(); + std::fs::remove_file(mods.join("b.jar")).unwrap(); + std::fs::create_dir(mods.join("b.jar")).unwrap(); + std::fs::write(mods.join("other.jar"), b"keep me").unwrap(); + let temps = download_plan(&core, &client, &files, &HashMap::new()) + .await + .unwrap(); + let err = stage_and_place(&core, ModTarget::Mods, &files, &temps) + .await + .unwrap_err(); + assert_eq!(err.code(), "IO"); + assert!(!mods.join("a.jar").exists()); + assert!(mods.join("b.jar").is_dir()); + assert_eq!(std::fs::read(mods.join("other.jar")).unwrap(), b"keep me"); + assert_eq!( + std::fs::read_dir(tmp.path().join("data/tmp")) + .unwrap() + .count(), + 0 + ); +} + +#[tokio::test] +async fn installed_index_on_this_computer_matches_names() { + let (_tmp, core) = test_core().await; + // An empty folder needs no request at all. + let index = installed_index(&core, &reqwest::Client::new(), ModTarget::Mods) + .await + .unwrap(); + assert!(index.filenames.is_empty() && index.projects.is_empty()); + // Cached answers are used for the same set of hashes (no network here). + let mods = core.settings().await.simple.instance_dir.join("mods"); + std::fs::create_dir_all(&mods).unwrap(); + std::fs::write(mods.join("Some.jar.disabled"), b"x").unwrap(); + let hash = sha1_of_file(&mods.join("Some.jar.disabled")).unwrap(); + *core.modrinth_hashes.lock().unwrap() = Some(HashCache { + hashes: vec![hash.clone()], + projects: HashMap::from([(hash, "proj".to_string())]), + }); + let index = installed_index(&core, &reqwest::Client::new(), ModTarget::Mods) + .await + .unwrap(); + assert!(index.has_file("some.jar.disabled")); + assert_eq!( + index.projects.get("proj").map(String::as_str), + Some("Some.jar.disabled") + ); +} + +#[test] +fn ids() { + assert!(valid_id("P7dR8mSH")); + assert!(valid_id("fabric-api")); + assert!(valid_id("my_mod")); + assert!(!valid_id("")); + assert!(!valid_id("a.b")); + assert!(!valid_id("%2e%2e")); + assert!(!valid_id(&"a".repeat(65))); +} diff --git a/crates/mineui-core/src/mods.rs b/crates/mineui-core/src/mods.rs index 6960c3d..9205d06 100644 --- a/crates/mineui-core/src/mods.rs +++ b/crates/mineui-core/src/mods.rs @@ -8,11 +8,13 @@ use std::path::{Path, PathBuf}; use crate::error::{Error, Result}; -use crate::model::{DownloadKind, DownloadedMod, ModEntry, ModTarget, ModsList, UploadedMod}; +use crate::model::{ + DownloadKind, DownloadedMod, ModEntry, ModTarget, ModsList, RenamedMod, UploadedMod, +}; use crate::settings::Mode; /// §3.5: 256 MB download cap. -const MOD_MAX_BYTES: u64 = 256 * 1024 * 1024; +pub(crate) const MOD_MAX_BYTES: u64 = 256 * 1024 * 1024; /// §3.5: upload source cap - 512 MiB comfortably covers real modpack jars /// while stopping accidental (or malicious) multi-GB copies into the @@ -271,6 +273,7 @@ async fn download_inner( max_bytes: Some(MOD_MAX_BYTES), expected_sha1: None, expected_sha256: None, + expected_sha512: None, client: None, allow_private_hosts: allow_private, }; @@ -324,6 +327,108 @@ async fn delete_inner(core: &crate::Core, filename: &str, target: ModTarget) -> } } +/// `set_mod_enabled` (§3.5, 2.13.0): constant script, zero interpolation - +/// the two paths arrive as positional arguments, never inside the text. +/// Exit 3 = no such file, 4 = the new name is taken. +const RENAME_SCRIPT: &str = + r#"[ -f "$1" ] || exit 3; if [ -e "$2" ] || [ -L "$2" ]; then exit 4; fi; mv -- "$1" "$2""#; + +const DISABLED_SUFFIX: &str = ".disabled"; + +/// `(from, to)` for `set_mod_enabled`: `.jar` ⇄ `.jar.disabled`, +/// both bare names under §6.2 rules 1 and 3. +pub(crate) fn enable_rename(filename: &str, enabled: bool) -> Result<(String, String)> { + let lower = filename.to_ascii_lowercase(); + if enabled { + if !lower.ends_with(".jar.disabled") { + return Err(Error::InvalidInput(format!( + "{filename} is not turned off (its name does not end in .jar.disabled)" + ))); + } + // The suffix is ASCII, so this cut is on a char boundary. + let base = &filename[..filename.len() - DISABLED_SUFFIX.len()]; + let base = crate::validate::mod_filename(base, false)?; + // `filename` is `base` plus an ASCII-letter suffix, so it is as safe. + Ok((filename.to_string(), base)) + } else { + if !lower.ends_with(".jar") { + return Err(Error::InvalidInput(format!( + "only a .jar file can be turned off, not {filename}" + ))); + } + let base = crate::validate::mod_filename(filename, false)?; + Ok((base.clone(), format!("{base}{DISABLED_SUFFIX}"))) + } +} + +/// The rename script's outcome as the contract's errors. +fn rename_outcome(out: &crate::runtime::ExecOutput, from: &str, to: &str) -> Result<()> { + if out.success() { + return Ok(()); + } + match out.exit_code { + Some(3) => Err(Error::InvalidInput(format!("{from} does not exist"))), + Some(4) => Err(Error::InvalidInput(format!( + "there is already a file named {to}" + ))), + code => Err(Error::Io(format!( + "failed to rename {from}: {}", + if out.stderr.trim().is_empty() { + format!("exit code {code:?}") + } else { + out.stderr.trim().to_string() + } + ))), + } +} + +/// Host-side rename with the same checks as the script. +async fn rename_on_host(dir: &Path, from: &str, to: &str) -> Result<()> { + let src = dir.join(from); + let dst = dir.join(to); + match tokio::fs::metadata(&src).await { + Ok(meta) if meta.is_file() => {} + _ => return Err(Error::InvalidInput(format!("{from} does not exist"))), + } + if tokio::fs::symlink_metadata(&dst).await.is_ok() { + return Err(Error::InvalidInput(format!( + "there is already a file named {to}" + ))); + } + tokio::fs::rename(&src, &dst) + .await + .map_err(|e| Error::Io(format!("failed to rename {from}: {e}"))) +} + +async fn set_enabled_inner( + core: &crate::Core, + filename: &str, + target: ModTarget, + enabled: bool, +) -> Result { + let (from, to) = enable_rename(filename, enabled)?; + let settings = core.settings().await; + match settings.active_mode { + Mode::Advanced => { + let runtime = crate::runtime::resolve(&settings.advanced).await?; + let root = container_root(target); + let (src, dst) = (format!("{root}/{from}"), format!("{root}/{to}")); + let out = crate::runtime::run_in_container( + runtime.as_ref(), + &settings.advanced.container_name, + &["sh", "-c", RENAME_SCRIPT, "sh", &src, &dst], + ) + .await?; + rename_outcome(&out, &from, &to)?; + } + Mode::Simple => { + let dir = settings.simple.instance_dir.join(target.dir_name()); + rename_on_host(&dir, &from, &to).await?; + } + } + Ok(RenamedMod { filename: to }) +} + /* ---------- audited entry points (§3.11) ---------- */ pub(crate) fn target_label(target: ModTarget) -> &'static str { @@ -395,6 +500,30 @@ pub async fn delete(core: &crate::Core, filename: &str, target: ModTarget) -> Re r } +/// `set_mod_enabled` (§3.5, 2.13.0), audited as `mod.enable` / `mod.disable`. +pub async fn set_enabled( + core: &crate::Core, + filename: &str, + target: ModTarget, + enabled: bool, +) -> Result { + let r = set_enabled_inner(core, filename, target, enabled).await; + let detail = match &r { + Ok(renamed) => format!("{} → {}", target_label(target), renamed.filename), + Err(_) => target_label(target).to_string(), + }; + crate::audit::record( + core, + crate::model::AuditSource::User, + if enabled { "mod.enable" } else { "mod.disable" }, + Some(filename), + Some(&detail), + r.as_ref().err(), + ) + .await; + r +} + #[cfg(test)] mod tests { use super::*; @@ -542,4 +671,135 @@ mod tests { drop(file); assert!(validate_upload_source(&ok).await.is_ok()); } + + /* ---------- set_mod_enabled (§3.5, 2.13.0) ---------- */ + + #[test] + fn enable_rename_names() { + assert_eq!( + enable_rename("sodium-0.6.jar", false).unwrap(), + ("sodium-0.6.jar".into(), "sodium-0.6.jar.disabled".into()) + ); + assert_eq!( + enable_rename("Chunky-1.4.23.JAR.Disabled", true).unwrap(), + ( + "Chunky-1.4.23.JAR.Disabled".into(), + "Chunky-1.4.23.JAR".into() + ) + ); + for (name, enabled) in [ + ("mod.jar.disabled", false), // already off + ("mod.jar", true), // already on + ("pack.zip", false), // zips cannot be switched + ("../evil.jar", false), + ("dir/mod.jar.disabled", true), + (".jar.disabled", true), + ("-x.jar", false), + ("bad name.jar", false), + ] { + assert_eq!( + enable_rename(name, enabled).unwrap_err().code(), + "INVALID_INPUT", + "{name} enabled={enabled}" + ); + } + } + + #[test] + fn rename_script_exit_codes_map_to_errors() { + let out = |code: i32, stderr: &str| crate::runtime::ExecOutput { + stdout: String::new(), + stderr: stderr.into(), + exit_code: Some(code), + }; + assert!(rename_outcome(&out(0, ""), "a.jar", "a.jar.disabled").is_ok()); + let missing = rename_outcome(&out(3, ""), "a.jar", "a.jar.disabled").unwrap_err(); + assert_eq!(missing.code(), "INVALID_INPUT"); + assert!(missing.to_string().contains("a.jar does not exist")); + let taken = rename_outcome(&out(4, ""), "a.jar", "a.jar.disabled").unwrap_err(); + assert_eq!(taken.code(), "INVALID_INPUT"); + assert!(taken + .to_string() + .contains("already a file named a.jar.disabled")); + let other = rename_outcome(&out(1, "mv: Permission denied"), "a.jar", "b").unwrap_err(); + assert_eq!(other.code(), "IO"); + assert!(other.to_string().contains("Permission denied")); + } + + /// The container script itself, run by this machine's `sh`: it renames, + /// refuses a taken name and a missing source, and treats `$1`/`$2` as + /// data (a name with shell syntax stays a name). + #[cfg(unix)] + #[test] + fn rename_script_behaves_under_sh() { + let tmp = tempfile::tempdir().unwrap(); + let run = |from: &str, to: &str| { + std::process::Command::new("sh") + .args(["-c", RENAME_SCRIPT, "sh"]) + .arg(tmp.path().join(from)) + .arg(tmp.path().join(to)) + .status() + .unwrap() + .code() + }; + std::fs::write(tmp.path().join("a.jar"), b"a").unwrap(); + assert_eq!(run("a.jar", "a.jar.disabled"), Some(0)); + assert!(tmp.path().join("a.jar.disabled").exists()); + assert!(!tmp.path().join("a.jar").exists()); + assert_eq!(run("a.jar", "a.jar.disabled"), Some(3), "source gone"); + std::fs::write(tmp.path().join("a.jar"), b"new").unwrap(); + assert_eq!(run("a.jar", "a.jar.disabled"), Some(4), "target taken"); + assert_eq!( + std::fs::read(tmp.path().join("a.jar.disabled")).unwrap(), + b"a" + ); + std::fs::write(tmp.path().join("$(touch pwned).jar"), b"x").unwrap(); + assert_eq!(run("$(touch pwned).jar", "x.jar"), Some(0)); + assert!(!tmp.path().join("pwned").exists()); + assert!(!std::path::Path::new("pwned").exists()); + } + + #[tokio::test] + async fn set_enabled_on_this_computer_renames_and_never_overwrites() { + let tmp = tempfile::tempdir().unwrap(); + let core = crate::Core::init(tmp.path().join("config"), tmp.path().join("data")) + .await + .unwrap(); + let mods = core.settings().await.simple.instance_dir.join("mods"); + std::fs::create_dir_all(&mods).unwrap(); + std::fs::write(mods.join("lithium.jar"), b"jar").unwrap(); + + let off = set_enabled(&core, "lithium.jar", ModTarget::Mods, false) + .await + .unwrap(); + assert_eq!(off.filename, "lithium.jar.disabled"); + assert!(mods.join("lithium.jar.disabled").is_file()); + assert!(!mods.join("lithium.jar").exists()); + + // A new lithium.jar appears; turning the old one back on must not + // replace it. + std::fs::write(mods.join("lithium.jar"), b"newer").unwrap(); + let err = set_enabled(&core, "lithium.jar.disabled", ModTarget::Mods, true) + .await + .unwrap_err(); + assert_eq!(err.code(), "INVALID_INPUT"); + assert_eq!(std::fs::read(mods.join("lithium.jar")).unwrap(), b"newer"); + assert!(mods.join("lithium.jar.disabled").is_file()); + + std::fs::remove_file(mods.join("lithium.jar")).unwrap(); + let on = set_enabled(&core, "lithium.jar.disabled", ModTarget::Mods, true) + .await + .unwrap(); + assert_eq!(on.filename, "lithium.jar"); + assert_eq!(std::fs::read(mods.join("lithium.jar")).unwrap(), b"jar"); + + let missing = set_enabled(&core, "nope.jar", ModTarget::Mods, false) + .await + .unwrap_err(); + assert!(missing.to_string().contains("does not exist")); + + let log = crate::audit::recent(&core, Some(10)).await.unwrap(); + let actions: Vec<_> = log.entries.iter().map(|e| e.action.as_str()).collect(); + assert!(actions.contains(&"mod.disable") && actions.contains(&"mod.enable")); + } } diff --git a/crates/mineui-core/src/mojang.rs b/crates/mineui-core/src/mojang.rs index 3603ff0..fa1843b 100644 --- a/crates/mineui-core/src/mojang.rs +++ b/crates/mineui-core/src/mojang.rs @@ -225,6 +225,7 @@ pub async fn download_server_jar( max_bytes: None, expected_sha1: Some(download.sha1.clone()), expected_sha256: None, + expected_sha512: None, client: None, // Server-jar URLs come from Mojang's HTTPS manifest and the content // is SHA-1 pinned; still use the strict client - piston-data has no diff --git a/crates/mineui-core/tests/fixtures/modrinth-search-chunky-fabric-1.21.1.json b/crates/mineui-core/tests/fixtures/modrinth-search-chunky-fabric-1.21.1.json new file mode 100644 index 0000000..abcbd77 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/modrinth-search-chunky-fabric-1.21.1.json @@ -0,0 +1,294 @@ +{ + "hits": [ + { + "project_id": "fALzjamp", + "project_type": "mod", + "all_project_types": [ + "mod", + "plugin" + ], + "slug": "chunky", + "author": "pop4959", + "author_id": "nfBsvT1J", + "organization": null, + "organization_id": null, + "title": "Chunky", + "description": "Pre-generates chunks, quickly and efficiently", + "categories": [ + "bukkit", + "fabric", + "folia", + "forge", + "neoforge", + "optimization", + "paper", + "spigot", + "sponge", + "utility", + "worldgen" + ], + "display_categories": [ + "bukkit", + "fabric", + "folia", + "forge", + "neoforge", + "optimization", + "paper", + "spigot", + "sponge", + "utility", + "worldgen" + ], + "versions": [ + "1.13.2", + "1.14", + "1.14.1", + "1.14.2", + "1.14.3", + "1.14.4", + "1.15", + "1.15.1", + "1.15.2", + "1.16", + "1.16.1", + "1.16.2", + "1.16.3", + "1.16.4", + "1.16.5", + "1.17", + "1.17.1", + "1.18", + "1.18.1", + "1.18.2", + "1.19", + "1.19.1", + "1.19.2", + "1.19.3", + "1.19.4", + "1.20", + "1.20.1", + "1.20.2", + "1.20.3", + "1.20.4", + "1.20.5", + "1.20.6", + "1.21", + "1.21.1", + "1.21.10", + "1.21.11", + "1.21.2", + "1.21.3", + "1.21.4", + "1.21.5", + "1.21.6", + "1.21.7", + "1.21.8", + "1.21.9", + "26.1", + "26.1.1", + "26.1.2", + "26.2", + "26.3" + ], + "downloads": 20152766, + "follows": 6603, + "icon_url": "https://cdn.modrinth.com/data/fALzjamp/e1954413665e57b7bae1feef44eda530270c7d47_96.webp", + "date_created": "2021-04-04T21:18:30.574917+00:00", + "date_modified": "2026-11-04T03:02:03.669546+00:00", + "latest_version": "RVFHfo1D", + "license": "GPL-3.0-only", + "client_side": "optional", + "server_side": "optional", + "environment": [ + "client_or_server_prefers_both" + ], + "disclosure_types": [], + "gallery": [], + "featured_gallery": null, + "color": 2391573 + }, + { + "project_id": "s86X568j", + "project_type": "mod", + "all_project_types": [ + "mod", + "plugin" + ], + "slug": "chunkyborder", + "author": "pop4959", + "author_id": "nfBsvT1J", + "organization": null, + "organization_id": null, + "title": "Chunky Border", + "description": "An add-on for Chunky which lets you create and manage world borders", + "categories": [ + "bukkit", + "fabric", + "folia", + "forge", + "game-mechanics", + "management", + "neoforge", + "paper", + "spigot", + "transportation", + "utility" + ], + "display_categories": [ + "bukkit", + "fabric", + "folia", + "forge", + "game-mechanics", + "management", + "neoforge", + "paper", + "spigot", + "utility" + ], + "versions": [ + "1.14.4", + "1.15", + "1.15.1", + "1.15.2", + "1.16", + "1.16.1", + "1.16.2", + "1.16.3", + "1.16.4", + "1.16.5", + "1.17", + "1.17.1", + "1.18", + "1.18.1", + "1.18.2", + "1.19", + "1.19.1", + "1.19.2", + "1.19.3", + "1.19.4", + "1.20", + "1.20.1", + "1.20.2", + "1.20.3", + "1.20.4", + "1.20.5", + "1.20.6", + "1.21", + "1.21.1", + "1.21.10", + "1.21.11", + "1.21.2", + "1.21.3", + "1.21.4", + "1.21.5", + "1.21.6", + "1.21.7", + "1.21.8", + "1.21.9", + "26.1", + "26.1.1", + "26.1.2", + "26.2", + "26.3" + ], + "downloads": 392059, + "follows": 516, + "icon_url": "https://cdn.modrinth.com/data/s86X568j/c7133164c01d0944b68082b81b39257a90d5eb81_96.webp", + "date_created": "2022-08-22T03:07:55.943514+00:00", + "date_modified": "2026-11-04T03:03:32.747184+00:00", + "latest_version": "uT1cdd3k", + "license": "GPL-3.0-only", + "client_side": "optional", + "server_side": "optional", + "environment": [ + "client_or_server_prefers_both" + ], + "disclosure_types": [], + "gallery": [ + "https://cdn.modrinth.com/data/s86X568j/images/089a31eb37e26efa58da59fb41807dfd98c7f4ad_350.webp", + "https://cdn.modrinth.com/data/s86X568j/images/045b495214641989a7628433ae0bb4507f352767_350.webp", + "https://cdn.modrinth.com/data/s86X568j/images/c8c9a90cc61a899f17869ce4837786166d76f4e1_350.webp", + "https://cdn.modrinth.com/data/s86X568j/images/b06ccc8dd424b59a86e9e892e58ec9584efaabb7_350.webp" + ], + "featured_gallery": null, + "color": 4094761 + }, + { + "project_id": "VfHc5JEX", + "project_type": "mod", + "all_project_types": [ + "datapack", + "mod" + ], + "slug": "chunky-offline", + "author": "lullaby", + "author_id": "U5ZYLCzs", + "organization": null, + "organization_id": null, + "title": "Chunky Offline", + "description": "An add-on/extension of Chunky to generate chunks when no players are online.", + "categories": [ + "datapack", + "fabric", + "forge", + "management", + "neoforge", + "optimization", + "quilt", + "utility", + "worldgen" + ], + "display_categories": [ + "datapack", + "fabric", + "forge", + "management", + "neoforge", + "optimization", + "quilt", + "worldgen" + ], + "versions": [ + "1.21", + "1.21.1", + "1.21.10", + "1.21.11", + "1.21.2", + "1.21.3", + "1.21.4", + "1.21.5", + "1.21.6", + "1.21.7", + "1.21.8", + "1.21.9", + "26.1", + "26.1.1", + "26.1.2", + "26.2", + "26.3" + ], + "downloads": 105655, + "follows": 68, + "icon_url": "https://cdn.modrinth.com/data/VfHc5JEX/f9a1f1d144892597794b3ffd89c06a09e397117a_96.webp", + "date_created": "2025-10-22T00:34:52.680805+00:00", + "date_modified": "2025-11-26T14:37:42.788786+00:00", + "latest_version": "XexlcJmN", + "license": "MIT", + "client_side": "optional", + "server_side": "required", + "environment": [ + "server_only", + "unknown" + ], + "disclosure_types": [], + "gallery": [], + "featured_gallery": null, + "color": 7039851 + } + ], + "offset": 0, + "limit": 3, + "total_hits": 5 +} diff --git a/crates/mineui-core/tests/fixtures/modrinth-version-files-sha1.json b/crates/mineui-core/tests/fixtures/modrinth-version-files-sha1.json new file mode 100644 index 0000000..1d5b7ba --- /dev/null +++ b/crates/mineui-core/tests/fixtures/modrinth-version-files-sha1.json @@ -0,0 +1,84 @@ +{ + "584d303f646287ee6be059ecb2fc451255be9ee9": { + "game_versions": [ + "1.21.1" + ], + "loaders": [ + "fabric" + ], + "environment": "client_or_server_prefers_both", + "id": "5SwzqWUu", + "project_id": "P7dR8mSH", + "author_id": "JZA4dW8o", + "featured": false, + "name": "[1.21.1] Fabric API 0.116.18+1.21.1", + "version_number": "0.116.18+1.21.1", + "changelog": "- Bump version (modmuss50)\n- Fix ContainerComponentStorage having a limit of 1 (#5680) (Jonathan Coates)\n- [1.21.1] Add `fabric:false` resource condition (#5410) (#5669) (Cassian)\n", + "changelog_url": null, + "date_published": "2026-11-09T15:02:24.365327Z", + "downloads": 40670, + "version_type": "release", + "status": "listed", + "requested_status": null, + "files": [ + { + "id": "S4NUqnSY", + "hashes": { + "sha512": "9f721c253ae2e9823cb548e8ec132c9928f80a65184e9b8dcfc489a8d632df20cbfea1e65ff8a4333bdb295c41fbe2228b43e4d41c7355d42ed4637a785840a1", + "sha1": "584d303f646287ee6be059ecb2fc451255be9ee9" + }, + "url": "https://cdn.modrinth.com/data/P7dR8mSH/versions/5SwzqWUu/fabric-api-0.116.18%2B1.21.1.jar", + "filename": "fabric-api-0.116.18+1.21.1.jar", + "primary": true, + "size": 2453884, + "file_type": null + } + ], + "dependencies": [] + }, + "6c8098fc0f124c7b6492de60db0108747f7f9821": { + "game_versions": [ + "1.21", + "1.21.1" + ], + "loaders": [ + "fabric" + ], + "environment": "client_or_server_prefers_both", + "id": "RVFHfo1D", + "project_id": "fALzjamp", + "author_id": "nfBsvT1J", + "featured": false, + "name": "Chunky 1.4.23", + "version_number": "1.4.23", + "changelog": "", + "changelog_url": null, + "date_published": "2025-04-04T06:33:52.501452Z", + "downloads": 1544202, + "version_type": "release", + "status": "listed", + "requested_status": null, + "files": [ + { + "id": "f8V7bDmI", + "hashes": { + "sha1": "6c8098fc0f124c7b6492de60db0108747f7f9821", + "sha512": "02ca6af1ed31e9ebc51af20948a2afb670fe653c80aaeb990947caf6b655d6ab8eda3f1b64ef478633b67ef5d2fd0d1fe67e2107a4a522ef45fd1f183c9a6c9c" + }, + "url": "https://cdn.modrinth.com/data/fALzjamp/versions/RVFHfo1D/Chunky-Fabric-1.4.23.jar", + "filename": "Chunky-Fabric-1.4.23.jar", + "primary": true, + "size": 342979, + "file_type": null + } + ], + "dependencies": [ + { + "version_id": null, + "project_id": "P7dR8mSH", + "file_name": null, + "dependency_type": "required" + } + ] + } +} diff --git a/crates/mineui-core/tests/fixtures/modrinth-versions-chunky-fabric-1.21.1.json b/crates/mineui-core/tests/fixtures/modrinth-versions-chunky-fabric-1.21.1.json new file mode 100644 index 0000000..5a393c5 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/modrinth-versions-chunky-fabric-1.21.1.json @@ -0,0 +1,90 @@ +[ + { + "game_versions": [ + "1.21", + "1.21.1" + ], + "loaders": [ + "fabric" + ], + "environment": "client_or_server_prefers_both", + "id": "RVFHfo1D", + "project_id": "fALzjamp", + "author_id": "nfBsvT1J", + "featured": false, + "name": "Chunky 1.4.23", + "version_number": "1.4.23", + "changelog_url": null, + "date_published": "2025-04-04T06:33:52.501452Z", + "downloads": 1544202, + "version_type": "release", + "status": "listed", + "requested_status": null, + "files": [ + { + "id": "f8V7bDmI", + "hashes": { + "sha1": "6c8098fc0f124c7b6492de60db0108747f7f9821", + "sha512": "02ca6af1ed31e9ebc51af20948a2afb670fe653c80aaeb990947caf6b655d6ab8eda3f1b64ef478633b67ef5d2fd0d1fe67e2107a4a522ef45fd1f183c9a6c9c" + }, + "url": "https://cdn.modrinth.com/data/fALzjamp/versions/RVFHfo1D/Chunky-Fabric-1.4.23.jar", + "filename": "Chunky-Fabric-1.4.23.jar", + "primary": true, + "size": 342979, + "file_type": null + } + ], + "dependencies": [ + { + "version_id": null, + "project_id": "P7dR8mSH", + "file_name": null, + "dependency_type": "required" + } + ] + }, + { + "game_versions": [ + "1.21", + "1.21.1" + ], + "loaders": [ + "fabric" + ], + "environment": "client_or_server_prefers_both", + "id": "dPliWter", + "project_id": "fALzjamp", + "author_id": "nfBsvT1J", + "featured": false, + "name": "Chunky 1.4.16", + "version_number": "1.4.16", + "changelog_url": null, + "date_published": "2024-06-17T06:00:13.853652Z", + "downloads": 849034, + "version_type": "release", + "status": "listed", + "requested_status": null, + "files": [ + { + "id": "Vo7cxYPm", + "hashes": { + "sha1": "2b68d2bd507cd9f45fdd637ba32e8a47de6bda35", + "sha512": "7e862f4db563bbb5cfa8bc0c260c9a97b7662f28d0f8405355c33d7b4100ce05378b39ed37c5d75d2919a40c244a3011bb4ba63f9d53f10d50b11b32656ea395" + }, + "url": "https://cdn.modrinth.com/data/fALzjamp/versions/dPliWter/Chunky-1.4.16.jar", + "filename": "Chunky-1.4.16.jar", + "primary": true, + "size": 343847, + "file_type": null + } + ], + "dependencies": [ + { + "version_id": null, + "project_id": "P7dR8mSH", + "file_name": null, + "dependency_type": "required" + } + ] + } +] diff --git a/crates/mineui-core/tests/fixtures/modrinth-versions-fabric-api-1.21.1.json b/crates/mineui-core/tests/fixtures/modrinth-versions-fabric-api-1.21.1.json new file mode 100644 index 0000000..2e99647 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/modrinth-versions-fabric-api-1.21.1.json @@ -0,0 +1,110 @@ +[ + { + "game_versions": [ + "1.21.1" + ], + "loaders": [ + "fabric" + ], + "environment": "client_or_server_prefers_both", + "id": "5SwzqWUu", + "project_id": "P7dR8mSH", + "author_id": "JZA4dW8o", + "featured": false, + "name": "[1.21.1] Fabric API 0.116.18+1.21.1", + "version_number": "0.116.18+1.21.1", + "changelog_url": null, + "date_published": "2026-11-09T15:02:24.365327Z", + "downloads": 40670, + "version_type": "release", + "status": "listed", + "requested_status": null, + "files": [ + { + "id": "S4NUqnSY", + "hashes": { + "sha1": "584d303f646287ee6be059ecb2fc451255be9ee9", + "sha512": "9f721c253ae2e9823cb548e8ec132c9928f80a65184e9b8dcfc489a8d632df20cbfea1e65ff8a4333bdb295c41fbe2228b43e4d41c7355d42ed4637a785840a1" + }, + "url": "https://cdn.modrinth.com/data/P7dR8mSH/versions/5SwzqWUu/fabric-api-0.116.18%2B1.21.1.jar", + "filename": "fabric-api-0.116.18+1.21.1.jar", + "primary": true, + "size": 2453884, + "file_type": null + } + ], + "dependencies": [] + }, + { + "game_versions": [ + "1.21.1" + ], + "loaders": [ + "fabric" + ], + "environment": "client_or_server_prefers_both", + "id": "Mys3P7lK", + "project_id": "P7dR8mSH", + "author_id": "JZA4dW8o", + "featured": false, + "name": "[1.21.1] Fabric API 0.116.17+1.21.1", + "version_number": "0.116.17+1.21.1", + "changelog_url": null, + "date_published": "2026-09-01T16:40:04.373428Z", + "downloads": 2876851, + "version_type": "release", + "status": "listed", + "requested_status": null, + "files": [ + { + "id": "WuOG3t7I", + "hashes": { + "sha512": "98c478217da19181f0e4df3ea6c2da6bdbda271c7544a4aea048513a49b444f1ff5b71dc0df6303017c48e8ff69b7bb6af6179bdf0d0e09ab3c1ee08411857a8", + "sha1": "810b2b0195371a012906241d8b85a32a1d6de53c" + }, + "url": "https://cdn.modrinth.com/data/P7dR8mSH/versions/Mys3P7lK/fabric-api-0.116.17%2B1.21.1.jar", + "filename": "fabric-api-0.116.17+1.21.1.jar", + "primary": true, + "size": 2452735, + "file_type": null + } + ], + "dependencies": [] + }, + { + "game_versions": [ + "1.21.1" + ], + "loaders": [ + "fabric" + ], + "environment": "client_or_server_prefers_both", + "id": "fpB2VatZ", + "project_id": "P7dR8mSH", + "author_id": "JZA4dW8o", + "featured": false, + "name": "[1.21.1] Fabric API 0.116.16+1.21.1", + "version_number": "0.116.16+1.21.1", + "changelog_url": null, + "date_published": "2026-09-01T10:29:57.072338Z", + "downloads": 26974, + "version_type": "release", + "status": "listed", + "requested_status": null, + "files": [ + { + "id": "DlvCfrJp", + "hashes": { + "sha1": "07fcbd957f45592ac3ac63161b0bf4f0b724c665", + "sha512": "1ee763b538619b917b3bf02568dd2fb6c4ca3dc98e5554dc944e4524c316437946b00b6c1c4597ca86871f820b894c4b7b2b5701f7479e2dd057b0ea947886df" + }, + "url": "https://cdn.modrinth.com/data/P7dR8mSH/versions/fpB2VatZ/fabric-api-0.116.16%2B1.21.1.jar", + "filename": "fabric-api-0.116.16+1.21.1.jar", + "primary": true, + "size": 2467467, + "file_type": null + } + ], + "dependencies": [] + } +] diff --git a/crates/mineui-core/tests/live_modrinth.rs b/crates/mineui-core/tests/live_modrinth.rs new file mode 100644 index 0000000..a52c099 --- /dev/null +++ b/crates/mineui-core/tests/live_modrinth.rs @@ -0,0 +1,303 @@ +//! Live test for Find mods (contract §3.5a, §6.3b, 2.13.0). **Opt-in** - +//! `#[ignore]`; CI never runs it. Needs the network: it searches Modrinth for +//! Chunky on a Fabric 1.21.1 server, resolves its one required dependency +//! (Fabric API) and downloads both files (under 3 MB) through the +//! host-allowlisted client into a temp data dir, checking each sha512. +//! +//! ```sh +//! cargo test -p mineui-core --test live_modrinth -- --ignored --nocapture +//! ``` + +use std::collections::HashMap; + +use mineui_core::model::{CoreEvent, DownloadKind, ModTarget}; +use mineui_core::modrinth::{self, InstalledIndex, LiveSource}; +use mineui_core::Core; + +#[tokio::test] +#[ignore = "needs the network (api.modrinth.com, cdn.modrinth.com)"] +async fn live_search_resolve_and_download_chunky_on_fabric() { + let server = modrinth::server_mods(&modrinth::support_for( + false, + Some("FABRIC"), + Some("1.21.1"), + )) + .unwrap(); + let client = modrinth::build_client(); + + // Search: Chunky is there, every hit is server-capable. + let page = modrinth::search_page(&client, &server, "chunky", 0, 10) + .await + .unwrap(); + println!( + "search: {} hits of {}: {:?}", + page.hits.len(), + page.total_hits, + page.hits.iter().map(|h| &h.slug).collect::>() + ); + assert!(page.hits.iter().any(|h| h.slug == "chunky")); + // An empty query lists the most downloaded mods for this server. + let popular = modrinth::search_page(&client, &server, "", 0, 5) + .await + .unwrap(); + assert!( + popular.total_hits > 1000, + "facets still match: {}", + popular.total_hits + ); + + // Resolve: Chunky plus Fabric API as a dependency. + let source = LiveSource { + client: client.clone(), + }; + let plan = modrinth::plan_install(&source, &server, "chunky", &InstalledIndex::default()) + .await + .unwrap(); + for f in &plan.files { + println!( + "plan: {} {} ({} bytes) dependency={} url={}", + f.project_id, + f.filename, + f.size, + f.dependency(), + f.url + ); + } + assert_eq!(plan.files.len(), 2); + assert!(!plan.files[0].dependency()); + assert_eq!(plan.files[1].project_id, "P7dR8mSH", "Fabric API"); + assert!(plan.files[1].dependency()); + + // Download both with the hash checks, into a temp data dir. + let tmp = tempfile::tempdir().unwrap(); + let core = Core::init(tmp.path().join("config"), tmp.path().join("data")) + .await + .unwrap(); + let mut events = core.subscribe_events(); + let temps = modrinth::download_plan(&core, &client, &plan.files, &HashMap::new()) + .await + .unwrap(); + for ((path, id), f) in temps.iter().zip(&plan.files) { + use sha2::Digest; + let bytes = std::fs::read(path).unwrap(); + assert_eq!(bytes.len() as u64, f.size); + assert_eq!(hex::encode(sha2::Sha512::digest(&bytes)), f.sha512); + println!( + "downloaded {} ({} bytes, download id {id})", + f.filename, + bytes.len() + ); + } + let mut done = 0; + while let Ok(ev) = events.try_recv() { + if let CoreEvent::DownloadProgress(p) = ev { + assert_eq!(p.kind, DownloadKind::Mod); + assert!(p.error.is_none()); + done += usize::from(p.done); + } + } + assert_eq!(done, 2, "one terminal event per file"); + + // Staged and placed for a server on this computer (host folder), then + // the temp dir is empty again. + modrinth::stage_and_place(&core, ModTarget::Mods, &plan.files, &temps) + .await + .unwrap(); + let mods = core.settings().await.simple.instance_dir.join("mods"); + for f in &plan.files { + assert!(mods.join(&f.filename).is_file(), "{}", f.filename); + } + let leftovers = std::fs::read_dir(tmp.path().join("data/tmp")) + .unwrap() + .count(); + assert_eq!(leftovers, 0); + + // The installed-projects lookup (real POST /v2/version_files) knows both + // files now, so a second install of Chunky is refused and Fabric API + // would count as already there. + let installed = modrinth::installed_index(&core, &client, ModTarget::Mods) + .await + .unwrap(); + println!("installed projects: {:?}", installed.projects); + assert!(installed.projects.contains_key("fALzjamp")); + assert!(installed.projects.contains_key("P7dR8mSH")); + let again = modrinth::plan_install(&source, &server, "chunky", &installed) + .await + .unwrap_err(); + println!("second install: {again}"); + assert_eq!(again.code(), "INVALID_INPUT"); +} + +/* ---------- the whole path on a throwaway container ---------- */ + +const NAME: &str = "mineui-live-modrinth"; +const IMAGE: &str = "docker.io/itzg/minecraft-server:java21"; + +fn podman(args: &[&str]) -> std::process::Output { + std::process::Command::new("podman") + .args(args) + .output() + .expect("podman on PATH") +} + +/// Removes the container and its volume however the test ends. +struct Cleanup; +impl Drop for Cleanup { + fn drop(&mut self) { + podman(&["rm", "-f", "-t", "0", NAME]); + podman(&["volume", "rm", "-f", &format!("{NAME}-data")]); + } +} + +fn names(list: &[mineui_core::model::ModEntry]) -> Vec { + list.iter().map(|m| m.filename.clone()).collect() +} + +/// Needs the network and podman with the itzg java21 image. Creates its own +/// `mineui-live-modrinth` container (TYPE=FABRIC, VERSION=1.21.1, entrypoint +/// `sleep`, so no Minecraft server runs) and removes it and its volume +/// afterwards. +/// +/// ```sh +/// cargo test -p mineui-core --test live_modrinth live_install_on_a_container -- --ignored --nocapture +/// ``` +#[tokio::test] +#[ignore = "needs the network and podman"] +async fn live_install_on_a_container() { + use mineui_core::settings::{Mode, Settings}; + let _cleanup = Cleanup; + podman(&["rm", "-f", "-t", "0", NAME]); + let volume = format!("{NAME}-data:/data"); + let made = podman(&[ + "run", + "-d", + "--name", + NAME, + "-v", + &volume, + "-e", + "TYPE=FABRIC", + "-e", + "VERSION=1.21.1", + "--entrypoint", + "sleep", + IMAGE, + "infinity", + ]); + assert!( + made.status.success(), + "{}", + String::from_utf8_lossy(&made.stderr) + ); + + let tmp = tempfile::tempdir().unwrap(); + let mut settings = Settings::default_with_data_dir(&tmp.path().join("data")); + settings.active_mode = Mode::Advanced; + settings.advanced.container_name = NAME.into(); + let core = + Core::init_with_settings(tmp.path().join("config"), tmp.path().join("data"), settings) + .await; + + let support = modrinth::support(&core).await.unwrap(); + println!("support: {support:?}"); + assert!(support.supported); + assert_eq!(support.target, Some(ModTarget::Mods)); + assert_eq!(support.loaders, ["fabric"]); + + // Install Chunky: Chunky + Fabric API land in /data/mods. + let result = modrinth::install(&core, "chunky").await.unwrap(); + println!("install: {result:?}"); + assert_eq!(result.installed.len(), 2); + assert_eq!(result.installed[0].slug, "chunky"); + assert!(!result.installed[0].dependency); + assert_eq!(result.installed[1].slug, "fabric-api"); + assert!(result.installed[1].dependency); + let listed = mineui_core::mods::list(&core).await.unwrap(); + println!("mods: {:?}", names(&listed.mods)); + for f in &result.installed { + assert!(names(&listed.mods).contains(&f.filename), "{}", f.filename); + } + + // Search marks it installed (hashes read in the container). + let page = modrinth::search(&core, "chunky", None, Some(5)) + .await + .unwrap(); + let hit = page.hits.iter().find(|h| h.slug == "chunky").unwrap(); + assert!(hit.installed); + // A second install is refused; nothing changes. + let again = modrinth::install(&core, "chunky").await.unwrap_err(); + println!("again: {again}"); + assert_eq!(again.code(), "INVALID_INPUT"); + + // Disable / enable through the container script, running ... + let chunky = result.installed[0].filename.clone(); + let off = mineui_core::mods::set_enabled(&core, &chunky, ModTarget::Mods, false) + .await + .unwrap(); + assert_eq!(off.filename, format!("{chunky}.disabled")); + let listed = mineui_core::mods::list(&core).await.unwrap(); + assert!(names(&listed.mods).contains(&off.filename)); + assert!(!names(&listed.mods).contains(&chunky)); + // ... and stopped (the volumes-from helper). + podman(&["stop", "-t", "0", NAME]); + let on = mineui_core::mods::set_enabled(&core, &off.filename, ModTarget::Mods, true) + .await + .unwrap(); + assert_eq!(on.filename, chunky); + // Refuses to overwrite: with Chunky off and a new file under its .jar + // name, turning the old one on fails and both files stay. + let off = mineui_core::mods::set_enabled(&core, &chunky, ModTarget::Mods, false) + .await + .unwrap(); + let stand_in = tmp.path().join("stand-in.jar"); + std::fs::write(&stand_in, b"not chunky").unwrap(); + let dest = format!("{NAME}:/data/mods/{chunky}"); + let copied = podman(&["cp", stand_in.to_str().unwrap(), &dest]); + assert!( + copied.status.success(), + "{}", + String::from_utf8_lossy(&copied.stderr) + ); + let taken = mineui_core::mods::set_enabled(&core, &off.filename, ModTarget::Mods, true) + .await + .unwrap_err(); + println!("taken: {taken}"); + assert_eq!(taken.code(), "INVALID_INPUT"); + let listed = mineui_core::mods::list(&core).await.unwrap(); + assert!(names(&listed.mods).contains(&off.filename)); + let size = listed + .mods + .iter() + .find(|m| m.filename == chunky) + .unwrap() + .size_bytes; + assert_eq!(size, 10, "the stand-in was not replaced"); + let missing = mineui_core::mods::set_enabled(&core, "nope.jar", ModTarget::Mods, false) + .await + .unwrap_err(); + assert!(missing.to_string().contains("does not exist"), "{missing}"); + let listed = mineui_core::mods::list(&core).await.unwrap(); + println!("mods after: {:?}", names(&listed.mods)); + + let log = mineui_core::audit::recent(&core, Some(20)).await.unwrap(); + let actions: Vec<_> = log + .entries + .iter() + .map(|e| { + format!( + "{} {} {}", + e.action, + e.target.clone().unwrap_or_default(), + e.detail.clone().unwrap_or_default() + ) + }) + .collect(); + println!("audit: {actions:#?}"); + assert_eq!( + log.entries + .iter() + .filter(|e| e.action == "mod.install" && e.ok) + .count(), + 2 + ); +} diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index e5636ef..e13ef72 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -13,9 +13,10 @@ use mineui_core::model::{ AppDir, AppInfo, AuditLog, BackupEntry, ChangedInstanceVersion, ConfigFileContent, ConfigFileList, CreateContainerArgs, CreateInstanceArgs, CreatedBackup, DeletedContainer, DownloadedMod, ExtraPort, InstanceStatus, JavaCheck, JobRunResult, JoinInfo, LogsTail, - McVersion, Metrics, ModTarget, ModpackHit, ModpackZipInfo, ModsList, PlayerHistory, PlayerNote, - PlayerNotes, PlayersResult, PublicAddress, RconOutput, RuntimeProbe, SchedulerStatus, - ServerList, ServerOverview, ServerState, ServerStatus, UnpackedMods, UpdateCheck, UploadedMod, + McVersion, Metrics, ModInstall, ModSearchPage, ModSupport, ModTarget, ModpackHit, + ModpackZipInfo, ModsList, PlayerHistory, PlayerNote, PlayerNotes, PlayersResult, PublicAddress, + RconOutput, RenamedMod, RuntimeProbe, SchedulerStatus, ServerList, ServerOverview, ServerState, + ServerStatus, UnpackedMods, UpdateCheck, UploadedMod, }; use mineui_core::settings::Mode; use mineui_core::{Core, Error, Hub, Settings}; @@ -230,6 +231,52 @@ pub async fn unpack_mod_archive( .await } +/// 2.13.0: `name.jar` ⇄ `name.jar.disabled`. +#[tauri::command] +pub async fn set_mod_enabled( + hub: HubState<'_>, + server_id: Option, + filename: String, + target: ModTarget, + enabled: bool, +) -> CmdResult { + let core = core_for(&hub, server_id).await?; + mineui_core::mods::set_enabled(&core, &filename, target, enabled).await +} + +/* ---------- §3.5a find mods on Modrinth (2.13.0) ---------- */ + +#[tauri::command] +pub async fn get_mod_support( + hub: HubState<'_>, + server_id: Option, +) -> CmdResult { + let core = core_for(&hub, server_id).await?; + mineui_core::modrinth::support(&core).await +} + +#[tauri::command] +pub async fn search_mods( + hub: HubState<'_>, + server_id: Option, + query: String, + offset: Option, + limit: Option, +) -> CmdResult { + let core = core_for(&hub, server_id).await?; + mineui_core::modrinth::search(&core, &query, offset, limit).await +} + +#[tauri::command] +pub async fn install_mod( + hub: HubState<'_>, + server_id: Option, + project_id: String, +) -> CmdResult { + let core = core_for(&hub, server_id).await?; + mineui_core::modrinth::install(&core, &project_id).await +} + /* ---------- §3.6 instance (simple mode only; WRONG_MODE enforced in core) ---------- */ #[tauri::command] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 037e0de..153860c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -128,6 +128,11 @@ pub fn run() { commands::download_mod, commands::delete_mod, commands::unpack_mod_archive, + commands::set_mod_enabled, + // §3.5a find mods on Modrinth (2.13.0) + commands::get_mod_support, + commands::search_mods, + commands::install_mod, // §3.6 instance commands::list_mc_versions, commands::create_instance, From 4e822fe703f9bd55803ee52bf2c60a02170bbf86 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 20:25:13 -0600 Subject: [PATCH 16/28] docs: v2-contract - delete_mod accepts a disabled mod (2.13.0) list_mods reports a disabled mod as .jar.disabled and set_mod_enabled makes such names, but the 6.2 filename rule only allowed .jar/.zip, so a disabled mod could not be deleted without enabling it first. New rule 3a: delete_mod also accepts a name ending .jar.disabled, with the bare-name, charset and length checks on the whole name and rule 3 on the name without the final .disabled. Nothing else changes; section 7 is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- docs/v2-contract.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/v2-contract.md b/docs/v2-contract.md index 32fc5e0..a30977d 100644 --- a/docs/v2-contract.md +++ b/docs/v2-contract.md @@ -769,6 +769,8 @@ Semantics: 256 MB (`FILE_TOO_LARGE`). - `delete_mod`: filename per §6.2; advanced → `runtime exec rm -f -- /`; simple → `std::fs::remove_file`. + A disabled mod (`.jar.disabled`, as `list_mods` reports it and + `set_mod_enabled` makes it) can be deleted as it is (2.13.0, §6.2 rule 3a). - `unpack_mod_archive` (2.7.0): installs the `.jar` files **inside** a `.zip` - a folder of mods zipped up, or a "server pack". `upload_mod`/`download_mod` place a `.zip` as one file, which is right for a mod shipped as a zip and useless for a @@ -2083,6 +2085,11 @@ Applied to the basename in `upload_mod`, `download_mod`, `delete_mod`: with `_` (v1 rule, kept). 3. Post-sanitization: non-empty, ≤ 255 bytes, does not start with `.` or `-`, not `..`, ends with `.jar` or `.zip` (case-insensitive). + 3a. `delete_mod` only (2.13.0): a name ending `.jar.disabled` (case-insensitive) + is also accepted. The whole name must pass rule 1, the charset of rule 2 + unchanged and the 255-byte limit, and the name without its final `.disabled` + must pass rule 3 and end in `.jar` (`x.disabled`, `x.jar.disabled.disabled`, + `x.zip.disabled` and `x.txt.disabled` are refused). 4. `target` must be exactly `"mods"` or `"plugins"`. ### 6.2a Mod archives (`unpack_mod_archive`, 2.7.0) From 27175c58db6823ca785d7a2d033848e752a12886 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 20:26:08 -0600 Subject: [PATCH 17/28] feat(core): delete_mod accepts a disabled mod (.jar.disabled) Contract 6.2 rule 3a: delete_mod also takes a name ending .jar.disabled (case-insensitive), as list_mods reports a disabled mod and set_mod_enabled makes it. The length check applies to the whole name; the bare-name, charset and leading-character checks and rule 3 apply to the name without the final .disabled, which must end in .jar. x.disabled, x.jar.disabled.disabled, x.txt.disabled, x.zip.disabled and traversal names stay refused. The container side moved into delete_in_container so both paths (exec when running, the helper when stopped) are unit-tested with FakeRuntime, whose exec and helper now record their argv. 309 unit tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- crates/mineui-core/src/fake_runtime.rs | 10 +- crates/mineui-core/src/mods.rs | 146 ++++++++++++++++++++++--- 2 files changed, 138 insertions(+), 18 deletions(-) diff --git a/crates/mineui-core/src/fake_runtime.rs b/crates/mineui-core/src/fake_runtime.rs index 72fb6e6..ae6f363 100644 --- a/crates/mineui-core/src/fake_runtime.rs +++ b/crates/mineui-core/src/fake_runtime.rs @@ -114,11 +114,13 @@ impl Runtime for FakeRuntime { async fn spawn_follow_logs(&self, _: &str) -> Result { unimplemented!() } - async fn exec(&self, _: &str, _: &[&str]) -> Result { - unimplemented!() + async fn exec(&self, name: &str, argv: &[&str]) -> Result { + self.log(format!("exec {name} {}", argv.join(" "))); + Ok(ok_output()) } - async fn run_with_volumes_from(&self, _: &str, _: &[&str]) -> Result { - unimplemented!() + async fn run_with_volumes_from(&self, name: &str, argv: &[&str]) -> Result { + self.log(format!("helper {name} {}", argv.join(" "))); + Ok(ok_output()) } async fn cp_to(&self, _: &str, _: &Path, _: &str) -> Result<()> { unimplemented!() diff --git a/crates/mineui-core/src/mods.rs b/crates/mineui-core/src/mods.rs index 9205d06..169aebd 100644 --- a/crates/mineui-core/src/mods.rs +++ b/crates/mineui-core/src/mods.rs @@ -287,28 +287,55 @@ async fn download_inner( }) } +/// §6.2 rules 1, 3 and 3a for `delete_mod`: a bare clean `.jar`/`.zip` +/// name, or (2.13.0) a disabled mod `.jar.disabled`. +pub(crate) fn delete_filename(filename: &str) -> Result { + if !filename.to_ascii_lowercase().ends_with(".jar.disabled") { + return crate::validate::mod_filename(filename, false); + } + if filename.len() > 255 { + return Err(Error::InvalidInput("filename exceeds 255 bytes".into())); + } + // The suffix is ASCII, so this cut is on a char boundary; the base + // check covers the bare name, the charset and the leading character, + // and the base ends in `.jar` by construction. + let base = &filename[..filename.len() - DISABLED_SUFFIX.len()]; + crate::validate::mod_filename(base, false)?; + Ok(filename.to_string()) +} + +/// Container side of `delete_mod`: `rm -f --` through `run_in_container`. +async fn delete_in_container( + runtime: &dyn crate::runtime::Runtime, + name: &str, + target: ModTarget, + filename: &str, +) -> Result<()> { + let path = format!("{}/{}", container_root(target), filename); + let out = crate::runtime::run_in_container(runtime, name, &["rm", "-f", "--", &path]).await?; + if !out.success() { + return Err(Error::Io(format!( + "failed to delete {filename}: {}", + out.stderr + ))); + } + Ok(()) +} + /// `delete_mod` (§3.5): filename must already be a bare clean name (§6.2). async fn delete_inner(core: &crate::Core, filename: &str, target: ModTarget) -> Result<()> { - let filename = crate::validate::mod_filename(filename, false)?; + let filename = delete_filename(filename)?; let settings = core.settings().await; match settings.active_mode { Mode::Advanced => { let runtime = crate::runtime::resolve(&settings.advanced).await?; - let name = &settings.advanced.container_name; - let path = format!("{}/{}", container_root(target), filename); - let out = crate::runtime::run_in_container( + delete_in_container( runtime.as_ref(), - name, - &["rm", "-f", "--", &path], + &settings.advanced.container_name, + target, + &filename, ) - .await?; - if !out.success() { - return Err(Error::Io(format!( - "failed to delete {filename}: {}", - out.stderr - ))); - } - Ok(()) + .await } Mode::Simple => { let path = settings @@ -672,6 +699,97 @@ mod tests { assert!(validate_upload_source(&ok).await.is_ok()); } + /* ---------- delete_mod of a disabled mod (§6.2 rule 3a, 2.13.0) ---------- */ + + #[test] + fn delete_accepts_a_disabled_jar_and_nothing_else_new() { + for ok in [ + "lithium.jar", + "pack.zip", + "lithium-0.14.jar.disabled", + "Chunky-1.4.23.JAR.Disabled", + ] { + assert_eq!(delete_filename(ok).unwrap(), ok); + } + for bad in [ + "x.disabled", + "x.jar.disabled.disabled", + "x.txt.disabled", + "x.zip.disabled", + ".jar.disabled", + "-x.jar.disabled", + "../x.jar.disabled", + "mods/x.jar.disabled", + "..\\x.jar.disabled", + "/data/mods/x.jar.disabled", + "bad name.jar.disabled", + "x.jar.disabled ", + "x.txt", + ] { + assert_eq!( + delete_filename(bad).unwrap_err().code(), + "INVALID_INPUT", + "{bad:?}" + ); + } + let long = format!("{}.jar.disabled", "a".repeat(250)); + assert_eq!(delete_filename(&long).unwrap_err().code(), "INVALID_INPUT"); + } + + #[tokio::test] + async fn delete_a_disabled_mod_on_this_computer() { + let tmp = tempfile::tempdir().unwrap(); + let core = crate::Core::init(tmp.path().join("config"), tmp.path().join("data")) + .await + .unwrap(); + let mods = core.settings().await.simple.instance_dir.join("mods"); + std::fs::create_dir_all(&mods).unwrap(); + std::fs::write(mods.join("sodium.jar.disabled"), b"jar").unwrap(); + std::fs::write(mods.join("keep.jar"), b"jar").unwrap(); + delete(&core, "sodium.jar.disabled", ModTarget::Mods) + .await + .unwrap(); + assert!(!mods.join("sodium.jar.disabled").exists()); + assert!(mods.join("keep.jar").exists()); + assert_eq!( + delete(&core, "x.txt.disabled", ModTarget::Mods) + .await + .unwrap_err() + .code(), + "INVALID_INPUT" + ); + } + + #[tokio::test] + async fn delete_a_disabled_mod_in_a_container() { + use crate::fake_runtime::FakeRuntime; + let name = delete_filename("sodium.jar.disabled").unwrap(); + // Stopped: the volumes-from helper. + let rt = FakeRuntime::default(); + delete_in_container(&rt, "mc", ModTarget::Mods, &name) + .await + .unwrap(); + assert_eq!( + rt.calls(), + ["ps mc", "helper mc rm -f -- /data/mods/sodium.jar.disabled"] + ); + // Running: exec. + let rt = FakeRuntime { + ps: Ok(Some("running".into())), + ..Default::default() + }; + delete_in_container(&rt, "mc", ModTarget::Plugins, &name) + .await + .unwrap(); + assert_eq!( + rt.calls(), + [ + "ps mc", + "exec mc rm -f -- /data/plugins/sodium.jar.disabled" + ] + ); + } + /* ---------- set_mod_enabled (§3.5, 2.13.0) ---------- */ #[test] From 163fdbe1e0cd396c027ca36e78930683c08916c9 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 21:37:49 -0600 Subject: [PATCH 18/28] feat(ui): find mods on Modrinth, enable and disable mods Add a Find tab to Add a mod or plugin: search Modrinth for what the server can load, install with the other mods it needs, progress per file, plain errors. A server that cannot load mods says why. The link tab is Advanced only, with a warning. Mod cards get a switch to turn a .jar off and on. Glossary gains Modrinth. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- app/components/AddModDialog.tsx | 94 ++++++- app/components/FindMods.tsx | 466 ++++++++++++++++++++++++++++++++ app/components/ModCard.tsx | 42 ++- app/lib/glossary.ts | 4 + app/mods/page.tsx | 24 ++ 5 files changed, 611 insertions(+), 19 deletions(-) create mode 100644 app/components/FindMods.tsx diff --git a/app/components/AddModDialog.tsx b/app/components/AddModDialog.tsx index 28be79f..1bf5568 100644 --- a/app/components/AddModDialog.tsx +++ b/app/components/AddModDialog.tsx @@ -17,6 +17,7 @@ import { FolderOpen, Link2, Plug, + Search, type LucideIcon, } from "lucide-react"; import { @@ -31,22 +32,26 @@ import { TextField, } from "@heroui/react"; import { useUISound } from "@/app/hooks/useUISound"; +import FindMods from "@/app/components/FindMods"; import ChoiceCards from "@/app/components/ChoiceCards"; import { identityLine, useServers } from "@/app/components/ServerProvider"; +import { useViewLevel } from "@/app/components/ViewLevelProvider"; import { onFileDrag, pickModFile } from "@/app/lib/dialog"; import { DropZone } from "@heroui-pro/react"; import { formatBytes } from "@/app/lib/format"; import { downloadMod, + getModSupport, onDownloadProgress, unpackModArchive, uploadMod, IpcError, type DownloadProgressEvent, + type ModSupport, type ModTarget, } from "@/app/lib/ipc"; -type Source = "link" | "file"; +type Source = "find" | "link" | "file"; /** What a .zip is: several mods to unpack, or one mod shipped as a zip. */ type ZipAs = "bundle" | "single"; @@ -159,7 +164,7 @@ export default function AddModDialog({ isOpen, onClose, onInstalled }: AddModDia variant="blur" > - + @@ -185,7 +190,38 @@ function AddModForm({ const loads = loader !== null && loader in LOADS ? LOADS[loader] : undefined; const [target, setTarget] = useState(loads ?? "mods"); - const [source, setSource] = useState("file"); + const { level } = useViewLevel(); + const [picked, setPicked] = useState("find"); + // The link tab only exists in Advanced view; Find is the front door. + const source: Source = picked === "link" && level !== "advanced" ? "find" : picked; + const setSource = setPicked; + const [support, setSupport] = useState(null); + useEffect(() => { + let live = true; + getModSupport() + .then((s) => live && setSupport(s)) + .catch( + () => + live && + setSupport({ + supported: false, + target: null, + serverType: null, + mcVersion: null, + loaders: [], + reason: "MineUI could not tell what this server can load.", + }), + ); + return () => { + live = false; + }; + }, []); + const matching = [ + support?.serverType ? (LOADER_NAMES[support.serverType] ?? support.serverType) : null, + support?.mcVersion, + ] + .filter(Boolean) + .join(" ") || "this server"; const [link, setLink] = useState(""); const [saveAs, setSaveAs] = useState(""); const [progress, setProgress] = useState(null); @@ -396,7 +432,8 @@ function AddModForm({ - {/* 1 - what it is */} + {/* 1 - what it is (Find knows from the server) */} + {source !== "find" && (
1 · What are you adding? @@ -416,11 +453,12 @@ function AddModForm({

)}
+ )} {/* 2 - where it comes from */}
- 2 · Where is the file? + {source === "find" ? "Where from?" : "2 · Where is the file?"} - + - - This computer + + Find - + - A link + + This computer + {level === "advanced" && ( + + + A link + + + + )} + + + + +

+ + + MineUI cannot check a file from a link the way it checks files from Find. Only use links you trust. + +

)} - {added.length > 0 && ( + {source !== "find" && added.length > 0 && (
play("hover")} > - {added.length > 0 ? "Done" : "Cancel"} + {added.length > 0 || (source === "find" && support?.supported) ? "Done" : "Cancel"} - {source === "link" ? ( + {source === "find" ? null : source === "link" ? ( + + )} + + ) : hits.length === 0 ? ( + + + + + + {term ? `No ${word} found for "${term}"` : `No ${word} to show`} + + Try another word, or a shorter one. Only {word} that work with {matching} are listed. + + + + ) : ( + <> +
    + {hits.map((hit) => { + const isInstalled = hit.installed || doneIds.has(hit.projectId); + const mine = installingId === hit.projectId; + return ( +
  • +
    + + {hit.iconUrl && } + + + + +
    +

    + { + if (el) titleRefs.current.set(hit.projectId, el); + else titleRefs.current.delete(hit.projectId); + }} + tabIndex={-1} + className="text-sm font-semibold text-foreground outline-none" + > + {hit.title} + + by {hit.author} +

    +

    {hit.description}

    +

    + +

    +
    +
    + {isInstalled ? ( + + + Installed + + ) : ( + + )} +
    +
    + + {hit.clientSide === "required" && !isInstalled && ( +

    + + Every player has to install this {noun} too, or they cannot join. +

    + )} + + {mine && ( +
    +
    + + + {progress + ? `Downloading ${progress.filename}${fileNo > 1 ? ` (file ${fileNo})` : ""}` + : "Getting ready..."} + + + + {progress + ? progress.totalBytes + ? `${formatBytes(progress.receivedBytes)} / ${formatBytes(progress.totalBytes)}` + : formatBytes(progress.receivedBytes) + : ""} + +
    + + + + + +
    + )} +
  • + ); + })} +
+ + {hasMore && ( + + )} + + )} + +

+ Results come from Modrinth ( + + modrinth.com + + ). MineUI checks every file against what Modrinth published before it keeps it. +

+
+ ); +} + +function ResultSkeletons() { + return ( +
+ {[0, 1, 2, 3].map((i) => ( +
+ +
+ + + +
+
+ ))} +
+ ); +} diff --git a/app/components/ModCard.tsx b/app/components/ModCard.tsx index 9c10aae..e77a131 100644 --- a/app/components/ModCard.tsx +++ b/app/components/ModCard.tsx @@ -3,7 +3,7 @@ // One mod or plugin on the Mods page: name, a few facts, copy / delete. import { motion, type Variants } from "motion/react"; import { Copy, Trash2 } from "lucide-react"; -import { Button, Card, Chip, Tooltip } from "@heroui/react"; +import { Button, Card, Chip, Switch, Tooltip } from "@heroui/react"; import { formatBytes, formatDateTime } from "@/app/lib/format"; import { useUISound } from "@/app/hooks/useUISound"; import type { ModEntry, ModTarget } from "@/app/lib/ipc"; @@ -33,10 +33,13 @@ interface ModCardProps { serverLoader: string | null; copied: boolean; deleting: boolean; + /** A switch for this file is being applied. */ + toggling: boolean; index: number; variants: Variants; onCopy: (filename: string) => void; onDelete: (item: ModEntry, kind: ModTarget) => void; + onToggle: (item: ModEntry, kind: ModTarget, enabled: boolean) => void; } export default function ModCard({ @@ -45,10 +48,12 @@ export default function ModCard({ serverLoader, copied, deleting, + toggling, index, variants, onCopy, onDelete, + onToggle, }: ModCardProps) { const { play } = useUISound(); const known = item.loader !== "unknown"; @@ -57,17 +62,42 @@ export default function ModCard({ const serverKnown = serverLoader !== null && serverLoader in LOADER_NAMES; const mismatch = known && serverKnown && item.loader !== serverLoader; const disabled = item.filename.toLowerCase().endsWith(".jar.disabled"); + // Only a .jar can be switched: a .zip has no off state. + const switchable = disabled || item.filename.toLowerCase().endsWith(".jar"); return ( - + - {item.name} +
+ + {item.name} + + {switchable && ( + { + play(on ? "toggle_on" : "toggle_off"); + onToggle(item, kind, on); + }} + className="shrink-0" + > + + + + + + + )} +
Updated {formatDateTime(item.updatedAtEpochMs)}
- + Size: {formatBytes(item.sizeBytes)} {known && Loader: {loaderName(item.loader)}} {mismatch && ( @@ -84,8 +114,8 @@ export default function ModCard({ - A file ending in .disabled is ignored by the server. Rename it back to .jar - to use it again. + The server skips this one. Turn the switch on to use it again. The change + applies after a restart. diff --git a/app/lib/glossary.ts b/app/lib/glossary.ts index 914cfe7..ee8c97f 100644 --- a/app/lib/glossary.ts +++ b/app/lib/glossary.ts @@ -49,6 +49,10 @@ export const GLOSSARY = { title: "Plugin", body: "A file that adds features to the server, like home commands or protection. It only runs on the server, so your friends do not install anything.", }, + Modrinth: { + title: "Modrinth", + body: "A free website where people share mods and plugins. MineUI searches it for you, so you do not have to download files by hand.", + }, modpack: { title: "Modpack", body: "A ready-made bundle of mods that work well together. Pick one and MineUI sets the whole thing up for you.", diff --git a/app/mods/page.tsx b/app/mods/page.tsx index 79091f8..7781a6b 100644 --- a/app/mods/page.tsx +++ b/app/mods/page.tsx @@ -39,6 +39,7 @@ import Term from "@/app/components/Term"; import { deleteMod, listMods, + setModEnabled, restartServer, IpcError, type ModEntry, @@ -180,6 +181,25 @@ export default function ModsPage() { } }; + const [toggling, setToggling] = useState(null); + const toggleMod = async (item: ModEntry, kind: ModTarget, enabled: boolean) => { + setToggling(`${kind}:${item.filename}`); + try { + await setModEnabled(item.filename, kind, enabled); + toast.success( + `${item.name} is ${enabled ? "on" : "off"}`, + { description: "The change applies after the server restarts." }, + ); + if (phase === "running") setNeedsRestart(true); + await refreshMods(); + } catch (error) { + play("error"); + toast.danger(error instanceof IpcError ? error.message : "The switch did not work"); + } finally { + setToggling(null); + } + }; + const doRestart = async () => { setRestarting(true); try { @@ -413,6 +433,8 @@ export default function ModsPage() { serverLoader={serverLoader} copied={copied === item.filename} deleting={deleting === `mods:${item.filename}`} + toggling={toggling === `mods:${item.filename}`} + onToggle={toggleMod} index={index} variants={cardMotion} onCopy={copyFilename} @@ -448,6 +470,8 @@ export default function ModsPage() { serverLoader={serverLoader} copied={copied === item.filename} deleting={deleting === `plugins:${item.filename}`} + toggling={toggling === `plugins:${item.filename}`} + onToggle={toggleMod} index={index} variants={cardMotion} onCopy={copyFilename} From a745b2fe9347734d86a3875b8bfd8d0910aba634 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 21:44:00 -0600 Subject: [PATCH 19/28] docs: find mods, mod switch, figures (309 tests, 61 commands) Changelog, README and SECURITY cover Find mods (Modrinth search and install with a sha512 check), the on/off switch for mods, and the link tab moving to the Advanced view. Test and IPC command counts updated. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- CHANGELOG.md | 19 ++++++++++++++++++- CLAUDE.md | 2 +- README.md | 23 +++++++++++++++++------ SECURITY.md | 4 +++- 4 files changed, 39 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7dc5f58..2eed545 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,8 +43,22 @@ All notable changes to MineUI are documented here. Format follows server made and the first friend joining. The join address is shown as a tilting "server pass" card with Copy. All of it stops under the system's reduce-motion setting, and sounds follow the existing sound setting. +- **Find mods.** The add dialog on Mods & plugins searches Modrinth for a + server In a container that runs Fabric, Quilt, Forge, NeoForge, Paper or + Purpur, and lists only what works with its type and Minecraft version, + the most downloaded first. Install also adds the other mods it needs, + checks every file against the sha512 Modrinth published before keeping + it, and says when every player has to install the mod too. Servers On + this computer, Vanilla servers and modpack servers get an explanation + instead of a search. Tried on a real Fabric server under rootless Podman; + the other server types are covered by tests only. +- **Switch a mod off and on.** Each mod and plugin jar has a switch. Off + renames the file to `.jar.disabled` so the server skips it; it applies + after a restart. A switched-off mod can be deleted as it is. - IPC: `install_java` and `required_java_major`, `JavaCheck.managed`, and - `DownloadKind` gains `"java"` (see `docs/v2-contract.md`). + `DownloadKind` gains `"java"`; `get_mod_support`, `search_mods`, + `install_mod` and `set_mod_enabled`, and `delete_mod` accepts a + `.jar.disabled` name (see `docs/v2-contract.md`). ### Changed @@ -54,6 +68,9 @@ All notable changes to MineUI are documented here. Format follows - **The create forms show less up front.** Server type, version, pack and the Mojang agreement come first; the rest is under More options, with the same defaults as before. +- **Adding a mod from a link is in the Advanced view only**, with a warning + that MineUI cannot check a file from a link the way it checks files from + Find. - **macOS builds are signed with a Developer ID and notarized** by the release workflow from this release on. Windows builds are still unsigned. - @heroui-pro/react 1.0.0-beta.11. The Java installer reads archive names diff --git a/CLAUDE.md b/CLAUDE.md index 3caa32d..b3971aa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ contribution process; this file is conventions and constraints only. - `pnpm lint` - ESLint - `pnpm tauri dev` - full app (Next.js dev server + Tauri window) - `pnpm tauri build` - production desktop bundle -- `cargo test -p mineui-core` - Rust unit tests (273 tests, must stay green) +- `cargo test -p mineui-core` - Rust unit tests (309 tests, must stay green) - `cargo fmt` / `cargo clippy` - run before committing any Rust change pnpm only. Do not use npm/yarn/bun. diff --git a/README.md b/README.md index deb6b27..1a2d7b7 100644 --- a/README.md +++ b/README.md @@ -232,9 +232,20 @@ confirmation before `stop`. ### Mods & plugins -Browse what's installed, upload a jar from disk, or download one from a URL. -The add dialog preselects mod or plugin from what the server runs and warns -when the choice cannot load there. Have a whole set of mods as a `.zip` - a +**Find mods.** For a server In a container that runs Fabric, Quilt, Forge, +NeoForge, Paper or Purpur, the add dialog searches +[Modrinth](https://modrinth.com) and lists only what works with that server's +type and Minecraft version. *Install* also adds the other mods it needs, +checks every file against the sha512 Modrinth published before keeping it, +and says when every player has to install the mod too. Servers On this +computer, Vanilla servers and modpack servers get a plain explanation instead +of a search. + +Browse what's installed, switch a mod off and on again without deleting it +(it applies after a restart), or upload a jar from disk. Downloading from a +link is still there in the Advanced view, with a warning that MineUI cannot +check such a file. The add dialog preselects mod or plugin from what the +server runs and warns when the choice cannot load there. Have a whole set of mods as a `.zip` - a zipped folder, or a server pack? MineUI unpacks the jars inside and installs them together, which is the way to put a pack's mods onto a server that already exists. @@ -285,8 +296,8 @@ plus container/process metrics; everything else still works. ### Every backend call is typed and contract-bound -`crates/mineui-core` is pure Rust (no Tauri dependency, 273 unit tests); -`src-tauri` is a thin `#[tauri::command]` shell (57 IPC commands) that +`crates/mineui-core` is pure Rust (no Tauri dependency, 309 unit tests); +`src-tauri` is a thin `#[tauri::command]` shell (61 IPC commands) that delegates to it. The full command/error/event surface is specified in [`docs/v2-contract.md`](docs/v2-contract.md) - binding, not a suggestion; see [CONTRIBUTING.md](CONTRIBUTING.md). @@ -314,7 +325,7 @@ Other commands: - `pnpm build` - static export to `out/` (what Tauri bundles) - `pnpm lint` - ESLint - `pnpm tauri build` - production desktop bundle -- `cargo test -p mineui-core` - Rust unit tests (273 tests; must stay green) +- `cargo test -p mineui-core` - Rust unit tests (309 tests; must stay green) CI (`.github/workflows/ci.yml`) runs lint/typecheck/build on the frontend and `cargo fmt`/`clippy`/`test` plus a `cargo check` of the Tauri shell, on every diff --git a/SECURITY.md b/SECURITY.md index dfd25ff..0494618 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -60,7 +60,9 @@ The following areas are in scope for security reports: - **RCON console** - command injection or allowlist bypass in the RCON command panel. - **Mods & Plugins** - path traversal or unsafe file handling in upload, - URL download, or delete flows. + URL download, enable/disable, or delete flows; for Find mods, a bypass of + the fixed Modrinth hosts (https only) or of the sha512 check MineUI makes + on every file before it keeps it. - **Configuration editor** - path traversal outside the intended `server.properties` / `config/` scope. - **World backups** - path traversal or archive extraction issues From 3986d4685aa116900dc4da45e8be68413a49b07c Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 22:49:38 -0600 Subject: [PATCH 20/28] docs: v2-contract - Minecraft versions per server type (2.13.0) list_mc_versions gains an optional serverType (a ContainerLoader wire name). Absent or "vanilla" keeps today's list. Otherwise the Mojang list is restricted, in Mojang order and with the same McVersion shape, to the versions that type publishes builds for: Paper (Fill v3), Purpur, Fabric and Quilt meta, Forge promotions_slim, NeoForge maven (the NeoForge to Minecraft version rule, released builds only, plus 1.20.1). Per-type 15-minute cache, stale cache over an error, and a fall-back to the unfiltered list whenever the type's list cannot be had, so creation is never blocked. New 6.3c for the fixed hosts, client and size cap; 3.13 says how the UI picks mcVersion and when it may send LATEST; section 7 and the module map follow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- docs/v2-contract.md | 71 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/docs/v2-contract.md b/docs/v2-contract.md index a30977d..6c4c89d 100644 --- a/docs/v2-contract.md +++ b/docs/v2-contract.md @@ -975,7 +975,7 @@ a supported type whose Minecraft version is unknown. | Command | Args | Returns | Mode | Core fn | v1 route | | --- | --- | --- | --- | --- | --- | -| `list_mc_versions` | `{ includeSnapshots?: boolean }` | `McVersion[]` | both (2.6.0: container creation, §3.13, picks from it too) | `mojang::list_versions` | - (new) | +| `list_mc_versions` | `{ includeSnapshots?: boolean; serverType?: ContainerLoader }` (`serverType` 2.13.0) | `McVersion[]` | both (2.6.0: container creation, §3.13, picks from it too) | `loader_versions::list_versions` → `mojang::list_versions` | - (new) | | `create_instance` | `CreateInstanceArgs` | `InstanceStatus` | simple | `instance::create` | - (new) | | `delete_instance` | `{ confirm: true }` | `void` | simple | `instance::delete` | - (new) | | `instance_status` | - | `InstanceStatus` | simple | `instance::status` | - (new) | @@ -1041,6 +1041,44 @@ Semantics: `https://piston-meta.mojang.com/mc/game/version_manifest_v2.json`; filter to `release` unless `includeSnapshots`; cache in memory for 15 minutes; network failure with warm cache → serve cache, otherwise `DOWNLOAD_FAILED`. +- `list_mc_versions` with `serverType` (2.13.0): the versions a server of that type + can really be created with (§3.13), so the UI never offers one the itzg image + cannot install. `serverType` is a `ContainerLoader` wire name (§3.13); any other + string → `INVALID_INPUT`. Absent or `"vanilla"`: the plain list above, unchanged. + Otherwise the result is that same list (same `McVersion` shape, same order, newest + first, same `includeSnapshots` meaning, `latest` still marking Mojang's latest + release / snapshot) restricted to the ids the type publishes builds for. The type's + own list comes from one GET of a fixed URL (§6.3c): + + | `serverType` | URL | Minecraft versions it has builds for | + | --- | --- | --- | + | `paper` | `https://fill.papermc.io/v3/projects/paper` | every string in the arrays of the `versions` object (family → versions) | + | `purpur` | `https://api.purpurmc.org/v2/purpur` | the `versions` array | + | `fabric` | `https://meta.fabricmc.net/v2/versions/game` | `version` of every entry | + | `quilt` | `https://meta.quiltmc.org/v3/versions/game` | `version` of every entry | + | `forge` | `https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json` | the keys of `promos` without their `-latest` / `-recommended` suffix | + | `neoforge` | `https://maven.neoforged.net/api/maven/versions/releases/net/neoforged/neoforge` | derived from each entry of `versions` (below), plus `1.20.1` | + + NeoForge versions name their Minecraft version (NeoForge's versioning docs, and the + same rule as the image's `mc-image-helper install-neoforge`): three numbers + `A.B.n` (before 26) → `1.A.B`, or `1.A` when `B` is `0` (`21.1.209` → `1.21.1`, + `21.0.167` → `1.21`); four numbers `Y.A.B.n` (26 and later) → `Y.A.B`, or `Y.A` + when `B` is `0` (`26.1.2.5` → `26.1.2`, `26.3.0.102` → `26.3`). Only entries with + no suffix count: the image installs the newest such build by default + (`NEOFORGE_VERSION=latest`), and it skips `-beta` and `-alpha…` builds, so a line + with only betas (today `26.1` and `26.1.1`) cannot be created. Entries of any + other shape are skipped. `1.20.1` is added because the image installs NeoForge + for 1.20.1 from NeoForge's older `net.neoforged:forge` artifact, which this list + does not include. + + Each type's list is cached in memory for 15 minutes, per profile like the + manifest; when a refresh fails, a cached list of any age is used. The filter must + never make creation impossible: when the type's list cannot be fetched or read + (network, non-2xx, a body over the size cap, an unreadable or empty answer) and + nothing is cached, or when the filter would leave nothing, the call returns the + unfiltered list and logs one line (`mineui: … versions …`) to stderr. Only the + Mojang manifest's own failure is an error (`DOWNLOAD_FAILED`, as above). Not + audited. - `create_instance` sequence (each failure uses the listed code, partial dirs cleaned up best-effort): 1. `acceptEula !== true` → `EULA_NOT_ACCEPTED`. @@ -1492,6 +1530,12 @@ type ModpackRef = { }; ``` +Picking `mcVersion` (2.13.0): for a server type the UI offers only the versions +`list_mc_versions` returns with `serverType` set to the chosen `loader` (§3.6), and +sends `LATEST` only when that list contains Mojang's latest release; otherwise it +picks the newest version in the list. Core does not repeat the check here (the image +stays the authority on what it can install). Modpacks keep their own versions. + Sequence (first failure wins; nothing is created before step 7): 1. Profile not in advanced mode → `WRONG_MODE`. @@ -2209,6 +2253,23 @@ Fixed hosts, no user-supplied URL. Error codes as listed in §3.5a. `/tmp/modrinth-/` under their final names; the staging folder and every temp file are removed whether the install succeeds or fails. +### 6.3c Server-type version lists (`list_mc_versions` with `serverType`, 2.13.0) + +Fixed URLs (the table in §3.6), no caller input in any URL. Never an error of its own: +every failure below makes `list_mc_versions` fall back to the unfiltered list (§3.6). + +1. One client for all six: https only, no credentials, the default port, and the hosts + `fill.papermc.io`, `api.purpurmc.org`, `meta.fabricmc.net`, `meta.quiltmc.org`, + `files.minecraftforge.net`, `maven.neoforged.net`. Every redirect hop is re-checked + against the same rule (≤ 5 hops). Observed on 2026-11-10: all six answer 200 + directly, no redirect. +2. 10 s timeout per request; the `User-Agent` `I4cTime/mineui/ + (mineui.i4c.studio)` of §6.3b (Fill refuses generic ones). +3. The body is read up to 4 MiB and refused beyond it (the largest today, NeoForge's, + is about 26 KB). The parsed list must hold at least one id; ids are kept only when + they are 1-64 characters of `[0-9A-Za-z._+-]`, and only ids that also appear in the + Mojang manifest ever reach the UI. + ### 6.4 RCON commands See §3.4: trim, strip one leading `/`, ≤ 200 chars, first token lowercased ∈ @@ -2820,8 +2881,11 @@ export type InstanceStatus = { createdAt: string | null; }; -export const listMcVersions = (includeSnapshots?: boolean) => - scoped("list_mc_versions", { includeSnapshots }); +/** 2.13.0 serverType: only the versions that server type has builds for; + * absent or "vanilla" = every Mojang version (the list falls back to that + * when the type's own list cannot be had). */ +export const listMcVersions = (includeSnapshots?: boolean, serverType?: ContainerLoader) => + scoped("list_mc_versions", { includeSnapshots, serverType }); /** 2.13.0, app-wide - the Java major a version ("LATEST" allowed) needs; * null when it cannot be resolved (offline, unknown version). */ export const requiredJavaMajor = (mcVersion: string) => @@ -3065,6 +3129,7 @@ Frontend rules: | `rcon` | RCON client (connect/auth/send/close) + allowlist enforcement | | `query` | Minecraft server-list-ping client (handshake + status packet, 3 s timeout) | | `mojang` | version manifest fetch/cache, per-version json, jar download + sha1 verify, progress callback; `required_java_major` (§3.6, 2.13.0, shared with `provision`) | +| `loader_versions` | `list_mc_versions` with `serverType` (§3.6, §6.3c, 2.13.0): the six fixed version-list URLs and their host-allowlisted client, one parser per type, the NeoForge → Minecraft version rule, the per-type 15-minute cache, the intersection with the Mojang list in Mojang order, and the fall-back to the unfiltered list | | `java` | java discovery + `-version` parsing; the managed-Java lookup and resolution order (§3.1, 2.13.0) | | `javainstall` | `install_java` (§3.1, §6.3a, 2.13.0): Adoptium API query, the host-allowlisted client, sha256-verified download, safe tar.gz/zip extraction, locate + probe, rename into place, per-major install lock, `java.install` audit | | `instance` | create/delete/status, change version in place (2.10.0), `mineui-instance.json`, eula.txt, server.properties RCON assertion (preserving user keys) | From 10cf19d8f28ceab83629e335a29fc1ab0b010c45 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 22:58:29 -0600 Subject: [PATCH 21/28] fix(core): list_mc_versions per server type (2.13.0) New loader_versions module (contract 3.6, 6.3c): list_mc_versions takes an optional serverType and restricts the Mojang list, in Mojang order, to the versions that type publishes builds for - Paper (Fill v3), Purpur, Fabric and Quilt meta, Forge promotions_slim, NeoForge maven. NeoForge versions map to Minecraft the way NeoForge's docs and itzg's install-neoforge do (A.B.n -> 1.A[.B], Y.A.B.n -> Y.A[.B]); only released builds count, since the image skips betas by default, and 1.20.1 is added for the older net.neoforged:forge artifact the image uses there. One client with a six-host https allowlist re-checked on every redirect, 10 s timeout, the I4cTime/mineui User-Agent, 4 MiB body cap. Per-type 15-minute cache on Core; a stale cache beats an error, and any failure (or an empty intersection) falls back to the unfiltered list with one stderr line, so creation is never blocked. Unknown serverType is INVALID_INPUT. The Tauri command stays a thin delegation. 18 unit tests on fixtures trimmed from today's real answers (327 total) and an ignored live test fetching all six. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- crates/mineui-core/src/lib.rs | 6 + crates/mineui-core/src/loader_versions.rs | 393 ++++++++++++++++++ .../mineui-core/src/loader_versions/tests.rs | 389 +++++++++++++++++ crates/mineui-core/src/model.rs | 2 +- .../fixtures/mojang-manifest-trimmed.json | 1 + .../tests/fixtures/versions-fabric.json | 1 + .../tests/fixtures/versions-forge.json | 1 + .../tests/fixtures/versions-neoforge.json | 1 + .../tests/fixtures/versions-paper.json | 1 + .../tests/fixtures/versions-purpur.json | 1 + .../tests/fixtures/versions-quilt.json | 1 + .../mineui-core/tests/live_loader_versions.rs | 52 +++ src-tauri/src/commands.rs | 8 +- 13 files changed, 855 insertions(+), 2 deletions(-) create mode 100644 crates/mineui-core/src/loader_versions.rs create mode 100644 crates/mineui-core/src/loader_versions/tests.rs create mode 100644 crates/mineui-core/tests/fixtures/mojang-manifest-trimmed.json create mode 100644 crates/mineui-core/tests/fixtures/versions-fabric.json create mode 100644 crates/mineui-core/tests/fixtures/versions-forge.json create mode 100644 crates/mineui-core/tests/fixtures/versions-neoforge.json create mode 100644 crates/mineui-core/tests/fixtures/versions-paper.json create mode 100644 crates/mineui-core/tests/fixtures/versions-purpur.json create mode 100644 crates/mineui-core/tests/fixtures/versions-quilt.json create mode 100644 crates/mineui-core/tests/live_loader_versions.rs diff --git a/crates/mineui-core/src/lib.rs b/crates/mineui-core/src/lib.rs index d26469d..972e7c9 100644 --- a/crates/mineui-core/src/lib.rs +++ b/crates/mineui-core/src/lib.rs @@ -22,6 +22,7 @@ pub mod java; pub mod javainstall; pub mod joininfo; pub mod lifecycle; +pub mod loader_versions; pub mod logs; pub mod machine; pub mod metrics; @@ -77,6 +78,10 @@ pub struct Core { pub logs: logs::Manager, pub(crate) events: tokio::sync::broadcast::Sender, pub(crate) mojang_cache: tokio::sync::Mutex>, + /// Each server type's Minecraft versions, cached 15 min (§3.6, 2.13.0). + pub(crate) loader_versions_cache: tokio::sync::Mutex< + std::collections::HashMap, + >, pub(crate) last_advanced_phase: std::sync::Mutex>, /// Loader/version of the attached container, cached per container id /// (§3.12 overview identity). @@ -147,6 +152,7 @@ impl Core { logs, events, mojang_cache: tokio::sync::Mutex::new(None), + loader_versions_cache: tokio::sync::Mutex::new(std::collections::HashMap::new()), last_advanced_phase: std::sync::Mutex::new(None), container_kind: std::sync::Mutex::new(None), modrinth_hashes: std::sync::Mutex::new(None), diff --git a/crates/mineui-core/src/loader_versions.rs b/crates/mineui-core/src/loader_versions.rs new file mode 100644 index 0000000..816ad9d --- /dev/null +++ b/crates/mineui-core/src/loader_versions.rs @@ -0,0 +1,393 @@ +//! Minecraft versions per server type (contract §3.6, §6.3c, 2.13.0). +//! +//! `list_mc_versions` with a `serverType` returns the Mojang list restricted +//! to the versions that type publishes builds for, so the create form never +//! offers a version the itzg image cannot install ("Version 26.1.1 does not +//! exist" from `install-purpur`). Each type's list comes from one fixed URL +//! through a client that only talks https to those six hosts, redirects +//! included. The filter never blocks creation: whenever the type's list +//! cannot be had, the unfiltered list is returned and one line is logged. + +use std::collections::{HashMap, HashSet}; +use std::future::Future; +use std::sync::LazyLock; +use std::time::{Duration, Instant}; + +use serde::Deserialize; + +use crate::error::{Error, Result}; +use crate::model::{ContainerLoader, McVersion}; + +/// §6.3c rule 1: the only hosts these lists may come from, redirects included. +pub const ALLOWED_HOSTS: &[&str] = &[ + "fill.papermc.io", + "api.purpurmc.org", + "meta.fabricmc.net", + "meta.quiltmc.org", + "files.minecraftforge.net", + "maven.neoforged.net", +]; +/// §6.3c rule 3: most bytes read from one answer. +pub const MAX_BODY_BYTES: usize = 4 * 1024 * 1024; +const TIMEOUT: Duration = Duration::from_secs(10); +const MAX_REDIRECTS: usize = 5; +/// Same idea as the Mojang manifest cache (§3.6). +const CACHE_TTL: Duration = Duration::from_secs(15 * 60); +/// The image installs NeoForge for 1.20.1 from the older `net.neoforged:forge` +/// artifact, which the `neoforge` list does not include (§3.6). +const NEOFORGE_FORGE_LIKE: &str = "1.20.1"; + +/// One type's list, cached per profile on `Core`. +pub struct TypeCache { + pub fetched_at: Instant, + pub versions: HashSet, +} + +/// `serverType` from the wire: absent → `None`; a `ContainerLoader` wire +/// name → that loader; anything else → `INVALID_INPUT`. +pub fn parse_server_type(server_type: Option<&str>) -> Result> { + let Some(raw) = server_type else { + return Ok(None); + }; + serde_json::from_value(serde_json::Value::String(raw.trim().to_string())) + .map(Some) + .map_err(|_| Error::InvalidInput(format!("unknown server type: {raw}"))) +} + +/// The fixed URL of a type's version list (§3.6 table); `None` for vanilla. +pub fn source_url(loader: ContainerLoader) -> Option<&'static str> { + match loader { + ContainerLoader::Vanilla => None, + ContainerLoader::Paper => Some("https://fill.papermc.io/v3/projects/paper"), + ContainerLoader::Purpur => Some("https://api.purpurmc.org/v2/purpur"), + ContainerLoader::Fabric => Some("https://meta.fabricmc.net/v2/versions/game"), + ContainerLoader::Quilt => Some("https://meta.quiltmc.org/v3/versions/game"), + ContainerLoader::Forge => { + Some("https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json") + } + ContainerLoader::Neoforge => { + Some("https://maven.neoforged.net/api/maven/versions/releases/net/neoforged/neoforge") + } + } +} + +/// For log lines. +fn type_name(loader: ContainerLoader) -> &'static str { + match loader { + ContainerLoader::Vanilla => "Vanilla", + ContainerLoader::Paper => "Paper", + ContainerLoader::Purpur => "Purpur", + ContainerLoader::Fabric => "Fabric", + ContainerLoader::Quilt => "Quilt", + ContainerLoader::Forge => "Forge", + ContainerLoader::Neoforge => "NeoForge", + } +} + +/* ---------- the host-allowlisted client (§6.3c rules 1-2) ---------- */ + +/// https, no credentials, default port, allowlisted host. +pub fn url_allowed(url: &reqwest::Url) -> bool { + url.scheme() == "https" + && url.username().is_empty() + && url.password().is_none() + && url.port().is_none() + && url + .host_str() + .is_some_and(|h| ALLOWED_HOSTS.iter().any(|a| a.eq_ignore_ascii_case(h))) +} + +fn build_client() -> reqwest::Client { + reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::custom(|attempt| { + if attempt.previous().len() > MAX_REDIRECTS { + return attempt.error("too many redirects"); + } + if !url_allowed(attempt.url()) { + let host = attempt.url().host_str().unwrap_or("?").to_string(); + return attempt.error(format!("redirect to a host MineUI does not trust ({host})")); + } + attempt.follow() + })) + .connect_timeout(TIMEOUT) + .timeout(TIMEOUT) + .user_agent(crate::modpacks::user_agent()) + .build() + .expect("reqwest client construction cannot fail with static config") +} + +static CLIENT: LazyLock = LazyLock::new(build_client); + +/// §6.3c rule 3: read at most `max` bytes of a body as UTF-8. +pub(crate) async fn read_capped(mut response: reqwest::Response, max: usize) -> Result { + if response + .content_length() + .is_some_and(|len| len > max as u64) + { + return Err(Error::DownloadFailed(format!( + "the answer is larger than {max} bytes" + ))); + } + let mut body: Vec = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .map_err(|e| Error::DownloadFailed(format!("could not read the answer: {e}")))? + { + if body.len() + chunk.len() > max { + return Err(Error::DownloadFailed(format!( + "the answer is larger than {max} bytes" + ))); + } + body.extend_from_slice(&chunk); + } + String::from_utf8(body) + .map_err(|_| Error::DownloadFailed("the answer is not valid UTF-8".into())) +} + +/// One GET of the type's fixed URL, parsed. `INVALID_INPUT` for vanilla +/// (it has no list), `DOWNLOAD_FAILED` for everything else that goes wrong. +pub async fn fetch_supported(loader: ContainerLoader) -> Result> { + let Some(url) = source_url(loader) else { + return Err(Error::InvalidInput("vanilla has no list of its own".into())); + }; + let url = reqwest::Url::parse(url) + .map_err(|e| Error::Internal(format!("bad version list URL: {e}")))?; + if !url_allowed(&url) { + return Err(Error::Internal(format!( + "not an allowed version list URL: {url}" + ))); + } + let response = CLIENT + .get(url) + .send() + .await + .map_err(|e| Error::DownloadFailed(format!("could not reach the list: {e}")))?; + if !response.status().is_success() { + return Err(Error::DownloadFailed(format!( + "the list answered HTTP {}", + response.status().as_u16() + ))); + } + let body = read_capped(response, MAX_BODY_BYTES).await?; + parse(loader, &body).map_err(Error::DownloadFailed) +} + +/* ---------- parsers (one per type, §3.6 table) ---------- */ + +#[derive(Deserialize)] +struct PurpurProject { + versions: Vec, +} + +#[derive(Deserialize)] +struct PaperProject { + versions: HashMap>, +} + +#[derive(Deserialize)] +struct MetaGameVersion { + version: String, +} + +#[derive(Deserialize)] +struct ForgePromotions { + promos: HashMap, +} + +#[derive(Deserialize)] +struct MavenVersions { + versions: Vec, +} + +/// §6.3c rule 3: what an id may look like before it is compared at all. +fn plausible_id(id: &str) -> bool { + (1..=64).contains(&id.len()) + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'-')) +} + +/// The Minecraft version a NeoForge version is built for (§3.6), or `None` +/// for a pre-release (`-beta`, `-alpha…`, `+…`) or an entry of another shape. +/// `A.B.n` → `1.A.B` (`1.A` when B is 0); `Y.A.B.n` → `Y.A.B` (`Y.A` when B +/// is 0) - NeoForge's versioning docs and the image's own resolver agree. +pub fn neoforge_mc_version(version: &str) -> Option { + if version.contains(['-', '+']) { + return None; + } + let parts: Vec<&str> = version.split('.').collect(); + if !parts + .iter() + .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) + { + return None; + } + match parts.as_slice() { + [minor, patch, _build] => Some(if *patch == "0" { + format!("1.{minor}") + } else { + format!("1.{minor}.{patch}") + }), + [year, minor, patch, _build] => Some(if *patch == "0" { + format!("{year}.{minor}") + } else { + format!("{year}.{minor}.{patch}") + }), + _ => None, + } +} + +fn json(body: &str) -> std::result::Result { + serde_json::from_str(body).map_err(|e| format!("an answer MineUI cannot read: {e}")) +} + +/// The Minecraft versions a type's answer names. Err when the answer cannot +/// be read or names none. +pub fn parse(loader: ContainerLoader, body: &str) -> std::result::Result, String> { + let ids: Vec = match loader { + ContainerLoader::Vanilla => return Err("vanilla has no list of its own".into()), + ContainerLoader::Purpur => json::(body)?.versions, + ContainerLoader::Paper => json::(body)? + .versions + .into_values() + .flatten() + .collect(), + ContainerLoader::Fabric | ContainerLoader::Quilt => json::>(body)? + .into_iter() + .map(|v| v.version) + .collect(), + ContainerLoader::Forge => json::(body)? + .promos + .into_keys() + .filter_map(|key| { + key.strip_suffix("-latest") + .or_else(|| key.strip_suffix("-recommended")) + .map(str::to_string) + }) + .collect(), + ContainerLoader::Neoforge => { + let mut ids: Vec = json::(body)? + .versions + .iter() + .filter_map(|v| neoforge_mc_version(v)) + .collect(); + if !ids.is_empty() { + ids.push(NEOFORGE_FORGE_LIKE.to_string()); + } + ids + } + }; + let set: HashSet = ids.into_iter().filter(|id| plausible_id(id)).collect(); + if set.is_empty() { + return Err("the list names no Minecraft versions".into()); + } + Ok(set) +} + +/// The Mojang list restricted to `supported`, in Mojang order. +pub fn restrict(all: &[McVersion], supported: &HashSet) -> Vec { + all.iter() + .filter(|v| supported.contains(&v.id)) + .cloned() + .collect() +} + +/* ---------- list_mc_versions with serverType (§3.6) ---------- */ + +/// `list_mc_versions` (§3.6): without `serverType` (or vanilla) the Mojang +/// list as before; with one, that list restricted to the type's builds, or +/// the unfiltered list when the type's list cannot be had. +pub async fn list_versions( + core: &crate::Core, + include_snapshots: bool, + server_type: Option<&str>, +) -> Result> { + let loader = parse_server_type(server_type)?; + list_versions_with(core, include_snapshots, loader, fetch_supported).await +} + +/// `list_versions` with the fetch injected (tests). +pub(crate) async fn list_versions_with( + core: &crate::Core, + include_snapshots: bool, + loader: Option, + fetch: F, +) -> Result> +where + F: FnOnce(ContainerLoader) -> Fut, + Fut: Future>>, +{ + let all = crate::mojang::list_versions(core, include_snapshots).await?; + let Some(loader) = loader.filter(|l| *l != ContainerLoader::Vanilla) else { + return Ok(all); + }; + let Some(supported) = supported_versions(core, loader, fetch).await else { + return Ok(all); + }; + let restricted = restrict(&all, &supported); + if restricted.is_empty() { + eprintln!( + "mineui: the {} versions list shares no version with Mojang's; showing every Minecraft version", + type_name(loader) + ); + return Ok(all); + } + Ok(restricted) +} + +/// The type's list: a fresh cache, else a fetch, else a cache of any age, +/// else `None` (logged). +async fn supported_versions( + core: &crate::Core, + loader: ContainerLoader, + fetch: F, +) -> Option> +where + F: FnOnce(ContainerLoader) -> Fut, + Fut: Future>>, +{ + { + let cache = core.loader_versions_cache.lock().await; + if let Some(cached) = cache.get(&loader) { + if cached.fetched_at.elapsed() < CACHE_TTL { + return Some(cached.versions.clone()); + } + } + } + // The lock is not held across the request: another type's list (or the + // same one) can be read meanwhile. + let fetched = fetch(loader).await; + let mut cache = core.loader_versions_cache.lock().await; + match fetched { + Ok(versions) => { + cache.insert( + loader, + TypeCache { + fetched_at: Instant::now(), + versions: versions.clone(), + }, + ); + Some(versions) + } + Err(e) => match cache.get(&loader) { + Some(stale) => { + eprintln!( + "mineui: could not refresh the {} versions list ({e}); using the one from earlier", + type_name(loader) + ); + Some(stale.versions.clone()) + } + None => { + eprintln!( + "mineui: could not get the {} versions list ({e}); showing every Minecraft version", + type_name(loader) + ); + None + } + }, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/mineui-core/src/loader_versions/tests.rs b/crates/mineui-core/src/loader_versions/tests.rs new file mode 100644 index 0000000..5902054 --- /dev/null +++ b/crates/mineui-core/src/loader_versions/tests.rs @@ -0,0 +1,389 @@ +//! Fixtures are trimmed from the real answers of 2026-11-10. + +use super::*; +use crate::mojang::{ManifestCache, VersionManifest}; + +const PURPUR: &str = include_str!("../../tests/fixtures/versions-purpur.json"); +const PAPER: &str = include_str!("../../tests/fixtures/versions-paper.json"); +const FABRIC: &str = include_str!("../../tests/fixtures/versions-fabric.json"); +const QUILT: &str = include_str!("../../tests/fixtures/versions-quilt.json"); +const FORGE: &str = include_str!("../../tests/fixtures/versions-forge.json"); +const NEOFORGE: &str = include_str!("../../tests/fixtures/versions-neoforge.json"); +const MANIFEST: &str = include_str!("../../tests/fixtures/mojang-manifest-trimmed.json"); + +fn set(ids: &[&str]) -> HashSet { + ids.iter().map(|s| s.to_string()).collect() +} + +fn sorted(set: &HashSet) -> Vec { + let mut v: Vec = set.iter().cloned().collect(); + v.sort(); + v +} + +/// A core whose Mojang manifest cache is warm with the trimmed manifest, so +/// no request ever reaches Mojang. +async fn core_with_manifest() -> (tempfile::TempDir, std::sync::Arc) { + let tmp = tempfile::tempdir().unwrap(); + let core = crate::Core::init(tmp.path().join("config"), tmp.path().join("data")) + .await + .unwrap(); + let manifest: VersionManifest = serde_json::from_str(MANIFEST).unwrap(); + *core.mojang_cache.lock().await = Some(ManifestCache { + fetched_at: Instant::now(), + manifest, + }); + (tmp, core) +} + +fn ids(versions: &[McVersion]) -> Vec<&str> { + versions.iter().map(|v| v.id.as_str()).collect() +} + +/* ---------- parsers ---------- */ + +#[test] +fn purpur_lists_its_versions() { + let got = parse(ContainerLoader::Purpur, PURPUR).unwrap(); + assert!(got.contains("26.3") && got.contains("26.2") && got.contains("26.1.2")); + assert!(got.contains("1.14.1") && got.contains("1.21.11")); + // The reported bug: no Purpur build for 26.1.1 or 26.1. + assert!(!got.contains("26.1.1")); + assert!(!got.contains("26.1")); +} + +#[test] +fn paper_flattens_the_families() { + let got = parse(ContainerLoader::Paper, PAPER).unwrap(); + for id in [ + "26.3", + "26.3-rc-3", + "26.1.1", + "26.1.2", + "1.21.11-pre5", + "1.7.10", + ] { + assert!(got.contains(id), "{id}"); + } + // A family name is not a version unless it is also listed under itself. + assert!(!got.contains("26.1")); + assert!(!got.contains("1.21.2")); +} + +#[test] +fn fabric_and_quilt_take_every_game_version() { + let fabric = parse(ContainerLoader::Fabric, FABRIC).unwrap(); + for id in ["26.4-snapshot-8", "26.3", "26.3-rc-3", "26.1", "1.14"] { + assert!(fabric.contains(id), "{id}"); + } + let quilt = parse(ContainerLoader::Quilt, QUILT).unwrap(); + assert!(quilt.contains("26.3") && quilt.contains("1.21.1") && quilt.contains("1.14.4")); + assert!(!quilt.contains("26.1.1")); +} + +#[test] +fn forge_reads_the_promotion_keys() { + let got = parse(ContainerLoader::Forge, FORGE).unwrap(); + assert_eq!( + sorted(&got), + vec!["1.20.1", "1.21.1", "1.21.11", "1.7.10", "26.1", "26.1.1", "26.1.2", "26.2", "26.3"] + ); +} + +#[test] +fn neoforge_mapping_follows_both_schemes() { + let cases = [ + // Before 26: A.B.n -> 1.A.B, 1.A when B is 0. + ("21.1.209", Some("1.21.1")), + ("21.0.167", Some("1.21")), + ("20.4.251", Some("1.20.4")), + ("21.11.42", Some("1.21.11")), + // 26 and later: Y.A.B.n -> Y.A.B, Y.A when B is 0. + ("26.1.2.40", Some("26.1.2")), + ("26.3.0.102", Some("26.3")), + ("26.1.0.5", Some("26.1")), + // Pre-releases are not installed by the image's default. + ("26.1.0.19-beta", None), + ("20.2.3-beta", None), + ("26.1.0.0-alpha.1+snapshot-1", None), + ("0.25w14craftmine.3-beta", None), + // Other shapes. + ("21.1", None), + ("21.1.x", None), + ("26.1.2.3.4", None), + ("", None), + ]; + for (neo, mc) in cases { + assert_eq!(neoforge_mc_version(neo).as_deref(), mc, "{neo}"); + } +} + +#[test] +fn neoforge_keeps_released_lines_and_adds_1_20_1() { + let got = parse(ContainerLoader::Neoforge, NEOFORGE).unwrap(); + assert_eq!( + sorted(&got), + vec!["1.20.1", "1.20.2", "1.20.4", "1.21", "1.21.1", "1.21.11", "26.2", "26.3"] + ); + // 1.20.3: only betas (20.3.8-beta) in the fixture, as in the real list. + assert!(!got.contains("1.20.3")); + // Only betas in the fixture for these: not creatable with the default. + assert!(!got.contains("26.1") && !got.contains("26.1.1") && !got.contains("26.1.2")); +} + +#[test] +fn unreadable_or_empty_answers_are_errors() { + assert!(parse(ContainerLoader::Purpur, "").is_err()); + assert!(parse(ContainerLoader::Purpur, r#"{"versions":[]}"#).is_err()); + assert!(parse(ContainerLoader::Paper, r#"{"versions":["26.3"]}"#).is_err()); + assert!(parse(ContainerLoader::Fabric, r#"{"version":"26.3"}"#).is_err()); + assert!(parse(ContainerLoader::Forge, r#"{"promos":{"homepage":"x"}}"#).is_err()); + // Only pre-releases: nothing to offer, and no 1.20.1 on its own. + assert!(parse( + ContainerLoader::Neoforge, + r#"{"versions":["26.3.0.1-beta"]}"# + ) + .is_err()); + assert!(parse(ContainerLoader::Vanilla, PURPUR).is_err()); + // Implausible ids are dropped before anything is compared. + let got = parse( + ContainerLoader::Purpur, + r#"{"versions":["26.3","a b",""]}"#, + ) + .unwrap(); + assert_eq!(sorted(&got), vec!["26.3"]); +} + +#[test] +fn server_type_wire_names() { + assert_eq!(parse_server_type(None).unwrap(), None); + assert_eq!( + parse_server_type(Some("purpur")).unwrap(), + Some(ContainerLoader::Purpur) + ); + assert_eq!( + parse_server_type(Some("neoforge")).unwrap(), + Some(ContainerLoader::Neoforge) + ); + assert_eq!( + parse_server_type(Some("vanilla")).unwrap(), + Some(ContainerLoader::Vanilla) + ); + for bad in ["spigot", "PURPUR", "", "modrinth"] { + assert!( + matches!(parse_server_type(Some(bad)), Err(Error::InvalidInput(_))), + "{bad}" + ); + } +} + +#[test] +fn every_source_is_on_the_allowlist() { + for loader in [ + ContainerLoader::Paper, + ContainerLoader::Purpur, + ContainerLoader::Fabric, + ContainerLoader::Quilt, + ContainerLoader::Forge, + ContainerLoader::Neoforge, + ] { + let url = reqwest::Url::parse(source_url(loader).unwrap()).unwrap(); + assert!(url_allowed(&url), "{url}"); + } + assert_eq!(source_url(ContainerLoader::Vanilla), None); + for bad in [ + "http://api.purpurmc.org/v2/purpur", + "https://api.purpurmc.org:8443/v2/purpur", + "https://user@api.purpurmc.org/v2/purpur", + "https://api.purpurmc.org.evil.example/v2/purpur", + "https://127.0.0.1/v2/purpur", + ] { + assert!(!url_allowed(&reqwest::Url::parse(bad).unwrap()), "{bad}"); + } +} + +/* ---------- the intersection and the fall-backs ---------- */ + +#[test] +fn restrict_keeps_mojang_order_and_flags() { + let manifest: VersionManifest = serde_json::from_str(MANIFEST).unwrap(); + let all = crate::mojang::manifest_to_versions(&manifest, true); + let got = restrict( + &all, + &set(&["1.20.1", "26.3", "26.4-snapshot-8", "26.1.2", "9.9"]), + ); + assert_eq!( + ids(&got), + vec!["26.4-snapshot-8", "26.3", "26.1.2", "1.20.1"] + ); + assert!(got[0].latest && got[0].version_type == "snapshot"); + assert!(got[1].latest && got[1].version_type == "release"); + assert!(!got[2].latest); +} + +#[tokio::test] +async fn purpur_list_drops_versions_without_a_build() { + let (_tmp, core) = core_with_manifest().await; + let got = list_versions_with(&core, false, Some(ContainerLoader::Purpur), |_| async { + Ok(parse(ContainerLoader::Purpur, PURPUR).unwrap()) + }) + .await + .unwrap(); + assert_eq!( + ids(&got), + vec!["26.3", "26.2", "26.1.2", "1.21.11", "1.21.1", "1.21", "1.20.4", "1.20.2", "1.20.1"] + ); + // Mojang's latest release is still marked, so the UI can offer "Latest". + assert!(got[0].latest); +} + +#[tokio::test] +async fn a_type_trailing_mojang_has_no_latest_entry() { + let (_tmp, core) = core_with_manifest().await; + let got = list_versions_with(&core, false, Some(ContainerLoader::Neoforge), |_| async { + Ok(set(&["26.2", "1.21.1"])) + }) + .await + .unwrap(); + assert_eq!(ids(&got), vec!["26.2", "1.21.1"]); + assert!(got.iter().all(|v| !v.latest)); +} + +#[tokio::test] +async fn snapshots_follow_include_snapshots() { + let (_tmp, core) = core_with_manifest().await; + let fabric = || async { Ok(parse(ContainerLoader::Fabric, FABRIC).unwrap()) }; + let with = list_versions_with(&core, true, Some(ContainerLoader::Fabric), |_| fabric()) + .await + .unwrap(); + assert_eq!(&ids(&with)[..3], &["26.4-snapshot-8", "26.3", "26.3-rc-3"]); + let without = list_versions_with(&core, false, Some(ContainerLoader::Fabric), |_| async { + panic!("the cached Fabric list must be used") + }) + .await + .unwrap(); + assert!(without.iter().all(|v| v.version_type == "release")); + assert_eq!(ids(&without)[0], "26.3"); +} + +#[tokio::test] +async fn vanilla_and_absent_are_unchanged() { + let (_tmp, core) = core_with_manifest().await; + let all = crate::mojang::list_versions(&core, false).await.unwrap(); + for loader in [None, Some(ContainerLoader::Vanilla)] { + let got = list_versions_with(&core, false, loader, |_| async { + panic!("vanilla has no list to fetch") + }) + .await + .unwrap(); + assert_eq!(ids(&got), ids(&all)); + } + // The public entry point with no serverType makes no request either. + let got = list_versions(&core, false, None).await.unwrap(); + assert_eq!(ids(&got), ids(&all)); + assert!(matches!( + list_versions(&core, false, Some("bukkit")).await, + Err(Error::InvalidInput(_)) + )); +} + +#[tokio::test] +async fn a_failed_list_falls_back_to_every_version() { + let (_tmp, core) = core_with_manifest().await; + let all = crate::mojang::list_versions(&core, false).await.unwrap(); + let got = list_versions_with(&core, false, Some(ContainerLoader::Purpur), |_| async { + Err(Error::DownloadFailed("offline".into())) + }) + .await + .unwrap(); + assert_eq!(ids(&got), ids(&all)); + // Nothing was cached by the failure. + assert!(core.loader_versions_cache.lock().await.is_empty()); +} + +#[tokio::test] +async fn a_list_sharing_nothing_falls_back_to_every_version() { + let (_tmp, core) = core_with_manifest().await; + let all = crate::mojang::list_versions(&core, false).await.unwrap(); + let got = list_versions_with(&core, false, Some(ContainerLoader::Paper), |_| async { + Ok(set(&["99.1"])) + }) + .await + .unwrap(); + assert_eq!(ids(&got), ids(&all)); +} + +#[tokio::test] +async fn a_stale_cache_beats_an_error() { + let (_tmp, core) = core_with_manifest().await; + core.loader_versions_cache.lock().await.insert( + ContainerLoader::Purpur, + TypeCache { + fetched_at: Instant::now() - CACHE_TTL - Duration::from_secs(1), + versions: set(&["26.2", "1.21.1"]), + }, + ); + let got = list_versions_with(&core, false, Some(ContainerLoader::Purpur), |_| async { + Err(Error::DownloadFailed("offline".into())) + }) + .await + .unwrap(); + assert_eq!(ids(&got), vec!["26.2", "1.21.1"]); + + // A successful refresh replaces it. + let got = list_versions_with(&core, false, Some(ContainerLoader::Purpur), |_| async { + Ok(set(&["26.3"])) + }) + .await + .unwrap(); + assert_eq!(ids(&got), vec!["26.3"]); +} + +/* ---------- the body cap ---------- */ + +/// Answers every request with `body`, announcing its length or not. +async fn body_server(body: Vec, announce_length: bool) -> std::net::SocketAddr { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = listener.accept().await else { + return; + }; + let mut buf = vec![0u8; 2048]; + let _ = sock.read(&mut buf).await; + let head = if announce_length { + format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ) + } else { + "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n".to_string() + }; + let _ = sock.write_all(head.as_bytes()).await; + let _ = sock.write_all(&body).await; + let _ = sock.flush().await; + } + }); + addr +} + +#[tokio::test] +async fn bodies_over_the_cap_are_refused() { + let client = reqwest::Client::new(); + for announce in [true, false] { + let addr = body_server(vec![b'x'; 2048], announce).await; + let response = client.get(format!("http://{addr}/")).send().await.unwrap(); + assert!( + matches!( + read_capped(response, 1024).await, + Err(Error::DownloadFailed(_)) + ), + "announce={announce}" + ); + } + let addr = body_server(PURPUR.as_bytes().to_vec(), false).await; + let response = client.get(format!("http://{addr}/")).send().await.unwrap(); + assert_eq!(read_capped(response, MAX_BODY_BYTES).await.unwrap(), PURPUR); +} diff --git a/crates/mineui-core/src/model.rs b/crates/mineui-core/src/model.rs index 58b3e43..0cb3594 100644 --- a/crates/mineui-core/src/model.rs +++ b/crates/mineui-core/src/model.rs @@ -691,7 +691,7 @@ pub struct ServerOverview { /* ---------- §3.13 container creation ---------- */ -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ContainerLoader { Vanilla, diff --git a/crates/mineui-core/tests/fixtures/mojang-manifest-trimmed.json b/crates/mineui-core/tests/fixtures/mojang-manifest-trimmed.json new file mode 100644 index 0000000..a060186 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/mojang-manifest-trimmed.json @@ -0,0 +1 @@ +{"latest":{"release":"26.3","snapshot":"26.4-snapshot-8"},"versions":[{"id":"26.4-snapshot-8","type":"snapshot","url":"https://piston-meta.mojang.com/v1/packages/46f6dc6a5cefe084af0ce2ecf7f433c1222d4dd1/26.4-snapshot-8.json","time":"2026-11-10T14:28:50+00:00","releaseTime":"2026-11-10T14:20:05+00:00"},{"id":"26.3","type":"release","url":"https://piston-meta.mojang.com/v1/packages/9f67e10ed013deeaad20ac3c800652765d493408/26.3.json","time":"2026-11-10T06:58:51+00:00","releaseTime":"2026-09-15T11:23:02+00:00"},{"id":"26.3-rc-3","type":"snapshot","url":"https://piston-meta.mojang.com/v1/packages/d9566fe12dbd75ab34529164b230759c471ea482/26.3-rc-3.json","time":"2026-11-10T06:58:51+00:00","releaseTime":"2026-09-14T12:58:38+00:00"},{"id":"26.2","type":"release","url":"https://piston-meta.mojang.com/v1/packages/f28ad96ed5d65e2438da836144a3de15bb9cafe7/26.2.json","time":"2026-11-10T06:57:30+00:00","releaseTime":"2026-06-16T12:03:33+00:00"},{"id":"26.1.2","type":"release","url":"https://piston-meta.mojang.com/v1/packages/0bbfbdb8272531060afbba5c671fe4ed3dd6f72f/26.1.2.json","time":"2026-11-10T06:56:10+00:00","releaseTime":"2026-04-09T10:12:23+00:00"},{"id":"26.1.1","type":"release","url":"https://piston-meta.mojang.com/v1/packages/63c56ca0cfc405b1679656db51c9006c43e59b1c/26.1.1.json","time":"2026-11-10T06:56:10+00:00","releaseTime":"2026-04-01T09:06:36+00:00"},{"id":"26.1","type":"release","url":"https://piston-meta.mojang.com/v1/packages/389f92510868468e073b7a12f19e70a7bf8684cd/26.1.json","time":"2026-11-10T06:56:10+00:00","releaseTime":"2026-03-24T12:11:04+00:00"},{"id":"1.21.11","type":"release","url":"https://piston-meta.mojang.com/v1/packages/812ee7fdfdf648bb872f7a1dca33718de4e786b4/1.21.11.json","time":"2026-11-10T06:55:03+00:00","releaseTime":"2025-12-09T12:23:30+00:00"},{"id":"1.21.1","type":"release","url":"https://piston-meta.mojang.com/v1/packages/9aa86ea608c3ec777dcdc09e6c5a06c85b53599e/1.21.1.json","time":"2026-11-10T06:47:48+00:00","releaseTime":"2024-08-08T12:24:45+00:00"},{"id":"1.21","type":"release","url":"https://piston-meta.mojang.com/v1/packages/4fc7dfb1d245736485d1f0e9c7a41c0273ad8638/1.21.json","time":"2026-11-10T06:47:48+00:00","releaseTime":"2024-06-13T08:24:03+00:00"},{"id":"1.20.4","type":"release","url":"https://piston-meta.mojang.com/v1/packages/bd984a42a9b403c620eae6cd77a1095850ca4479/1.20.4.json","time":"2026-11-10T06:45:14+00:00","releaseTime":"2023-12-07T12:56:20+00:00"},{"id":"1.20.2","type":"release","url":"https://piston-meta.mojang.com/v1/packages/2b1c2be7cf1d1137b77716962b71e147b614c50c/1.20.2.json","time":"2026-11-10T07:01:57+00:00","releaseTime":"2023-09-20T09:02:57+00:00"},{"id":"1.20.1","type":"release","url":"https://piston-meta.mojang.com/v1/packages/3ecf2cab995685d345a257326ba72192b7911250/1.20.1.json","time":"2026-11-10T07:00:30+00:00","releaseTime":"2023-06-12T13:25:51+00:00"},{"id":"1.14","type":"release","url":"https://piston-meta.mojang.com/v1/packages/0fd01dd81eaa451d3130b1cf025a10f129585b10/1.14.json","time":"2023-06-07T11:25:16+00:00","releaseTime":"2019-04-23T14:52:44+00:00"},{"id":"1.7.10","type":"release","url":"https://piston-meta.mojang.com/v1/packages/ed5d8789ed29872ea2ef1c348302b0c55e3f3468/1.7.10.json","time":"2021-12-15T15:44:05+00:00","releaseTime":"2014-05-14T17:29:23+00:00"}]} diff --git a/crates/mineui-core/tests/fixtures/versions-fabric.json b/crates/mineui-core/tests/fixtures/versions-fabric.json new file mode 100644 index 0000000..d48f366 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/versions-fabric.json @@ -0,0 +1 @@ +[{"version":"26.4-snapshot-8","stable":false},{"version":"26.4-snapshot-7","stable":false},{"version":"26.4-snapshot-6","stable":false},{"version":"26.3","stable":true},{"version":"26.3-rc-3","stable":false},{"version":"26.2","stable":true},{"version":"26.1.2","stable":true},{"version":"26.1.1","stable":true},{"version":"26.1","stable":true},{"version":"1.21.11","stable":true},{"version":"1.21.1","stable":true},{"version":"1.14","stable":true}] diff --git a/crates/mineui-core/tests/fixtures/versions-forge.json b/crates/mineui-core/tests/fixtures/versions-forge.json new file mode 100644 index 0000000..3bc30a4 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/versions-forge.json @@ -0,0 +1 @@ +{"homepage":"https://files.minecraftforge.net/net/minecraftforge/forge/","promos":{"1.7.10-latest":"10.13.4.1614","1.7.10-recommended":"10.13.4.1614","1.20.1-recommended":"47.4.28","1.20.1-latest":"47.4.29","1.21.1-latest":"52.1.21","1.21.1-recommended":"52.1.20","1.21.11-latest":"61.2.5","1.21.11-recommended":"61.2.4","26.1-latest":"62.0.9","26.1.1-latest":"63.0.2","26.1.2-latest":"64.1.6","26.1.2-recommended":"64.1.5","26.2-latest":"65.1.6","26.2-recommended":"65.1.5","26.3-latest":"66.1.5","26.3-recommended":"66.1.5"}} diff --git a/crates/mineui-core/tests/fixtures/versions-neoforge.json b/crates/mineui-core/tests/fixtures/versions-neoforge.json new file mode 100644 index 0000000..4285744 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/versions-neoforge.json @@ -0,0 +1 @@ +{"isSnapshot":false,"versions":["0.25w14craftmine.3-beta","20.2.3-beta","20.2.88","20.3.8-beta","20.4.251","21.0.167","21.1.209","21.11.42","26.1.0.0-alpha.1+snapshot-1","26.1.0.19-beta","26.1.1.15-beta","26.1.2.0-beta","26.2.0.58","26.3.0.75-beta","26.3.0.102"]} diff --git a/crates/mineui-core/tests/fixtures/versions-paper.json b/crates/mineui-core/tests/fixtures/versions-paper.json new file mode 100644 index 0000000..4807934 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/versions-paper.json @@ -0,0 +1 @@ +{"project":{"id":"paper","name":"Paper"},"versions":{"26.3":["26.3","26.3-rc-3"],"26.2":["26.2","26.2-rc-2"],"26.1":["26.1.2","26.1.1"],"1.21":["1.21.11","1.21.11-rc3","1.21.11-rc2","1.21.11-rc1","1.21.11-pre5","1.21.11-pre4","1.21.11-pre3","1.21.10","1.21.9","1.21.9-rc1","1.21.9-pre4","1.21.9-pre3","1.21.9-pre2","1.21.8","1.21.7","1.21.6","1.21.5","1.21.4","1.21.3","1.21.1","1.21"],"1.20":["1.20.6","1.20.5","1.20.4","1.20.2","1.20.1","1.20"],"1.19":["1.19.4","1.19.3","1.19.2","1.19.1","1.19"],"1.18":["1.18.2","1.18.1","1.18"],"1.17":["1.17.1","1.17"],"1.16":["1.16.5","1.16.4","1.16.3","1.16.2","1.16.1"],"1.15":["1.15.2","1.15.1","1.15"],"1.14":["1.14.4","1.14.3","1.14.2","1.14.1","1.14"],"1.13":["1.13.2","1.13.1","1.13","1.13-pre7"],"1.12":["1.12.2","1.12.1","1.12"],"1.11":["1.11.2"],"1.10":["1.10.2"],"1.9":["1.9.4"],"1.8":["1.8.8"],"1.7":["1.7.10"]}} diff --git a/crates/mineui-core/tests/fixtures/versions-purpur.json b/crates/mineui-core/tests/fixtures/versions-purpur.json new file mode 100644 index 0000000..a537007 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/versions-purpur.json @@ -0,0 +1 @@ +{"project":"purpur","metadata":{"current":"26.3"},"versions":["1.14.1","1.14.2","1.14.3","1.14.4","1.15","1.15.1","1.15.2","1.16.1","1.16.2","1.16.3","1.16.4","1.16.5","1.17","1.17.1","1.18","1.18.1","1.18.2","1.19","1.19.1","1.19.2","1.19.3","1.19.4","1.20","1.20.1","1.20.2","1.20.4","1.20.6","1.21","1.21.1","1.21.3","1.21.4","1.21.5","1.21.6","1.21.7","1.21.8","1.21.9","1.21.10","1.21.11","26.1.2","26.2","26.3"]} diff --git a/crates/mineui-core/tests/fixtures/versions-quilt.json b/crates/mineui-core/tests/fixtures/versions-quilt.json new file mode 100644 index 0000000..5ab2e99 --- /dev/null +++ b/crates/mineui-core/tests/fixtures/versions-quilt.json @@ -0,0 +1 @@ +[{"version":"26.4-snapshot-7","stable":false},{"version":"26.4-snapshot-6","stable":false},{"version":"26.3","stable":true},{"version":"26.2","stable":true},{"version":"26.1.2","stable":true},{"version":"1.21.1","stable":true},{"version":"1.14.4","stable":true}] diff --git a/crates/mineui-core/tests/live_loader_versions.rs b/crates/mineui-core/tests/live_loader_versions.rs new file mode 100644 index 0000000..6a33a5d --- /dev/null +++ b/crates/mineui-core/tests/live_loader_versions.rs @@ -0,0 +1,52 @@ +//! Live check of the six server-type version lists (contract §3.6, §6.3c). +//! Needs the network: `cargo test -p mineui-core --test live_loader_versions -- --ignored`. + +use std::collections::HashSet; + +use mineui_core::loader_versions::fetch_supported; +use mineui_core::model::ContainerLoader; + +#[tokio::test] +#[ignore] +async fn live_every_type_list_overlaps_mojang() { + let tmp = tempfile::tempdir().unwrap(); + let core = mineui_core::Core::init(tmp.path().join("config"), tmp.path().join("data")) + .await + .unwrap(); + let releases: HashSet = mineui_core::mojang::list_versions(&core, false) + .await + .expect("Mojang manifest") + .into_iter() + .map(|v| v.id) + .collect(); + for loader in [ + ContainerLoader::Paper, + ContainerLoader::Purpur, + ContainerLoader::Fabric, + ContainerLoader::Quilt, + ContainerLoader::Forge, + ContainerLoader::Neoforge, + ] { + let list = fetch_supported(loader) + .await + .unwrap_or_else(|e| panic!("{loader:?}: {e}")); + assert!(!list.is_empty(), "{loader:?}: empty"); + let shared = list.iter().filter(|id| releases.contains(*id)).count(); + assert!( + shared > 0, + "{loader:?}: no version in common with Mojang's releases" + ); + + // The same list through the command's entry point, by wire name. + let wire = serde_json::to_value(loader).unwrap(); + let filtered = mineui_core::loader_versions::list_versions(&core, false, wire.as_str()) + .await + .unwrap(); + assert!(filtered.iter().all(|v| list.contains(&v.id)), "{loader:?}"); + let newest: Vec<&str> = filtered.iter().take(3).map(|v| v.id.as_str()).collect(); + println!( + "{loader:?}: {} ids listed, {shared} Mojang releases, newest {newest:?}", + list.len() + ); + } +} diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index e13ef72..6b9911b 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -284,9 +284,15 @@ pub async fn list_mc_versions( hub: HubState<'_>, server_id: Option, include_snapshots: Option, + server_type: Option, ) -> CmdResult> { let core = core_for(&hub, server_id).await?; - mineui_core::mojang::list_versions(&core, include_snapshots.unwrap_or(false)).await + mineui_core::loader_versions::list_versions( + &core, + include_snapshots.unwrap_or(false), + server_type.as_deref(), + ) + .await } #[tauri::command] From aa5478c6712e39f183d68e0f570e19dad90f6f45 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 22:58:29 -0600 Subject: [PATCH 22/28] fix(ui): offer only Minecraft versions the server type can run The container create form reloads the version list for the chosen server type (a late answer for an earlier type is ignored), resets a picked version the new type lacks, and offers "Latest release" only when the type has a build for Mojang's newest release; otherwise it picks the type's newest version and says why under the picker. Start here's no-mods Fabric path asks for Fabric's list and sends LATEST only when Fabric has the newest release. If a list cannot be had, the form and Start here behave as before. Modpacks keep their own versions. listMcVersions gains serverType, matching contract section 7. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- app/components/CreateContainerFlow.tsx | 66 ++++++++++++++++++++++++-- app/components/StartHere.tsx | 6 ++- app/lib/ipc.ts | 7 ++- 3 files changed, 72 insertions(+), 7 deletions(-) diff --git a/app/components/CreateContainerFlow.tsx b/app/components/CreateContainerFlow.tsx index 2d7414e..8d9e8d9 100644 --- a/app/components/CreateContainerFlow.tsx +++ b/app/components/CreateContainerFlow.tsx @@ -95,6 +95,23 @@ const LOADERS: { id: ContainerLoader; label: string; term: GlossaryTerm; hint: s { id: "neoforge", label: "NeoForge", term: "NeoForge", hint: "Forge's successor, for 1.20.2 and newer." }, ]; +/** Whether a server type's version list has Mojang's newest release in it. + * An empty list means "not known", which keeps "Latest release". */ +const hasNewestRelease = (list: McVersion[]) => + list.length === 0 || list.some((item) => item.latest && item.type === "release"); + +/** What to create a server type with when nobody picks: LATEST when the type + * has a build for Mojang's newest release, else the newest version it has. + * Falls back to LATEST when the list cannot be had (as before 2.13.0). */ +export const newestVersionFor = async (loader: ContainerLoader): Promise => { + try { + const list = await listMcVersions(undefined, loader); + return hasNewestRelease(list) ? LATEST : list[0].id; + } catch { + return LATEST; + } +}; + /** "Fabric survival" → "mc-fabric-survival" (container-name grammar). */ export const containerNameFor = (serverName: string) => { const slug = serverName @@ -128,6 +145,12 @@ export default function CreateContainerFlow({ const [runtimeChecking, setRuntimeChecking] = useState(false); const [loader, setLoader] = useState("vanilla"); const [versions, setVersions] = useState([]); + // The versions the chosen server type has builds for, tagged with that type + // so a list that arrives late for another type is never used. + const [typeVersions, setTypeVersions] = useState<{ + loader: ContainerLoader; + list: McVersion[]; + } | null>(null); const [version, setVersion] = useState(LATEST); const [containerName, setContainerName] = useState( settings.advanced.containerName !== DEFAULT_CONTAINER_NAME @@ -153,6 +176,31 @@ export default function CreateContainerFlow({ .catch(() => setVersions([])); }, []); + useEffect(() => { + if (kind !== "type") return; + let current = true; + listMcVersions(undefined, loader) + .then((list) => { + if (!current) return; + setTypeVersions({ loader, list }); + // Keep the pick to a version this type can run. + const latestOk = hasNewestRelease(list); + setVersion((picked) => { + if (list.length === 0) return picked; + if (picked === LATEST) return latestOk ? LATEST : list[0].id; + if (list.some((item) => item.id === picked)) return picked; + return latestOk ? LATEST : list[0].id; + }); + }) + .catch(() => { + // Not known: the full list and "Latest release", as before. + if (current) setTypeVersions(null); + }); + return () => { + current = false; + }; + }, [kind, loader]); + const checkRuntime = useCallback(() => { setRuntimeChecking(true); detectRuntimes() @@ -198,10 +246,21 @@ export default function CreateContainerFlow({ modpack?.source === "modrinth" || modpack?.source === "curseforge-zip" ? modpack.gameVersions : null; - const versionIds = packVersions ?? versions.map((item) => item.id); + const typeList = + kind === "type" && typeVersions?.loader === loader && typeVersions.list.length > 0 + ? typeVersions.list + : null; + const latestOffered = typeList === null || hasNewestRelease(typeList); + const versionIds = packVersions ?? (typeList ?? versions).map((item) => item.id); + const loaderMeta = LOADERS.find((item) => item.id === loader); + const newestRelease = versions.find((item) => item.latest && item.type === "release")?.id; const versionHint = kind === "type" - ? "Mod loaders can trail the newest release - for a modded server, pick the version your mods are built for." + ? !latestOffered && loaderMeta + ? `${loaderMeta.label} has no build for ${ + newestRelease ? `Minecraft ${newestRelease}` : "the newest Minecraft release" + } yet, so the newest it can run is picked.` + : "Mod loaders can trail the newest release - for a modded server, pick the version your mods are built for." : modpack === null ? "Choose the modpack first." : modpack.source === "modrinth" @@ -210,7 +269,6 @@ export default function CreateContainerFlow({ ? "From the pack's manifest." : "The Minecraft version the pack is made for - it decides which Java the server gets, and a pack on the wrong Java does not start."; - const loaderMeta = LOADERS.find((item) => item.id === loader); const workloadReady = kind === "type" || (modpack !== null && version !== "" && version !== LATEST); const portProblems = portsProblems(extraPorts, gamePort, rconPort); @@ -373,7 +431,7 @@ export default function CreateContainerFlow({ - {kind === "type" && ( + {kind === "type" && latestOffered && ( Latest release diff --git a/app/components/StartHere.tsx b/app/components/StartHere.tsx index d36a19d..a8c9d1c 100644 --- a/app/components/StartHere.tsx +++ b/app/components/StartHere.tsx @@ -34,6 +34,7 @@ import { LATEST, MEMORY_DEFAULT, MEMORY_DEFAULT_MODPACK, + newestVersionFor, } from "@/app/components/CreateContainerFlow"; import GetJavaForMe from "@/app/components/GetJavaForMe"; import { useMode } from "@/app/components/ModeProvider"; @@ -315,9 +316,12 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) ? current.advanced.containerName : containerNameFor(serverName); const withPack = modsPath === "pack" && modpack !== null; + // No pack: the newest version Fabric has a build for (LATEST only + // when that is Mojang's newest release). + const mcVersion = withPack ? packVersion : await newestVersionFor("fabric"); await createContainer({ loader: "fabric", - mcVersion: withPack ? packVersion : LATEST, + mcVersion, containerName, memoryMb: withPack ? MEMORY_DEFAULT_MODPACK : MEMORY_DEFAULT, gamePort: current.advanced.queryPort, diff --git a/app/lib/ipc.ts b/app/lib/ipc.ts index 4a0522e..b5dc1fc 100644 --- a/app/lib/ipc.ts +++ b/app/lib/ipc.ts @@ -594,8 +594,11 @@ export type InstanceStatus = { createdAt: string | null; }; -export const listMcVersions = (includeSnapshots?: boolean) => - scoped("list_mc_versions", { includeSnapshots }); +/** 2.13.0 serverType: only the versions that server type has builds for; + * absent or "vanilla" = every Mojang version (the list falls back to that + * when the type's own list cannot be had). */ +export const listMcVersions = (includeSnapshots?: boolean, serverType?: ContainerLoader) => + scoped("list_mc_versions", { includeSnapshots, serverType }); /** 2.13.0, app-wide - the Java major a version ("LATEST" allowed) needs; * null when it cannot be resolved (offline, unknown version). */ export const requiredJavaMajor = (mcVersion: string) => From 02378aa2917b52d916cab31d909ac809da2383b9 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 22:58:29 -0600 Subject: [PATCH 23/28] docs: versions per server type (changelog, README, 327 tests) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- CHANGELOG.md | 13 +++++++++++++ CLAUDE.md | 2 +- README.md | 10 +++++----- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2eed545..9b23050 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,6 +76,19 @@ All notable changes to MineUI are documented here. Format follows - @heroui-pro/react 1.0.0-beta.11. The Java installer reads archive names the way zip 9 returns them. +### Fixed + +- **Creating a server in a container only offers Minecraft versions the + server type can run.** Picking Purpur with Minecraft 26.1.1 failed inside + the container with "Version 26.1.1 does not exist", because the version + list showed every Minecraft release whatever the type. Now the list + follows the server type you choose (from Paper, Purpur, Fabric, Quilt, + Forge and NeoForge's own version lists), "Latest release" appears only + when the type has a build for it, and otherwise the newest version the + type supports is picked, with a line under the picker saying why. Start + here's "Minecraft with mods" does the same for Fabric. When a type's list + cannot be fetched, the full list is shown as before. + ## [2.12.1] - 2026-11-10 ### Security diff --git a/CLAUDE.md b/CLAUDE.md index b3971aa..1d49e0d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ contribution process; this file is conventions and constraints only. - `pnpm lint` - ESLint - `pnpm tauri dev` - full app (Next.js dev server + Tauri window) - `pnpm tauri build` - production desktop bundle -- `cargo test -p mineui-core` - Rust unit tests (309 tests, must stay green) +- `cargo test -p mineui-core` - Rust unit tests (327 tests, must stay green) - `cargo fmt` / `cargo clippy` - run before committing any Rust change pnpm only. Do not use npm/yarn/bun. diff --git a/README.md b/README.md index 1a2d7b7..5983229 100644 --- a/README.md +++ b/README.md @@ -166,9 +166,9 @@ container), a **Normal Minecraft, on this computer** server (vanilla, no containers), or **A container I already run**. For a new container MineUI creates an [`itzg/minecraft-server`](https://github.com/itzg/docker-minecraft-server) container for you - pick Vanilla, Paper, Purpur, Fabric, Quilt, Forge or -NeoForge, the Minecraft version, memory and ports - picks the image with the -right Java for that version, generates the RCON password, and connects itself -to the result. The world lives in a named volume. +NeoForge, the Minecraft version (only the ones that type has a build for), +memory and ports - picks the image with the right Java for that version, +generates the RCON password, and connects itself to the result. The world lives in a named volume. **Deleting is always your call.** MineUI removes a container only when you ask it to - *Delete container* in Server Settings, or the tick box when you @@ -296,7 +296,7 @@ plus container/process metrics; everything else still works. ### Every backend call is typed and contract-bound -`crates/mineui-core` is pure Rust (no Tauri dependency, 309 unit tests); +`crates/mineui-core` is pure Rust (no Tauri dependency, 327 unit tests); `src-tauri` is a thin `#[tauri::command]` shell (61 IPC commands) that delegates to it. The full command/error/event surface is specified in [`docs/v2-contract.md`](docs/v2-contract.md) - binding, not a suggestion; see @@ -325,7 +325,7 @@ Other commands: - `pnpm build` - static export to `out/` (what Tauri bundles) - `pnpm lint` - ESLint - `pnpm tauri build` - production desktop bundle -- `cargo test -p mineui-core` - Rust unit tests (309 tests; must stay green) +- `cargo test -p mineui-core` - Rust unit tests (327 tests; must stay green) CI (`.github/workflows/ci.yml`) runs lint/typecheck/build on the frontend and `cargo fmt`/`clippy`/`test` plus a `cargo check` of the Tauri shell, on every From 1335e7b25b788abb1a9ae3a58ae648da2b368360 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 23:10:12 -0600 Subject: [PATCH 24/28] feat: 2.13.0 - beginner friendly, Find mods, signed macOS builds Version bump in every manifest, changelog section dated, install table filenames. The release carries Start here, MineUI gets Java, the Simple and Advanced view, What's this?, the Getting started checklist, the alive touches, Find mods on Modrinth with a mod on/off switch, Minecraft versions per server type, and macOS signing and notarization in the release workflow. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- CHANGELOG.md | 2 ++ Cargo.lock | 4 ++-- README.md | 10 +++++----- crates/mineui-core/Cargo.toml | 2 +- package.json | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 7 files changed, 13 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b23050..6573221 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ All notable changes to MineUI are documented here. Format follows ## [Unreleased] +## [2.13.0] - 2026-11-10 + ### Added - **Simple and Advanced view.** A switch in the header, Simple by default, diff --git a/Cargo.lock b/Cargo.lock index 460106b..f2f198b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1821,7 +1821,7 @@ checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" [[package]] name = "mineui-core" -version = "2.12.1" +version = "2.13.0" dependencies = [ "async-trait", "chrono", @@ -1845,7 +1845,7 @@ dependencies = [ [[package]] name = "mineui-tauri" -version = "2.12.1" +version = "2.13.0" dependencies = [ "mineui-core", "serde", diff --git a/README.md b/README.md index 5983229..882c324 100644 --- a/README.md +++ b/README.md @@ -63,11 +63,11 @@ Grab the build for your platform from the | Platform | Package | | --- | --- | -| Linux x86_64 | `MineUI_2.12.1_amd64.AppImage` - `chmod +x` and run | -| Debian/Ubuntu | `MineUI_2.12.1_amd64.deb` - `sudo apt install ./MineUI_2.12.1_amd64.deb` | -| Windows x64 | `MineUI_2.12.1_x64-setup.exe` | -| macOS (Apple Silicon) | `MineUI_2.12.1_aarch64.dmg` | -| macOS (Intel) | `MineUI_2.12.1_x64.dmg` | +| Linux x86_64 | `MineUI_2.13.0_amd64.AppImage` - `chmod +x` and run | +| Debian/Ubuntu | `MineUI_2.13.0_amd64.deb` - `sudo apt install ./MineUI_2.13.0_amd64.deb` | +| Windows x64 | `MineUI_2.13.0_x64-setup.exe` | +| macOS (Apple Silicon) | `MineUI_2.13.0_aarch64.dmg` | +| macOS (Intel) | `MineUI_2.13.0_x64.dmg` | A server On this computer needs Java. If the computer has none that fits the Minecraft version you pick, MineUI offers *Get Java for me* and downloads diff --git a/crates/mineui-core/Cargo.toml b/crates/mineui-core/Cargo.toml index 02e2bc3..242bbe5 100644 --- a/crates/mineui-core/Cargo.toml +++ b/crates/mineui-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mineui-core" -version = "2.12.1" +version = "2.13.0" edition = "2021" description = "MineUI core business logic (no Tauri dependency)" license = "AGPL-3.0-only" diff --git a/package.json b/package.json index 12da5e1..5707aea 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mineui", - "version": "2.12.1", + "version": "2.13.0", "private": true, "packageManager": "pnpm@10.32.1", "productName": "MineUI", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index c069a4c..511184f 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mineui-tauri" -version = "2.12.1" +version = "2.13.0" edition = "2021" description = "MineUI - Minecraft server manager (Tauri shell)" license = "AGPL-3.0-only" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index cf647e9..61eaff8 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "MineUI", - "version": "2.12.1", + "version": "2.13.0", "identifier": "studio.i4c.mineui", "build": { "beforeDevCommand": "pnpm dev", From 410054cf2ae46525b8700171233eb517074b8425 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 23:19:22 -0600 Subject: [PATCH 25/28] docs: v2-contract - concrete mcVersion from the UI, disabled jars not installed (2.13.0) Section 3.13: the UI resolves "Latest release" (and Start here's default) to a concrete version id from the server type's list and sends LATEST only when that list cannot be loaded. Section 3.5a: a .jar.disabled file does not count as installed for the installed flag, dependency resolution or the refusal of the project asked for; a fresh x.jar is placed beside x.jar.disabled and never replaces it. Section 7 ModSearchHit.installed comment follows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- docs/v2-contract.md | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/docs/v2-contract.md b/docs/v2-contract.md index 6c4c89d..528ec44 100644 --- a/docs/v2-contract.md +++ b/docs/v2-contract.md @@ -846,7 +846,8 @@ type ModSearchHit = { downloads: number; /** "required": every player must install the mod too. */ clientSide: ModClientSide; - /** Already in this server's folder (enabled or disabled). */ + /** Already in this server's folder and switched on (a `.jar.disabled` + * copy does not count). */ installed: boolean; }; @@ -926,6 +927,11 @@ a supported type whose Minecraft version is unknown. (at most 1000 hashes; files past that are only matched by name), and the answer maps each known hash to its version and so its `project_id`. A file Modrinth does not know (an upload, a jar from elsewhere) is simply not a project. + A switched-off file (name ending `.jar.disabled`, any case, §3.5 `set_mod_enabled`) + is not loaded by the server, so it does not count: it is not looked up, and its + project is not installed for `installed`, step 3 or step 4. Its name still counts + for the name checks, but no planned file (always a `.jar`) can equal it, so a fresh + `x.jar` is placed beside an existing `x.jar.disabled` and never replaces it. The answer is cached on the server's core for the same set of hashes. - `install_mod`: `projectId` is a Modrinth project id or slug, `^[A-Za-z0-9_-]{1,64}$` (`INVALID_INPUT`). Steps: @@ -946,13 +952,13 @@ a supported type whose Minecraft version is unknown. versions are the author's call and are not checked). Otherwise its `project_id` goes through step 2. A dependency with neither (only a `file_name`) cannot be resolved. A project already planned is not visited - again (cycles end there); a dependency whose project is already installed, or - whose chosen file name is already in the folder, is skipped and reported in - `alreadyInstalled`. A required dependency that cannot be resolved fails the + again (cycles end there); a dependency whose project is already installed + (switched on; a `.jar.disabled` copy does not count), or whose chosen file name + is already in the folder, is skipped and reported in `alreadyInstalled`. A required dependency that cannot be resolved fails the whole install with `INVALID_INPUT` naming it and the mod that needs it. More than 50 files in total → `INVALID_INPUT`. - 4. The project asked for is refused when it is already installed (its project id - is in the folder, enabled or disabled) or its file name is already taken + 4. The project asked for is refused when it is already installed (a switched-on + file of that project is in the folder) or its file name is already taken (`INVALID_INPUT`): MineUI never overwrites a file here. 5. Each planned file is downloaded host-side under §6.3b (progress events with `kind: "mod"`, one `downloadId` per file), all of them before any is placed. @@ -1532,9 +1538,15 @@ type ModpackRef = { Picking `mcVersion` (2.13.0): for a server type the UI offers only the versions `list_mc_versions` returns with `serverType` set to the chosen `loader` (§3.6), and -sends `LATEST` only when that list contains Mojang's latest release; otherwise it -picks the newest version in the list. Core does not repeat the check here (the image -stays the authority on what it can install). Modpacks keep their own versions. +sends a concrete version id from that list. "Latest release" is offered only when the +list contains Mojang's latest release, and is a label: at create time the UI resolves +it to that release's id. With nothing picked (Start here) the UI takes the type's +newest version the same way (Mojang's latest release when the list has it, else the +newest version in the list). The UI sends `LATEST` only when that list cannot be +loaded. So a server made by the UI keeps the version it was made with on every +restart, and Find mods (§3.5a) can tell its version. Core still accepts `LATEST` +(step 3) and does not repeat the check here (the image stays the authority on what it +can install). Modpacks keep their own versions. Sequence (first failure wins; nothing is created before step 7): @@ -2806,7 +2818,8 @@ export type ModSearchHit = { downloads: number; /** "required": every player must install the mod too. */ clientSide: ModClientSide; - /** Already in this server's folder (enabled or disabled). */ + /** Already in this server's folder and switched on (a `.jar.disabled` + * copy does not count). */ installed: boolean; }; From ba24090f0e8b63e0c17a1750cd62d5e0f2ccff6c Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 23:32:20 -0600 Subject: [PATCH 26/28] fix(core): a switched-off mod does not count as installed for Find mods installed_index no longer looks up files ending .jar.disabled (any case): their project is not installed for the installed flag on search hits, for dependency resolution or for the refusal of the project asked for. With Fabric API switched off, installing Sodium now installs Fabric API too instead of reporting it under alreadyInstalled. Every name still counts for the name checks; a planned file is always a .jar, so a fresh x.jar is placed beside x.jar.disabled and never replaces it. The index is built by build_index, tested without the network. ipc.ts follows the section 7 comment on ModSearchHit.installed. 328 core tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- app/lib/ipc.ts | 3 +- crates/mineui-core/src/modrinth.rs | 59 +++++++++++++------ crates/mineui-core/src/modrinth/tests.rs | 75 +++++++++++++++++++++--- 3 files changed, 110 insertions(+), 27 deletions(-) diff --git a/app/lib/ipc.ts b/app/lib/ipc.ts index b5dc1fc..a99a95e 100644 --- a/app/lib/ipc.ts +++ b/app/lib/ipc.ts @@ -519,7 +519,8 @@ export type ModSearchHit = { downloads: number; /** "required": every player must install the mod too. */ clientSide: ModClientSide; - /** Already in this server's folder (enabled or disabled). */ + /** Already in this server's folder and switched on (a `.jar.disabled` + * copy does not count). */ installed: boolean; }; diff --git a/crates/mineui-core/src/modrinth.rs b/crates/mineui-core/src/modrinth.rs index 031d9f5..55f8409 100644 --- a/crates/mineui-core/src/modrinth.rs +++ b/crates/mineui-core/src/modrinth.rs @@ -551,6 +551,44 @@ async fn projects_for_hashes( Ok(projects) } +/// A switched-off mod (`.jar.disabled`, any case): the server does not +/// load it, so it does not count as installed (§3.5a installed projects). +pub fn is_switched_off(name: &str) -> bool { + name.to_ascii_lowercase().ends_with(".jar.disabled") +} + +/// The files that can make a project installed: every file but a +/// switched-off one, at most `MAX_HASHES` of them. +fn counted_files(files: &[(String, String)]) -> Vec<&(String, String)> { + files + .iter() + .filter(|(_, name)| !is_switched_off(name)) + .take(MAX_HASHES) + .collect() +} + +/// The index from the folder's (sha1, filename) pairs and the hash → project +/// answer. Every name counts for the name checks; only files that are not +/// switched off make their project installed. +pub fn build_index( + files: &[(String, String)], + projects: &HashMap, +) -> InstalledIndex { + let mut index = InstalledIndex::default(); + for (_, name) in files { + index.filenames.insert(name.to_ascii_lowercase()); + } + for (hash, name) in counted_files(files) { + if let Some(project) = projects.get(hash) { + index + .projects + .entry(project.clone()) + .or_insert_with(|| name.clone()); + } + } + index +} + /// What is already in the target folder, by name and by Modrinth project. pub async fn installed_index( core: &crate::Core, @@ -558,28 +596,15 @@ pub async fn installed_index( target: ModTarget, ) -> Result { let files = file_hashes(core, target).await?; - let mut index = InstalledIndex::default(); - for (_, name) in &files { - index.filenames.insert(name.to_ascii_lowercase()); - } - let hashes: Vec = files - .iter() - .take(MAX_HASHES) + let hashes: Vec = counted_files(&files) + .into_iter() .map(|(h, _)| h.clone()) .collect(); if hashes.is_empty() { - return Ok(index); + return Ok(build_index(&files, &HashMap::new())); } let projects = projects_for_hashes(core, client, &hashes).await?; - for (hash, name) in &files { - if let Some(project) = projects.get(hash) { - index - .projects - .entry(project.clone()) - .or_insert_with(|| name.clone()); - } - } - Ok(index) + Ok(build_index(&files, &projects)) } /* ---------- search (§3.5a search_mods) ---------- */ diff --git a/crates/mineui-core/src/modrinth/tests.rs b/crates/mineui-core/src/modrinth/tests.rs index 09b390d..ef3c5df 100644 --- a/crates/mineui-core/src/modrinth/tests.rs +++ b/crates/mineui-core/src/modrinth/tests.rs @@ -583,10 +583,8 @@ async fn installed_dependencies_are_skipped() { .with("b", "B", vec![ver("b1", "b", "release", D1, vec![])]) .with("c", "C", vec![ver("c1", "c", "release", D1, vec![])]); let mut installed = InstalledIndex::default(); - // b by project (any version, e.g. an older or disabled jar) ... - installed - .projects - .insert("b".into(), "b-older.jar.disabled".into()); + // b by project (any version, e.g. an older jar) ... + installed.projects.insert("b".into(), "b-older.jar".into()); // ... c by the exact file name. installed.filenames.insert("c-c1.jar".into()); let plan = plan_install(&source, &fabric(), "a", &installed) @@ -601,6 +599,51 @@ async fn installed_dependencies_are_skipped() { ); } +#[tokio::test] +async fn a_switched_off_copy_does_not_count_as_installed() { + // a needs b; the folder has b switched off (exactly the file the plan + // would place, plus ".disabled") and an unrelated enabled mod. + let source = FakeSource::default() + .with( + "a", + "A", + vec![ver("a1", "a", "release", D1, vec![required("b")])], + ) + .with("b", "B", vec![ver("b1", "b", "release", D1, vec![])]); + let files = vec![ + ("h-b".to_string(), "B-B1.JAR.DISABLED".to_string()), + ("h-c".to_string(), "c.jar".to_string()), + ]; + let projects = HashMap::from([ + ("h-b".to_string(), "b".to_string()), + ("h-c".to_string(), "c".to_string()), + ]); + let installed = build_index(&files, &projects); + assert!(!installed.projects.contains_key("b")); + assert_eq!( + installed.projects.get("c").map(String::as_str), + Some("c.jar") + ); + // Its name still counts, but no planned .jar can equal it. + assert!(installed.has_file("b-b1.jar.disabled")); + assert!(!installed.has_file("b-b1.jar")); + + let plan = plan_install(&source, &fabric(), "a", &installed) + .await + .unwrap(); + let names: Vec<&str> = plan.files.iter().map(|f| f.filename.as_str()).collect(); + assert_eq!(names, ["a-a1.jar", "b-b1.jar"]); + assert!(plan.already_installed.is_empty()); + + // The same holds for the project asked for. + let plan = plan_install(&source, &fabric(), "b", &installed) + .await + .unwrap(); + assert_eq!(plan.files[0].filename, "b-b1.jar"); + assert!(is_switched_off("x.jar.disabled") && is_switched_off("X.Jar.Disabled")); + assert!(!is_switched_off("x.jar") && !is_switched_off("x.disabled.jar")); +} + #[tokio::test] async fn the_mod_asked_for_is_never_installed_twice() { let source = FakeSource::default().with( @@ -989,20 +1032,34 @@ async fn installed_index_on_this_computer_matches_names() { // Cached answers are used for the same set of hashes (no network here). let mods = core.settings().await.simple.instance_dir.join("mods"); std::fs::create_dir_all(&mods).unwrap(); - std::fs::write(mods.join("Some.jar.disabled"), b"x").unwrap(); - let hash = sha1_of_file(&mods.join("Some.jar.disabled")).unwrap(); + std::fs::write(mods.join("Some.jar"), b"x").unwrap(); + std::fs::write(mods.join("Off.jar.disabled"), b"y").unwrap(); + let hash = sha1_of_file(&mods.join("Some.jar")).unwrap(); + let off = sha1_of_file(&mods.join("Off.jar.disabled")).unwrap(); + // The cache key is only the enabled file's hash: the switched-off one is + // not looked up (a different key would go to the network and fail here). *core.modrinth_hashes.lock().unwrap() = Some(HashCache { hashes: vec![hash.clone()], - projects: HashMap::from([(hash, "proj".to_string())]), + projects: HashMap::from([(hash, "proj".to_string()), (off, "off-proj".to_string())]), }); let index = installed_index(&core, &reqwest::Client::new(), ModTarget::Mods) .await .unwrap(); - assert!(index.has_file("some.jar.disabled")); + assert!(index.has_file("some.jar")); + assert!(index.has_file("off.jar.disabled")); assert_eq!( index.projects.get("proj").map(String::as_str), - Some("Some.jar.disabled") + Some("Some.jar") ); + assert!(!index.projects.contains_key("off-proj")); + + // Only switched-off files: nothing to look up, no request. + std::fs::remove_file(mods.join("Some.jar")).unwrap(); + *core.modrinth_hashes.lock().unwrap() = None; + let index = installed_index(&core, &reqwest::Client::new(), ModTarget::Mods) + .await + .unwrap(); + assert!(index.has_file("off.jar.disabled") && index.projects.is_empty()); } #[test] From 14b69dc4ab1377c4b8b603f82bdc480e8657adcd Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 23:32:20 -0600 Subject: [PATCH 27/28] fix(ui): concrete versions for new containers, honest Get Java, locked Start here answers - The container create form resolves "Latest release" to the newest concrete version in the server type's list at create time and shows it ("Latest release (26.4)"); newestVersionFor returns that version, so Start here's no-mods Fabric path does too. LATEST is sent only when the list cannot be loaded (contract 3.13). Find mods can then tell the version of a new container, and it no longer moves to each new release on restart. - Get Java for me reads the returned JavaCheck: when the server still cannot use a Java of that major it says why instead of "Java N is ready." (the Java location in Server Settings wins over the download) and offers Check again. The Dashboard shows "Java is ready" and Start again only when the check says so. - Start here locks its answers once the server is made but did not start, and says so in the error box; Try again only starts it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- app/components/CreateContainerFlow.tsx | 30 +++++++++++---- app/components/GetJavaForMe.tsx | 53 ++++++++++++++++++++++---- app/components/StartHere.tsx | 30 ++++++++------- app/page.tsx | 12 ++++-- 4 files changed, 92 insertions(+), 33 deletions(-) diff --git a/app/components/CreateContainerFlow.tsx b/app/components/CreateContainerFlow.tsx index 8d9e8d9..1816eab 100644 --- a/app/components/CreateContainerFlow.tsx +++ b/app/components/CreateContainerFlow.tsx @@ -100,13 +100,18 @@ const LOADERS: { id: ContainerLoader; label: string; term: GlossaryTerm; hint: s const hasNewestRelease = (list: McVersion[]) => list.length === 0 || list.some((item) => item.latest && item.type === "release"); -/** What to create a server type with when nobody picks: LATEST when the type - * has a build for Mojang's newest release, else the newest version it has. - * Falls back to LATEST when the list cannot be had (as before 2.13.0). */ +/** The newest concrete version in a server type's list: Mojang's newest + * release when the type has a build for it, else the newest it has; null + * for an empty list. */ +const newestIn = (list: McVersion[]): string | null => + list.find((item) => item.latest && item.type === "release")?.id ?? list[0]?.id ?? null; + +/** What to create a server type with when nobody picks: the newest concrete + * version the type can run (contract 3.13), so the server keeps it on every + * restart and Find mods can tell it. LATEST only when the list cannot be had. */ export const newestVersionFor = async (loader: ContainerLoader): Promise => { try { - const list = await listMcVersions(undefined, loader); - return hasNewestRelease(list) ? LATEST : list[0].id; + return newestIn(await listMcVersions(undefined, loader)) ?? LATEST; } catch { return LATEST; } @@ -254,6 +259,9 @@ export default function CreateContainerFlow({ const versionIds = packVersions ?? (typeList ?? versions).map((item) => item.id); const loaderMeta = LOADERS.find((item) => item.id === loader); const newestRelease = versions.find((item) => item.latest && item.type === "release")?.id; + // What "Latest release" stands for with this type's list (null: not known). + const latestId = typeList ? newestIn(typeList) : null; + const latestLabel = latestId ? `Latest release (${latestId})` : "Latest release"; const versionHint = kind === "type" ? !latestOffered && loaderMeta @@ -297,9 +305,15 @@ export default function CreateContainerFlow({ play("click_confirm"); setCreating(true); try { + // "Latest release" is a label: send the concrete version it stands for + // (contract 3.13), LATEST only when the type's list cannot be had. + const mcVersion = + kind === "type" && version === LATEST + ? (latestId ?? (await newestVersionFor(loader))) + : version; await createContainer({ loader, - mcVersion: version, + mcVersion, containerName: containerName.trim(), memoryMb, gamePort, @@ -432,8 +446,8 @@ export default function CreateContainerFlow({ {kind === "type" && latestOffered && ( - - Latest release + + {latestLabel} )} diff --git a/app/components/GetJavaForMe.tsx b/app/components/GetJavaForMe.tsx index 833f912..b330716 100644 --- a/app/components/GetJavaForMe.tsx +++ b/app/components/GetJavaForMe.tsx @@ -3,10 +3,11 @@ // "Get Java for me": MineUI downloads the Java a Minecraft version needs into // its own folder (install_java, contract 2.13.0) and shows the progress. Used // by Start here, the Create server flow and a failed Start on the Dashboard. -// The caller decides when Java is "ready" from the JavaCheck handed back. +// It says "ready" only when the JavaCheck handed back says the server can use +// a Java of that major; the caller gets the check either way. import { TextShimmer } from "@heroui-pro/react"; import { useState } from "react"; -import { CheckCircle2, Download, Loader2, RefreshCw } from "lucide-react"; +import { CheckCircle2, Download, Loader2, RefreshCw, TriangleAlert } from "lucide-react"; import { Button, ProgressBar } from "@heroui/react"; import { useUISound } from "@/app/hooks/useUISound"; import { formatBytes } from "@/app/lib/format"; @@ -18,10 +19,16 @@ import { type JavaCheck, } from "@/app/lib/ipc"; +/** Whether the server can run on the Java a check found, for a version that + * needs `major`. */ +export const javaUsable = (check: JavaCheck, major: number) => + check.found && check.compatible !== false && (check.majorVersion ?? 0) >= major; + interface GetJavaForMeProps { /** The Java major the Minecraft version needs. */ major: number; - /** Called with the Java check after a successful download. */ + /** Called with the Java check after a successful download, also when the + * server still cannot use it (see javaUsable). */ onInstalled: (check: JavaCheck) => void; isDisabled?: boolean; /** Button text; defaults to "Get Java for me". */ @@ -39,19 +46,34 @@ export default function GetJavaForMe({ const [progress, setProgress] = useState(null); const [error, setError] = useState(null); const [done, setDone] = useState(false); + // Downloaded, but the server still does not use it: why, in a sentence. + const [unused, setUnused] = useState(null); const run = async () => { play("click_confirm"); setBusy(true); setError(null); + setUnused(null); setProgress(null); const unlisten = await onDownloadProgress((event) => { if (event.kind === "java") setProgress(event); }); try { const check = await installJava(major); - play("success"); - setDone(true); + if (javaUsable(check, major)) { + play("success"); + setDone(true); + } else { + play("error"); + // The check prefers MineUI's own Java over anything else on the + // computer, except the Java location set in Server Settings (contract + // 3.1 java_check). Not using the download means that setting won. + setUnused( + check.managed + ? `MineUI downloaded Java ${major}, but the server still cannot use it.` + : `MineUI downloaded Java ${major}, but this server is set to use a different Java: the Java location under Server Settings → Advanced (in Advanced view). Clear that setting to use the downloaded one.`, + ); + } onInstalled(check); } catch (e) { play("error"); @@ -87,14 +109,22 @@ export default function GetJavaForMe({ > {busy ? ( - ) : error ? ( + ) : error || unused ? ( ) : ( )} - {busy ? Getting Java... : error ? "Try again" : label} + {busy ? ( + Getting Java... + ) : error ? ( + "Try again" + ) : unused ? ( + "Check again" + ) : ( + label + )} - {!busy && !error && ( + {!busy && !error && !unused && ( Free download (about 50 MB). MineUI keeps it in its own folder. @@ -132,6 +162,13 @@ export default function GetJavaForMe({ {error}

)} + + {unused && !busy && ( +

+ + {unused} +

+ )}
); } diff --git a/app/components/StartHere.tsx b/app/components/StartHere.tsx index a8c9d1c..44c6016 100644 --- a/app/components/StartHere.tsx +++ b/app/components/StartHere.tsx @@ -167,6 +167,9 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) const [error, setError] = useState(null); // The server exists but did not start: Try again only starts it. const [made, setMade] = useState(false); + // Once the server is made its answers are fixed: changing them could not + // change the server Try again starts. + const locked = busy || made; const checkJava = useCallback(async () => { setJava({ kind: "checking" }); @@ -316,8 +319,8 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) ? current.advanced.containerName : containerNameFor(serverName); const withPack = modsPath === "pack" && modpack !== null; - // No pack: the newest version Fabric has a build for (LATEST only - // when that is Mojang's newest release). + // No pack: the newest concrete version Fabric has a build for + // (LATEST only when Fabric's list cannot be had, contract 3.13). const mcVersion = withPack ? packVersion : await newestVersionFor("fabric"); await createContainer({ loader: "fabric", @@ -377,7 +380,7 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) -
+
1. What do you want to play?
-
+
2. Who will play? { setWho(next); setError(null); @@ -420,7 +423,7 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) className="flex max-w-sm flex-col gap-2" value={name} onChange={setName} - isDisabled={busy} + isDisabled={locked} maxLength={MAX_NAME} > @@ -461,7 +464,7 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps)

setJava( javaIsEnough(check, java.major) @@ -520,7 +523,7 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) good to go.
-
+
Which mods do you want? @@ -530,7 +533,7 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) className="sm:grid-cols-2" options={MODS_OPTIONS} value={modsPath as ModsPath} - isDisabled={busy} + isDisabled={locked} onChange={(next) => { setModsPath(next); if (next === "none") setModpack(null); @@ -538,7 +541,7 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) />
{modsPath === "pack" && ( - + )} )} @@ -551,7 +554,7 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps) type="checkbox" className="mt-1" checked={eula} - disabled={busy} + disabled={locked} onChange={(event) => { play(event.target.checked ? "toggle_on" : "click_back"); setEula(event.target.checked); @@ -612,7 +615,8 @@ export default function StartHere({ onActive, onDone, onSkip }: StartHereProps)

{error}

{made && (

- Your server was made. Only starting it failed, so Try again just starts it. + Your server is already made, so the answers above are locked. Only + starting it failed, and Try again just starts it.

)}
diff --git a/app/page.tsx b/app/page.tsx index 2162f77..bd21121 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -32,7 +32,7 @@ import { useViewLevel } from "@/app/components/ViewLevelProvider"; import { SkeletonCard } from "@/app/components/Skeleton"; import CreateContainerFlow from "@/app/components/CreateContainerFlow"; import CreateServerFlow from "@/app/components/CreateServerFlow"; -import GetJavaForMe from "@/app/components/GetJavaForMe"; +import GetJavaForMe, { javaUsable } from "@/app/components/GetJavaForMe"; import GettingStartedCard, { TARGET_BACKUP, TARGET_START, @@ -690,9 +690,13 @@ export default function Home() { ) : javaProblem.major !== null ? ( - setJavaProblem((p) => (p ? { ...p, fixed: true } : p)) - } + onInstalled={(check) => { + // Not usable (a Java location set in Server + // Settings wins): GetJavaForMe says so in place. + if (javaUsable(check, javaProblem.major ?? 0)) { + setJavaProblem((p) => (p ? { ...p, fixed: true } : p)); + } + }} /> ) : (

From b6a983c9595b37bfc167fb200f7dd28a1ea4c608 Mon Sep 17 00:00:00 2001 From: I4cDeath Date: Tue, 10 Nov 2026 23:32:20 -0600 Subject: [PATCH 28/28] docs: Latest release pinned at create time (changelog), 328 core tests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XgcbjaB3r6DZJEwWqR8xyv --- CHANGELOG.md | 6 ++++++ CLAUDE.md | 2 +- README.md | 4 ++-- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6573221..bffb4e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,6 +70,12 @@ All notable changes to MineUI are documented here. Format follows - **The create forms show less up front.** Server type, version, pack and the Mojang agreement come first; the rest is under More options, with the same defaults as before. +- **"Latest release" in the container create form is the newest release at + the time you create the server.** The picker shows which version that is + next to "Latest release", and the container is created with that version, + so it stays on it instead of moving to each new Minecraft release on a + restart. Only when the server type's version list cannot be fetched does + the server follow the latest release, as before. - **Adding a mod from a link is in the Advanced view only**, with a warning that MineUI cannot check a file from a link the way it checks files from Find. diff --git a/CLAUDE.md b/CLAUDE.md index 1d49e0d..10ec739 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ contribution process; this file is conventions and constraints only. - `pnpm lint` - ESLint - `pnpm tauri dev` - full app (Next.js dev server + Tauri window) - `pnpm tauri build` - production desktop bundle -- `cargo test -p mineui-core` - Rust unit tests (327 tests, must stay green) +- `cargo test -p mineui-core` - Rust unit tests (328 tests, must stay green) - `cargo fmt` / `cargo clippy` - run before committing any Rust change pnpm only. Do not use npm/yarn/bun. diff --git a/README.md b/README.md index 882c324..56e4b3c 100644 --- a/README.md +++ b/README.md @@ -296,7 +296,7 @@ plus container/process metrics; everything else still works. ### Every backend call is typed and contract-bound -`crates/mineui-core` is pure Rust (no Tauri dependency, 327 unit tests); +`crates/mineui-core` is pure Rust (no Tauri dependency, 328 unit tests); `src-tauri` is a thin `#[tauri::command]` shell (61 IPC commands) that delegates to it. The full command/error/event surface is specified in [`docs/v2-contract.md`](docs/v2-contract.md) - binding, not a suggestion; see @@ -325,7 +325,7 @@ Other commands: - `pnpm build` - static export to `out/` (what Tauri bundles) - `pnpm lint` - ESLint - `pnpm tauri build` - production desktop bundle -- `cargo test -p mineui-core` - Rust unit tests (327 tests; must stay green) +- `cargo test -p mineui-core` - Rust unit tests (328 tests; must stay green) CI (`.github/workflows/ci.yml`) runs lint/typecheck/build on the frontend and `cargo fmt`/`clippy`/`test` plus a `cargo check` of the Tauri shell, on every