diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 46c4330..932135f 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -167,9 +167,12 @@ jobs:
run: |
New-Item -ItemType Directory -Force ../build | Out-Null
+ . (Join-Path (Get-Location) '..\keycipher.ps1')
$ldflags = "-s -w -buildid="
- if ($env:JHMC_CURSEFORGE_API_KEY) {
- $ldflags += " -X main.defaultCurseForgeKey=$($env:JHMC_CURSEFORGE_API_KEY)"
+ $keyFragment = Get-CurseForgeKeyLdflagsFragment
+ Remove-Item Env:JHMC_CURSEFORGE_API_KEY -ErrorAction SilentlyContinue
+ if ($keyFragment) {
+ $ldflags += " $keyFragment"
}
go build -trimpath -buildvcs=false -mod=readonly `
diff --git a/AGENTS.md b/AGENTS.md
index ecd2531..81b250a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -144,13 +144,33 @@ both sides, then implement the Go `*Service` and call it from a C# ViewModel.
`export.go`), and **mod-metadata parsers** (`ParserSet`, `LuaParser`,
`builtin_parsers/*.lua` — fabric/quilt/forge/neoforge/forge-legacy/bukkit; they
enrich `ModService.List` with icon/name/authors/version, cached per jar), and
- **mod shops** (`ShopSet`, `LuaShop`, `builtin_shops/*.lua` — modrinth,
- curseforge; the home/search/detail/versions/resolve_file contract behind
- `ShopService` and the app's Mod Shop window. Shop HTTP goes through
- `internal/httpcache` via `jhmc.http_cache` (disk ETag cache); keyed sources
- declare `needs_key` and read `ctx.config.api_key`, resolved from settings
- `shop_keys` then the `-X main.defaultCurseForgeKey` build default —
- `build.ps1` injects env `JHMC_CURSEFORGE_API_KEY`).
+ **mod shops** (`ShopSet`, `LuaShop`; the home/search/detail/versions/resolve_file
+ contract behind `ShopService` and the app's Mod Shop window). The first-party
+ shops now ship as **multi-role source scripts** in `builtin_sources/*.lua`
+ (modrinth, curseforge, ftb): one file declaring a `shop` role table and a hidden
+ `provider` role table under one `meta.id`, loaded by `LoadBuiltinSources` into
+ both `ShopSet` and `Registry` and sharing one `shop-config.json` entry. Role
+ tables are optional/back-compat — legacy top-level-function scripts still work;
+ role-scoped `kinds`/`needs_key` (shop) and `hidden`/`mod_layout` (provider)
+ override the `meta`-level fields. `meta.aliases` redirects an old id (e.g.
+ `curseforge_modpacks`) to the canonical entry in both registries so existing
+ modpack servers keep resolving. Shop HTTP goes through `internal/httpcache` via
+ `jhmc.http_cache` (disk ETag cache); keyed sources declare `needs_key` and read
+ `ctx.config.api_key` — a stored config key wins, with the
+ `-X main.defaultCurseForgeKeyCipher` + `-X main.defaultCurseForgeKeyPad` build
+ default as fallback. The key + pad injection now applies to **every build path**
+ — `build.ps1` AND the dotnet/VS/MSIX build (via `app/Engine.targets`'
+ `BuildEngine` target, which is what Store/MSIX packaging uses, not `build.ps1`).
+ Both paths get the ldflags fragment from the single source of truth
+ `keycipher.ps1` at the repo root, which XOR-obfuscates + hex-encodes env
+ `JHMC_CURSEFORGE_API_KEY` and emits BOTH the cipher and the pad as `-X` flags
+ (`build.ps1` dot-sources it; `Engine.targets` executes it and folds the fragment
+ into the default `-ldflags`). The pad is generated fresh per keyed build — set
+ `JHMC_KEY_CIPHER_PAD` (hex, ≥32 bytes) for a reproducible build, otherwise each
+ keyed binary is unique. Neither pad nor cipher is committed.
+ `engine/cmd/engine/keycipher.go` decodes it at startup; a one-time startup
+ migration folds any legacy `settings.json` `shop_keys["curseforge"]` into the
+ shared shop config.
`GrantStore` (`grants.go`) persists per-script permission decisions
(`grants.json`, `script-grants.json`, `parser-grants.json`, `shop-grants.json`).
`ProviderService`/`ScriptService`/`ParserService`/`ShopService` are wired in
diff --git a/README.md b/README.md
index 6165936..0fb8429 100644
--- a/README.md
+++ b/README.md
@@ -132,6 +132,18 @@ automatically runs `buf generate` when Go gRPC stubs are missing, then compiles
the Go engine before the C# build begins — no manual steps needed on a fresh
clone.
+To bake the optional default CurseForge API key into `engine.exe`, set
+`JHMC_CURSEFORGE_API_KEY` in the environment that starts the build. For
+`build.ps1`, set it in the same PowerShell session. For Visual Studio, set the
+environment variable before starting Visual Studio, then restart Visual Studio
+after changing it. Do not put the key in `launchSettings.json`: launch profiles
+apply only when the app starts, after MSBuild has already compiled the engine,
+and the file is committed. Set `JHMC_KEY_CIPHER_PAD` to at least 32 bytes of hex
+only when a reproducible keyed binary is required; otherwise each build creates
+a fresh random pad. The XOR encoding keeps plaintext out of the binary and
+normal build logs, but it is obfuscation rather than encryption because the
+binary contains everything needed to decode the key.
+
The app uses the packaged MSIX model by default. Double-click
`Package.appxmanifest` in Solution Explorer to open Visual Studio's manifest
designer. See [MSIX packaging](docs/packaging.md) for command-line packaging,
diff --git a/app/Engine.targets b/app/Engine.targets
index d9d83a5..77a74f5 100644
--- a/app/Engine.targets
+++ b/app/Engine.targets
@@ -15,6 +15,16 @@
$([MSBuild]::NormalizeDirectory('$(MSBuildThisFileDirectory)..'))
$(RepoRoot)engine
$(RepoRoot)build\engine.exe
+
+ <_EngineGoBuildArgsIsDefault Condition="'$(EngineGoBuildArgs)' == ''">true
-trimpath -buildvcs=false -mod=readonly -ldflags="-s -w -buildid="
CGO_ENABLED=0
@@ -71,11 +81,25 @@
+
+
+
-
+
+
+
+
@@ -156,7 +157,6 @@
SettingsSame visible value as SettingsButton.Content; kept separate for this property or translation context.
CloseSame visible value as ConsoleDialog.CloseButtonText; kept separate for this property or translation context.
Engine & Servers
- Integrations
Application
Log retention
Install and console logs are pruned automatically. Use 0 for no limit.
@@ -327,6 +327,16 @@
Open instance folder
+ Update modpack…
+ Export modpack…
+ Pick a version for "{0}" (currently {1}). The world and your own files are kept; pack files are replaced.
+ CurseForge modpack
+ Import modpackSame visible value as HomeImportButtonLabel.Text; kept separate for dialog-title translation context.
+ Server nameCanonical duplicate value in this locale; semantic identifier: ImportModpack_NameHeader.
+ MemoryCanonical duplicate value in this locale; semantic identifier: ImportModpack_MemoryHeader.
+ Preparing modpack export…
+ Packaging modpack…
+ Modpack exported.
OP
@@ -428,6 +438,14 @@
Mod Metadata Parsers
No parsers installed. Parsers read a mod or plugin jar's embedded metadata (name, version, authors, icon) for the server Mods panel.
Reads: {formats}
+ Mod Shops
+ No shop sources installed. Shop sources let you browse and download mods or plugins from a remote catalog such as Modrinth or CurseForge.
+ Requires an API key — set it in Settings.
+ Configure
+ SaveSame visible value as SettingsSaveButton.Content; kept separate for script-configuration dialog context.
+ CancelSame visible value as Scripts_RemoveConfirmCancel; kept separate for script-configuration dialog context.
+ Leave blank to keep the current value
+ Not set
Website
Show scripts in folder
Show in Folder
@@ -487,6 +505,11 @@
GitHub Repository
Report an Issue
Mod ShopCanonical Mod Shop window title; copied to Window.Title after XAML initialization.
+ Modpack Shop
+ Modpack shopHome-page label for opening the modpack shop.
+ Import modpackCanonical duplicate value in this locale; semantic identifier: HomeImportButtonLabel.Text.
+ Start a new server from a modpack
+ Browse community modpacks. Installing one creates a brand-new server, fully set up.
Find something brilliant for your server
Explore community projects selected for this server. Compatibility filters are on by default, so what you see is ready to fit.
DismissSame visible value as InstallDismissButton.Content; kept separate for this property or translation context.
@@ -517,8 +540,8 @@
World generationCanonical duplicate value in this locale; semantic identifier: shop.category.worldgen.
Search mods…
Back
- This source needs an API key. Add one in Settings to enable it.
-Needs an API key (see Settings)
+ This source needs an API key. Add one from the Scripts page (Configure the source) to enable it.
+ Needs an API key (Configure it on the Scripts page)
{0} results for “{1}”
Sort by
Relevance
@@ -565,10 +588,23 @@
World Editing and Management
World Generators
InstallCanonical duplicate value in this locale; semantic identifier: ShopInstallButton.Content.
- Install latest release
+ Install latest releaseCanonical duplicate value in this locale; semantic identifier: ShopInstallLatestButton.Content.
No compatible versions for this server. Relax the filters to see more.
The source no longer lists this project or version.
The author disallows third-party downloads for this file. Use “Open website” instead.
+ Built for {modLoaders}; your server runs {serverLoader}.
+ Built for Minecraft {modVersions}; your server runs {serverVersion}.
+ This project may not support your server ({serverLoader}, Minecraft {serverVersion}). Check the Versions tab.
+ InstallSame visible value as ShopInstallButton.Content; kept separate for programmatic action-label context.
+ Install latest releaseSame visible value as ShopInstallLatestButton.Content; kept separate for programmatic action-label context.
+ Create serverSame visible value as CreateServerButtonLabel.Text; kept separate for modpack action-label context.
+ Create a new server from {0}.
+ Server nameSame visible value as ImportModpack_NameHeader; kept separate for modpack creation context.
+ Memory (MB)Same visible value as CreateServerMemory.Header; kept separate for modpack creation context.
+ CreateSame visible value as CreateServerDialog.PrimaryButtonText; kept separate for modpack creation context.
+ Server creation started. Track progress in the main window.
+ Couldn't create the server.
+ No shop sources are available here.
This source needs an API key. Add one in Settings.
Stop the server before installing mods.
Most downloaded
@@ -584,10 +620,6 @@
Download all
Browse
Add custom jars
- Mod shopSame visible value as ShopWindow.Title; kept separate for this property or translation context.
- CurseForge requires a personal API key from console.curseforge.com. Modrinth needs no key.
- CurseForge API key
- Save key
Current task is running
Hide to system tray
@@ -595,7 +627,7 @@
CancelSame visible value as Scripts_RemoveConfirmCancel; kept separate for this property or translation context.
Closing now interrupts the current task. You can keep JustHostMC running in the system tray or close it anyway.
Create serverSame visible value as CreateServerButtonLabel.Text; kept separate for this property or translation context.
- Create
+ CreateCanonical duplicate value in this locale; semantic identifier: CreateServerDialog.PrimaryButtonText.
CancelSame visible value as Scripts_RemoveConfirmCancel; kept separate for this property or translation context.
Edit serverSame visible value as HomeCardEditButton.[using:Microsoft.UI.Xaml.Automation]AutomationProperties.Name; kept separate for this property or translation context.
SaveSame visible value as SettingsSaveButton.Content; kept separate for this property or translation context.
@@ -643,7 +675,6 @@
Monitor server resource usage and network metrics
No players online.
Manage online players, operators, and ban lists
- API Key
JustHostMCSame visible value as AppDisplayName; kept separate for this property or translation context.
Start server
The server is ready to run.
@@ -721,9 +752,6 @@
Servers run in Docker containers on this PC.
Servers run directly on this PC (isolated with Windows Job Objects).
Docker was not detected. Start Docker Desktop to enable this option.
- No CurseForge key is configured — the CurseForge tab stays disabled.
- A personal CurseForge key is configured. Save an empty key to remove it.
- Using this build's bundled CurseForge key. A personal key overrides it.
Could not load settings.
Settings saved.
Could not save settings.
@@ -737,6 +765,44 @@
Could not load results from this source.Canonical duplicate value in this locale; semantic identifier: ShopLoadFailedBar.Message.
Could not load results from this source.Same visible value as ShopLoadFailedBar.Message; kept separate for this property or translation context.
InstallSame visible value as ShopInstallButton.Content; kept separate for this property or translation context.
+ Create serverLocalized action shown on a modpack version row.
Installed. The server's mod list has been updated.
Install failed.
+
+ Import modpackLocal modpack import dialog title.
+ ImportPrimary action for the local modpack import dialog.
+ CancelCancel action for the local modpack import dialog.
+ Server nameName field in the local modpack import dialog.
+ Memory (MB)Memory picker in the local modpack import dialog.
+ 2048 MBMemory choice in the local modpack import dialog.
+ 4096 MBMemory choice in the local modpack import dialog.
+ 6144 MBMemory choice in the local modpack import dialog.
+ 8192 MBMemory choice in the local modpack import dialog.
+ 12288 MBMemory choice in the local modpack import dialog.
+ 16384 MBMemory choice in the local modpack import dialog.
+ Configure {name}Per-source configuration dialog title; {name} is replaced at runtime.
+ SavePrimary action for the per-source configuration dialog.
+ CancelCancel action for the per-source configuration dialog.
+
+ Create a serverModpack-shop create-server dialog title.
+ CreatePrimary action for the modpack-shop create-server dialog.
+ CancelCancel action for the modpack-shop create-server dialog.
+ Create a new server from this modpack.Introductory text above the selected modpack name.
+ Server nameName field in the modpack-shop create-server dialog.
+ Memory (MB)Memory field in the modpack-shop create-server dialog.
+ Update modpackModpack update dialog title.
+ UpdatePrimary action for the modpack update dialog.
+ CancelCancel action for the modpack update dialog.
+ Choose the version to install.Introductory text in the modpack update dialog.
+ ServerLabel for the server name in the modpack update dialog.
+ Current versionLabel for the installed version in the modpack update dialog.
+ New versionVersion picker in the modpack update dialog.
+ No other versions are available.Empty state in the modpack update dialog.
+ Modpack shopTitle for a serverless shop window browsing modpacks.
+ Loader compatibility warningAccessible name for the loader mismatch warning icon.
+ This project may target a different mod loader.Tooltip for the loader mismatch warning icon.
+ Minecraft version compatibility warningAccessible name for the version mismatch warning icon.
+ This project may target a different Minecraft version.Tooltip for the version mismatch warning icon.
+ Discover modpacksHeading for the serverless modpack shop home page.
+ Choose a modpack to create a new server.Subtitle for the serverless modpack shop home page.
diff --git a/app/JustHostMC.App/Strings/zh-TW/Resources.resw b/app/JustHostMC.App/Strings/zh-TW/Resources.resw
index 77fad35..1a7fcfb 100644
--- a/app/JustHostMC.App/Strings/zh-TW/Resources.resw
+++ b/app/JustHostMC.App/Strings/zh-TW/Resources.resw
@@ -111,7 +111,7 @@
無法載入版本
請檢查網路連線,然後重新選取伺服器類型。
進階設定
- 記憶體 (MB)
+ 記憶體 (MB)Canonical duplicate value in this locale; semantic identifier: CreateServerMemory.Header.
Java 行程的最大堆積記憶體。多數伺服器建議使用 2048 MB。
連接埠Canonical duplicate value in this locale; semantic identifier: CreateServerPort.Header.
保留為 0 可自動指派可用連接埠。Minecraft 預設值為 25565。
@@ -126,6 +126,7 @@
解壓縮 Java 執行階段中
下載安裝程式中
執行安裝程式中
+ 下載整合包檔案中
完成。
@@ -154,7 +155,6 @@
設定Same visible value as SettingsButton.Content; kept separate for this property or translation context.
關閉Same visible value as ConsoleDialog.CloseButtonText; kept separate for this property or translation context.
引擎與伺服器
- 整合
應用程式
記錄保留
安裝與控制台記錄會自動清理。使用 0 表示不限制。
@@ -325,6 +325,16 @@
開啟執行個體資料夾
+ 更新模組包…
+ 匯出模組包…
+ 為「{0}」選擇版本(目前為 {1})。世界與你自己的檔案會保留,模組包檔案將被更換。
+ CurseForge 模組包
+ 匯入模組包Same visible value as HomeImportButtonLabel.Text; kept separate for dialog-title translation context.
+ 伺服器名稱Canonical duplicate value in this locale; semantic identifier: ImportModpack_NameHeader.
+ 記憶體Canonical duplicate value in this locale; semantic identifier: ImportModpack_MemoryHeader.
+ 正在準備匯出模組包…
+ 正在打包模組包…
+ 模組包已匯出。
OP
@@ -399,6 +409,14 @@
提供者
模組資訊解析器
尚未安裝任何解析器。解析器會讀取模組或外掛 jar 內嵌的資訊(名稱、版本、作者、圖示),顯示在伺服器的模組面板。
+ 模組商店Shop-source section heading; kept separate from other shop labels for this translation context.
+ 尚未安裝任何商店來源。商店來源讓您從 Modrinth 或 CurseForge 等遠端目錄瀏覽並下載模組或外掛。
+ 需要 API 金鑰 — 請在設定中設定。
+ 設定Accessible action name for per-source configuration; kept separate from navigation and section labels.
+ 儲存Same visible value as SettingsSaveButton.Content; kept separate for script-configuration dialog context.
+ 取消Same visible value as Scripts_RemoveConfirmCancel; kept separate for script-configuration dialog context.
+ 留空以保留目前的值
+ 未設定
讀取:{formats}
網站
在資料夾中顯示腳本
@@ -476,6 +494,11 @@
GitHub 儲存庫
回報問題
模組商店模組商店視窗的標準標題;XAML 初始化後複製到 Window.Title。
+ 模組包商店Canonical duplicate value in this locale; semantic identifier: ShopWindow_TitleModpacks.
+ 模組包商店Same visible value as ShopWindow_TitleModpacks; kept separate for home-button translation context.
+ 匯入模組包Canonical duplicate value in this locale; semantic identifier: HomeImportButtonLabel.Text.
+ 用模組包建立新的伺服器
+ 瀏覽社群製作的模組包,安裝後會自動建立並設定好一台全新伺服器。
為你的伺服器找到精彩內容
探索社群製作的專案。相容性篩選預設開啟,顯示的內容都更適合目前的伺服器。
關閉Same visible value as ConsoleDialog.CloseButtonText; kept separate for this property or translation context.
@@ -506,8 +529,8 @@
世界生成Canonical duplicate value in this locale; semantic identifier: shop.category.worldgen.
搜尋模組…
返回
- 此來源需要 API 金鑰,請先到「設定」新增金鑰。
-需要 API 金鑰(請見「設定」)
+ 此來源需要 API 金鑰,請到「腳本」頁面設定此來源以啟用。
+ 需要 API 金鑰(請到「腳本」頁面設定)
「{1}」共 {0} 筆結果
排序方式
關聯性
@@ -554,10 +577,23 @@
世界編輯與管理
世界生成器
安裝Canonical duplicate value in this locale; semantic identifier: ShopInstallButton.Content.
- 安裝最新正式版
+ 安裝最新正式版Semantic identifier: ShopInstallLatestButton.Content; this locale distinguishes the XAML action from the programmatic release label.
沒有與此伺服器相容的版本,放寬篩選即可看到更多。
來源已不再提供此專案或版本。
作者不允許第三方下載此檔案,請改用「開啟網站」。
+ 此版本適用於 {modLoaders};你的伺服器執行的是 {serverLoader}。
+ 此版本適用於 Minecraft {modVersions};你的伺服器執行的是 {serverVersion}。
+ 此專案可能不支援你的伺服器({serverLoader},Minecraft {serverVersion})。請查看「版本」分頁。
+ 安裝Same visible value as ShopInstallButton.Content; kept separate for programmatic action-label context.
+ 安裝最新發行版Programmatic release action label; kept separate from ShopInstallLatestButton.Content for locale-specific wording.
+ 建立伺服器Same visible value as CreateServerButtonLabel.Text; kept separate for modpack action-label context.
+ 從 {0} 建立新的伺服器。
+ 伺服器名稱Same visible value as ImportModpack_NameHeader; kept separate for modpack creation context.
+ 記憶體 (MB)Same visible value as CreateServerMemory.Header; kept separate for modpack creation context.
+ 建立Same visible value as CreateServerDialog.PrimaryButtonText; kept separate for modpack creation context.
+ 已開始建立伺服器,請在主視窗查看安裝進度。
+ 無法建立伺服器。
+ 目前沒有可用的商店來源。
此來源需要 API 金鑰,請到「設定」新增。
請先停止伺服器再安裝模組。
下載最多
@@ -573,10 +609,6 @@
全部下載
瀏覽
加入自訂 Jar
- 模組商店Same visible value as ShopWindow.Title; kept separate for this property or translation context.
- CurseForge 需要個人 API 金鑰(console.curseforge.com);Modrinth 不需要金鑰。
- CurseForge API 金鑰
- 儲存金鑰
目前工作仍在執行
隱藏到系統匣
@@ -584,7 +616,7 @@
取消Same visible value as Scripts_RemoveConfirmCancel; kept separate for this property or translation context.
現在關閉會中斷目前的工作。您可以讓 JustHostMC 繼續在系統匣執行,或仍然關閉。
建立伺服器Same visible value as CreateServerButtonLabel.Text; kept separate for this property or translation context.
- 建立
+ 建立Canonical duplicate value in this locale; semantic identifier: CreateServerDialog.PrimaryButtonText.
取消Same visible value as Scripts_RemoveConfirmCancel; kept separate for this property or translation context.
編輯伺服器Same visible value as ServerEditMenuItem.Text; kept separate for this property or translation context.
儲存Same visible value as SettingsSaveButton.Content; kept separate for this property or translation context.
@@ -632,7 +664,6 @@
監控伺服器資源使用與網路指標
目前沒有玩家在線上。
管理線上玩家、管理員與封鎖名單
- API 金鑰
JustHostMCSame visible value as AppDisplayName; kept separate for this property or translation context.
啟動伺服器
伺服器已準備好執行。
@@ -710,9 +741,6 @@
伺服器會在這台電腦上的 Docker 容器中執行。
伺服器會直接在這台電腦上執行(使用 Windows Job Objects 隔離)。
未偵測到 Docker。啟動 Docker Desktop 以啟用此選項。
- 尚未設定 CurseForge 金鑰,CurseForge 分頁將維持停用。
- 已設定個人 CurseForge 金鑰。儲存空白金鑰即可移除。
- 正在使用此版本內建的 CurseForge 金鑰,個人金鑰可覆蓋它。
無法載入設定。
設定已儲存。Same visible value as ConfigStatusSaved.Text; kept separate for this property or translation context.
無法儲存設定。
@@ -726,6 +754,44 @@
無法從此來源載入結果。Canonical duplicate value in this locale; semantic identifier: ShopLoadFailedBar.Message.
無法從此來源載入結果。Same visible value as ShopLoadFailedBar.Message; kept separate for this property or translation context.
安裝Same visible value as ShopInstallButton.Content; kept separate for this property or translation context.
+ 建立伺服器模組包版本列顯示的本地化動作。
安裝完成,伺服器的模組清單已更新。
安裝失敗。
+
+ 匯入模組包本機模組包匯入對話方塊標題。
+ 匯入本機模組包匯入對話方塊的主要動作。
+ 取消本機模組包匯入對話方塊的取消動作。
+ 伺服器名稱本機模組包匯入對話方塊的名稱欄位。
+ 記憶體 (MB)本機模組包匯入對話方塊的記憶體選擇器。
+ 2048 MB本機模組包匯入對話方塊的記憶體選項。
+ 4096 MB本機模組包匯入對話方塊的記憶體選項。
+ 6144 MB本機模組包匯入對話方塊的記憶體選項。
+ 8192 MB本機模組包匯入對話方塊的記憶體選項。
+ 12288 MB本機模組包匯入對話方塊的記憶體選項。
+ 16384 MB本機模組包匯入對話方塊的記憶體選項。
+ 設定 {name}每個來源的設定對話方塊標題;{name} 會在執行階段取代。
+ 儲存每個來源設定對話方塊的主要動作。
+ 取消每個來源設定對話方塊的取消動作。
+
+ 建立伺服器模組包商店的建立伺服器對話方塊標題。
+ 建立模組包商店建立伺服器對話方塊的主要動作。
+ 取消模組包商店建立伺服器對話方塊的取消動作。
+ 從此模組包建立新的伺服器。所選模組包名稱上方的說明文字。
+ 伺服器名稱模組包商店建立伺服器對話方塊的名稱欄位。
+ 記憶體 (MB)模組包商店建立伺服器對話方塊的記憶體欄位。
+ 更新模組包模組包更新對話方塊標題。
+ 更新模組包更新對話方塊的主要動作。
+ 取消模組包更新對話方塊的取消動作。
+ 選擇要安裝的版本。模組包更新對話方塊的說明文字。
+ 伺服器模組包更新對話方塊中的伺服器名稱標籤。
+ 目前版本模組包更新對話方塊中的已安裝版本標籤。
+ 新版本模組包更新對話方塊中的版本選擇器。
+ 沒有其他可用版本。模組包更新對話方塊的空白狀態。
+ 模組包商店瀏覽模組包時無伺服器範圍商店視窗的標題。
+ 載入器相容性警告載入器不相符警告圖示的無障礙名稱。
+ 此專案可能適用於不同的模組載入器。載入器不相符警告圖示的工具提示。
+ Minecraft 版本相容性警告版本不相符警告圖示的無障礙名稱。
+ 此專案可能適用於不同的 Minecraft 版本。版本不相符警告圖示的工具提示。
+ 探索模組包無伺服器範圍模組包商店首頁的標題。
+ 選擇模組包以建立新的伺服器。無伺服器範圍模組包商店首頁的副標題。
diff --git a/app/JustHostMC.App/ViewModels/BackupsViewModel.cs b/app/JustHostMC.App/ViewModels/BackupsViewModel.cs
index b1152b7..b41356b 100644
--- a/app/JustHostMC.App/ViewModels/BackupsViewModel.cs
+++ b/app/JustHostMC.App/ViewModels/BackupsViewModel.cs
@@ -137,6 +137,8 @@ public async Task LoadAsync() {
[RelayCommand]
private async Task CreateBackup() {
+ using var backgroundTask =
+ App.Current.BackgroundTasks.Begin("backup-create");
RunOnUI(() => {
IsBusy = true;
SetStatus(BackupStatus.Creating);
@@ -160,6 +162,8 @@ await daemon.Backups.CreateAsync(
private async Task Restore(BackupItem? item) {
if (item is null)
return;
+ using var backgroundTask =
+ App.Current.BackgroundTasks.Begin("backup-restore");
RunOnUI(() => {
IsBusy = true;
SetStatus(BackupStatus.Restoring);
@@ -182,6 +186,8 @@ await daemon.Backups.RestoreAsync(
private async Task Delete(BackupItem? item) {
if (item is null)
return;
+ using var backgroundTask =
+ App.Current.BackgroundTasks.Begin("backup-delete");
RunOnUI(() => {
IsBusy = true;
SetStatus(BackupStatus.Deleting);
diff --git a/app/JustHostMC.App/ViewModels/MainViewModel.cs b/app/JustHostMC.App/ViewModels/MainViewModel.cs
index 2fbad62..fa506c0 100644
--- a/app/JustHostMC.App/ViewModels/MainViewModel.cs
+++ b/app/JustHostMC.App/ViewModels/MainViewModel.cs
@@ -30,6 +30,8 @@ public partial class MainViewModel : ObservableObject, IAsyncDisposable {
private readonly ILocalizer _localizer;
private readonly DispatcherQueue _dispatcher;
private readonly BackgroundTaskService _backgroundTasks;
+ private readonly TaskCompletionSource _initialServerSync =
+ new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly PendingServerUpdates _pendingUpdates = new();
private readonly ServerChangeSynchronizer _serverChanges = new();
private readonly ServerListState _serverState = new();
@@ -115,6 +117,7 @@ public MainViewModel(ILocalizer localizer, DispatcherQueue dispatcher,
/// Waits for the engine, probes Health, and starts the server
/// change stream.
public async Task ConnectAsync() {
+ using var backgroundTask = _backgroundTasks.Begin("server-sync");
RunOnUI(() => EngineConnectionState =
EngineConnectionStatus.Connecting);
try {
@@ -131,6 +134,7 @@ await daemon.Engine.HealthAsync(
TaskContinuationOptions.OnlyOnFaulted);
_serverChangesSession ??= CreateServerChangeSession(daemon);
await _serverChangesSession.StartAsync();
+ await _initialServerSync.Task;
} catch (Exception) {
RunOnUI(() => EngineConnectionState =
EngineConnectionStatus.Failed);
@@ -185,9 +189,31 @@ private async Task Refresh() {
/// Creates a server, streaming localized install progress + raw
/// log.
- public async Task InstallServerAsync(CreateServerRequest request) {
+ public Task InstallServerAsync(CreateServerRequest request) =>
+ RunNewServerInstallAsync(request.Name,
+ daemon => daemon.Servers.Create(request));
+
+ /// Imports a local modpack file (CurseForge zip or Modrinth
+ /// .mrpack) as a brand-new server, streaming the same install progress as a
+ /// shop install.
+ public Task ImportModpackAsync(string name, string srcPath, int memoryMb) =>
+ RunNewServerInstallAsync(name, daemon => daemon.Servers.ImportModpack(
+ new ImportModpackRequest {
+ Name = name,
+ SrcPath = srcPath,
+ MemoryMb = memoryMb,
+ }));
+
+ /// Shared flow behind creating and importing a brand-new server:
+ /// drives both the global install UI and the server's progress tracker off
+ /// one InstallProgress stream, so the operation survives window/page
+ /// changes.
+ private async Task RunNewServerInstallAsync(
+ string name,
+ Func>
+ startCall) {
using var backgroundTask = _backgroundTasks.Begin("server-install");
- var tracker = ProgressService.GetOrCreateTracker(null, request.Name);
+ var tracker = ProgressService.GetOrCreateTracker(null, name);
RunOnUI(() => {
tracker.InstallLog.Clear();
tracker.HasFailed = false;
@@ -212,7 +238,7 @@ public async Task InstallServerAsync(CreateServerRequest request) {
try {
var daemon = await App.Current.DaemonReady;
- using var call = daemon.Servers.Create(request);
+ using var call = startCall(daemon);
await foreach (var progress in call.ResponseStream.ReadAllAsync()
.ConfigureAwait(false)) {
progressBuffer.Post(progress);
@@ -245,7 +271,106 @@ public async Task InstallServerAsync(CreateServerRequest request) {
}
}
+ /// Moves a modpack server to another pack version, streaming
+ /// progress into the server's global tracker so the operation survives
+ /// window/page changes.
+ public async Task UpdateModpackAsync(ServerItem server, string version) {
+ using var backgroundTask = _backgroundTasks.Begin("modpack-update");
+ var tracker =
+ ProgressService.GetOrCreateTracker(server.Id, server.Name);
+ RunOnUI(() => {
+ tracker.InstallLog.Clear();
+ tracker.HasFailed = false;
+ tracker.IsInstalling = true;
+ tracker.IsActive = true;
+ tracker.IsReadyToRun = false;
+ tracker.IsIndeterminate = true;
+ tracker.ProgressFraction = 0;
+ tracker.CurrentStep = _localizer.Get("install.progress.preparing");
+ });
+ try {
+ var daemon = await App.Current.DaemonReady;
+ using var call = daemon.Servers.UpdateModpack(
+ new UpdateModpackRequest { Id = server.Id, Version = version });
+ await foreach (var progress in call.ResponseStream.ReadAllAsync()
+ .ConfigureAwait(false)) {
+ var snapshot = progress;
+ RunOnUI(() => ApplyTrackerProgress(tracker, snapshot));
+ }
+ await Refresh();
+ RunOnUI(() => {
+ tracker.IsInstalling = false;
+ tracker.IsActive = false;
+ tracker.CurrentStep = _localizer.Get("install.progress.done");
+ });
+ } catch (RpcException ex) {
+ FailTracker(tracker, ex);
+ }
+ }
+
+ /// Exports a modpack server as a CurseForge client pack zip,
+ /// streaming progress into the server's global tracker.
+ public async Task ExportModpackAsync(ServerItem server, string destPath) {
+ using var backgroundTask = _backgroundTasks.Begin("modpack-export");
+ var tracker =
+ ProgressService.GetOrCreateTracker(server.Id, server.Name);
+ RunOnUI(() => {
+ tracker.InstallLog.Clear();
+ tracker.HasFailed = false;
+ tracker.IsInstalling = true;
+ tracker.IsActive = true;
+ tracker.IsReadyToRun = false;
+ tracker.IsIndeterminate = true;
+ tracker.ProgressFraction = 0;
+ tracker.CurrentStep = _localizer.Get("shop.export.preparing");
+ });
+ try {
+ var daemon = await App.Current.DaemonReady;
+ using var call = daemon.Servers.ExportModpack(
+ new ExportModpackRequest { Id = server.Id,
+ DestPath = destPath });
+ await foreach (var progress in call.ResponseStream.ReadAllAsync()
+ .ConfigureAwait(false)) {
+ var snapshot = progress;
+ RunOnUI(() => ApplyTrackerProgress(tracker, snapshot));
+ }
+ RunOnUI(() => {
+ tracker.IsInstalling = false;
+ tracker.IsActive = false;
+ tracker.CurrentStep = _localizer.Get("shop.export.done");
+ });
+ } catch (RpcException ex) {
+ FailTracker(tracker, ex);
+ }
+ }
+
+ private void ApplyTrackerProgress(ServerProgressTracker tracker,
+ InstallProgress snapshot) {
+ if (snapshot.Step is { Key.Length : > 0 } step)
+ tracker.CurrentStep = _localizer.Get(step.Key);
+ if (snapshot.Fraction >= 0) {
+ tracker.IsIndeterminate = false;
+ tracker.ProgressFraction = snapshot.Fraction;
+ } else {
+ tracker.IsIndeterminate = true;
+ }
+ if (!string.IsNullOrEmpty(snapshot.LogLine))
+ tracker.AppendLogs([snapshot.LogLine]);
+ }
+
+ private void FailTracker(ServerProgressTracker tracker, RpcException ex) {
+ var key = MapErrorKey(ex);
+ RunOnUI(() => {
+ tracker.HasFailed = true;
+ tracker.IsInstalling = false;
+ tracker.IsIndeterminate = false;
+ tracker.IsActive = false;
+ tracker.CurrentStep = _localizer.Get(key);
+ });
+ }
+
public async Task UpdateServerAsync(UpdateServerRequest request) {
+ using var backgroundTask = _backgroundTasks.Begin("server-update");
var item = Servers.FirstOrDefault(s => s.Id == request.Id);
var rollback = item is null ? null : BuildUpdateRequest(item);
var optimistic = request.Clone();
@@ -358,6 +483,7 @@ await daemon.Servers.StopAsync(
private async Task DeleteServer(ServerItem? item) {
if (item is null)
return;
+ using var backgroundTask = _backgroundTasks.Begin("server-delete");
try {
var daemon = await App.Current.DaemonReady;
await daemon.Servers.DeleteAsync(
@@ -399,7 +525,8 @@ private void MergeServers(
System.Collections.Generic.IEnumerable incoming) {
var list = incoming.ToList();
_serverState.Reconcile(list);
- _backgroundTasks.SynchronizeServers(list);
+ SynchronizeBackgroundTasks();
+ _initialServerSync.TrySetResult();
foreach (var proto in list) UpsertServer(proto);
@@ -415,6 +542,7 @@ private void MergeServers(
private void ApplyServerChange(ServerChangeEvent change) {
_serverState.Apply(change);
+ SynchronizeBackgroundTasks();
switch (change.ChangeCase) {
case ServerChangeEvent.ChangeOneofCase.Upsert:
UpsertServer(change.Upsert);
@@ -428,6 +556,9 @@ private void ApplyServerChange(ServerChangeEvent change) {
OnServerStatsChanged();
}
+ private void SynchronizeBackgroundTasks() =>
+ _backgroundTasks.SynchronizeServers(_serverState.Servers);
+
private void UpsertServer(Server proto) {
var tracker = ProgressService.GetOrCreateTracker(proto.Id, proto.Name);
if (proto.Status is not(ServerStatus.Installing or ServerStatus
@@ -519,6 +650,7 @@ private ServerChangeSession CreateServerChangeSession(
change => RunOnUI(() => ApplyServerChange(change)));
public async ValueTask DisposeAsync() {
+ _initialServerSync.TrySetCanceled();
if (_serverChangesSession is not null)
await _serverChangesSession.DisposeAsync();
}
diff --git a/app/JustHostMC.App/ViewModels/ScriptsViewModel.cs b/app/JustHostMC.App/ViewModels/ScriptsViewModel.cs
index e8cc7eb..1a571a3 100644
--- a/app/JustHostMC.App/ViewModels/ScriptsViewModel.cs
+++ b/app/JustHostMC.App/ViewModels/ScriptsViewModel.cs
@@ -41,6 +41,7 @@ public ScriptsViewModel(DispatcherQueue dispatcher, ILocalizer localizer) {
public ObservableCollection Providers { get; } = new();
public ObservableCollection Scripts { get; } = new();
public ObservableCollection Parsers { get; } = new();
+ public ObservableCollection Shops { get; } = new();
///
/// Application logging sessions in reverse chronological order. The current
@@ -83,6 +84,7 @@ public async Task RefreshAsync() {
await RefreshProvidersAsync(daemon);
await RefreshScriptsAsync(daemon);
await RefreshParsersAsync(daemon);
+ await RefreshShopsAsync(daemon);
} finally {
RunOnUI(() => IsBusy = false);
}
@@ -94,8 +96,14 @@ private async Task
var list = await daemon.Providers.ListAsync(new Empty());
RunOnUI(() => {
Providers.Clear();
- foreach (var p in list.Providers)
+ foreach (var p in list.Providers) {
+ // Hidden provider roles (e.g. a merged modpack source's
+ // provider) install from elsewhere (the modpack shop), so
+ // they are not offered here.
+ if (p.Capabilities?.Hidden == true)
+ continue;
Providers.Add(new ProviderItem(p, _localizer));
+ }
});
} catch (RpcException ex) {
RunOnUI(() => StatusMessage = _localizer.Get(MapErrorKey(ex)));
@@ -135,6 +143,19 @@ private async Task
}
}
+ private async Task RefreshShopsAsync(JustHostMC.Core.DaemonClient daemon) {
+ try {
+ var list = await daemon.Shop.ListAsync(new Empty());
+ RunOnUI(() => {
+ Shops.Clear();
+ foreach (var s in list.Shops)
+ Shops.Add(new ShopSourceItem(s, _localizer));
+ });
+ } catch (RpcException ex) {
+ RunOnUI(() => StatusMessage = _localizer.Get(MapErrorKey(ex)));
+ }
+ }
+
/// Imports a provider script (+ optional jar) with the granted
/// permissions.
public async Task
@@ -207,6 +228,27 @@ public async Task ImportParserAsync(string luaSource,
}
}
+ /// Imports a mod shop source with the granted
+ /// permissions.
+ public async Task ImportShopAsync(string luaSource,
+ IReadOnlyList granted) {
+ RunOnUI(() => {
+ IsBusy = true;
+ StatusMessage = "";
+ });
+ try {
+ var daemon = await App.Current.DaemonReady;
+ var info = await daemon.Shop.ImportAsync(
+ new ImportShopRequest { LuaSource = luaSource });
+ await SetShopPermissionsAsync(daemon, info.Id, granted);
+ await RefreshShopsAsync(daemon);
+ } catch (RpcException ex) {
+ RunOnUI(() => StatusMessage = _localizer.Get(MapErrorKey(ex)));
+ } finally {
+ RunOnUI(() => IsBusy = false);
+ }
+ }
+
public async Task SetScriptEnabledAsync(ScriptItem item, bool enabled) {
try {
var daemon = await App.Current.DaemonReady;
@@ -254,6 +296,16 @@ public async Task RemoveParserAsync(ParserItem item) {
}
}
+ public async Task RemoveShopAsync(ShopSourceItem item) {
+ try {
+ var daemon = await App.Current.DaemonReady;
+ await daemon.Shop.RemoveAsync(new ProviderRef { Id = item.Id });
+ await RefreshShopsAsync(daemon);
+ } catch (RpcException ex) {
+ RunOnUI(() => StatusMessage = _localizer.Get(MapErrorKey(ex)));
+ }
+ }
+
private static async Task
SetParserPermissionsAsync(JustHostMC.Core.DaemonClient daemon, string id,
IReadOnlyList granted) {
@@ -262,6 +314,69 @@ private static async Task
await daemon.Parsers.SetPermissionsAsync(req);
}
+ private static async Task
+ SetShopPermissionsAsync(JustHostMC.Core.DaemonClient daemon, string id,
+ IReadOnlyList granted) {
+ var req = new SetPermissionsRequest { Id = id };
+ req.Granted.AddRange(granted);
+ await daemon.Shop.SetPermissionsAsync(req);
+ }
+
+ /// Fetches the current config values for a scriptable item
+ /// (provider, automation script, parser or shop). Returns null on
+ /// error.
+ public async Task GetConfigAsync(ScriptEntryItem item) {
+ try {
+ var daemon = await App.Current.DaemonReady;
+ var reference = new ProviderRef { Id = item.Id };
+ return item switch {
+ ProviderItem =>
+ await daemon.Providers.GetConfigAsync(reference),
+ ScriptItem => await daemon.Scripts.GetConfigAsync(reference),
+ ParserItem => await daemon.Parsers.GetConfigAsync(reference),
+ ShopSourceItem => await daemon.Shop.GetConfigAsync(reference),
+ _ => null,
+ };
+ } catch (RpcException ex) {
+ RunOnUI(() => StatusMessage = _localizer.Get(MapErrorKey(ex)));
+ return null;
+ }
+ }
+
+ /// Persists the changed config values for a scriptable item, then
+ /// refreshes so derived state (e.g. a shop's Ready flag) updates.
+ public async Task SetConfigAsync(ScriptEntryItem item,
+ SetConfigRequest req) {
+ if (req.Values.Count == 0)
+ return;
+ RunOnUI(() => {
+ IsBusy = true;
+ StatusMessage = "";
+ });
+ try {
+ var daemon = await App.Current.DaemonReady;
+ switch (item) {
+ case ProviderItem:
+ await daemon.Providers.SetConfigAsync(req);
+ break;
+ case ScriptItem:
+ await daemon.Scripts.SetConfigAsync(req);
+ break;
+ case ParserItem:
+ await daemon.Parsers.SetConfigAsync(req);
+ break;
+ case ShopSourceItem:
+ await daemon.Shop.SetConfigAsync(req);
+ break;
+ }
+ await RefreshAsync();
+ } catch (RpcException ex) {
+ RunOnUI(() => StatusMessage = _localizer.Get(MapErrorKey(ex)));
+ } finally {
+ RunOnUI(() => IsBusy = false);
+ }
+ }
+
private static async Task
SetProviderPermissionsAsync(JustHostMC.Core.DaemonClient daemon, string id,
IReadOnlyList granted) {
diff --git a/app/JustHostMC.App/ViewModels/SettingsViewModel.cs b/app/JustHostMC.App/ViewModels/SettingsViewModel.cs
index 3a6f176..b8e6afa 100644
--- a/app/JustHostMC.App/ViewModels/SettingsViewModel.cs
+++ b/app/JustHostMC.App/ViewModels/SettingsViewModel.cs
@@ -21,13 +21,6 @@ public enum SettingsWorkflowStatus {
RemoveIncompleteInstallationsFailed,
}
-public enum ShopKeyConfiguration {
- Unknown,
- None,
- User,
- Builtin,
-}
-
public enum BackendMode {
Unknown,
OnMachine,
@@ -145,26 +138,6 @@ public partial string AppVersionText {
public string AppName =>
JustHostMC.App.Helpers.ProcessInfoHelper.ProductName;
- /// User-entered CurseForge API key (write-only; never read
- /// back).
- [ObservableProperty]
- public partial string CurseForgeKey { get; set; } = "";
-
- [ObservableProperty]
- [NotifyPropertyChangedFor(nameof(HasNoShopKey))]
- [NotifyPropertyChangedFor(nameof(HasUserShopKey))]
- [NotifyPropertyChangedFor(nameof(HasBuiltinShopKey))]
- public partial ShopKeyConfiguration CurseForgeKeyConfiguration {
- get; private set;
- }
-
- public bool HasNoShopKey =>
- CurseForgeKeyConfiguration == ShopKeyConfiguration.None;
- public bool HasUserShopKey =>
- CurseForgeKeyConfiguration == ShopKeyConfiguration.User;
- public bool HasBuiltinShopKey =>
- CurseForgeKeyConfiguration == ShopKeyConfiguration.Builtin;
-
private bool _loadingBackend;
private bool _isLoadingLogs;
@@ -198,7 +171,6 @@ public async Task LoadAsync() {
}
await LoadBackendAsync();
- await LoadShopKeysAsync();
await RefreshIncompleteInstallationsAsync();
}
@@ -215,45 +187,6 @@ private async Task RefreshIncompleteInstallationsAsync() {
}
}
- private async Task LoadShopKeysAsync() {
- try {
- var daemon = await App.Current.DaemonReady;
- var keys = await daemon.Settings.GetShopKeysAsync(
- new Empty(), deadline: DateTime.UtcNow.AddSeconds(30));
- var status = ShopKeyConfiguration.None;
- foreach (var key in keys.Keys) {
- if (key.ShopId != "curseforge")
- continue;
- status = key.HasUserKey ? ShopKeyConfiguration.User
- : key.HasBuiltinKey ? ShopKeyConfiguration.Builtin
- : ShopKeyConfiguration.None;
- }
- RunOnUI(() => CurseForgeKeyConfiguration = status);
- } catch (RpcException) {
- // The shop key line stays empty; the rest of the page still works.
- }
- }
-
- [RelayCommand]
- private async Task SaveCurseForgeKey() {
- try {
- var daemon = await App.Current.DaemonReady;
- await daemon.Settings.SetShopKeyAsync(
- new ShopKey {
- ShopId = "curseforge",
- ApiKey = CurseForgeKey,
- },
- deadline: DateTime.UtcNow.AddSeconds(30));
- RunOnUI(() => {
- CurseForgeKey = "";
- SetWorkflowStatus(SettingsWorkflowStatus.Saved);
- });
- await LoadShopKeysAsync();
- } catch (RpcException) {
- RunOnUI(() => SetWorkflowStatus(SettingsWorkflowStatus.SaveFailed));
- }
- }
-
private async Task LoadBackendAsync() {
try {
var daemon = await App.Current.DaemonReady;
@@ -341,6 +274,8 @@ private async Task PurgeNow() {
[RelayCommand]
private async Task RemoveAllData() {
+ using var backgroundTask =
+ App.Current.BackgroundTasks.Begin("data-remove");
RunOnUI(() => {
IsBusy = true;
SetWorkflowStatus(SettingsWorkflowStatus.RemovingData);
@@ -361,6 +296,8 @@ await daemon.Servers.RemoveAllDataAsync(
[RelayCommand]
private async Task RemoveIncompleteInstallations() {
+ using var backgroundTask =
+ App.Current.BackgroundTasks.Begin("incomplete-install-remove");
RunOnUI(() => {
IsBusy = true;
SetWorkflowStatus(
diff --git a/app/JustHostMC.App/ViewModels/ShopDetailViewModel.cs b/app/JustHostMC.App/ViewModels/ShopDetailViewModel.cs
index 18bb831..2f86c8c 100644
--- a/app/JustHostMC.App/ViewModels/ShopDetailViewModel.cs
+++ b/app/JustHostMC.App/ViewModels/ShopDetailViewModel.cs
@@ -29,16 +29,27 @@ public sealed partial class ShopDetailViewModel : ObservableObject {
public ShopDetailViewModel(ShopViewModel shop, ShopProjectItem card,
DispatcherQueue dispatcher,
ILocalizer localizer) {
- _shop = shop;
- _dispatcher = dispatcher;
- _localizer = localizer;
- _shopId = card.Project.ShopId;
- _projectId = card.Project.ProjectId;
- SourceName =
- shop.Shops.FirstOrDefault(s => s.Id == _shopId)?.Name ?? _shopId;
- Card = card;
+ _shop = shop;
+ _dispatcher = dispatcher;
+ _localizer = localizer;
+ _shopId = card.Project.ShopId;
+ _projectId = card.Project.ProjectId;
+ Card = card;
+ var shopInfo = shop.Shops.FirstOrDefault(s => s.Id == _shopId);
+ SourceName = shopInfo?.Name ?? _shopId;
+ IsModpack = shop.SelectedShopIsModpack;
}
+ /// True when this project is a modpack: its versions create whole
+ /// new servers (via the ftb provider) instead of installing a file into
+ /// one.
+ public bool IsModpack { get; }
+
+ /// Label for the header action button, matching the project
+ /// kind.
+ public string InstallActionLabel => _localizer.Get(
+ IsModpack ? "Shop_CreateServerButton" : "Shop_InstallLatestButtonText");
+
/// The card the user clicked; the header shows it immediately
/// while the full detail loads.
[ObservableProperty]
@@ -125,8 +136,29 @@ public partial string WebsiteUrl {
get; private set;
} = "";
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(HasProjectCompatWarning))]
+ public partial string ProjectCompatMessage {
+ get; private set;
+ } = "";
+
+ /// Whether to show the project-level "may not fit your server"
+ /// banner.
+ public bool HasProjectCompatWarning => ProjectCompatMessage.Length > 0;
+
public bool HasGallery => Gallery.Count > 0;
+ // A project-level mismatch means none of the project's loaders/versions
+ // fit the server, so both mismatch kinds collapse to one summary banner.
+ private string ProjectCompatText(
+ ShopCompatVerdict compat) => compat switch {
+ ShopCompatVerdict.LoaderMismatch or ShopCompatVerdict.VersionMismatch =>
+ _localizer.Get("Shop_CompatProjectWarning",
+ ("serverLoader", _shop.Context.Loader),
+ ("serverVersion", _shop.Context.McVersion)),
+ _ => "",
+ };
+
/// Loads detail + versions concurrently.
public Task LoadAsync(bool darkTheme) =>
Task.WhenAll(LoadDetailAsync(darkTheme), LoadVersionsAsync());
@@ -145,16 +177,31 @@ private async Task LoadDetailAsync(bool darkTheme) {
? ShopBodyRenderer.ToHtml(
detail.Body, detail.BodyFormat, darkTheme)
: "";
+ // The detail lists every loader/version the project supports; a
+ // mismatch here means none of them fits this server. Suppressed
+ // while filtering.
+ var filtersActive = _shop.UseVersionFilter || _shop.UseLoaderFilter;
+ var projectCompat =
+ filtersActive
+ ? ShopCompatVerdict.Unknown
+ : ShopCompat.Evaluate(_shop.Context.Loader,
+ _shop.Context.McVersion,
+ detail.Loaders, detail.GameVersions);
+ var compatMessage = ProjectCompatText(projectCompat);
await RunOnUIAsync(() => {
if (detail.Project is not null &&
- detail.Project.Title.Length > 0)
+ detail.Project.Title.Length > 0) {
+ if (string.IsNullOrWhiteSpace(detail.Project.Author))
+ detail.Project.Author = Card.Author;
Card = new ShopProjectItem(detail.Project);
+ }
WebsiteUrl = detail.Links?.Website ?? "";
Gallery.Clear();
foreach (var image in detail.Gallery)
Gallery.Add(new ShopGalleryItem(image));
OnPropertyChanged(nameof(HasGallery));
- BodyHtml = html;
+ BodyHtml = html;
+ ProjectCompatMessage = compatMessage;
RefreshPrimaryAction();
});
} catch {
@@ -177,10 +224,15 @@ private async Task LoadVersionsAsync() {
Loader = _shop.UseLoaderFilter ? _shop.Context.Loader : "",
},
deadline: DateTime.UtcNow.AddSeconds(30));
+ // With a filter on, the engine already narrowed the list to
+ // matches, so a per-row badge would be redundant noise.
+ var showBadge = !_shop.UseVersionFilter && !_shop.UseLoaderFilter;
await RunOnUIAsync(() => {
Versions.Clear();
foreach (var version in list.Versions)
- Versions.Add(new ShopVersionItem(version));
+ Versions.Add(new ShopVersionItem(version, _shop.Context,
+ showBadge, IsModpack,
+ _localizer));
LatestRelease =
Versions
.Where(version => version.Version.Channel ==
@@ -285,6 +337,33 @@ private void RefreshPrimaryAction() {
}
}
+ /// Creates a brand-new server from a modpack version by handing
+ /// the request to the main window's global install flow, which owns the
+ /// stream: the install survives this window closing, and the global
+ /// progress UI shows steps, logs, and errors.
+ public async Task CreateServerAsync(ShopVersionItem version, string name,
+ int memoryMb) {
+ if (_shop.Context.CreateServer is null) {
+ await RunOnUIAsync(() => StatusMessage =
+ _localizer.Get("Shop_CreateServerFailed"));
+ return;
+ }
+ var request = new CreateServerRequest {
+ Name = name,
+ // A modpack shop's id doubles as its whole-server provider id
+ // (e.g. "ftb"); the provider parses "{projectId}/{versionId}".
+ ProviderId = _shopId,
+ McVersion = $"{_projectId}/{version.Version.Id}",
+ MemoryMb = memoryMb,
+ Port = 0,
+ };
+ _ = _shop.Context.CreateServer(request);
+ await RunOnUIAsync(() => {
+ InstallSucceeded = true;
+ StatusMessage = _localizer.Get("Shop_ServerCreateStarted");
+ });
+ }
+
// Follows the app's StatusCode-level mapping convention (see
// ModsViewModel.MapErrorKey); the diagnostic text disambiguates the two
// FailedPrecondition causes without unpacking ErrorDetail.
diff --git a/app/JustHostMC.App/ViewModels/ShopViewModel.cs b/app/JustHostMC.App/ViewModels/ShopViewModel.cs
index 8678aa5..29aa354 100644
--- a/app/JustHostMC.App/ViewModels/ShopViewModel.cs
+++ b/app/JustHostMC.App/ViewModels/ShopViewModel.cs
@@ -102,6 +102,16 @@ partial void OnSelectedShopChanged(ShopInfo? value) {
OnPropertyChanged(nameof(SelectedShopName));
var categoryGeneration = Interlocked.Increment(ref _categoryGeneration);
+ OnPropertyChanged(nameof(SelectedShopIsModpack));
+ OnPropertyChanged(nameof(ShowVersionFilter));
+ OnPropertyChanged(nameof(ShowLoaderFilter));
+ // Modpacks browse unfiltered; clear any active compat filter so its
+ // chip (bound to Use*Filter) also disappears, not just the hidden
+ // toggle.
+ if (SelectedShopIsModpack) {
+ UseVersionFilter = false;
+ UseLoaderFilter = false;
+ }
CategoryFilters.Clear();
if (value?.Id == "modrinth") {
foreach (var id in ModrinthCategories)
@@ -164,21 +174,53 @@ public void ResetCategoryFilters() {
foreach (var category in CategoryFilters) category.IsSelected = false;
}
+ /// True when this window is browsing modpacks (installed as whole
+ /// servers). The context is authoritative because a merged source can also
+ /// advertise mod and plugin capabilities.
+ public bool SelectedShopIsModpack => Context.Kind == ModKind.Modpack;
+
+ /// Version/loader filter toggles only make sense for mod/plugin
+ /// shops.
+ public bool ShowVersionFilter => !SelectedShopIsModpack && HasVersionFilter;
+ public bool ShowLoaderFilter => !SelectedShopIsModpack && HasLoaderFilter;
+
+ private ModKind EffectiveKind =>
+ SelectedShopIsModpack ? ModKind.Modpack : Context.Kind;
+
+ /// The shop-kind string a server-scoped browser filters sources
+ /// on: "plugin" for a Paper/Spigot server, "mod" otherwise. A merged source
+ /// (e.g. curseforge, whose Kinds are mod/plugin/modpack) still qualifies as
+ /// long as it carries this kind — it is no longer excluded merely for also
+ /// serving modpacks.
+ private string ServerBrowseKind =>
+ Context.Kind == ModKind.Plugin ? "plugin" : "mod";
+
+ // Modpacks pin their own MC version + loader, so a modpack shop always
+ // browses unfiltered regardless of the (hidden) toggle state.
private string EffectiveVersion =>
- UseVersionFilter ? Context.McVersion : "";
- private string EffectiveLoader => UseLoaderFilter ? Context.Loader : "";
-
- /// Loads the shop list and selects the first ready
- /// source.
+ !SelectedShopIsModpack && UseVersionFilter ? Context.McVersion : "";
+ private string EffectiveLoader =>
+ !SelectedShopIsModpack && UseLoaderFilter ? Context.Loader : "";
+
+ /// Loads the shop list and selects the first ready source.
+ /// Modpack sources create brand-new servers, so they only appear in the
+ /// server-less shop; a server-scoped shop lists mod/plugin sources
+ /// only.
public async Task LoadShopsAsync() {
try {
var daemon = await App.Current.DaemonReady;
var list = await daemon.Shop.ListAsync(new Empty());
+ var visible =
+ Context.IsServerScoped
+ ? list.Shops.Where(s => s.Kinds.Contains(ServerBrowseKind))
+ .ToArray()
+ : list.Shops.Where(s => s.Kinds.Contains("modpack"))
+ .ToArray();
await RunOnUIAsync(() => {
Shops.Clear();
- foreach (var shop in list.Shops) Shops.Add(shop);
- SelectedShop = list.Shops.FirstOrDefault(s => s.Ready) ??
- list.Shops.FirstOrDefault();
+ foreach (var shop in visible) Shops.Add(shop);
+ SelectedShop = visible.FirstOrDefault(s => s.Ready) ??
+ visible.FirstOrDefault();
});
} catch {
await RunOnUIAsync(() => HasLoadFailure = true);
@@ -205,7 +247,7 @@ await RunOnUIAsync(() => {
ShopId = shop.Id,
McVersion = EffectiveVersion,
Loader = EffectiveLoader,
- Kind = Context.Kind,
+ Kind = EffectiveKind,
},
deadline: DateTime.UtcNow.AddSeconds(30));
@@ -270,7 +312,7 @@ private async Task> LoadSearchPageAsync(
Query = Query,
McVersion = EffectiveVersion,
Loader = EffectiveLoader,
- Kind = Context.Kind,
+ Kind = EffectiveKind,
Sort = Sort,
Offset = offset,
Limit = PageSize,
@@ -305,7 +347,7 @@ public async Task> GetSuggestionsAsync(string text) {
Query = text,
McVersion = EffectiveVersion,
Loader = EffectiveLoader,
- Kind = Context.Kind,
+ Kind = EffectiveKind,
Sort = ShopSort.Relevance,
Offset = 0,
Limit = SuggestionCount,
diff --git a/app/JustHostMC.App/Views/CreateShopServerDialog.xaml b/app/JustHostMC.App/Views/CreateShopServerDialog.xaml
new file mode 100644
index 0000000..18b733e
--- /dev/null
+++ b/app/JustHostMC.App/Views/CreateShopServerDialog.xaml
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/app/JustHostMC.App/Views/CreateShopServerDialog.xaml.cs b/app/JustHostMC.App/Views/CreateShopServerDialog.xaml.cs
new file mode 100644
index 0000000..b43b02b
--- /dev/null
+++ b/app/JustHostMC.App/Views/CreateShopServerDialog.xaml.cs
@@ -0,0 +1,21 @@
+using JustHostMC.App.Controls;
+using Microsoft.UI.Xaml.Controls;
+
+namespace JustHostMC.App.Views;
+
+public sealed partial class CreateShopServerDialog : ContentDialog {
+ public CreateShopServerDialog(string projectName) {
+ ProjectName = projectName;
+ InitializeComponent();
+ ContentDialogSizing.Apply(this);
+ NameBox.Text = projectName;
+ }
+
+ public string ProjectName { get; }
+
+ public string ServerName => NameBox.Text.Trim().Length >
+ 0? NameBox.Text.Trim() : ProjectName;
+
+ public int MemoryMb =>
+ double.IsNaN(MemoryBox.Value) ? 4096 : (int)MemoryBox.Value;
+}
diff --git a/app/JustHostMC.App/Views/HomePage.xaml b/app/JustHostMC.App/Views/HomePage.xaml
index 21d83e7..2ee6753 100644
--- a/app/JustHostMC.App/Views/HomePage.xaml
+++ b/app/JustHostMC.App/Views/HomePage.xaml
@@ -395,6 +395,8 @@
+
+
@@ -427,6 +429,24 @@
+
+
+ private bool TryGetPackIdentity(out string packId, out string versionId) {
+ var parts = Server.ProviderVersion.Split('/', 2);
+ if (parts.Length == 2 && parts[0].Length > 0 && parts[1].Length > 0) {
+ packId = parts[0];
+ versionId = parts[1];
+ return true;
+ }
+ packId = "";
+ versionId = "";
+ return false;
+ }
+
+ private async void OnUpdateModpackClick(object sender, RoutedEventArgs e) {
+ // Imported packs have no upstream source to update from (the menu item
+ // is hidden for them; this guards a programmatic call).
+ if (Server.ProviderId == "import")
+ return;
+ if (!TryGetPackIdentity(out var packId, out var currentVersionId))
+ return;
+
+ ShopVersionList list;
+ try {
+ var daemon = await App.Current.DaemonReady;
+ list = await daemon.Shop.GetVersionsAsync(
+ new ShopVersionsRequest {
+ ShopId = Server.ProviderId,
+ ProjectId = packId,
+ },
+ deadline: DateTime.UtcNow.AddSeconds(30));
+ } catch (Exception) {
+ list = new ShopVersionList();
+ }
+ var current =
+ list.Versions.FirstOrDefault(v => v.Id == currentVersionId);
+ var choices =
+ list.Versions.Where(v => v.Id != currentVersionId).ToArray();
+ var currentName =
+ current is null ? currentVersionId
+ : (current.Name.Length > 0 ? current.Name
+ : current.VersionNumber);
+ var dialog =
+ new ServerUpdateModpackDialog(Server.Name, currentName, choices) {
+ XamlRoot = XamlRoot,
+ };
+ if (await dialog.ShowAsync() != ContentDialogResult.Primary)
+ return;
+ if (dialog.SelectedVersion is not {} picked)
+ return;
+ _ = _main.UpdateModpackAsync(Server, $"{packId}/{picked.Id}");
+ }
+
+ private async void OnExportModpackClick(object sender, RoutedEventArgs e) {
+ if (!TryGetPackIdentity(out _, out _))
+ return;
+ var picker = new FileSavePicker {
+ SuggestedFileName = Server.Name,
+ SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
+ };
+ picker.FileTypeChoices.Add(".zip", new List { ".zip" });
+ var hwnd =
+ WinRT.Interop.WindowNative.GetWindowHandle(App.Current.MainWindow);
+ WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd);
+
+ var file = await picker.PickSaveFileAsync();
+ if (file is not null)
+ _ = _main.ExportModpackAsync(Server, file.Path);
+ }
+
private async void OnTitleRenameClick(object sender, RoutedEventArgs e) =>
await ShowRenameDialogAsync();
diff --git a/app/JustHostMC.App/Views/ServerUpdateModpackDialog.xaml b/app/JustHostMC.App/Views/ServerUpdateModpackDialog.xaml
new file mode 100644
index 0000000..7f5fdd1
--- /dev/null
+++ b/app/JustHostMC.App/Views/ServerUpdateModpackDialog.xaml
@@ -0,0 +1,46 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/JustHostMC.App/Views/ServerUpdateModpackDialog.xaml.cs b/app/JustHostMC.App/Views/ServerUpdateModpackDialog.xaml.cs
new file mode 100644
index 0000000..d122d4b
--- /dev/null
+++ b/app/JustHostMC.App/Views/ServerUpdateModpackDialog.xaml.cs
@@ -0,0 +1,43 @@
+using JustHostMC.App.Controls;
+using McManager.Grpc;
+using Microsoft.UI.Xaml;
+using Microsoft.UI.Xaml.Controls;
+
+namespace JustHostMC.App.Views;
+
+public sealed partial class ServerUpdateModpackDialog : ContentDialog {
+ private readonly IReadOnlyList _versions;
+
+ public ServerUpdateModpackDialog(string serverName,
+ string currentVersionName,
+ IReadOnlyList versions) {
+ ServerName = serverName;
+ CurrentVersionName = currentVersionName;
+ _versions = versions;
+ VersionNames = versions.Select(DisplayName).ToArray();
+
+ InitializeComponent();
+ ContentDialogSizing.Apply(this);
+
+ var hasVersions = versions.Count > 0;
+ ChoicesPanel.Visibility =
+ hasVersions ? Visibility.Visible : Visibility.Collapsed;
+ NoVersionsText.Visibility =
+ hasVersions ? Visibility.Collapsed : Visibility.Visible;
+ if (!hasVersions)
+ PrimaryButtonText = "";
+ }
+
+ public string ServerName { get; }
+ public string CurrentVersionName { get; }
+ public IReadOnlyList VersionNames { get; }
+
+ public ShopVersion? SelectedVersion =>
+ VersionBox.SelectedIndex >= 0 &&
+ VersionBox.SelectedIndex < _versions.Count
+ ? _versions[VersionBox.SelectedIndex]
+ : null;
+
+ private static string DisplayName(ShopVersion version) =>
+ version.Name.Length > 0? version.Name : version.VersionNumber;
+}
diff --git a/app/JustHostMC.App/Views/SettingsPage.xaml b/app/JustHostMC.App/Views/SettingsPage.xaml
index 6a5e5e8..1128a1b 100644
--- a/app/JustHostMC.App/Views/SettingsPage.xaml
+++ b/app/JustHostMC.App/Views/SettingsPage.xaml
@@ -141,44 +141,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
@@ -255,7 +255,7 @@
Style="{StaticResource AccentButtonStyle}"
Tag="{x:Bind ViewModel.LatestRelease, Mode=OneWay}">
-
+
@@ -292,11 +292,22 @@
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
RowSpacing="8">
+
-
+
+
+
-
+
@@ -358,6 +369,20 @@
Foreground="{ThemeResource TextFillColorTertiaryBrush}"
Style="{StaticResource CaptionTextBlockStyle}"
Text="{x:Bind VersionNumber}" />
+
+
-
-
+
+
+
diff --git a/app/JustHostMC.App/Views/ShopDetailPage.xaml.cs b/app/JustHostMC.App/Views/ShopDetailPage.xaml.cs
index 2f2d1fb..2ed664c 100644
--- a/app/JustHostMC.App/Views/ShopDetailPage.xaml.cs
+++ b/app/JustHostMC.App/Views/ShopDetailPage.xaml.cs
@@ -95,6 +95,11 @@ private async void OnInstallClick(object sender, RoutedEventArgs e) {
return;
}
+ if (ViewModel.IsModpack) {
+ await CreateServerFlow(version);
+ return;
+ }
+
var dependencies = ViewModel.MissingDependencies(version);
IReadOnlyList chosen = [];
if (dependencies.Count > 0) {
@@ -109,6 +114,19 @@ private async void OnInstallClick(object sender, RoutedEventArgs e) {
await ViewModel.InstallAsync(version, chosen);
}
+ // Prompts for a name + memory, then creates a new server from a modpack
+ // version. The dialog owns its localized chrome and sizing in XAML.
+ private async Task CreateServerFlow(ShopVersionItem version) {
+ var fallbackName = ViewModel.Card?.Title ?? "Modpack";
+ var dialog = new CreateShopServerDialog(fallbackName) {
+ XamlRoot = XamlRoot,
+ };
+ if (await dialog.ShowAsync() != ContentDialogResult.Primary)
+ return;
+ await ViewModel.CreateServerAsync(version, dialog.ServerName,
+ dialog.MemoryMb);
+ }
+
private async void OnOpenWebsite(object sender, RoutedEventArgs e) {
await OpenWebsiteAsync();
}
diff --git a/app/JustHostMC.App/Views/ShopHomePage.xaml b/app/JustHostMC.App/Views/ShopHomePage.xaml
index 84eca1b..36bb2ee 100644
--- a/app/JustHostMC.App/Views/ShopHomePage.xaml
+++ b/app/JustHostMC.App/Views/ShopHomePage.xaml
@@ -197,20 +197,37 @@
HorizontalAlignment="Left"
VerticalAlignment="Center"
Spacing="10">
-
-
+
+
+
+
+
+
+
+
+ Visibility="{x:Bind ViewModel.ShowVersionFilter, Mode=OneWay}">
@@ -219,7 +236,7 @@
+ Visibility="{x:Bind ViewModel.ShowLoaderFilter, Mode=OneWay}">
diff --git a/app/JustHostMC.App/Views/ShopSearchPage.xaml b/app/JustHostMC.App/Views/ShopSearchPage.xaml
index 67e0dd4..c368c61 100644
--- a/app/JustHostMC.App/Views/ShopSearchPage.xaml
+++ b/app/JustHostMC.App/Views/ShopSearchPage.xaml
@@ -269,12 +269,12 @@
Click="OnVersionFilterChanged"
Content="{x:Bind ViewModel.VersionFilterLabel, Mode=OneWay}"
IsChecked="{x:Bind ViewModel.UseVersionFilter, Mode=TwoWay}"
- Visibility="{x:Bind ViewModel.HasVersionFilter}" />
+ Visibility="{x:Bind ViewModel.ShowVersionFilter, Mode=OneWay}" />
+ Visibility="{x:Bind ViewModel.ShowLoaderFilter, Mode=OneWay}" />
@@ -363,12 +363,12 @@
Click="OnVersionFilterChanged"
Content="{x:Bind ViewModel.VersionFilterLabel, Mode=OneWay}"
IsChecked="{x:Bind ViewModel.UseVersionFilter, Mode=TwoWay}"
- Visibility="{x:Bind ViewModel.HasVersionFilter}" />
+ Visibility="{x:Bind ViewModel.ShowVersionFilter, Mode=OneWay}" />
+ Visibility="{x:Bind ViewModel.ShowLoaderFilter, Mode=OneWay}" />
diff --git a/app/JustHostMC.App/Views/ShopWindow.xaml b/app/JustHostMC.App/Views/ShopWindow.xaml
index 799b5cf..eb0b5ee 100644
--- a/app/JustHostMC.App/Views/ShopWindow.xaml
+++ b/app/JustHostMC.App/Views/ShopWindow.xaml
@@ -33,6 +33,12 @@
+
+
+
+ Visibility="{x:Bind ViewModel.ShowVersionFilter, Mode=OneWay}">
+ Visibility="{x:Bind ViewModel.ShowLoaderFilter, Mode=OneWay}">
$Command $($Arguments -join ' ')" -ForegroundColor DarkGray
+ if (-not $PSBoundParameters.ContainsKey('DisplayArguments')) {
+ $DisplayArguments = $Arguments
+ }
+ Write-Host " > $Command $($DisplayArguments -join ' ')" -ForegroundColor DarkGray
$psi = [System.Diagnostics.ProcessStartInfo]::new()
$psi.FileName = $Command
@@ -158,10 +162,20 @@ if (-not $SkipEngine) {
-WorkingDirectory $EngineDir
# Optional baked-in CurseForge API key (never committed): set
- # JHMC_CURSEFORGE_API_KEY in the environment before building.
+ # JHMC_CURSEFORGE_API_KEY in the environment before building. The XOR/pad
+ # obfuscation and the ldflags fragment are produced by the shared
+ # keycipher.ps1 (the single source of truth used by every build path,
+ # including the dotnet/VS/MSIX build via app/Engine.targets). Dot-sourcing
+ # imports its functions without running its stdout/exit main block; an
+ # invalid JHMC_KEY_CIPHER_PAD throws and is surfaced by Invoke-Step. See
+ # keycipher.ps1 and engine/cmd/engine/keycipher.go for the full contract.
+ . (Join-Path $RepoRoot 'keycipher.ps1')
+
$ldflags = '-s -w -buildid='
- if ($env:JHMC_CURSEFORGE_API_KEY) {
- $ldflags += " -X main.defaultCurseForgeKey=$($env:JHMC_CURSEFORGE_API_KEY)"
+ $keyFragment = Get-CurseForgeKeyLdflagsFragment
+ Remove-Item Env:JHMC_CURSEFORGE_API_KEY -ErrorAction SilentlyContinue
+ if ($keyFragment) {
+ $ldflags += " $keyFragment"
}
Invoke-External `
@@ -170,6 +184,9 @@ if (-not $SkipEngine) {
-Arguments @('build', '-trimpath', '-buildvcs=false', '-mod=readonly',
"-ldflags=`"$ldflags`"",
'-o', "`"$EngineExe`"", './cmd/engine') `
+ -DisplayArguments @('build', '-trimpath', '-buildvcs=false', '-mod=readonly',
+ '-ldflags=""',
+ '-o', "`"$EngineExe`"", './cmd/engine') `
-WorkingDirectory $EngineDir `
-Environment @{ CGO_ENABLED = '0' }
}
diff --git a/docs/scripting.md b/docs/scripting.md
index 6da6951..5af1d78 100644
--- a/docs/scripting.md
+++ b/docs/scripting.md
@@ -523,10 +523,12 @@ Contract details:
## 9. Shop scripts (mod browsing/downloading)
Shop scripts power the app's **Mod Shop** window: browsing, searching, and
-installing mods/plugins from an online source. Built-ins live in
-`engine/internal/scripting/builtin_shops/` (`modrinth.lua`, `curseforge.lua`);
-user shops are imported via `ShopService.Import` and stored under
-`/shops/`. Grants persist in `shop-grants.json`.
+installing mods/plugins from an online source. The first-party shops now ship as
+**multi-role source scripts** in `engine/internal/scripting/builtin_sources/`
+(`modrinth.lua`, `curseforge.lua`, `ftb.lua`) — one file that declares a `shop`
+role and a hidden `provider` role (see §11); user shops are imported via
+`ShopService.Import` and stored under `/shops/`. Grants persist in
+`shop-grants.json`.
A shop script declares the usual `meta` table (plus `needs_key = true` when
the source requires an API key), five required globals, and an optional
@@ -583,6 +585,62 @@ revalidation; `ttl` seconds within which no request is made at all.
The built-in CurseForge shop uses a 24-hour (`86400` second) TTL for its
class-specific category list and keeps Mods and Plugins in separate cache keys.
+## 9a. Multi-role source scripts (`shop` + `provider` in one file)
+
+One `.lua` can fill more than one subsystem role. Instead of top-level
+functions, declare optional global **role sub-tables** alongside the shared
+`meta`, and the engine registers each role into its subsystem under the same
+`meta.id`, sharing **one** stored config entry:
+
+```lua
+meta = {
+ id = "curseforge", name = "CurseForge", version = "1.0.0", author = "JustHostMC",
+ aliases = { "curseforge_modpacks" }, -- NEW: old ids this script answers to
+ config = { { key = "api_key", type = "secret", name = "CurseForge API key" } },
+ permissions = { { kind = "network", reason = "…" }, { kind = "install", reason = "…" },
+ { kind = "fs_server", reason = "…" } },
+}
+
+shop = { -- registered into ShopSet
+ kinds = { "mod", "plugin", "modpack" }, -- role-scoped (replaces meta.kinds)
+ needs_key = true, -- role-scoped (replaces meta.needs_key)
+ home = function(ctx) … end, search = …, detail = …, versions = …, resolve_file = …,
+}
+
+provider = { -- registered into Registry
+ hidden = true, -- role-scoped (replaces meta.hidden)
+ mod_layout = "mods", -- role-scoped (replaces meta.mod_layout)
+ versions = function() return {} end,
+ install = function(ctx) … end, update = function(ctx) … end,
+}
+```
+
+Rules:
+
+- **Role-scoped fields.** When a `shop` table exists, `kinds`/`needs_key` are read
+ from it; when a `provider` table exists, `hidden`/`mod_layout` are read from it.
+ A field absent from the role table falls back to the `meta`-level value.
+- **Function resolution.** The shop adapter looks up `home`/`search`/… in the
+ `shop` table first, then top-level globals; the provider adapter looks up
+ `versions`/`install`/`update` in the `provider` table first, then top-level.
+- **Shared config.** Both roles read *and* write the same entry, keyed by
+ `meta.id` in the shop config store (`shop-config.json`). Declare each key once in
+ `meta.config` (e.g. `api_key`); both roles see it as `ctx.config.`.
+- **`meta.aliases`.** A list of prior ids the script also answers to. `Registry.Get`
+ and `ShopSet.Get` redirect an alias to this canonical entry (so servers persisted
+ under an old id keep resolving), and neither `List()` shows an alias as a
+ separate entry. Each alias must be a valid id, distinct from `meta.id` and the
+ other aliases.
+- **Back-compat.** A legacy single-role script — top-level functions with
+ `needs_key`/`kinds`/`hidden`/`mod_layout` on `meta` — keeps working unchanged;
+ role tables are purely additive.
+
+First-party sources live in `builtin_sources/` and are loaded by
+`LoadBuiltinSources(ctx, providers, shops, providerCfg)`, which registers the
+shop role into the `ShopSet` and the provider role into the `Registry`. The
+provider role's `ctx.config` is routed through `providerCfg` to the shared shop
+config store (plus any baked-key fallbacks the caller layers on).
+
## 10. Extending: fetching data from online services
The host API is deliberately composable so future features are scripts, not
diff --git a/docs/superpowers/plans/2026-07-11-ftb-parallel-update-export.md b/docs/superpowers/plans/2026-07-11-ftb-parallel-update-export.md
new file mode 100644
index 0000000..5c89963
--- /dev/null
+++ b/docs/superpowers/plans/2026-07-11-ftb-parallel-update-export.md
@@ -0,0 +1,525 @@
+# FTB Parallel Downloads + Modpack Update/Export Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Speed up FTB modpack installs with a parallel batch-download host function, and add "update modpack" (manifest diff) and "export modpack" (CurseForge client zip) for modpack servers.
+
+**Architecture:** A new Go host function `jhmc.download_all` gives single-threaded Lua a worker pool; the pack identity (`packId/versionId`) is persisted on the server record so two new streaming RPCs (`UpdateModpack`, `ExportModpack`) can act on it. The app adds two flyout items on the server header, streaming both operations through the existing global install-progress tracker.
+
+**Tech Stack:** Go (engine, gopher-lua host), Lua (ftb.lua provider), protobuf/buf, WinUI 3 C# (app).
+
+**Spec:** `docs/superpowers/specs/2026-07-11-ftb-parallel-update-export-design.md`
+
+## Global Constraints
+
+- Go tests: `go test ./...` from `engine/`. App build: `dotnet build app\JustHostMC.App\JustHostMC.App.csproj -p:Platform=x64`.
+- After editing `proto/mcmanager/v1/mcmanager.proto`: run `buf generate` from `proto/`. If Go later reports `undefined: mcmanagerv1.X`, a background VS build clobbered the stubs — just re-run `buf generate`.
+- All edited `.xaml` files MUST keep their UTF-8 BOM.
+- No `[ObservableProperty]` partial properties in C# (breaks the XAML compiler); use plain properties/`SetProperty`.
+- Localized strings go in BOTH `app\JustHostMC.App\Strings\en-US\Resources.resw` and `app\JustHostMC.App\Strings\zh-TW\Resources.resw` (folder is `zh-TW`, not zh-Hant).
+- gRPC stream sends are NOT concurrency-safe: any concurrent progress emission must be serialized with a mutex.
+- Commit after each task; message prefix `feat:`/`test:` as appropriate, ending with the Claude Co-Authored-By trailer.
+
+---
+
+### Task 1: Proto — provider_version field + UpdateModpack/ExportModpack RPCs
+
+**Files:**
+- Modify: `proto/mcmanager/v1/mcmanager.proto`
+
+**Interfaces (produces):**
+- `Server.provider_version = 11` (string)
+- `message UpdateModpackRequest { string id = 1; string version = 2; }`
+- `message ExportModpackRequest { string id = 1; string dest_path = 2; }`
+- `rpc UpdateModpack(UpdateModpackRequest) returns (stream InstallProgress);`
+- `rpc ExportModpack(ExportModpackRequest) returns (stream InstallProgress);`
+
+- [ ] **Step 1: Edit the proto.** In `message Server` (line ~36) add after `loader = 10`:
+```proto
+ // Opaque provider pack version ("packId/versionId") for modpack servers;
+ // empty for normal servers. Non-empty means update/export are available.
+ string provider_version = 11;
+```
+After `UpdateServerRequest` (line ~66) add:
+```proto
+message UpdateModpackRequest {
+ string id = 1;
+ string version = 2; // new opaque "packId/versionId"
+}
+message ExportModpackRequest {
+ string id = 1;
+ string dest_path = 2; // absolute .zip path chosen by the user
+}
+```
+In `service ServerService` (line ~748) add after `rpc Update`:
+```proto
+ rpc UpdateModpack(UpdateModpackRequest) returns (stream InstallProgress); // manifest-diff move to another pack version
+ rpc ExportModpack(ExportModpackRequest) returns (stream InstallProgress); // CurseForge client pack zip
+```
+- [ ] **Step 2: Regenerate stubs.** Run from `proto/`: `buf generate`. Expected: exit 0, `engine/gen/...` updated.
+- [ ] **Step 3: Engine still compiles.** Run from `engine/`: `go build ./...`. Expected: exit 0 (new RPCs unimplemented is fine — the generated server uses `mustEmbedUnimplemented`).
+- [ ] **Step 4: Commit** `feat(proto): provider_version + UpdateModpack/ExportModpack RPCs`.
+
+---
+
+### Task 2: Persist pack identity end-to-end
+
+**Files:**
+- Modify: `engine/internal/provider/provider.go` (LaunchSpec, ~line 19)
+- Modify: `engine/internal/scripting/host.go` (`invocation.install`, ~line 225)
+- Modify: `engine/internal/store/store.go` (Server struct + Proto, lines 15-45)
+- Modify: `engine/internal/grpc/serverservice.go` (Create bookkeeping, ~line 188)
+- Modify: `engine/internal/scripting/builtin/ftb.lua` (install return, ~line 265)
+- Test: `engine/internal/scripting/luaprovider_test.go` (extend the existing `TestInstallLaunchSpecReadsMcVersionAndLoader` pattern)
+
+**Interfaces:**
+- Produces: `provider.LaunchSpec.PackVersion string`; `store.Server.ProviderVersion string`; Lua spec key `pack_version`.
+
+- [ ] **Step 1: Write the failing test** — copy `TestInstallLaunchSpecReadsMcVersionAndLoader`, have the script return `pack_version = "95/12695"`, assert `spec.PackVersion == "95/12695"`.
+- [ ] **Step 2: Run it** — `go test ./internal/scripting/ -run PackVersion -v` → FAIL (unknown field).
+- [ ] **Step 3: Implement.**
+ - `provider.go` LaunchSpec: add `PackVersion string // opaque "packId/versionId" for modpack providers; empty otherwise`.
+ - `host.go` install() return: add `PackVersion: strField(spec, "pack_version"),`.
+ - `store.go` Server: add `ProviderVersion string`; Proto(): add `ProviderVersion: s.ProviderVersion,`.
+ - `serverservice.go` Create, next to `rec.Loader = spec.Loader` (~line 194): `rec.ProviderVersion = spec.PackVersion`.
+ - `ftb.lua` install() return table: add `pack_version = tostring(ctx.version),`.
+- [ ] **Step 4: Test passes** — `go test ./internal/scripting/ ./internal/store/... ./internal/grpc/... ` → PASS.
+- [ ] **Step 5: Commit** `feat(engine): persist modpack pack identity on the server record`.
+
+---
+
+### Task 3: `jhmc.download_all` host function (parallel worker pool)
+
+**Files:**
+- Modify: `engine/internal/scripting/hostfuncs.go` (register next to `download`, ~line 283; registration table near the `fs` table, look for `RawSetString("download", ...)`)
+- Test: `engine/internal/scripting/hostfuncs_download_all_test.go` (new)
+
+**Interfaces:**
+- Produces (Lua): `jhmc.download_all(items, opts?)`;
+ item = `{ dest = "mods/x.jar", sha1?, sha256?, url = "https://…" }` OR
+ `{ dest, sha1?, resolve = { url = "https://…", headers = { ["x-api-key"] = key } } }`;
+ opts = `{ concurrency = 6 }` (cap 16). Returns nothing; raises on first error.
+- `resolve` semantics: GET the URL with headers, expect JSON `{ "data": "" }`
+ (the CurseForge download-url convention); 403 maps to the author-disallows message.
+
+- [ ] **Step 1: Write failing tests** (httptest server; use the package's existing test helpers for building an `invocation` — see how `hostfuncs` tests construct a Host):
+ - N files download concurrently and all land at their dests with correct content.
+ - A `resolve` item fetches the JSON endpoint and downloads `data`.
+ - One 404 item fails the whole call, error names the dest, and the context cancels in-flight work (assert with a slow handler + elapsed-time bound).
+ - `sha1` mismatch fails with `provider.ErrChecksumMismatch`.
+ - Progress: emitted fractions are `completed/total` and monotonically observed count == number of files.
+- [ ] **Step 2: Run** — `go test ./internal/scripting/ -run DownloadAll -v` → FAIL (no `download_all`).
+- [ ] **Step 3: Implement** in `hostfuncs.go`:
+```go
+type batchItem struct {
+ dest, full, url string // full = resolved absolute path
+ resolveURL string
+ resolveHeaders map[string]string
+ h func() hash.Hash // sha constructor or nil
+ want string
+}
+
+// downloadAll backs jhmc.download_all: everything Lua-facing (arg parsing,
+// resolvePath) happens on the Lua thread up front; workers are pure Go.
+func (inv *invocation) downloadAll(L *lua.LState) int {
+ inv.require(L, mcmanagerv1.PermissionKind_PERMISSION_NETWORK)
+ itemsTbl := L.CheckTable(1)
+ concurrency := 6
+ if opts, ok := L.Get(2).(*lua.LTable); ok {
+ if n, ok := opts.RawGetString("concurrency").(lua.LNumber); ok && int(n) > 0 {
+ concurrency = min(int(n), 16)
+ }
+ }
+ var items []batchItem
+ var parseErr error
+ itemsTbl.ForEach(func(_, v lua.LValue) { /* build batchItem; resolvePath(L, dest);
+ strField url/sha1/sha256; nested resolve table url+headers; set parseErr on bad item */ })
+ if parseErr != nil { inv.fail(L, parseErr); return 0 }
+
+ total := len(items)
+ var done atomic.Int64
+ var emitMu sync.Mutex
+ emit := func(p provider.Progress) { emitMu.Lock(); inv.emit(p); emitMu.Unlock() }
+
+ g, ctx := errgroup.WithContext(inv.ctx)
+ g.SetLimit(concurrency)
+ for _, it := range items {
+ it := it
+ g.Go(func() error {
+ url := it.url
+ if url == "" { // resolve chain
+ u, err := resolveDownloadURL(ctx, &inv.host.client, it.resolveURL, it.resolveHeaders)
+ if err != nil { return fmt.Errorf("%s: %w", it.dest, err) }
+ url = u
+ }
+ var h hash.Hash
+ if it.h != nil { h = it.h() }
+ sum, _, err := dl.Download(ctx, &inv.host.client, url, it.full, h, nil)
+ if err != nil { return fmt.Errorf("%s: %w", it.dest, err) }
+ if it.want != "" && !strings.EqualFold(sum, it.want) {
+ return fmt.Errorf("%s: %w (got %s want %s)", it.dest, provider.ErrChecksumMismatch, sum, it.want)
+ }
+ n := done.Add(1)
+ emit(provider.Progress{Step: "shop.install.downloading",
+ Fraction: float64(n) / float64(total), LogLine: path.Base(it.dest)})
+ return nil
+ })
+ }
+ if err := g.Wait(); err != nil { inv.fail(L, err); return 0 }
+ return 0
+}
+```
+ `resolveDownloadURL` (same file): GET with headers via `http.NewRequestWithContext`, 403 → `errors.New("CurseForge denied downloading (the author disallows third-party downloads)")`, non-2xx → status error, decode `{Data string}` and require non-empty. Register: `jhmcTbl.RawSetString("download_all", L.NewFunction(inv.downloadAll))` next to the existing `download` registration. Add `golang.org/x/sync/errgroup` to go.mod if absent (`go get golang.org/x/sync/errgroup`).
+ Note: per-byte progress is intentionally NOT forwarded (pass `nil` to `dl.Download`) — per-file completion only, so fractions don't interleave across workers.
+- [ ] **Step 4: Tests pass** — `go test ./internal/scripting/ -run DownloadAll -v` → PASS.
+- [ ] **Step 5: Commit** `feat(engine): jhmc.download_all parallel batch download host function`.
+
+---
+
+### Task 4: ftb.lua uses download_all
+
+**Files:**
+- Modify: `engine/internal/scripting/builtin/ftb.lua` (`download_file`/`install_files`, lines 66-118)
+- Test: `engine/internal/scripting/builtin_ftb_test.go` if a test harness for the script exists (check for existing ftb.lua tests; else covered by Task 3 unit tests + live verify)
+
+- [ ] **Step 1: Replace `install_files`** (keep `join_path`; `download_file` is deleted):
+```lua
+-- install_files downloads every server-side file in the manifest through one
+-- parallel batch; CurseForge-hosted files resolve their real URL inside the
+-- batch workers.
+local function install_files(ctx, files)
+ local key = curseforge_key(ctx)
+ local items = {}
+ for _, f in ipairs(files) do
+ if type(f) == "table" and not f.clientonly and (f.name or "") ~= "" then
+ local dest = join_path(f.path, f.name)
+ if (f.url or "") ~= "" then
+ items[#items + 1] = { dest = dest, sha1 = f.sha1, url = f.url }
+ else
+ local cf = f.curseforge
+ if type(cf) == "table" and cf.project and cf.file then
+ if key == "" then
+ error("install failed: file " .. (f.name or dest) ..
+ " is hosted on CurseForge and needs a CurseForge API key (set it in the FTB provider settings)")
+ end
+ items[#items + 1] = { dest = dest, sha1 = f.sha1, resolve = {
+ url = "https://api.curseforge.com/v1/mods/" .. cf.project ..
+ "/files/" .. cf.file .. "/download-url",
+ headers = { ["x-api-key"] = key },
+ } }
+ else
+ error("install failed: file " .. (f.name or dest) .. " has no download source")
+ end
+ end
+ end
+ end
+ if #items == 0 then return end
+ ctx.step("shop.install.downloading", 0)
+ jhmc.download_all(items)
+end
+```
+- [ ] **Step 2: Engine tests still green** — `go test ./...` from `engine/` → PASS.
+- [ ] **Step 3: Commit** `feat(engine): parallel FTB modpack file downloads`.
+
+---
+
+### Task 5: Lua `update()` contract + LuaProvider.Update
+
+**Files:**
+- Modify: `engine/internal/provider/provider.go` (new interface)
+- Modify: `engine/internal/scripting/host.go` (new `invocation.update`, mirror `install` at line 177)
+- Modify: `engine/internal/scripting/luaprovider.go` (new method)
+- Test: `engine/internal/scripting/luaprovider_test.go`
+
+**Interfaces (produces):**
+```go
+// provider.go
+// Updater is optionally implemented by providers that can move an installed
+// server to another version in place (modpack manifest diff).
+type Updater interface {
+ Update(ctx context.Context, dir, version, oldVersion string, progress func(Progress)) (LaunchSpec, error)
+}
+var ErrUpdateUnsupported = errors.New("provider does not support update")
+```
+- Lua side: optional global `update(ctx)`; ctx has everything install's ctx has plus `ctx.old_version`.
+
+- [ ] **Step 1: Failing tests** — script with `update(ctx)` returning a spec echoing `ctx.old_version` in a field; assert `LuaProvider.Update` passes both versions and parses the spec (incl. `pack_version`). Script WITHOUT `update` → `ErrUpdateUnsupported`.
+- [ ] **Step 2: Run** — FAIL (no Update method).
+- [ ] **Step 3: Implement.** `host.go`: `func (inv *invocation) update(src, dir, version, oldVersion string) (provider.LaunchSpec, error)` — copy of `install` with: global name `"update"`, missing-function returns `provider.ErrUpdateUnsupported`, and `ictx.RawSetString("old_version", lua.LString(oldVersion))`. Extract the shared ctx-table construction and spec parsing into helpers (`installCtxTable`, `parseLaunchSpec`) used by both, so the two entry points can't drift. `luaprovider.go`:
+```go
+// Update implements provider.Updater.
+func (p *LuaProvider) Update(ctx context.Context, dir, version, oldVersion string, progress func(provider.Progress)) (provider.LaunchSpec, error) {
+ inv := &invocation{ctx: ctx, host: p.host, granted: p.grants(), report: progress, assetDir: p.assetDir, config: p.config()}
+ return inv.update(p.source, dir, version, oldVersion)
+}
+```
+- [ ] **Step 4: Tests pass; Step 5: Commit** `feat(engine): optional update() provider entry point`.
+
+---
+
+### Task 6: ftb.lua `update()` — manifest diff
+
+**Files:**
+- Modify: `engine/internal/scripting/builtin/ftb.lua` (append after `install`)
+
+- [ ] **Step 1: Implement** (reuses `read_targets`, `join_path`, `install_files`, `install_loader`):
+```lua
+-- server_files indexes a manifest's server-side files by relative dest path.
+local function server_files(manifest)
+ local by_dest = {}
+ for _, f in ipairs(manifest.files or {}) do
+ if type(f) == "table" and not f.clientonly and (f.name or "") ~= "" then
+ by_dest[join_path(f.path, f.name)] = f
+ end
+ end
+ return by_dest
+end
+
+-- update moves an installed pack to another version: files only the old
+-- version listed are deleted, new/changed ones are downloaded, and the loader
+-- is reinstalled only when its pinned version changed. Files the pack never
+-- listed (world, user configs) are untouched.
+function update(ctx)
+ local pack, ver = tostring(ctx.version):match("^([^/]+)/([^/]+)$")
+ local opack, over = tostring(ctx.old_version):match("^([^/]+)/([^/]+)$")
+ if not pack or not ver then error("invalid modpack version id: " .. tostring(ctx.version)) end
+ if not opack or not over then error("invalid modpack version id: " .. tostring(ctx.old_version)) end
+ if pack ~= opack then error("update must stay within the same pack (" .. opack .. " -> " .. pack .. ")") end
+
+ ctx.step("install.progress.resolving_version", -1)
+ local old_manifest = jhmc.http_json(FTB_API .. "/modpack/" .. opack .. "/" .. over)
+ local new_manifest = jhmc.http_json(FTB_API .. "/modpack/" .. pack .. "/" .. ver)
+ if type(old_manifest) ~= "table" or type(new_manifest) ~= "table" then
+ error("ftb: bad manifest")
+ end
+
+ local old_files, new_files = server_files(old_manifest), server_files(new_manifest)
+
+ -- Delete files the new version dropped.
+ for dest in pairs(old_files) do
+ if not new_files[dest] and jhmc.fs.exists(dest) then
+ ctx.log("- " .. dest)
+ jhmc.fs.remove(dest)
+ end
+ end
+
+ -- Download new files and files whose pack hash changed.
+ local changed = {}
+ for dest, f in pairs(new_files) do
+ local old = old_files[dest]
+ if not old or (old.sha1 or "") ~= (f.sha1 or "") then
+ changed[#changed + 1] = f
+ end
+ end
+ install_files(ctx, changed)
+
+ local mc, loader_name, loader_version = read_targets(new_manifest)
+ if not mc or mc == "" then error("ftb: modpack has no Minecraft version target") end
+ if not loader_name or loader_name == "" then error("ftb: modpack has no modloader target") end
+ local omc, oloader_name, oloader_version = read_targets(old_manifest)
+
+ local java_major = jhmc.java_major_for(mc)
+ local args
+ if loader_name ~= oloader_name or loader_version ~= oloader_version or mc ~= omc then
+ args = install_loader(ctx, loader_name, loader_version, mc, java_major)
+ end
+
+ ctx.step("install.progress.done", 1)
+ local spec = {
+ java_major = java_major,
+ mc_version = mc,
+ loader = loader_name,
+ pack_version = tostring(ctx.version),
+ }
+ spec.args = args -- nil = keep existing launch args (engine side)
+ return spec
+end
+```
+ Note: `install_files` sorts nothing; changed-list order doesn't matter. `jhmc.fs.remove` exists (hostfuncs.go:368).
+- [ ] **Step 2: Engine tests green** — `go test ./...` → PASS. **Step 3: Commit** `feat(engine): ftb.lua manifest-diff update()`.
+
+---
+
+### Task 7: ServerService.UpdateModpack RPC
+
+**Files:**
+- Modify: `engine/internal/grpc/serverservice.go` (new method after `Update`, ~line 310)
+- Test: `engine/internal/grpc/serverservice_update_test.go` (extend; see `TestUpdateVersionRefreshesLaunchSpec` for the harness)
+
+**Interfaces:**
+- Consumes: `provider.Updater`, `store.Server.ProviderVersion`, `newProgressSender`, `openInstallLog`, `maxJavaMajor`, `mapInstallError`.
+
+- [ ] **Step 1: Failing tests** (fake provider implementing Updater): happy path updates `ProviderVersion`/`McVersion`/status back to STOPPED; keeps old `LaunchArgs` when spec.Args is nil, replaces when set; rejects RUNNING server (`FailedPrecondition`); rejects server with empty `ProviderVersion`; provider error → status back to STOPPED, dir NOT deleted, record intact.
+- [ ] **Step 2: Run** — FAIL. **Step 3: Implement:**
+```go
+// UpdateModpack moves a modpack server to another pack version in place,
+// streaming progress. Unlike Create, a failure leaves the existing install
+// untouched (no cleanup wipe) — the old version keeps working.
+func (s *ServerService) UpdateModpack(req *mcmanagerv1.UpdateModpackRequest, stream grpc.ServerStreamingServer[mcmanagerv1.InstallProgress]) error {
+ ctx := stream.Context()
+ rec, ok := s.cfg.Store.Get(req.Id)
+ if !ok { return status.Error(codes.NotFound, "server not found") }
+ if rec.Status != mcmanagerv1.ServerStatus_STOPPED {
+ return status.Error(codes.FailedPrecondition, "server must be stopped")
+ }
+ if rec.ProviderVersion == "" {
+ return status.Error(codes.FailedPrecondition, "server was not installed from a modpack")
+ }
+ newVersion := strings.TrimSpace(req.Version)
+ if newVersion == "" { return status.Error(codes.InvalidArgument, "version is required") }
+ entry, ok := s.cfg.Providers.Get(rec.ProviderID)
+ if !ok { return status.Errorf(codes.Unimplemented, "provider %q not installed", rec.ProviderID) }
+ up, ok := entry.Provider.(provider.Updater)
+ if !ok { return status.Error(codes.Unimplemented, "provider does not support update") }
+
+ oldVersion := rec.ProviderVersion
+ rec.Status = mcmanagerv1.ServerStatus_INSTALLING
+ _ = s.cfg.Store.Put(rec)
+ restore := func() { rec.Status = mcmanagerv1.ServerStatus_STOPPED; _ = s.cfg.Store.Put(rec) }
+
+ il := s.openInstallLog(rec.ID)
+ defer il.Close()
+ il.recordLine("[update] " + oldVersion + " -> " + newVersion)
+ base := newProgressSender(stream)
+ send := func(p provider.Progress) { il.record(p); base(p) }
+
+ spec, err := up.Update(ctx, s.cfg.Paths.ServerDir(rec.ID), newVersion, oldVersion, send)
+ if err != nil {
+ send(provider.Progress{LogLine: "[error] " + err.Error()})
+ il.recordLine("[error] update: " + err.Error())
+ restore()
+ return mapInstallError(err)
+ }
+ resolved := rec.McVersion
+ if spec.McVersion != "" { resolved = spec.McVersion }
+ spec.JavaMajor = maxJavaMajor(spec.JavaMajor, resolved)
+ if _, err := s.cfg.JRE.EnsureJRE(ctx, spec.JavaMajor, send); err != nil {
+ send(provider.Progress{LogLine: "[error] " + err.Error()})
+ restore()
+ return mapInstallError(err)
+ }
+ rec.JavaMajor = spec.JavaMajor
+ if len(spec.Args) > 0 { rec.LaunchArgs = spec.Args }
+ if spec.McVersion != "" { rec.McVersion = spec.McVersion }
+ if spec.Loader != "" { rec.Loader = spec.Loader }
+ if spec.PackVersion != "" { rec.ProviderVersion = spec.PackVersion }
+ rec.Status = mcmanagerv1.ServerStatus_STOPPED
+ _ = s.cfg.Store.Put(rec)
+ send(provider.Progress{Step: "install.progress.done", Fraction: 1})
+ return nil
+}
+```
+- [ ] **Step 4: Tests pass. Step 5: Commit** `feat(engine): UpdateModpack RPC (manifest-diff modpack update)`.
+
+---
+
+### Task 8: ExportModpack — CurseForge zip builder + RPC
+
+**Files:**
+- Create: `engine/internal/modpack/export.go` + `export_test.go` (pure logic, testable without gRPC)
+- Modify: `engine/internal/grpc/serverservice.go` (thin RPC wrapper)
+
+**Interfaces (produces):**
+```go
+// package modpack
+// Export builds a CurseForge-format client pack zip for an FTB pack install.
+func Export(ctx context.Context, client *http.Client, o Options, progress func(provider.Progress)) error
+type Options struct {
+ ServerDir string
+ DestZip string // absolute .zip
+ PackVersion string // "packId/versionId"
+ ServerName string
+ FTBAPIBase string // default https://api.feed-the-beast.com/v1/modpacks/public; overridable in tests
+}
+```
+
+- [ ] **Step 1: Failing tests** (httptest FTB API fixture + temp server dir):
+ - `manifest.json` content: manifestType/manifestVersion/name/version, `minecraft.version`, `modLoaders[0].id` formatted `"-"` with the mc prefix stripped (reuse the ftb.lua `strip_mc_prefix` rule in Go), `files[]` includes CF entries for BOTH server and `clientonly` files, `overrides: "overrides"`.
+ - Overrides content: existing `config/`, `defaultconfigs/`, `kubejs/`, `scripts/`, `resourcepacks/`, `shaderpacks/` copied; `world/`, `logs/`, `backups/`, `libraries/`, `crash-reports/`, root `*.jar`, `server.properties`, `eula.txt`, `.jhmc*` excluded; local `mods/*.jar` NOT matched by a CF manifest entry included.
+ - `clientonly` file with direct `url` and no CF ids → downloaded into `overrides//`.
+ - Progress emits `shop.export.preparing` → downloading fractions → `shop.export.zipping` → done.
+- [ ] **Step 2: Run** — FAIL. **Step 3: Implement `export.go`:** fetch manifest JSON (struct with `Name`, `Targets []{Type,Name,Version}`, `Files []{Path,Name,URL,SHA1,Clientonly bool, Curseforge *{Project,File int64}}`); build the manifest.json struct; identify CF-covered mod filenames (set of `Name` where `Curseforge != nil`); walk allow-listed dirs + `mods/` (skipping CF-covered jars); download client-only direct-URL files to a temp staging dir; stream everything into `zip.NewWriter` (forward-slash paths, `overrides/` prefix). Serialize progress with a mutex if downloads are parallel (reuse `errgroup` pattern from Task 3, concurrency 6).
+- [ ] **Step 4: Tests pass** — `go test ./internal/modpack/ -v`.
+- [ ] **Step 5: RPC wrapper** in `serverservice.go`:
+```go
+// ExportModpack writes a CurseForge-format client pack zip for a modpack
+// server. Read-only with respect to the server dir; allowed while running.
+func (s *ServerService) ExportModpack(req *mcmanagerv1.ExportModpackRequest, stream grpc.ServerStreamingServer[mcmanagerv1.InstallProgress]) error {
+ rec, ok := s.cfg.Store.Get(req.Id)
+ if !ok { return status.Error(codes.NotFound, "server not found") }
+ if rec.ProviderVersion == "" || rec.ProviderID != "ftb" {
+ return status.Error(codes.FailedPrecondition, "server was not installed from an FTB modpack")
+ }
+ dest := req.DestPath
+ if !filepath.IsAbs(dest) || !strings.EqualFold(filepath.Ext(dest), ".zip") {
+ return status.Error(codes.InvalidArgument, "dest_path must be an absolute .zip path")
+ }
+ send := newProgressSender(stream)
+ err := modpack.Export(stream.Context(), s.httpClient(), modpack.Options{
+ ServerDir: s.cfg.Paths.ServerDir(rec.ID), DestZip: dest,
+ PackVersion: rec.ProviderVersion, ServerName: rec.Name,
+ }, send)
+ if err != nil { return status.Errorf(codes.Internal, "export: %v", err) }
+ send(provider.Progress{Step: "shop.export.done", Fraction: 1})
+ return nil
+}
+```
+ (`s.httpClient()`: check what ServerService already has; if nothing, add `HTTP *http.Client` to its cfg wired from `main.go` — same client the scripting host uses.)
+- [ ] **Step 6: `go test ./...` green. Step 7: Commit** `feat(engine): ExportModpack RPC (CurseForge client pack zip)`.
+
+---
+
+### Task 9: App — ProviderVersion + flyout items + dialogs + global-tracker streaming
+
+**Files:**
+- Modify: `app/JustHostMC.App/Models/ServerItem.cs` (add `ProviderVersion` from proto — follow how `ProviderId` is mapped/applied)
+- Modify: `app/JustHostMC.App/Controls/Server/ServerHeaderPanel.xaml` (+ `.xaml.cs`) — two `MenuFlyoutItem`s in the existing flyout (after `ServerOpenInstanceFolderMenuItem`, line ~111): `x:Uid="ServerUpdateModpackMenuItem"` (Glyph ``) and `x:Uid="ServerExportModpackMenuItem"` (Glyph ``). Visibility bound to a code-behind helper `ModpackItemVisibility(Server)` (`ProviderVersion != ""`); update item additionally disabled unless stopped. **Preserve BOM.**
+- Modify: `app/JustHostMC.App/ViewModels/MainViewModel.cs` — two new methods next to `InstallServerAsync` (line 174):
+ - `public async Task UpdateModpackAsync(ServerItem server, string version)` — clone of `InstallServerAsync`'s tracker/stream/error handling with `daemon.Servers.UpdateModpack(new UpdateModpackRequest { Id = server.Id, Version = version })`; tracker name = server name; on success `await RefreshAsync()`.
+ - `public async Task ExportModpackAsync(ServerItem server, string destPath)` — same shape over `ExportModpack`; no `RefreshAsync`; tracker `IsReadyToRun` stays false, `CurrentStep` = localized `shop.export.done` on completion.
+- Modify: `app/JustHostMC.App/Views/ServerPage.xaml.cs` — handle the two new header-panel events (follow the existing `OnBackupsClick`/BackupsDialog wiring pattern in ServerHeaderPanel → ServerPage):
+ - **Update:** dialog (imperative, like `ShopDetailPage.CreateServerFlow`) that awaits `daemon.Shop.GetVersionsAsync(new ShopVersionsRequest { ShopId = server.ProviderId, ProjectId = packId })` where `packId = server.ProviderVersion.Split('/')[0]`; ComboBox of `ShopVersion.Name` newest-first; the entry whose `Id` == current `versionId` (`Split('/')[1]`) labeled with the "current" suffix and disabled; confirm → `_ = _main.UpdateModpackAsync(server, $"{packId}/{picked.Id}")`.
+ - **Export:** `FileSavePicker` (init with `WinRT.Interop.InitializeWithWindow` — copy the existing ExportAll picker usage, see `ModsViewModel.ExportAllAsync` call site), suggested filename `$"{server.Name}.zip"`, then `_ = _main.ExportModpackAsync(server, file.Path)`.
+
+- [ ] **Step 1: ServerItem.ProviderVersion** (map in ctor + `ApplyLocal`/merge path — mirror `ProviderId` handling).
+- [ ] **Step 2: MainViewModel methods** (complete code mirroring lines 174-240, swapping the RPC call; keep `RunOnUI`, `MapErrorKey`, `ex.Status.Detail` handling identical).
+- [ ] **Step 3: Flyout items + events + handlers** as above.
+- [ ] **Step 4: Build** `dotnet build app\JustHostMC.App\JustHostMC.App.csproj -p:Platform=x64` → 0 errors.
+- [ ] **Step 5: Commit** `feat(app): modpack update and export actions`.
+
+---
+
+### Task 10: Localization
+
+**Files:**
+- Modify: `app/JustHostMC.App/Strings/en-US/Resources.resw`, `app/JustHostMC.App/Strings/zh-TW/Resources.resw`
+
+- [ ] **Step 1: Add keys to BOTH files:**
+
+| Key | en-US | zh-TW |
+|---|---|---|
+| `ServerUpdateModpackMenuItem.Text` | Update modpack… | 更新模組包… |
+| `ServerExportModpackMenuItem.Text` | Export modpack… | 匯出模組包… |
+| `Server_UpdateModpackTitle` | Update modpack | 更新模組包 |
+| `Server_UpdateModpackBody` | Pick a version for "{0}". The world and your own files are kept; pack files are replaced. | 為「{0}」選擇版本。世界與你自己的檔案會保留,模組包檔案將被更換。 |
+| `Server_UpdateModpackConfirm` | Update | 更新 |
+| `Server_UpdateModpackCurrent` | (current) | (目前版本) |
+| `Server_UpdateModpackNoVersions` | No other versions available. | 沒有其他可用版本。 |
+| `Server_ExportModpackPickerName` | CurseForge modpack | CurseForge 模組包 |
+| `shop.export.preparing` | Preparing modpack export… | 正在準備匯出模組包… |
+| `shop.export.zipping` | Packaging modpack… | 正在打包模組包… |
+| `shop.export.done` | Modpack exported. | 模組包已匯出。 |
+
+- [ ] **Step 2: Build → 0 errors. Step 3: Commit** `feat(app): modpack update/export strings`.
+
+---
+
+### Task 11: Full build + live verification
+
+- [ ] **Step 1:** `.\build.ps1` (runs buf generate + go build + go test + dotnet build + dotnet test) → all green.
+- [ ] **Step 2: Live verify** (invoke the repo `verify` skill — `.claude/skills/verify/SKILL.md` has the launch/UIA recipe):
+ 1. Install a small FTB pack from the home-page modpack shop; compare wall-clock of the `shop.install.downloading` phase against the previous serial run (log timestamps in `%LOCALAPPDATA%\JustHostMC\logs\\install-*.log`) — expect a clear speedup.
+ 2. On the new server: actions flyout shows both items; Update lists versions with the current one disabled; pick the adjacent older version → global tracker streams; server flips back to stopped; `install-*.log` shows `[update]` line, deletions (`- path`) and downloads; world/eula untouched.
+ 3. Export → save zip → open it: `manifest.json` well-formed (spot-check `files[]` count vs manifest, `modLoaders[0].id`), `overrides/config/` present, no `world/`.
+ 4. Regression: normal (non-modpack) server shows neither flyout item; create-server and mod-shop installs still work.
+- [ ] **Step 3: Commit** any fixes; final commit `feat: FTB parallel downloads, modpack update and export`.
diff --git a/docs/superpowers/specs/2026-07-11-ftb-parallel-update-export-design.md b/docs/superpowers/specs/2026-07-11-ftb-parallel-update-export-design.md
new file mode 100644
index 0000000..d71b121
--- /dev/null
+++ b/docs/superpowers/specs/2026-07-11-ftb-parallel-update-export-design.md
@@ -0,0 +1,162 @@
+# FTB modpacks: parallel downloads, update, and export
+
+Date: 2026-07-11 · Branch: `feature/modpack-support` · Status: approved
+
+## Problem
+
+1. FTB modpack installs are slow: `ftb.lua` downloads the manifest's files one at
+ a time, and every CurseForge-hosted file adds a blocking API round-trip to
+ resolve its download URL.
+2. Once installed, a modpack server is frozen: the pack identity
+ (`packId/versionId`) is discarded after install (`ServerService.Create`
+ overwrites `rec.McVersion` with the resolved MC version), so there is no way
+ to move a server to a newer pack version.
+3. Players joining a modded server need the matching client pack with the
+ server's configs. There is no way to export one.
+
+## Decisions (user-approved)
+
+- Update = **manifest diff** (like the official FTB App): delete files the new
+ version dropped, download new/changed ones; world and non-pack files
+ untouched.
+- Export = **CurseForge pack zip** (`manifest.json` + `overrides/`), importable
+ by the CurseForge app, Prism, ATLauncher.
+- UI placement: **server actions flyout** (伺服器動作), items visible only for
+ modpack servers.
+- All four pieces in one round.
+
+## 1. Parallel downloads — `jhmc.download_all`
+
+New host function in `engine/internal/scripting/hostfuncs.go`:
+
+```lua
+jhmc.download_all(items, { concurrency = 6 })
+-- item: { dest = "mods/x.jar", sha1 = "…", url = "https://…" }
+-- or: { dest = "…", sha1 = "…", resolve = { url = "https://…", headers = {…} } }
+```
+
+- `resolve` means: GET the JSON endpoint, take the `data` string field as the
+ real download URL (the CurseForge `download-url` convention), then download.
+ Resolution happens inside the worker, so CF API round-trips parallelize too.
+- Go side: worker pool (errgroup + semaphore), default concurrency 6, capped
+ (say 16). First error cancels the batch via context; the failing file's name
+ is in the error. Requires `network` permission; every `dest` goes through
+ `resolvePath` (server-dir confinement, unchanged).
+- Progress: on each completed file emit `Progress{Step: "shop.install.downloading",
+ Fraction: completed/total, LogLine: dest-basename}`. Per-byte fractions from
+ individual downloads are NOT emitted (they'd interleave across workers).
+- HTTP status/error semantics per item match today's `download_file` behavior,
+ including the CF 403 "author disallows third-party downloads" message.
+
+`ftb.lua` `install_files` builds the full item list (direct-URL files, and
+CF-hosted ones as `resolve` items with the configured key header) and makes one
+`download_all` call. The missing-CF-key check stays in Lua, up front, before
+any download starts.
+
+## 2. Persist pack identity
+
+- `ftb.lua` `install()` (and `update()`) return `pack_version = ctx.version`
+ (the opaque `"packId/versionId"`) in the launch spec.
+- Engine: new field on the provider spec struct, stored on the server registry
+ record (`ProviderVersion`), returned in the proto `Server` message as
+ `string provider_version` (new field, next free tag).
+- Empty for every non-modpack provider. The app treats "non-empty
+ provider_version" as "this is a modpack server".
+
+## 3. Update modpack
+
+**Proto:** `rpc UpdateModpack(UpdateModpackRequest) returns (stream InstallProgress)`
+on `ServerService`; request = `{ string id; string version; }` where version is
+the new `"packId/versionId"`.
+
+**Engine (`serverservice.go`):**
+- Server must be `STOPPED` (same guard style as delete/update); status flips to
+ `INSTALLING` during the run, back to `STOPPED` on success, and on failure the
+ server dir is NOT wiped (unlike create) — status returns to `STOPPED` and the
+ error is returned; the old install keeps working.
+- Looks up the provider from `rec.ProviderID`, requires it to implement the new
+ optional Lua entry point `update(ctx)`; `ctx.version` = new id,
+ `ctx.old_version` = stored `ProviderVersion`. Progress streams through the
+ same `newProgressSender` + install log as create.
+- On success: store new `ProviderVersion`, update `McVersion`/`JavaMajor`/launch
+ args from the returned spec (same post-install bookkeeping as create).
+
+**`ftb.lua` `update(ctx)`:**
+- Fetch old + new version manifests. Diff server-side files by `path+name`:
+ - present only in old → delete (via `jhmc.fs` remove).
+ - present in both with different `sha1` → re-download.
+ - present only in new → download.
+ - user files (configs they edited that the pack doesn't own, world, etc.) are
+ untouched because only manifest-listed paths are considered. A pack file
+ the user edited (sha1 differs from BOTH old and new manifest) is
+ overwritten with the new pack version — pack files belong to the pack.
+- Downloads go through `download_all`.
+- If the modloader target (name or version) changed: re-run the loader install
+ (existing `install_loader`); else keep existing launch args.
+- Returns the same spec shape as `install` (including `pack_version`).
+
+**App:**
+- `ServerActionsFlyout` (wherever 伺服器動作 menu is built): add
+ "更新模組包…" / "Update modpack…", visible iff `Server.ProviderVersion != ""`,
+ enabled iff server stopped.
+- Dialog lists versions from the existing `Shop.GetVersions(shopId, projectId)`
+ (shopId = `Server.ProviderId`, projectId = pack half of `ProviderVersion`),
+ newest first, current one marked, older ones allowed (downgrade) but the
+ current one disabled.
+- Confirm → hand off to a new `MainViewModel.UpdateModpackAsync(server, version)`
+ that streams into the global `ProgressService` tracker exactly like
+ `InstallServerAsync` (step text, log lines, error detail, `RefreshAsync`).
+
+## 4. Export modpack
+
+**Proto:** `rpc ExportModpack(ExportModpackRequest) returns (stream InstallProgress)`;
+request = `{ string id; string dest_path; }` (absolute zip path picked by the
+user, following the existing `ExportAll` dest_path pattern).
+
+**Engine:** Go-side (not Lua — needs no provider polymorphism yet; FTB-only,
+gated on `rec.ProviderID == "ftb"` + stored `ProviderVersion`):
+- Refetch the pack version manifest for `ProviderVersion`.
+- Build CurseForge pack zip:
+ - `manifest.json`: `manifestType: "minecraftModpack"`, `manifestVersion: 1`,
+ pack name (server name), `version` (pack version name), `minecraft`
+ `{ version, modLoaders: [{ id: "neoforge-"|"forge-"|"fabric-", primary: true }] }`,
+ `files[]` = every manifest file with `curseforge` project/file ids —
+ **including `clientonly` ones** — as `{ projectID, fileID, required: true }`,
+ `overrides: "overrides"`.
+ - `overrides/`: the server's live config-ish dirs (`config/`, `defaultconfigs/`,
+ `kubejs/`, `scripts/`, `resourcepacks/`, `shaderpacks/` — those that exist),
+ plus server-local mod jars NOT covered by a CF manifest entry. Excluded
+ always: `world*/`, `logs/`, `backups/`, `libraries/`, `crash-reports/`,
+ `.jhmc*`, `server.properties`, `eula.txt`, `*.jar` at root (loader/installer).
+ - `clientonly` files without CF ids (direct-URL) are downloaded at export time
+ into `overrides/` at their manifest path — hence the progress stream
+ (`shop.install.downloading` steps reuse existing localization).
+- Progress: manifest fetch → client-only downloads (fraction) → zipping → done.
+- No CurseForge API key needed (only CF-id references, no CF downloads).
+
+**App:** "匯出模組包…" / "Export modpack…" in the same flyout (visible iff
+`ProviderVersion != ""`; works while running — read-only). `FileSavePicker`
+(`.zip`, suggested name `-.zip`) → stream into the global
+tracker with a distinct step key (`shop.export.*`).
+
+## Localization
+
+New keys (en-US + zh-TW): flyout items (`ServerAction_UpdateModpack`,
+`ServerAction_ExportModpack`), update-dialog title/body/confirm, version-list
+"current" badge, export step keys (`shop.export.preparing`, `shop.export.zipping`,
+`shop.export.done`), tracker labels for update/export runs.
+
+## Testing
+
+- Go: unit tests for `download_all` (worker pool, resolve chain, error cancels
+ batch, checksum mismatch), manifest diff (delete/changed/new/user-file cases),
+ CF manifest.json builder (clientonly included, overrides exclusions).
+- Live verify: install a pack (should be visibly faster), update it to an
+ adjacent version, export it and inspect the zip's manifest.json + overrides.
+
+## Out of scope
+
+- Update/export for non-FTB modpack sources (design leaves room: `update()` is
+ a generic provider entry point; export is FTB-gated in the engine for now).
+- `.mrpack` export, server-pack export, config-only export.
+- Parallelizing non-modpack providers' downloads (they're single large files).
diff --git a/engine/cmd/engine/keycipher.go b/engine/cmd/engine/keycipher.go
new file mode 100644
index 0000000..24509d2
--- /dev/null
+++ b/engine/cmd/engine/keycipher.go
@@ -0,0 +1,69 @@
+package main
+
+import (
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "log"
+)
+
+// defaultCurseForgeKeyCipher is an optional build-time CurseForge API key,
+// XOR-obfuscated with defaultCurseForgeKeyPad and hex-encoded so it survives
+// PowerShell ldflags interpolation (CurseForge keys contain '$' and '/'). It is
+// injected with: -ldflags "-X main.defaultCurseForgeKeyCipher=". The repo
+// ships none; a user key set in Settings always wins over this default.
+//
+// NOTE: this is obfuscation, not encryption. Cipher and pad are BOTH injected at
+// build time and neither is committed, so the repo alone cannot decode the key;
+// but anyone with the built binary can (both values live in it). It keeps the
+// plaintext key out of source, out of the binary's plaintext, and out of
+// shell-mangling range.
+var defaultCurseForgeKeyCipher string
+
+// defaultCurseForgeKeyPad is the XOR pad, hex-encoded, injected alongside the
+// cipher with -ldflags "-X main.defaultCurseForgeKeyPad=". build.ps1
+// generates a fresh random pad per keyed build (or takes JHMC_KEY_CIPHER_PAD),
+// so the pad is never committed and must match the pad used to produce the
+// cipher. An empty pad (unkeyed dev build) yields no baked key.
+var defaultCurseForgeKeyPad string
+
+// decodeKeyCipher reverses the build-time obfuscation: hex-decode both the cipher
+// and the pad, then XOR the cipher bytes with the pad (cycling the pad when the
+// cipher is longer). It is a pure function of its inputs so it can be tested
+// without touching the package-level ldflags vars. It returns an error for
+// invalid hex in either argument or a zero-length pad; callers decide how to
+// degrade.
+func decodeKeyCipher(cipherHex, padHex string) (string, error) {
+ cipher, err := hex.DecodeString(cipherHex)
+ if err != nil {
+ return "", fmt.Errorf("invalid cipher hex: %w", err)
+ }
+ pad, err := hex.DecodeString(padHex)
+ if err != nil {
+ return "", fmt.Errorf("invalid pad hex: %w", err)
+ }
+ if len(pad) == 0 {
+ return "", errors.New("pad decodes to zero bytes")
+ }
+ out := make([]byte, len(cipher))
+ for i := range cipher {
+ out[i] = cipher[i] ^ pad[i%len(pad)]
+ }
+ return string(out), nil
+}
+
+// decodeDefaultCurseForgeKey decodes the ldflags-injected default CurseForge key.
+// An empty cipher OR pad yields "" silently (the normal case for an unkeyed dev
+// build). Invalid hex or a zero-length pad logs a warning and yields "" rather
+// than crashing startup.
+func decodeDefaultCurseForgeKey() string {
+ if defaultCurseForgeKeyCipher == "" || defaultCurseForgeKeyPad == "" {
+ return ""
+ }
+ key, err := decodeKeyCipher(defaultCurseForgeKeyCipher, defaultCurseForgeKeyPad)
+ if err != nil {
+ log.Printf("[WARN] baked CurseForge key: %v, ignoring", err)
+ return ""
+ }
+ return key
+}
diff --git a/engine/cmd/engine/keycipher_test.go b/engine/cmd/engine/keycipher_test.go
new file mode 100644
index 0000000..bf4a0ba
--- /dev/null
+++ b/engine/cmd/engine/keycipher_test.go
@@ -0,0 +1,244 @@
+package main
+
+import (
+ "encoding/hex"
+ "encoding/xml"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+// testPad is an arbitrary 48-byte pad (hex-encoded) used to exercise the
+// obfuscation round-trip without depending on any build-injected value.
+const testPad = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f"
+
+func repositoryFile(t *testing.T, path ...string) string {
+ t.Helper()
+ _, thisFile, _, ok := runtime.Caller(0)
+ if !ok {
+ t.Fatal("locate keycipher_test.go")
+ }
+ parts := append([]string{filepath.Dir(thisFile), "..", "..", ".."}, path...)
+ b, err := os.ReadFile(filepath.Clean(filepath.Join(parts...)))
+ if err != nil {
+ t.Fatalf("read repository file: %v", err)
+ }
+ return string(b)
+}
+
+// encodeForTest mirrors the build.ps1 Encode-CurseForgeKeyCipher helper: XOR the
+// UTF-8 key bytes with the given hex pad (cycling) and lowercase-hex the result.
+func encodeForTest(t *testing.T, key, padHex string) string {
+ t.Helper()
+ pad, err := hex.DecodeString(padHex)
+ if err != nil {
+ t.Fatalf("pad is not valid hex: %v", err)
+ }
+ kb := []byte(key)
+ out := make([]byte, len(kb))
+ for i := range kb {
+ out[i] = kb[i] ^ pad[i%len(pad)]
+ }
+ return hex.EncodeToString(out)
+}
+
+func TestDecodeKeyCipher_RoundTrip(t *testing.T) {
+ // A realistic bcrypt-style CurseForge key: contains '$', '/', and '.'.
+ const key = "$2a$10$AbCdEf/GhIjKl.MnOpQrStUvWxYz0123456789"
+
+ cipher := encodeForTest(t, key, testPad)
+ got, err := decodeKeyCipher(cipher, testPad)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != key {
+ t.Fatalf("round-trip mismatch:\n got=%q\nwant=%q", got, key)
+ }
+}
+
+func TestDecodeKeyCipher_PadShorterThanKey(t *testing.T) {
+ // Force pad cycling: a key longer than the pad. Use a short 4-byte pad.
+ const padHex = "deadbeef"
+ key := ""
+ for i := 0; i < 40; i++ {
+ key += "x"
+ }
+
+ cipher := encodeForTest(t, key, padHex)
+ got, err := decodeKeyCipher(cipher, padHex)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != key {
+ t.Fatalf("round-trip mismatch on long key:\n got=%q\nwant=%q", got, key)
+ }
+}
+
+func TestDecodeKeyCipher_EmptyCipher(t *testing.T) {
+ got, err := decodeKeyCipher("", testPad)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "" {
+ t.Fatalf("empty cipher: got %q, want \"\"", got)
+ }
+}
+
+func TestDecodeKeyCipher_EmptyPad(t *testing.T) {
+ // An empty pad string is not valid hex for a pad — it decodes to zero bytes.
+ if _, err := decodeKeyCipher("abcd", ""); err == nil {
+ t.Fatal("empty pad: expected error, got nil")
+ }
+}
+
+func TestDecodeKeyCipher_InvalidCipherHex(t *testing.T) {
+ for _, bad := range []string{"zzz", "abc", "$2a$10$notes"} {
+ if _, err := decodeKeyCipher(bad, testPad); err == nil {
+ t.Fatalf("invalid cipher hex %q: expected error, got nil", bad)
+ }
+ }
+}
+
+func TestDecodeKeyCipher_InvalidPadHex(t *testing.T) {
+ for _, bad := range []string{"zzz", "abc", "nothex"} {
+ if _, err := decodeKeyCipher("abcd", bad); err == nil {
+ t.Fatalf("invalid pad hex %q: expected error, got nil", bad)
+ }
+ }
+}
+
+func TestDecodeKeyCipher_ZeroLengthPad(t *testing.T) {
+ // "00" is a single zero byte (valid, length 1); a genuinely zero-length pad
+ // comes from an empty hex string, which is valid hex decoding to 0 bytes.
+ if _, err := decodeKeyCipher("abcd", ""); err == nil {
+ t.Fatal("zero-length pad: expected error, got nil")
+ }
+}
+
+func TestDecodeDefaultCurseForgeKey_EmptyVars(t *testing.T) {
+ // Save and restore the ldflags-injected package vars.
+ origCipher, origPad := defaultCurseForgeKeyCipher, defaultCurseForgeKeyPad
+ defer func() {
+ defaultCurseForgeKeyCipher = origCipher
+ defaultCurseForgeKeyPad = origPad
+ }()
+
+ // Any combination with an empty cipher or pad must silently yield "".
+ cases := []struct{ cipher, pad string }{
+ {"", ""},
+ {"", testPad},
+ {encodeForTest(t, "anything", testPad), ""},
+ }
+ for _, c := range cases {
+ defaultCurseForgeKeyCipher = c.cipher
+ defaultCurseForgeKeyPad = c.pad
+ if got := decodeDefaultCurseForgeKey(); got != "" {
+ t.Fatalf("cipher=%q pad=%q: got %q, want \"\"", c.cipher, c.pad, got)
+ }
+ }
+}
+
+func TestDecodeDefaultCurseForgeKey_RoundTrip(t *testing.T) {
+ const key = "$2a$10$AbCdEf/GhIjKl.MnOpQrStUvWxYz0123456789"
+
+ origCipher, origPad := defaultCurseForgeKeyCipher, defaultCurseForgeKeyPad
+ defer func() {
+ defaultCurseForgeKeyCipher = origCipher
+ defaultCurseForgeKeyPad = origPad
+ }()
+
+ defaultCurseForgeKeyCipher = encodeForTest(t, key, testPad)
+ defaultCurseForgeKeyPad = testPad
+ if got := decodeDefaultCurseForgeKey(); got != key {
+ t.Fatalf("round-trip mismatch:\n got=%q\nwant=%q", got, key)
+ }
+}
+
+func TestDecodeDefaultCurseForgeKey_InvalidHexDegrades(t *testing.T) {
+ origCipher, origPad := defaultCurseForgeKeyCipher, defaultCurseForgeKeyPad
+ defer func() {
+ defaultCurseForgeKeyCipher = origCipher
+ defaultCurseForgeKeyPad = origPad
+ }()
+
+ // Invalid cipher hex with a valid pad must degrade to "" (logged), not panic.
+ defaultCurseForgeKeyCipher = "zzz"
+ defaultCurseForgeKeyPad = testPad
+ if got := decodeDefaultCurseForgeKey(); got != "" {
+ t.Fatalf("invalid cipher hex: got %q, want \"\"", got)
+ }
+
+ // Valid cipher hex with invalid pad hex must also degrade to "".
+ defaultCurseForgeKeyCipher = "abcd"
+ defaultCurseForgeKeyPad = "zzz"
+ if got := decodeDefaultCurseForgeKey(); got != "" {
+ t.Fatalf("invalid pad hex: got %q, want \"\"", got)
+ }
+}
+
+func TestBuildConfigurationDoesNotPersistCurseForgeKey(t *testing.T) {
+ launchSettings := repositoryFile(t, "app", "JustHostMC.App", "Properties", "launchSettings.json")
+ if strings.Contains(launchSettings, "JHMC_CURSEFORGE_API_KEY") {
+ t.Fatal("launchSettings.json must not persist a CurseForge key; set it in the build environment")
+ }
+}
+
+func TestMSBuildDoesNotEchoReversibleKeyMaterial(t *testing.T) {
+ targets := repositoryFile(t, "app", "Engine.targets")
+ if strings.Contains(targets, "_CurseForgeKeyLdflags") {
+ t.Fatal("MSBuild must not store reversible key material in a property or binlog")
+ }
+ if !strings.Contains(targets, "-BuildEngine") {
+ t.Fatal("MSBuild default builds must delegate key injection to the non-echoing helper")
+ }
+ decoder := xml.NewDecoder(strings.NewReader(targets))
+ for {
+ tok, err := decoder.Token()
+ if err != nil {
+ if err == io.EOF {
+ break
+ }
+ t.Fatalf("parse Engine.targets: %v", err)
+ }
+ start, ok := tok.(xml.StartElement)
+ if !ok {
+ continue
+ }
+ attrs := make(map[string]string, len(start.Attr))
+ for _, attr := range start.Attr {
+ attrs[attr.Name.Local] = attr.Value
+ }
+ if start.Name.Local == "Message" && strings.Contains(attrs["Text"], "EngineGoBuildArgs") {
+ t.Fatal("MSBuild message must not print EngineGoBuildArgs containing the cipher and pad")
+ }
+ if start.Name.Local == "Exec" && strings.Contains(attrs["Command"], "go build $(EngineGoBuildArgs)") && attrs["EchoOff"] != "true" {
+ t.Fatal("secret-bearing go build Exec must set EchoOff=true")
+ }
+ }
+}
+
+func TestBuildScriptRedactsEngineLdflags(t *testing.T) {
+ buildScript := repositoryFile(t, "build.ps1")
+ if !strings.Contains(buildScript, "-DisplayArguments") || !strings.Contains(buildScript, "") {
+ t.Fatal("build.ps1 must supply redacted display arguments for the key-bearing engine build")
+ }
+ if !strings.Contains(buildScript, "Remove-Item Env:JHMC_CURSEFORGE_API_KEY") {
+ t.Fatal("build.ps1 must not pass the plaintext key to the child go process")
+ }
+}
+
+func TestReleaseWorkflowUsesObfuscatedKeyFragment(t *testing.T) {
+ workflow := repositoryFile(t, ".github", "workflows", "release.yml")
+ if strings.Contains(workflow, "main.defaultCurseForgeKey=") {
+ t.Fatal("release workflow must not inject the CurseForge key as plaintext")
+ }
+ if !strings.Contains(workflow, "Get-CurseForgeKeyLdflagsFragment") {
+ t.Fatal("release workflow must use the shared XOR key helper")
+ }
+ if !strings.Contains(workflow, "Remove-Item Env:JHMC_CURSEFORGE_API_KEY") {
+ t.Fatal("release workflow must not pass the plaintext key to the child go process")
+ }
+}
diff --git a/engine/cmd/engine/main.go b/engine/cmd/engine/main.go
index 852ddd5..7d16339 100644
--- a/engine/cmd/engine/main.go
+++ b/engine/cmd/engine/main.go
@@ -38,11 +38,6 @@ const (
readyLine = "MCMANAGER_READY"
)
-// defaultCurseForgeKey is an optional build-time CurseForge API key, injected
-// with: -ldflags "-X main.defaultCurseForgeKey=". The repo ships none;
-// a user key set in Settings always wins over this default.
-var defaultCurseForgeKey string
-
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -78,6 +73,8 @@ func main() {
host := scripting.NewHost(nil, jreMgr.EnsureJRE, jreMgr.EnsureJDK)
grants := scripting.NewGrantStore(filepath.Join(paths.Base, "grants.json"))
providers := scripting.NewRegistry(host, grants)
+ providerConfig := scripting.NewConfigStore(filepath.Join(paths.Base, "provider-config.json"))
+ providers.SetConfigStore(providerConfig)
if err := scripting.LoadBuiltins(ctx, providers); err != nil {
log.Fatalf("[FATAL] load builtin providers: %v", err)
}
@@ -89,6 +86,8 @@ func main() {
// embedded descriptor (fabric.mod.json, mods.toml, plugin.yml, ...).
parserGrants := scripting.NewGrantStore(filepath.Join(paths.Base, "parser-grants.json"))
parsers := scripting.NewParserSet(host, parserGrants)
+ parserConfig := scripting.NewConfigStore(filepath.Join(paths.Base, "parser-config.json"))
+ parsers.SetConfigStore(parserConfig)
if err := scripting.LoadBuiltinParsers(ctx, parsers); err != nil {
log.Fatalf("[FATAL] load builtin parsers: %v", err)
}
@@ -131,19 +130,59 @@ func main() {
// through a disk-backed ETag cache. Keyed sources resolve their API key
// from the user's settings first, then the baked-in build default.
host.SetHTTPCache(httpcache.New(paths.HTTPCache(), 0))
- bakedShopKeys := map[string]string{"curseforge": defaultCurseForgeKey}
- shopKey := func(shopID string) string {
- if s, err := settingsStore.Load(); err == nil {
- if k := s.ShopKeys[shopID]; k != "" {
- return k
- }
- }
- return bakedShopKeys[shopID]
+ // The CurseForge source (mod/plugin/modpack shop + hidden modpack provider)
+ // carries a baked-in build default key. The user's own key now lives in the
+ // shared shop-config entry (keyed "curseforge") and wins over the baked
+ // default via LuaShop.effectiveKey's flipped precedence.
+ bakedCurseForgeKey := decodeDefaultCurseForgeKey()
+ bakedShopKeys := map[string]string{
+ "curseforge": bakedCurseForgeKey,
+ "curseforge_modpacks": bakedCurseForgeKey,
}
+ // shopKey supplies only the baked build default; a stored user key is read
+ // from shop-config and takes precedence in the shop adapter.
+ shopKey := func(shopID string) string { return bakedShopKeys[shopID] }
shopGrants := scripting.NewGrantStore(filepath.Join(paths.Base, "shop-grants.json"))
shops := scripting.NewShopSet(host, shopGrants, shopKey)
- if err := scripting.LoadBuiltinShops(ctx, shops); err != nil {
- log.Fatalf("[FATAL] load builtin shops: %v", err)
+ shopConfig := scripting.NewConfigStore(filepath.Join(paths.Base, "shop-config.json"))
+ shops.SetConfigStore(shopConfig)
+ // One-time migration: fold a CurseForge key previously stored on the global
+ // Settings page (settings.json shop_keys) or under the old modpack provider
+ // config into the shared shop-config entry, so it survives the merge.
+ migrateCurseForgeKey(settingsStore, shopConfig, providerConfig)
+
+ // curseEffectiveKey resolves CurseForge's usable key: the stored shop-config
+ // api_key, else the baked build default. FTB and the local-import provider
+ // reuse it for CurseForge-hosted files.
+ curseEffectiveKey := func() string {
+ if k := shopConfig.Values("curseforge")["api_key"]; k != "" {
+ return k
+ }
+ return bakedCurseForgeKey
+ }
+ // Source provider roles read their typed config from the shared shop-config
+ // store (so both roles see one entry), with the baked key filling api_key for
+ // CurseForge and CurseForge's effective key filling FTB's curseforge_api_key.
+ sourceProviderCfg := scripting.NewFallbackConfigReader(shopConfig, "curseforge", "api_key", func() string { return bakedCurseForgeKey })
+ sourceProviderCfg = scripting.NewFallbackConfigReader(sourceProviderCfg, "ftb", "curseforge_api_key", curseEffectiveKey)
+ // The local-import provider (registered via LoadBuiltins) pulls CF-hosted
+ // files and falls back to CurseForge's effective key when its own key is
+ // unset. The raw providerConfig still backs GetConfig/SetConfig.
+ providerCfg := scripting.NewFallbackConfigReader(providerConfig, "import", "curseforge_api_key", curseEffectiveKey)
+ providers.SetConfigStore(providerCfg)
+
+ sharedSourceIDs, err := scripting.LoadBuiltinSources(ctx, providers, shops, sourceProviderCfg)
+ if err != nil {
+ log.Fatalf("[FATAL] load builtin sources: %v", err)
+ }
+ // Only providers loaded from an actual multi-role source share shop config.
+ // An unrelated provider and shop that happen to use the same id remain
+ // independent.
+ sharedSourceConfig := func(id string) *scripting.ConfigStore {
+ if sharedSourceIDs.Contains(id) {
+ return shopConfig
+ }
+ return nil
}
shopsDir := filepath.Join(paths.Base, "shops")
if err := scripting.LoadUserShops(ctx, shops, shopsDir); err != nil {
@@ -172,11 +211,10 @@ func main() {
})
settingsService := grpcsvc.NewSettingsService(grpcsvc.SettingsServiceConfig{
- Store: settingsStore,
- LogsRoot: paths.LogsRoot(),
- ActiveMode: string(activeMode),
- CloseLogs: closeLogs,
- BakedShopKeys: bakedShopKeys,
+ Store: settingsStore,
+ LogsRoot: paths.LogsRoot(),
+ ActiveMode: string(activeMode),
+ CloseLogs: closeLogs,
})
// The startup pass ran before history was restored; continue periodically.
go runLogJanitor(settingsStore, paths.LogsRoot(), closeLogs)
@@ -187,6 +225,7 @@ func main() {
// server service. They are sandboxed and permission-gated like providers.
scriptGrants := scripting.NewGrantStore(filepath.Join(paths.Base, "script-grants.json"))
scriptsEnabled := scripting.NewEnabledStore(filepath.Join(paths.Base, "scripts-enabled.json"))
+ scriptConfig := scripting.NewConfigStore(filepath.Join(paths.Base, "script-config.json"))
scripts := automation.NewManager(automation.ManagerConfig{
Host: host,
Grants: scriptGrants,
@@ -197,6 +236,7 @@ func main() {
Players: &playerManagerAdapter{events: eventBus, players: playerService},
Events: eventBus,
KV: scriptdata.NewKVStore(filepath.Join(paths.Base, "script-data")),
+ Config: scriptConfig,
})
scriptsDir := paths.ScriptsRoot()
if err := automation.LoadUserScripts(ctx, scripts, scriptsDir); err != nil {
@@ -220,10 +260,10 @@ func main() {
MetricsService: grpcsvc.NewMetricsService(serverService),
ModService: modService,
ConfigService: grpcsvc.NewConfigService(registry, paths),
- ProviderService: grpcsvc.NewProviderService(providers, grants, providersDir),
- ScriptService: grpcsvc.NewScriptService(scripts, scriptGrants, scriptsEnabled, scriptsDir),
- ParserService: grpcsvc.NewParserService(parsers, parserGrants, parsersDir),
- ShopService: grpcsvc.NewShopService(shops, shopGrants, shopsDir, registry, modService),
+ ProviderService: grpcsvc.NewProviderService(providers, grants, providerConfig, providersDir, sharedSourceConfig),
+ ScriptService: grpcsvc.NewScriptService(scripts, scriptGrants, scriptsEnabled, scriptConfig, scriptsDir),
+ ParserService: grpcsvc.NewParserService(parsers, parserGrants, parserConfig, parsersDir),
+ ShopService: grpcsvc.NewShopService(shops, shopGrants, shopConfig, shopsDir, registry, modService),
})
log.Printf("[INFO] engine data dir: %s", paths.Base)
@@ -294,6 +334,43 @@ func applyLogRetention(settingsStore *settings.Store, logsRoot string, closeLogs
// waitForShutdown gracefully stops the server when the OS signals termination or
// when the parent process goes away (our stdin reaches EOF). The latter guards
+// migrateCurseForgeKey folds a CurseForge API key stored under the pre-merge
+// layouts into the shared shop-config entry (id "curseforge", key "api_key"),
+// once. It is a no-op when the target already has a value. Sources, in order:
+// 1. settings.json shop_keys["curseforge"] (the old global Settings page card);
+// the migrated entry is then removed so key resolution stops reading it.
+// 2. the old modpack provider config "curseforge_modpacks"/"curseforge_api_key";
+// the stale provider-config entry is forgotten after copying.
+func migrateCurseForgeKey(settingsStore *settings.Store, shopConfig, providerConfig *scripting.ConfigStore) {
+ if shopConfig.Values("curseforge")["api_key"] != "" {
+ return // already migrated (or set directly) — leave it alone
+ }
+ if s, err := settingsStore.Load(); err == nil {
+ if k := s.ShopKeys["curseforge"]; k != "" {
+ if err := shopConfig.Set("curseforge", "api_key", k); err != nil {
+ log.Printf("[WARN] migrate CurseForge key from settings: %v", err)
+ } else {
+ delete(s.ShopKeys, "curseforge")
+ if err := settingsStore.Save(s); err != nil {
+ log.Printf("[WARN] clear migrated CurseForge shop key: %v", err)
+ }
+ log.Printf("[INFO] migrated CurseForge key from settings to shop config")
+ }
+ return
+ }
+ }
+ if k := providerConfig.Values("curseforge_modpacks")["curseforge_api_key"]; k != "" {
+ if err := shopConfig.Set("curseforge", "api_key", k); err != nil {
+ log.Printf("[WARN] migrate CurseForge key from provider config: %v", err)
+ return
+ }
+ if err := providerConfig.Forget("curseforge_modpacks"); err != nil {
+ log.Printf("[WARN] forget legacy modpack provider config: %v", err)
+ }
+ log.Printf("[INFO] migrated CurseForge key from provider config to shop config")
+ }
+}
+
// against leaking the engine if the app crashes without an explicit stop.
func waitForShutdown(srv interface{ GracefulStop() }, cancel context.CancelFunc) {
sig := make(chan os.Signal, 1)
diff --git a/engine/go.mod b/engine/go.mod
index ed674c2..1cd9d84 100644
--- a/engine/go.mod
+++ b/engine/go.mod
@@ -7,6 +7,7 @@ require (
github.com/Microsoft/go-winio v0.6.2
github.com/Tnze/go-mc v1.20.2
github.com/yuin/gopher-lua v1.1.2
+ golang.org/x/sync v0.20.0
golang.org/x/sys v0.46.0
google.golang.org/grpc v1.81.1
google.golang.org/protobuf v1.36.11
diff --git a/engine/internal/backup/backup.go b/engine/internal/backup/backup.go
index 451d860..06ba605 100644
--- a/engine/internal/backup/backup.go
+++ b/engine/internal/backup/backup.go
@@ -30,12 +30,8 @@ func Archive(srcDir, destZip string) error {
if err != nil {
return err
}
- defer out.Close()
-
zw := zip.NewWriter(out)
- defer zw.Close()
-
- return filepath.WalkDir(srcDir, func(path string, d os.DirEntry, walkErr error) error {
+ walkErr := filepath.WalkDir(srcDir, func(path string, d os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
@@ -51,6 +47,22 @@ func Archive(srcDir, destZip string) error {
}
return addFile(zw, path, filepath.ToSlash(rel))
})
+ if walkErr != nil {
+ _ = zw.Close()
+ _ = out.Close()
+ _ = os.Remove(destZip)
+ return walkErr
+ }
+ if err := zw.Close(); err != nil {
+ _ = out.Close()
+ _ = os.Remove(destZip)
+ return fmt.Errorf("finalize archive: %w", err)
+ }
+ if err := out.Close(); err != nil {
+ _ = os.Remove(destZip)
+ return fmt.Errorf("close archive: %w", err)
+ }
+ return nil
}
func addFile(zw *zip.Writer, path, name string) error {
diff --git a/engine/internal/grpc/configrpc.go b/engine/internal/grpc/configrpc.go
new file mode 100644
index 0000000..cd9388d
--- /dev/null
+++ b/engine/internal/grpc/configrpc.go
@@ -0,0 +1,92 @@
+package grpcsvc
+
+import (
+ "fmt"
+ "strconv"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+ "github.com/000hen/justhostmc/engine/internal/scripting"
+ "google.golang.org/grpc/codes"
+)
+
+// configOptions maps a script's declared typed config options to their proto
+// form (nil when the script declares none).
+func configOptions(opts []scripting.ConfigOption) []*mcmanagerv1.ConfigOption {
+ if len(opts) == 0 {
+ return nil
+ }
+ out := make([]*mcmanagerv1.ConfigOption, 0, len(opts))
+ for _, o := range opts {
+ out = append(out, &mcmanagerv1.ConfigOption{
+ Key: o.Key,
+ Type: o.Type,
+ Name: o.Name,
+ Description: o.Description,
+ Default: o.Default,
+ Required: o.Required,
+ })
+ }
+ return out
+}
+
+// getConfigView builds the ScriptConfig get-reply for id: one value per declared
+// option. Secrets are reported only as present (has_value), never their value.
+func getConfigView(id string, opts []scripting.ConfigOption, store *scripting.ConfigStore) *mcmanagerv1.ScriptConfig {
+ var stored map[string]string
+ if store != nil {
+ stored = store.Values(id)
+ }
+ values := make([]*mcmanagerv1.ScriptConfigValue, 0, len(opts))
+ for _, o := range opts {
+ v, has := stored[o.Key]
+ out := &mcmanagerv1.ScriptConfigValue{Key: o.Key, HasValue: has}
+ if o.Type != mcmanagerv1.ConfigOptionType_CONFIG_OPTION_SECRET {
+ out.Value = v
+ }
+ values = append(values, out)
+ }
+ return &mcmanagerv1.ScriptConfig{Id: id, Values: values}
+}
+
+// applyConfig validates and persists the requested overrides for id, then
+// returns the refreshed get-view. Unknown keys and values that don't parse for
+// their declared type are rejected; an empty value clears the override.
+func applyConfig(id string, opts []scripting.ConfigOption, store *scripting.ConfigStore, req *mcmanagerv1.SetConfigRequest) (*mcmanagerv1.ScriptConfig, error) {
+ if store == nil {
+ return nil, errorStatus(codes.FailedPrecondition, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, "config store not available", nil)
+ }
+ byKey := make(map[string]scripting.ConfigOption, len(opts))
+ for _, o := range opts {
+ byKey[o.Key] = o
+ }
+ for _, v := range req.Values {
+ o, ok := byKey[v.Key]
+ if !ok {
+ return nil, errorStatus(codes.InvalidArgument, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, fmt.Sprintf("unknown config key %q", v.Key), nil)
+ }
+ if v.Value != "" {
+ if err := validateConfigValue(o.Type, v.Value); err != nil {
+ return nil, errorStatus(codes.InvalidArgument, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, err.Error(), nil)
+ }
+ }
+ if err := store.Set(id, v.Key, v.Value); err != nil {
+ return nil, errorStatus(codes.Internal, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, err.Error(), nil)
+ }
+ }
+ return getConfigView(id, opts, store), nil
+}
+
+// validateConfigValue enforces that number/boolean overrides parse.
+func validateConfigValue(t mcmanagerv1.ConfigOptionType, val string) error {
+ switch t {
+ case mcmanagerv1.ConfigOptionType_CONFIG_OPTION_NUMBER:
+ if _, err := strconv.ParseFloat(val, 64); err != nil {
+ return fmt.Errorf("value %q is not a number", val)
+ }
+ case mcmanagerv1.ConfigOptionType_CONFIG_OPTION_BOOLEAN:
+ if _, err := strconv.ParseBool(val); err != nil {
+ return fmt.Errorf("value %q is not a boolean", val)
+ }
+ }
+ return nil
+}
diff --git a/engine/internal/grpc/configrpc_test.go b/engine/internal/grpc/configrpc_test.go
new file mode 100644
index 0000000..c0874d6
--- /dev/null
+++ b/engine/internal/grpc/configrpc_test.go
@@ -0,0 +1,86 @@
+package grpcsvc
+
+import (
+ "path/filepath"
+ "testing"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+ "github.com/000hen/justhostmc/engine/internal/scripting"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+func cfgOpts() []scripting.ConfigOption {
+ return []scripting.ConfigOption{
+ {Key: "region", Type: mcmanagerv1.ConfigOptionType_CONFIG_OPTION_STRING, Default: "us"},
+ {Key: "count", Type: mcmanagerv1.ConfigOptionType_CONFIG_OPTION_NUMBER},
+ {Key: "token", Type: mcmanagerv1.ConfigOptionType_CONFIG_OPTION_SECRET},
+ }
+}
+
+func valueByKey(sc *mcmanagerv1.ScriptConfig, key string) *mcmanagerv1.ScriptConfigValue {
+ for _, v := range sc.Values {
+ if v.Key == key {
+ return v
+ }
+ }
+ return nil
+}
+
+func setReq(id string, kv ...string) *mcmanagerv1.SetConfigRequest {
+ req := &mcmanagerv1.SetConfigRequest{Id: id}
+ for i := 0; i+1 < len(kv); i += 2 {
+ req.Values = append(req.Values, &mcmanagerv1.ScriptConfigValue{Key: kv[i], Value: kv[i+1]})
+ }
+ return req
+}
+
+func TestConfigRPCRoundTrip(t *testing.T) {
+ opts := cfgOpts()
+ store := scripting.NewConfigStore(filepath.Join(t.TempDir(), "c.json"))
+
+ // Nothing stored: every declared option appears, none has a value.
+ view := getConfigView("id", opts, store)
+ if len(view.Values) != 3 {
+ t.Fatalf("values = %d, want 3", len(view.Values))
+ }
+ if v := valueByKey(view, "region"); v.HasValue || v.Value != "" {
+ t.Fatalf("unset region: %+v", v)
+ }
+
+ // Set a string and a secret.
+ view, err := applyConfig("id", opts, store, setReq("id", "region", "eu", "token", "secret123"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if v := valueByKey(view, "region"); !v.HasValue || v.Value != "eu" {
+ t.Fatalf("region after set: %+v", v)
+ }
+ // Secret is present but never echoed back.
+ if v := valueByKey(view, "token"); !v.HasValue || v.Value != "" {
+ t.Fatalf("secret must report present without value: %+v", v)
+ }
+
+ // Unknown key is rejected.
+ if _, err := applyConfig("id", opts, store, setReq("id", "nope", "x")); status.Code(err) != codes.InvalidArgument {
+ t.Fatalf("unknown key err = %v, want InvalidArgument", err)
+ }
+ // A non-numeric value for a number option is rejected.
+ if _, err := applyConfig("id", opts, store, setReq("id", "count", "abc")); status.Code(err) != codes.InvalidArgument {
+ t.Fatalf("bad number err = %v, want InvalidArgument", err)
+ }
+
+ // An empty value clears the override.
+ view, err = applyConfig("id", opts, store, setReq("id", "region", ""))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if v := valueByKey(view, "region"); v.HasValue {
+ t.Fatalf("region should be cleared: %+v", v)
+ }
+
+ // A nil store cannot be written.
+ if _, err := applyConfig("id", opts, nil, setReq("id", "region", "eu")); status.Code(err) != codes.FailedPrecondition {
+ t.Fatalf("nil store err = %v, want FailedPrecondition", err)
+ }
+}
diff --git a/engine/internal/grpc/errors.go b/engine/internal/grpc/errors.go
index 2203948..dcb34bd 100644
--- a/engine/internal/grpc/errors.go
+++ b/engine/internal/grpc/errors.go
@@ -33,6 +33,10 @@ func mapInstallError(err error) error {
return status.FromContextError(context.Canceled).Err()
case errors.Is(err, provider.ErrVersionNotFound):
return errorStatus(codes.NotFound, mcmanagerv1.ErrorCode_VERSION_NOT_FOUND, err.Error(), nil)
+ case errors.Is(err, provider.ErrUpdateUnsupported):
+ // A provider whose script has no update() (e.g. imported packs) — surface
+ // it as Unimplemented, matching the non-Updater path in UpdateModpack.
+ return errorStatus(codes.Unimplemented, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, err.Error(), nil)
case errors.Is(err, jre.ErrJREUnavailable):
return errorStatus(codes.Unavailable, mcmanagerv1.ErrorCode_JRE_DOWNLOAD_FAILED, err.Error(), nil)
case errors.Is(err, provider.ErrChecksumMismatch):
diff --git a/engine/internal/grpc/modservice.go b/engine/internal/grpc/modservice.go
index 9649c6f..ba3a565 100644
--- a/engine/internal/grpc/modservice.go
+++ b/engine/internal/grpc/modservice.go
@@ -111,6 +111,13 @@ func (s *ModService) List(ctx context.Context, req *mcmanagerv1.ModListRequest)
return nil, status.Errorf(codes.Internal, "read %s: %v", subdir, err)
}
+ // The effective loader is the server's recorded loader (set by providers that
+ // resolve one, e.g. a modpack), falling back to the provider id.
+ serverLoader := rec.Loader
+ if serverLoader == "" {
+ serverLoader = rec.ProviderID
+ }
+
files := make([]modFileInfo, 0, len(entries))
for _, e := range entries {
if e.IsDir() || !supportedModFile(e.Name(), kind) {
@@ -131,7 +138,7 @@ func (s *ModService) List(ctx context.Context, req *mcmanagerv1.ModListRequest)
fresh := s.currentMetadataCache(req.ServerId, files)
for _, file := range files[offset:end] {
parsed := s.jarMetadata(ctx, req.ServerId, subdir, file.name, file.size, file.mtime, fresh)
- meta := selectModMetadata(parsed, rec.ProviderID, rec.McVersion, kind)
+ meta := selectModMetadata(parsed, serverLoader, rec.McVersion, kind)
meta.Icon = nil
list.Files = append(list.Files, &mcmanagerv1.ModFile{
Name: file.name,
@@ -253,7 +260,11 @@ func (s *ModService) GetIcon(ctx context.Context, req *mcmanagerv1.ModIconReques
}
s.metaCache[req.ServerId][modMetadataCacheKey(file)] = parsed
s.metaMu.Unlock()
- meta := selectModMetadata(parsed, rec.ProviderID, rec.McVersion, kind)
+ serverLoader := rec.Loader
+ if serverLoader == "" {
+ serverLoader = rec.ProviderID
+ }
+ meta := selectModMetadata(parsed, serverLoader, rec.McVersion, kind)
if !meta.HasIcon || len(meta.Icon) == 0 {
return &mcmanagerv1.ModIcon{}, nil
}
diff --git a/engine/internal/grpc/parserservice.go b/engine/internal/grpc/parserservice.go
index e6fd9f8..bc52778 100644
--- a/engine/internal/grpc/parserservice.go
+++ b/engine/internal/grpc/parserservice.go
@@ -20,13 +20,14 @@ type ParserService struct {
mcmanagerv1.UnimplementedParserServiceServer
parsers *scripting.ParserSet
grants *scripting.GrantStore
+ config *scripting.ConfigStore
dir string // root dir where user parsers are persisted
}
// NewParserService builds a ParserService. dir is where imported user parser
// scripts are stored; grants persists permission decisions.
-func NewParserService(parsers *scripting.ParserSet, grants *scripting.GrantStore, dir string) *ParserService {
- return &ParserService{parsers: parsers, grants: grants, dir: dir}
+func NewParserService(parsers *scripting.ParserSet, grants *scripting.GrantStore, config *scripting.ConfigStore, dir string) *ParserService {
+ return &ParserService{parsers: parsers, grants: grants, config: config, dir: dir}
}
func (s *ParserService) List(_ context.Context, _ *mcmanagerv1.Empty) (*mcmanagerv1.ParserList, error) {
@@ -68,6 +69,9 @@ func (s *ParserService) Remove(_ context.Context, ref *mcmanagerv1.ProviderRef)
if s.grants != nil {
_ = s.grants.Forget(ref.Id)
}
+ if s.config != nil {
+ _ = s.config.Forget(ref.Id)
+ }
_ = os.Remove(s.parserPath(ref.Id))
return &mcmanagerv1.Empty{}, nil
}
@@ -116,15 +120,32 @@ func (s *ParserService) info(p *scripting.LuaParser) *mcmanagerv1.ParserInfo {
}
slices.Sort(granted)
return &mcmanagerv1.ParserInfo{
- Id: meta.ID,
- Name: meta.Name,
- Website: meta.Website,
- Description: meta.Description,
- Version: meta.Version,
- Author: meta.Author,
- Builtin: p.Builtin(),
- Permissions: perms,
- Granted: granted,
- Formats: meta.Formats,
+ Id: meta.ID,
+ Name: meta.Name,
+ Website: meta.Website,
+ Description: meta.Description,
+ Version: meta.Version,
+ Author: meta.Author,
+ Builtin: p.Builtin(),
+ Permissions: perms,
+ Granted: granted,
+ Formats: meta.Formats,
+ ConfigOptions: configOptions(meta.Config),
+ }
+}
+
+func (s *ParserService) GetConfig(_ context.Context, ref *mcmanagerv1.ProviderRef) (*mcmanagerv1.ScriptConfig, error) {
+ p, ok := s.parsers.Get(ref.Id)
+ if !ok {
+ return nil, errorStatus(codes.NotFound, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, "parser not found", nil)
+ }
+ return getConfigView(ref.Id, p.Meta().Config, s.config), nil
+}
+
+func (s *ParserService) SetConfig(_ context.Context, req *mcmanagerv1.SetConfigRequest) (*mcmanagerv1.ScriptConfig, error) {
+ p, ok := s.parsers.Get(req.Id)
+ if !ok {
+ return nil, errorStatus(codes.NotFound, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, "parser not found", nil)
}
+ return applyConfig(req.Id, p.Meta().Config, s.config, req)
}
diff --git a/engine/internal/grpc/parserservice_test.go b/engine/internal/grpc/parserservice_test.go
index 64e2a16..d9bf0f8 100644
--- a/engine/internal/grpc/parserservice_test.go
+++ b/engine/internal/grpc/parserservice_test.go
@@ -32,11 +32,13 @@ func newTestParserService(t *testing.T) (*ParserService, *scripting.ParserSet, s
dir := t.TempDir()
grants := scripting.NewGrantStore(filepath.Join(dir, "parser-grants.json"))
ps := scripting.NewParserSet(scripting.NewHost(nil, nil, nil), grants)
+ config := scripting.NewConfigStore(filepath.Join(dir, "parser-config.json"))
+ ps.SetConfigStore(config)
if err := scripting.LoadBuiltinParsers(context.Background(), ps); err != nil {
t.Fatalf("LoadBuiltinParsers: %v", err)
}
parsersDir := filepath.Join(dir, "parsers")
- return NewParserService(ps, grants, parsersDir), ps, parsersDir
+ return NewParserService(ps, grants, config, parsersDir), ps, parsersDir
}
func TestParserServiceListIncludesBuiltins(t *testing.T) {
diff --git a/engine/internal/grpc/providerservice.go b/engine/internal/grpc/providerservice.go
index 8f6f2c6..bc87f67 100644
--- a/engine/internal/grpc/providerservice.go
+++ b/engine/internal/grpc/providerservice.go
@@ -19,13 +19,31 @@ type ProviderService struct {
mcmanagerv1.UnimplementedProviderServiceServer
registry *scripting.Registry
grants *scripting.GrantStore
- dir string // root dir where user providers are persisted
+ config *scripting.ConfigStore
+ // sharedConfig routes a provider id to an alternate store when its config
+ // entry is shared with another subsystem (a multi-role source script whose
+ // values live in the shop store). nil result (or nil func) = use config.
+ sharedConfig func(id string) *scripting.ConfigStore
+ dir string // root dir where user providers are persisted
}
// NewProviderService builds a ProviderService. dir is where imported user
-// scripts (and any bundled jars) are stored.
-func NewProviderService(reg *scripting.Registry, grants *scripting.GrantStore, dir string) *ProviderService {
- return &ProviderService{registry: reg, grants: grants, dir: dir}
+// scripts (and any bundled jars) are stored. sharedConfig may be nil.
+func NewProviderService(reg *scripting.Registry, grants *scripting.GrantStore, config *scripting.ConfigStore, dir string, sharedConfig func(id string) *scripting.ConfigStore) *ProviderService {
+ return &ProviderService{registry: reg, grants: grants, config: config, dir: dir, sharedConfig: sharedConfig}
+}
+
+// configFor picks the store backing id's config RPCs: the shared store when the
+// id belongs to a multi-role source, the provider store otherwise. Remove's
+// Forget intentionally stays on the provider store so removing a provider can
+// never wipe a live shop's shared entry.
+func (s *ProviderService) configFor(id string) *scripting.ConfigStore {
+ if s.sharedConfig != nil {
+ if cs := s.sharedConfig(id); cs != nil {
+ return cs
+ }
+ }
+ return s.config
}
func (s *ProviderService) List(_ context.Context, _ *mcmanagerv1.Empty) (*mcmanagerv1.ProviderList, error) {
@@ -83,6 +101,9 @@ func (s *ProviderService) Remove(_ context.Context, ref *mcmanagerv1.ProviderRef
if s.grants != nil {
_ = s.grants.Forget(ref.Id)
}
+ if s.config != nil {
+ _ = s.config.Forget(ref.Id)
+ }
_ = os.RemoveAll(filepath.Join(s.dir, ref.Id))
return &mcmanagerv1.Empty{}, nil
}
@@ -125,15 +146,40 @@ func (s *ProviderService) info(e *scripting.Entry) *mcmanagerv1.ProviderInfo {
}
slices.Sort(granted)
return &mcmanagerv1.ProviderInfo{
- Id: e.Meta.ID,
- Name: e.Meta.Name,
- Website: e.Meta.Website,
- Description: e.Meta.Description,
- Version: e.Meta.Version,
- Author: e.Meta.Author,
- Builtin: e.Builtin,
- Permissions: perms,
- Granted: granted,
- Capabilities: &mcmanagerv1.ProviderCapabilities{ModLayout: e.Meta.ModLayout},
+ Id: e.Meta.ID,
+ Name: e.Meta.Name,
+ Website: e.Meta.Website,
+ Description: e.Meta.Description,
+ Version: e.Meta.Version,
+ Author: e.Meta.Author,
+ Builtin: e.Builtin,
+ Permissions: perms,
+ Granted: granted,
+ Capabilities: &mcmanagerv1.ProviderCapabilities{
+ ModLayout: e.Meta.ModLayout,
+ Hidden: e.Meta.Hidden,
+ // v1: a hidden provider installs from an opaque version id, so its
+ // Versions() list is not a real picker either.
+ FreeFormVersions: e.Meta.Hidden,
+ },
+ ConfigOptions: configOptions(e.Meta.Config),
+ }
+}
+
+func (s *ProviderService) GetConfig(_ context.Context, ref *mcmanagerv1.ProviderRef) (*mcmanagerv1.ScriptConfig, error) {
+ e, ok := s.registry.Get(ref.Id)
+ if !ok {
+ return nil, errorStatus(codes.NotFound, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, "provider not found", nil)
+ }
+ // Resolve to the canonical id so an alias reads the shared config entry.
+ return getConfigView(e.Meta.ID, e.Meta.Config, s.configFor(e.Meta.ID)), nil
+}
+
+func (s *ProviderService) SetConfig(_ context.Context, req *mcmanagerv1.SetConfigRequest) (*mcmanagerv1.ScriptConfig, error) {
+ e, ok := s.registry.Get(req.Id)
+ if !ok {
+ return nil, errorStatus(codes.NotFound, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, "provider not found", nil)
}
+ // Resolve to the canonical id so an alias writes the shared config entry.
+ return applyConfig(e.Meta.ID, e.Meta.Config, s.configFor(e.Meta.ID), req)
}
diff --git a/engine/internal/grpc/scriptservice.go b/engine/internal/grpc/scriptservice.go
index bbc0186..aa08fb7 100644
--- a/engine/internal/grpc/scriptservice.go
+++ b/engine/internal/grpc/scriptservice.go
@@ -25,14 +25,15 @@ type ScriptService struct {
mgr *automation.Manager
grants *scripting.GrantStore
enabled *scripting.EnabledStore
+ config *scripting.ConfigStore
dir string // root dir where user scripts are persisted
}
// NewScriptService builds a ScriptService. dir is where imported user scripts are
// stored; grants persists permission decisions; enabled persists which scripts
// the user has turned on.
-func NewScriptService(mgr *automation.Manager, grants *scripting.GrantStore, enabled *scripting.EnabledStore, dir string) *ScriptService {
- return &ScriptService{mgr: mgr, grants: grants, enabled: enabled, dir: dir}
+func NewScriptService(mgr *automation.Manager, grants *scripting.GrantStore, enabled *scripting.EnabledStore, config *scripting.ConfigStore, dir string) *ScriptService {
+ return &ScriptService{mgr: mgr, grants: grants, enabled: enabled, config: config, dir: dir}
}
func (s *ScriptService) List(_ context.Context, _ *mcmanagerv1.Empty) (*mcmanagerv1.ScriptList, error) {
@@ -129,6 +130,9 @@ func (s *ScriptService) Remove(_ context.Context, ref *mcmanagerv1.ProviderRef)
if s.enabled != nil {
_ = s.enabled.Forget(ref.Id)
}
+ if s.config != nil {
+ _ = s.config.Forget(ref.Id)
+ }
_ = os.Remove(s.scriptPath(ref.Id))
return &mcmanagerv1.Empty{}, nil
}
@@ -187,14 +191,42 @@ func (s *ScriptService) info(a *automation.Automation) *mcmanagerv1.ScriptInfo {
}
slices.Sort(granted)
return &mcmanagerv1.ScriptInfo{
- Id: meta.ID,
- Name: meta.Name,
- Website: meta.Website,
- Description: meta.Description,
- Version: meta.Version,
- Author: meta.Author,
- Enabled: s.mgr.Enabled(meta.ID),
- Permissions: perms,
- Granted: granted,
+ Id: meta.ID,
+ Name: meta.Name,
+ Website: meta.Website,
+ Description: meta.Description,
+ Version: meta.Version,
+ Author: meta.Author,
+ Enabled: s.mgr.Enabled(meta.ID),
+ Permissions: perms,
+ Granted: granted,
+ ConfigOptions: configOptions(meta.Config),
+ }
+}
+
+func (s *ScriptService) GetConfig(_ context.Context, ref *mcmanagerv1.ProviderRef) (*mcmanagerv1.ScriptConfig, error) {
+ a, ok := s.mgr.Get(ref.Id)
+ if !ok {
+ return nil, errorStatus(codes.NotFound, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, "script not found", nil)
+ }
+ return getConfigView(ref.Id, a.Meta().Config, s.config), nil
+}
+
+func (s *ScriptService) SetConfig(_ context.Context, req *mcmanagerv1.SetConfigRequest) (*mcmanagerv1.ScriptConfig, error) {
+ a, ok := s.mgr.Get(req.Id)
+ if !ok {
+ return nil, errorStatus(codes.NotFound, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, "script not found", nil)
+ }
+ view, err := applyConfig(req.Id, a.Meta().Config, s.config, req)
+ if err != nil {
+ return nil, err
+ }
+ // Bounce an enabled script so its hooks pick up the new config on restart.
+ if s.mgr.Enabled(req.Id) {
+ s.mgr.Disable(req.Id)
+ if err := s.mgr.Enable(req.Id); err != nil {
+ return nil, errorStatus(codes.Internal, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, err.Error(), nil)
+ }
}
+ return view, nil
}
diff --git a/engine/internal/grpc/scriptservice_test.go b/engine/internal/grpc/scriptservice_test.go
index eae2339..55a350f 100644
--- a/engine/internal/grpc/scriptservice_test.go
+++ b/engine/internal/grpc/scriptservice_test.go
@@ -24,13 +24,15 @@ func newTestScriptService(t *testing.T) (*ScriptService, *automation.Manager, st
t.Helper()
dir := t.TempDir()
grants := scripting.NewGrantStore(filepath.Join(dir, "grants.json"))
+ config := scripting.NewConfigStore(filepath.Join(dir, "script-config.json"))
mgr := automation.NewManager(automation.ManagerConfig{
Host: scripting.NewHost(nil, nil, nil),
Grants: grants,
Logs: scriptlog.NewLogBuffer(0),
+ Config: config,
})
enabled := scripting.NewEnabledStore(filepath.Join(dir, "enabled.json"))
- return NewScriptService(mgr, grants, enabled, dir), mgr, dir
+ return NewScriptService(mgr, grants, enabled, config, dir), mgr, dir
}
const validScript = `
diff --git a/engine/internal/grpc/serverservice.go b/engine/internal/grpc/serverservice.go
index 6f8d794..0142005 100644
--- a/engine/internal/grpc/serverservice.go
+++ b/engine/internal/grpc/serverservice.go
@@ -3,6 +3,8 @@ package grpcsvc
import (
"context"
"fmt"
+ "io"
+ "net/http"
"os"
"path/filepath"
"strings"
@@ -11,10 +13,12 @@ import (
mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
"github.com/000hen/justhostmc/engine/internal/appdata"
+ "github.com/000hen/justhostmc/engine/internal/backup"
"github.com/000hen/justhostmc/engine/internal/console"
"github.com/000hen/justhostmc/engine/internal/isolation"
"github.com/000hen/justhostmc/engine/internal/jre"
"github.com/000hen/justhostmc/engine/internal/logging"
+ "github.com/000hen/justhostmc/engine/internal/modpack"
"github.com/000hen/justhostmc/engine/internal/provider"
"github.com/000hen/justhostmc/engine/internal/scripting"
"github.com/000hen/justhostmc/engine/internal/store"
@@ -38,6 +42,9 @@ type ServerServiceConfig struct {
// OnExit, if set, is called after a server's instance exits (stop or crash),
// e.g. to reset the player event bus roster for that server.
OnExit func(id string)
+ // HTTP, if set, is used for engine-side downloads outside the scripting
+ // host (modpack export); nil falls back to http.DefaultClient.
+ HTTP *http.Client
}
// ServerService implements the ServerService RPCs: it orchestrates the provider
@@ -162,15 +169,41 @@ func (s *ServerService) Instance(id string) (isolation.Instance, bool) {
return inst, ok
}
-// Create provisions a new server, streaming install progress, and registers it
-// ready to start.
+// Create provisions a new server from a provider version, streaming install
+// progress, and registers it ready to start.
func (s *ServerService) Create(req *mcmanagerv1.CreateServerRequest, stream grpc.ServerStreamingServer[mcmanagerv1.InstallProgress]) error {
+ return s.runCreate(stream, createParams{
+ name: req.Name,
+ providerID: req.ProviderId,
+ version: req.McVersion,
+ memoryMB: int(req.MemoryMb),
+ port: int(req.Port),
+ customJavaArgs: req.CustomJavaArgs,
+ })
+}
+
+// createParams carries the inputs shared by Create and ImportModpack.
+type createParams struct {
+ name string
+ providerID string
+ version string // opaque version handed to the provider
+ memoryMB int
+ port int
+ customJavaArgs string
+ stage func(dir string) error // optional: runs after dir creation, before install
+}
+
+// runCreate is the shared provisioning flow behind Create and ImportModpack: it
+// makes the server dir (optionally staging input into it first), runs the
+// provider install, ensures the JRE, writes server files, and persists the
+// record. Any failure wipes the new server dir.
+func (s *ServerService) runCreate(stream grpc.ServerStreamingServer[mcmanagerv1.InstallProgress], p createParams) error {
ctx := stream.Context()
- entry, ok := s.cfg.Providers.Get(req.ProviderId)
+ entry, ok := s.cfg.Providers.Get(p.providerID)
if !ok {
return errorStatus(codes.Unimplemented, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED,
- fmt.Sprintf("provider %q not installed", req.ProviderId), nil)
+ fmt.Sprintf("provider %q not installed", p.providerID), nil)
}
id := genID()
@@ -183,11 +216,11 @@ func (s *ServerService) Create(req *mcmanagerv1.CreateServerRequest, stream grpc
_ = os.RemoveAll(dir)
}
- port := resolvePort(int(req.Port))
+ port := resolvePort(p.port)
rec := &store.Server{
- ID: id, Name: req.Name, ProviderID: req.ProviderId, ModLayout: entry.Meta.ModLayout,
- McVersion: req.McVersion,
- MemoryMB: int(req.MemoryMb), Port: port, Status: mcmanagerv1.ServerStatus_INSTALLING,
+ ID: id, Name: p.name, ProviderID: p.providerID, ModLayout: entry.Meta.ModLayout,
+ McVersion: p.version,
+ MemoryMB: p.memoryMB, Port: port, Status: mcmanagerv1.ServerStatus_INSTALLING,
SortOrder: s.nextSortOrder(),
}
_ = s.cfg.Store.Put(rec)
@@ -215,12 +248,21 @@ func (s *ServerService) Create(req *mcmanagerv1.CreateServerRequest, stream grpc
il := s.openInstallLog(id)
defer il.Close()
base := newProgressSender(stream)
- send := func(p provider.Progress) {
- il.record(p)
- base(p)
+ send := func(pr provider.Progress) {
+ il.record(pr)
+ base(pr)
+ }
+
+ if p.stage != nil {
+ if err := p.stage(dir); err != nil {
+ send(provider.Progress{LogLine: "[error] " + err.Error()})
+ il.recordLine("[error] stage: " + err.Error())
+ cleanup()
+ return status.Errorf(codes.Internal, "stage modpack: %v", err)
+ }
}
- spec, err := entry.Provider.Install(installCtx, dir, req.McVersion, send)
+ spec, err := entry.Provider.Install(installCtx, dir, p.version, send)
if err != nil {
// Surface the error in the live log so the user can see what went wrong.
send(provider.Progress{LogLine: "[error] " + err.Error()})
@@ -228,7 +270,14 @@ func (s *ServerService) Create(req *mcmanagerv1.CreateServerRequest, stream grpc
cleanup()
return mapInstallError(err)
}
- spec.JavaMajor = maxJavaMajor(spec.JavaMajor, req.McVersion)
+ // A modpack provider takes an opaque "packId/versionId" as the version and
+ // resolves the concrete Minecraft version in spec.McVersion; prefer it for
+ // Java selection and the stored record.
+ resolvedVersion := p.version
+ if spec.McVersion != "" {
+ resolvedVersion = spec.McVersion
+ }
+ spec.JavaMajor = maxJavaMajor(spec.JavaMajor, resolvedVersion)
if _, err := s.cfg.JRE.EnsureJRE(installCtx, spec.JavaMajor, send); err != nil {
send(provider.Progress{LogLine: "[error] " + err.Error()})
il.recordLine("[error] jre: " + err.Error())
@@ -247,7 +296,12 @@ func (s *ServerService) Create(req *mcmanagerv1.CreateServerRequest, stream grpc
rec.JavaMajor = spec.JavaMajor
rec.LaunchArgs = spec.Args
- rec.CustomJavaArgs = req.CustomJavaArgs
+ rec.CustomJavaArgs = p.customJavaArgs
+ if spec.McVersion != "" {
+ rec.McVersion = spec.McVersion
+ }
+ rec.Loader = spec.Loader
+ rec.ProviderVersion = spec.PackVersion
rec.Status = mcmanagerv1.ServerStatus_STOPPED
_ = s.cfg.Store.Put(rec)
@@ -309,6 +363,13 @@ func (s *ServerService) Update(ctx context.Context, req *mcmanagerv1.UpdateServe
return nil, errorStatus(codes.Unimplemented, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED,
fmt.Sprintf("provider %q not installed", rec.ProviderID), nil)
}
+ // Hidden providers (e.g. a modpack) install from an opaque version id, so
+ // the version picker is meaningless; the app hides it, and this backstops
+ // a direct API edit.
+ if entry.Meta.Hidden {
+ return nil, errorStatus(codes.FailedPrecondition, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED,
+ "this server's version is managed by its source and cannot be changed", nil)
+ }
spec, err := entry.Provider.Install(ctx, dir, version, nil)
if err != nil {
return nil, mapInstallError(err)
@@ -340,6 +401,260 @@ func (s *ServerService) Update(ctx context.Context, req *mcmanagerv1.UpdateServe
return rec.Proto(), nil
}
+// UpdateModpack moves a modpack server to another pack version in place,
+// streaming progress like Create. Unlike Create, a failure leaves the existing
+// install untouched (no cleanup wipe) — the old version keeps working.
+func (s *ServerService) UpdateModpack(req *mcmanagerv1.UpdateModpackRequest, stream grpc.ServerStreamingServer[mcmanagerv1.InstallProgress]) error {
+ rec, ok := s.cfg.Store.Get(req.Id)
+ if !ok {
+ return status.Error(codes.NotFound, "server not found")
+ }
+ if rec.ProviderVersion == "" {
+ return errorStatus(codes.FailedPrecondition, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED,
+ "server was not installed from a modpack", nil)
+ }
+ if rec.Status != mcmanagerv1.ServerStatus_STOPPED {
+ return errorStatus(codes.FailedPrecondition, mcmanagerv1.ErrorCode_SERVER_RUNNING,
+ "server must be stopped before updating the modpack", nil)
+ }
+ newVersion := strings.TrimSpace(req.Version)
+ if newVersion == "" {
+ return status.Error(codes.InvalidArgument, "version is required")
+ }
+ entry, ok := s.cfg.Providers.Get(rec.ProviderID)
+ if !ok {
+ return status.Errorf(codes.Unimplemented, "provider %q not installed", rec.ProviderID)
+ }
+ up, ok := entry.Provider.(provider.Updater)
+ if !ok {
+ return status.Error(codes.Unimplemented, "provider does not support update")
+ }
+
+ updateCtx, cancelUpdate := context.WithCancel(stream.Context())
+ installation := &activeInstallation{
+ cancel: cancelUpdate,
+ done: make(chan struct{}),
+ }
+
+ // Claim the server and persist INSTALLING while holding the lifecycle lock.
+ // Start makes its reciprocal STOPPED -> STARTING transition under this same
+ // lock, so exactly one of the two operations can win.
+ s.mu.Lock()
+ rec, ok = s.cfg.Store.Get(req.Id)
+ if !ok {
+ s.mu.Unlock()
+ cancelUpdate()
+ return status.Error(codes.NotFound, "server not found")
+ }
+ if s.installations[req.Id] != nil {
+ s.mu.Unlock()
+ cancelUpdate()
+ return status.Error(codes.FailedPrecondition, "server installation is already in progress")
+ }
+ if s.instances[req.Id] != nil || rec.Status != mcmanagerv1.ServerStatus_STOPPED {
+ s.mu.Unlock()
+ cancelUpdate()
+ return errorStatus(codes.FailedPrecondition, mcmanagerv1.ErrorCode_SERVER_RUNNING,
+ "server must be stopped before updating the modpack", nil)
+ }
+ original := *rec
+ original.LaunchArgs = append([]string(nil), rec.LaunchArgs...)
+ s.installations[req.Id] = installation
+ rec.Status = mcmanagerv1.ServerStatus_INSTALLING
+ if err := s.cfg.Store.Put(rec); err != nil {
+ delete(s.installations, req.Id)
+ s.mu.Unlock()
+ cancelUpdate()
+ return status.Errorf(codes.Internal, "save update state: %v", err)
+ }
+ s.mu.Unlock()
+ defer func() {
+ cancelUpdate()
+ s.mu.Lock()
+ if s.installations[req.Id] == installation {
+ delete(s.installations, req.Id)
+ }
+ close(installation.done)
+ s.mu.Unlock()
+ }()
+
+ oldVersion := rec.ProviderVersion
+ dir := s.cfg.Paths.ServerDir(rec.ID)
+ snapshotDir := filepath.Join(s.cfg.Paths.Base, ".update-snapshots")
+ snapshotPath := filepath.Join(snapshotDir, rec.ID+"-"+genID()+".zip")
+ if err := backup.Archive(dir, snapshotPath); err != nil {
+ original.Status = mcmanagerv1.ServerStatus_STOPPED
+ if restoreErr := s.cfg.Store.Put(&original); restoreErr != nil {
+ return status.Errorf(codes.Internal, "snapshot server before update: %v; restore state: %v", err, restoreErr)
+ }
+ return status.Errorf(codes.Internal, "snapshot server before update: %v", err)
+ }
+ defer func() {
+ _ = os.Remove(snapshotPath)
+ _ = os.Remove(snapshotDir)
+ }()
+
+ rollback := func(updateErr error) error {
+ if err := backup.Restore(snapshotPath, dir); err != nil {
+ return status.Errorf(codes.Internal, "update failed (%v) and restore failed: %v", updateErr, err)
+ }
+ original.Status = mcmanagerv1.ServerStatus_STOPPED
+ if err := s.cfg.Store.Put(&original); err != nil {
+ return status.Errorf(codes.Internal, "update failed (%v) and restoring server state failed: %v", updateErr, err)
+ }
+ return mapInstallError(updateErr)
+ }
+ if err := updateCtx.Err(); err != nil {
+ return rollback(err)
+ }
+
+ il := s.openInstallLog(rec.ID)
+ defer il.Close()
+ il.recordLine("[update] " + oldVersion + " -> " + newVersion)
+ base := newProgressSender(stream)
+ send := func(p provider.Progress) {
+ il.record(p)
+ base(p)
+ }
+
+ spec, err := up.Update(updateCtx, dir, newVersion, oldVersion, send)
+ if err != nil {
+ send(provider.Progress{LogLine: "[error] " + err.Error()})
+ il.recordLine("[error] update: " + err.Error())
+ return rollback(err)
+ }
+ resolved := rec.McVersion
+ if spec.McVersion != "" {
+ resolved = spec.McVersion
+ }
+ spec.JavaMajor = maxJavaMajor(spec.JavaMajor, resolved)
+ if _, err := s.cfg.JRE.EnsureJRE(updateCtx, spec.JavaMajor, send); err != nil {
+ send(provider.Progress{LogLine: "[error] " + err.Error()})
+ il.recordLine("[error] jre: " + err.Error())
+ return rollback(err)
+ }
+ if err := updateCtx.Err(); err != nil {
+ return rollback(err)
+ }
+
+ rec.JavaMajor = spec.JavaMajor
+ if len(spec.Args) > 0 {
+ rec.LaunchArgs = spec.Args
+ }
+ if spec.McVersion != "" {
+ rec.McVersion = spec.McVersion
+ }
+ if spec.Loader != "" {
+ rec.Loader = spec.Loader
+ }
+ if spec.PackVersion != "" {
+ rec.ProviderVersion = spec.PackVersion
+ }
+ rec.Status = mcmanagerv1.ServerStatus_STOPPED
+ if err := s.cfg.Store.Put(rec); err != nil {
+ return rollback(fmt.Errorf("save updated server: %w", err))
+ }
+
+ send(provider.Progress{Step: "install.progress.done", Fraction: 1})
+ return nil
+}
+
+// ExportModpack writes a CurseForge-format client pack zip for a modpack
+// server. Read-only with respect to the server dir, so it is allowed while the
+// server runs.
+func (s *ServerService) ExportModpack(req *mcmanagerv1.ExportModpackRequest, stream grpc.ServerStreamingServer[mcmanagerv1.InstallProgress]) error {
+ rec, ok := s.cfg.Store.Get(req.Id)
+ if !ok {
+ return status.Error(codes.NotFound, "server not found")
+ }
+ // Any modpack server can be exported: providers persist a normalized
+ // manifest (.jhmc/modpack.json) that Export reads, falling back to the FTB
+ // API only for legacy FTB servers installed before manifests were persisted.
+ if rec.ProviderVersion == "" {
+ return errorStatus(codes.FailedPrecondition, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED,
+ "server was not installed from a modpack", nil)
+ }
+ dest := req.DestPath
+ if !filepath.IsAbs(dest) || !strings.EqualFold(filepath.Ext(dest), ".zip") {
+ return status.Error(codes.InvalidArgument, "dest_path must be an absolute .zip path")
+ }
+
+ client := s.cfg.HTTP
+ if client == nil {
+ client = http.DefaultClient
+ }
+ send := newProgressSender(stream)
+ if err := modpack.Export(stream.Context(), client, modpack.Options{
+ ServerDir: s.cfg.Paths.ServerDir(rec.ID),
+ DestZip: dest,
+ PackVersion: rec.ProviderVersion,
+ ServerName: rec.Name,
+ ProviderID: rec.ProviderID,
+ }, send); err != nil {
+ send(provider.Progress{LogLine: "[error] " + err.Error()})
+ return status.Errorf(codes.Internal, "export modpack: %v", err)
+ }
+ send(provider.Progress{Step: "shop.export.done", Fraction: 1})
+ return nil
+}
+
+// ImportModpack provisions a new server from a local modpack file (a CurseForge
+// client pack zip or a Modrinth .mrpack), streaming install progress like
+// Create. The file is staged into the new server dir and installed by the
+// "import" provider, which detects the format. Imported servers can be exported
+// but not updated (a local file has no upstream to diff against).
+func (s *ServerService) ImportModpack(req *mcmanagerv1.ImportModpackRequest, stream grpc.ServerStreamingServer[mcmanagerv1.InstallProgress]) error {
+ name := strings.TrimSpace(req.Name)
+ if name == "" {
+ return status.Error(codes.InvalidArgument, "server name is required")
+ }
+ src := req.SrcPath
+ if !filepath.IsAbs(src) {
+ return status.Error(codes.InvalidArgument, "src_path must be an absolute path")
+ }
+ if ext := strings.ToLower(filepath.Ext(src)); ext != ".zip" && ext != ".mrpack" {
+ return errorStatus(codes.InvalidArgument, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED,
+ "modpack file must be a .zip (CurseForge) or .mrpack (Modrinth)", nil)
+ }
+ if info, err := os.Stat(src); err != nil || info.IsDir() {
+ return status.Error(codes.InvalidArgument, "modpack file not found")
+ }
+
+ return s.runCreate(stream, createParams{
+ name: name,
+ providerID: "import",
+ version: "import/local",
+ memoryMB: int(req.MemoryMb),
+ port: int(req.Port),
+ customJavaArgs: req.CustomJavaArgs,
+ stage: func(dir string) error { return stageModpackFile(src, dir) },
+ })
+}
+
+// stageModpackFile copies the user's modpack file into the new server dir at
+// .jhmc/import.zip, where the import provider (sandboxed to the server dir) picks
+// it up. Streamed rather than read whole — packs can be hundreds of MB.
+func stageModpackFile(src, dir string) error {
+ dst := filepath.Join(dir, ".jhmc", "import.zip")
+ if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
+ return err
+ }
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer in.Close()
+ out, err := os.Create(dst)
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(out, in); err != nil {
+ out.Close()
+ return err
+ }
+ return out.Close()
+}
+
// Start launches a previously created server.
func (s *ServerService) Start(ctx context.Context, req *mcmanagerv1.ServerId) (*mcmanagerv1.Empty, error) {
rec, ok := s.cfg.Store.Get(req.Id)
@@ -347,12 +662,65 @@ func (s *ServerService) Start(ctx context.Context, req *mcmanagerv1.ServerId) (*
return nil, status.Error(codes.NotFound, "server not found")
}
+ startCtx, cancelStart := context.WithCancel(ctx)
+ operation := &activeInstallation{
+ cancel: cancelStart,
+ done: make(chan struct{}),
+ }
s.mu.Lock()
- _, running := s.instances[req.Id]
- s.mu.Unlock()
- if running {
+ if s.instances[req.Id] != nil {
+ s.mu.Unlock()
+ cancelStart()
return &mcmanagerv1.Empty{}, nil // idempotent
}
+ if s.installations[req.Id] != nil {
+ s.mu.Unlock()
+ cancelStart()
+ return nil, status.Error(codes.FailedPrecondition, "server installation is in progress")
+ }
+ rec, ok = s.cfg.Store.Get(req.Id)
+ if !ok {
+ s.mu.Unlock()
+ cancelStart()
+ return nil, status.Error(codes.NotFound, "server not found")
+ }
+ if rec.Status == mcmanagerv1.ServerStatus_STARTING {
+ s.mu.Unlock()
+ cancelStart()
+ return &mcmanagerv1.Empty{}, nil
+ }
+ if rec.Status == mcmanagerv1.ServerStatus_INSTALLING {
+ s.mu.Unlock()
+ cancelStart()
+ return nil, status.Error(codes.FailedPrecondition, "server installation is in progress")
+ }
+ previousStatus := rec.Status
+ s.installations[req.Id] = operation
+ rec.Status = mcmanagerv1.ServerStatus_STARTING
+ if err := s.cfg.Store.Put(rec); err != nil {
+ delete(s.installations, req.Id)
+ close(operation.done)
+ s.mu.Unlock()
+ cancelStart()
+ return nil, status.Errorf(codes.Internal, "save start state: %v", err)
+ }
+ s.mu.Unlock()
+ defer func() {
+ cancelStart()
+ s.mu.Lock()
+ if s.installations[req.Id] == operation {
+ delete(s.installations, req.Id)
+ }
+ close(operation.done)
+ s.mu.Unlock()
+ }()
+ restoreStatus := func() {
+ latest, exists := s.cfg.Store.Get(req.Id)
+ if exists && latest.Status == mcmanagerv1.ServerStatus_STARTING {
+ latest.Status = previousStatus
+ _ = s.cfg.Store.Put(latest)
+ }
+ }
javaMajor := maxJavaMajor(rec.JavaMajor, rec.McVersion)
if javaMajor != rec.JavaMajor {
@@ -360,12 +728,13 @@ func (s *ServerService) Start(ctx context.Context, req *mcmanagerv1.ServerId) (*
_ = s.cfg.Store.Put(rec)
}
- javaPath, err := s.cfg.JRE.EnsureJRE(ctx, javaMajor, nil)
+ javaPath, err := s.cfg.JRE.EnsureJRE(startCtx, javaMajor, nil)
if err != nil {
+ restoreStatus()
return nil, mapInstallError(err)
}
- inst, err := s.cfg.Backend.Start(ctx, isolation.InstanceSpec{
+ inst, err := s.cfg.Backend.Start(startCtx, isolation.InstanceSpec{
ID: rec.ID,
Dir: s.cfg.Paths.ServerDir(rec.ID),
JavaPath: javaPath,
@@ -375,21 +744,44 @@ func (s *ServerService) Start(ctx context.Context, req *mcmanagerv1.ServerId) (*
Port: rec.Port,
})
if err != nil {
+ restoreStatus()
+ if startCtx.Err() != nil {
+ return nil, status.FromContextError(startCtx.Err()).Err()
+ }
return nil, status.Errorf(codes.Internal, "start server: %v", err)
}
s.mu.Lock()
+ if startCtx.Err() != nil {
+ s.mu.Unlock()
+ cleanupCtx, cancelCleanup := context.WithTimeout(context.Background(), 30*time.Second)
+ _ = s.cfg.Backend.Stop(cleanupCtx, req.Id, false)
+ select {
+ case <-inst.Done():
+ case <-cleanupCtx.Done():
+ }
+ cancelCleanup()
+ restoreStatus()
+ return nil, status.FromContextError(startCtx.Err()).Err()
+ }
s.instances[rec.ID] = inst
delete(s.stopping, rec.ID)
+ rec.Status = mcmanagerv1.ServerStatus_RUNNING
+ if err := s.cfg.Store.Put(rec); err != nil {
+ delete(s.instances, rec.ID)
+ s.mu.Unlock()
+ cleanupCtx, cancelCleanup := context.WithTimeout(context.Background(), 30*time.Second)
+ _ = s.cfg.Backend.Stop(cleanupCtx, req.Id, false)
+ cancelCleanup()
+ restoreStatus()
+ return nil, status.Errorf(codes.Internal, "save running state: %v", err)
+ }
s.mu.Unlock()
if s.cfg.Console != nil {
s.cfg.Console.Register(rec.ID, inst)
}
- rec.Status = mcmanagerv1.ServerStatus_RUNNING
- _ = s.cfg.Store.Put(rec)
-
go s.watchExit(rec.ID, inst)
return &mcmanagerv1.Empty{}, nil
}
@@ -403,11 +795,36 @@ func (s *ServerService) Stop(ctx context.Context, req *mcmanagerv1.ServerId) (*m
s.mu.Lock()
inst := s.instances[req.Id]
+ operation := s.installations[req.Id]
if inst != nil {
s.stopping[req.Id] = true
}
+ if operation != nil {
+ operation.cancel()
+ }
s.mu.Unlock()
+ if operation != nil {
+ select {
+ case <-operation.done:
+ case <-ctx.Done():
+ return nil, status.FromContextError(ctx.Err()).Err()
+ }
+ // The operation may have published an instance immediately before Stop
+ // acquired the lifecycle lock, so refresh both persisted and live state.
+ latest, exists := s.cfg.Store.Get(req.Id)
+ if !exists {
+ return &mcmanagerv1.Empty{}, nil
+ }
+ rec = latest
+ s.mu.Lock()
+ inst = s.instances[req.Id]
+ if inst != nil {
+ s.stopping[req.Id] = true
+ }
+ s.mu.Unlock()
+ }
+
if inst == nil {
rec.Status = mcmanagerv1.ServerStatus_STOPPED
_ = s.cfg.Store.Put(rec)
@@ -479,14 +896,26 @@ func (s *ServerService) Delete(ctx context.Context, req *mcmanagerv1.ServerId) (
// lives at the data-dir root (not under a wiped subtree), so its open handle stays
// valid and the engine keeps running afterwards.
func (s *ServerService) RemoveAllData(ctx context.Context, _ *mcmanagerv1.Empty) (*mcmanagerv1.Empty, error) {
- // Snapshot and force-stop every running instance.
+ // Snapshot and cancel every active operation before wiping its data.
s.mu.Lock()
insts := make(map[string]isolation.Instance, len(s.instances))
for id, inst := range s.instances {
insts[id] = inst
s.stopping[id] = true
}
+ installations := make([]*activeInstallation, 0, len(s.installations))
+ for _, installation := range s.installations {
+ installation.cancel()
+ installations = append(installations, installation)
+ }
s.mu.Unlock()
+ for _, installation := range installations {
+ select {
+ case <-installation.done:
+ case <-ctx.Done():
+ return nil, status.FromContextError(ctx.Err()).Err()
+ }
+ }
for id, inst := range insts {
_ = s.cfg.Backend.Stop(ctx, id, false)
@@ -527,6 +956,7 @@ func (s *ServerService) RemoveAllData(ctx context.Context, _ *mcmanagerv1.Empty)
s.mu.Lock()
s.instances = make(map[string]isolation.Instance)
s.stopping = make(map[string]bool)
+ s.installations = make(map[string]*activeInstallation)
s.mu.Unlock()
return &mcmanagerv1.Empty{}, nil
diff --git a/engine/internal/grpc/serverservice_importmodpack_test.go b/engine/internal/grpc/serverservice_importmodpack_test.go
new file mode 100644
index 0000000..87d4912
--- /dev/null
+++ b/engine/internal/grpc/serverservice_importmodpack_test.go
@@ -0,0 +1,117 @@
+package grpcsvc
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+ "github.com/000hen/justhostmc/engine/internal/appdata"
+ "github.com/000hen/justhostmc/engine/internal/jre"
+ "github.com/000hen/justhostmc/engine/internal/provider"
+ "github.com/000hen/justhostmc/engine/internal/store"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+// importStubProvider records the dir/version it was installed with and whether
+// the modpack file was staged into the server dir before install ran.
+type importStubProvider struct {
+ spec provider.LaunchSpec
+ stagedSeen bool
+ gotVersion string
+}
+
+func (p *importStubProvider) Versions(context.Context) ([]string, error) { return nil, nil }
+func (p *importStubProvider) Install(_ context.Context, dir, version string, _ func(provider.Progress)) (provider.LaunchSpec, error) {
+ p.gotVersion = version
+ if _, err := os.Stat(filepath.Join(dir, ".jhmc", "import.zip")); err == nil {
+ p.stagedSeen = true
+ }
+ return p.spec, nil
+}
+
+func importTestService(t *testing.T, prov provider.Provider) (*ServerService, *store.Memory) {
+ t.Helper()
+ paths := appdata.New(t.TempDir())
+ cacheJava(t, paths.JRECache(), 21)
+ st := store.NewMemory()
+ svc := NewServerService(ServerServiceConfig{
+ Store: st,
+ Providers: testRegistry("import", "mods", prov),
+ Paths: paths,
+ JRE: jre.NewManager(paths.JRECache()),
+ })
+ return svc, st
+}
+
+func writeTempFile(t *testing.T, name, content string) string {
+ t.Helper()
+ p := filepath.Join(t.TempDir(), name)
+ if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return p
+}
+
+func TestImportModpackStagesAndCreates(t *testing.T) {
+ prov := &importStubProvider{spec: provider.LaunchSpec{
+ JavaMajor: 21, McVersion: "1.20.1", Loader: "forge",
+ Args: []string{"@run"}, PackVersion: "import/1.0",
+ }}
+ svc, st := importTestService(t, prov)
+ src := writeTempFile(t, "pack.zip", "PK fake zip")
+
+ if err := svc.ImportModpack(&mcmanagerv1.ImportModpackRequest{
+ Name: "My Import", SrcPath: src, MemoryMb: 4096,
+ }, &fakeInstallStream{}); err != nil {
+ t.Fatalf("ImportModpack: %v", err)
+ }
+ if !prov.stagedSeen {
+ t.Error("staged .jhmc/import.zip missing when the provider ran")
+ }
+ if prov.gotVersion != "import/local" {
+ t.Errorf("provider version = %q, want import/local", prov.gotVersion)
+ }
+ servers := st.List()
+ if len(servers) != 1 {
+ t.Fatalf("servers = %d, want 1", len(servers))
+ }
+ rec := servers[0]
+ if rec.Name != "My Import" || rec.ProviderID != "import" || rec.ProviderVersion != "import/1.0" {
+ t.Errorf("record = %+v", rec)
+ }
+ if rec.Status != mcmanagerv1.ServerStatus_STOPPED {
+ t.Errorf("status = %v, want STOPPED", rec.Status)
+ }
+ if rec.McVersion != "1.20.1" || rec.Loader != "forge" {
+ t.Errorf("record mc/loader = %q/%q", rec.McVersion, rec.Loader)
+ }
+}
+
+func TestImportModpackValidation(t *testing.T) {
+ svc, st := importTestService(t, &importStubProvider{})
+ good := writeTempFile(t, "ok.zip", "z")
+
+ cases := []struct {
+ name string
+ req *mcmanagerv1.ImportModpackRequest
+ }{
+ {"empty name", &mcmanagerv1.ImportModpackRequest{Name: " ", SrcPath: good}},
+ {"relative path", &mcmanagerv1.ImportModpackRequest{Name: "n", SrcPath: "pack.zip"}},
+ {"bad extension", &mcmanagerv1.ImportModpackRequest{Name: "n", SrcPath: writeTempFile(t, "pack.rar", "z")}},
+ {"missing file", &mcmanagerv1.ImportModpackRequest{Name: "n", SrcPath: filepath.Join(t.TempDir(), "nope.zip")}},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ err := svc.ImportModpack(c.req, &fakeInstallStream{})
+ if status.Code(err) != codes.InvalidArgument {
+ t.Fatalf("code = %v, want InvalidArgument (err=%v)", status.Code(err), err)
+ }
+ })
+ }
+ if n := len(st.List()); n != 0 {
+ t.Errorf("no server should be created on validation failure, got %d", n)
+ }
+}
diff --git a/engine/internal/grpc/serverservice_start_test.go b/engine/internal/grpc/serverservice_start_test.go
index 482ef0f..f764e64 100644
--- a/engine/internal/grpc/serverservice_start_test.go
+++ b/engine/internal/grpc/serverservice_start_test.go
@@ -2,18 +2,35 @@ package grpcsvc
import (
"context"
+ "errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
+ "time"
mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
"github.com/000hen/justhostmc/engine/internal/appdata"
+ "github.com/000hen/justhostmc/engine/internal/isolation"
"github.com/000hen/justhostmc/engine/internal/jre"
"github.com/000hen/justhostmc/engine/internal/store"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
)
+type blockingStartBackend struct {
+ fakeBackend
+ started chan struct{}
+}
+
+func (b *blockingStartBackend) Start(ctx context.Context, spec isolation.InstanceSpec) (isolation.Instance, error) {
+ b.startSpec = spec
+ close(b.started)
+ <-ctx.Done()
+ return nil, ctx.Err()
+}
+
func TestStartUpgradesStaleJavaMajorForCurrentMinecraft(t *testing.T) {
paths := appdata.New(t.TempDir())
cacheJava(t, paths.JRECache(), 25)
@@ -50,6 +67,108 @@ func TestStartUpgradesStaleJavaMajorForCurrentMinecraft(t *testing.T) {
}
}
+func TestDeleteCancelsAndWaitsForStart(t *testing.T) {
+ svc, st, paths, backend := startRaceService(t)
+ startDone := make(chan error, 1)
+ go func() {
+ _, err := svc.Start(context.Background(), &mcmanagerv1.ServerId{Id: "s1"})
+ startDone <- err
+ }()
+ waitForStart(t, backend.started)
+
+ if _, err := svc.Delete(context.Background(), &mcmanagerv1.ServerId{Id: "s1"}); err != nil {
+ t.Fatalf("Delete: %v", err)
+ }
+ if err := <-startDone; status.Code(err) != codes.Canceled {
+ t.Fatalf("Start error = %v, want context canceled", err)
+ }
+ if _, ok := st.Get("s1"); ok {
+ t.Fatal("canceled Start resurrected deleted server")
+ }
+ if _, err := os.Stat(paths.ServerDir("s1")); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("server directory still exists after delete: %v", err)
+ }
+}
+
+func TestRemoveAllDataCancelsAndWaitsForStart(t *testing.T) {
+ svc, st, paths, backend := startRaceService(t)
+ startDone := make(chan error, 1)
+ go func() {
+ _, err := svc.Start(context.Background(), &mcmanagerv1.ServerId{Id: "s1"})
+ startDone <- err
+ }()
+ waitForStart(t, backend.started)
+
+ if _, err := svc.RemoveAllData(context.Background(), &mcmanagerv1.Empty{}); err != nil {
+ t.Fatalf("RemoveAllData: %v", err)
+ }
+ if err := <-startDone; status.Code(err) != codes.Canceled {
+ t.Fatalf("Start error = %v, want context canceled", err)
+ }
+ if _, ok := st.Get("s1"); ok {
+ t.Fatal("canceled Start resurrected server after RemoveAllData")
+ }
+ if _, err := os.Stat(paths.ServersRoot()); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("servers root still exists after RemoveAllData: %v", err)
+ }
+}
+
+func TestStopCancelsAndWaitsForStart(t *testing.T) {
+ svc, st, _, backend := startRaceService(t)
+ startDone := make(chan error, 1)
+ go func() {
+ _, err := svc.Start(context.Background(), &mcmanagerv1.ServerId{Id: "s1"})
+ startDone <- err
+ }()
+ waitForStart(t, backend.started)
+
+ if _, err := svc.Stop(context.Background(), &mcmanagerv1.ServerId{Id: "s1"}); err != nil {
+ t.Fatalf("Stop: %v", err)
+ }
+ if err := <-startDone; status.Code(err) != codes.Canceled {
+ t.Fatalf("Start error = %v, want context canceled", err)
+ }
+ rec, ok := st.Get("s1")
+ if !ok {
+ t.Fatal("Stop deleted the server record")
+ }
+ if rec.Status != mcmanagerv1.ServerStatus_STOPPED {
+ t.Fatalf("status = %v, want STOPPED", rec.Status)
+ }
+ if _, running := svc.Instance("s1"); running {
+ t.Fatal("canceled Start published a running instance after Stop")
+ }
+}
+
+func startRaceService(t *testing.T) (*ServerService, *store.Memory, appdata.Paths, *blockingStartBackend) {
+ t.Helper()
+ paths := appdata.New(t.TempDir())
+ cacheJava(t, paths.JRECache(), 21)
+ if err := os.MkdirAll(paths.ServerDir("s1"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ st := store.NewMemory()
+ _ = st.Put(&store.Server{
+ ID: "s1", Name: "s1", McVersion: "1.21.1", MemoryMB: 1024,
+ Port: 25565, Status: mcmanagerv1.ServerStatus_STOPPED,
+ JavaMajor: 21, LaunchArgs: []string{"-jar", "server.jar", "nogui"},
+ })
+ backend := &blockingStartBackend{started: make(chan struct{})}
+ svc := NewServerService(ServerServiceConfig{
+ Store: st, JRE: jre.NewManager(paths.JRECache()), Backend: backend, Paths: paths,
+ })
+ return svc, st, paths, backend
+}
+
+func waitForStart(t *testing.T, started <-chan struct{}) {
+ t.Helper()
+ select {
+ case <-started:
+ case <-time.After(5 * time.Second):
+ t.Fatal("Start did not reach the backend")
+ }
+}
+
func cacheJava(t *testing.T, cache string, major int) {
t.Helper()
binDir := filepath.Join(cache, fmt.Sprint(major), fmt.Sprintf("jdk-%d-jre", major), "bin")
diff --git a/engine/internal/grpc/serverservice_updatemodpack_test.go b/engine/internal/grpc/serverservice_updatemodpack_test.go
new file mode 100644
index 0000000..3105524
--- /dev/null
+++ b/engine/internal/grpc/serverservice_updatemodpack_test.go
@@ -0,0 +1,299 @@
+package grpcsvc
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+ "github.com/000hen/justhostmc/engine/internal/appdata"
+ "github.com/000hen/justhostmc/engine/internal/jre"
+ "github.com/000hen/justhostmc/engine/internal/provider"
+ "github.com/000hen/justhostmc/engine/internal/store"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+// updateStubProvider is an installStubProvider that also implements
+// provider.Updater, recording the versions it was called with.
+type updateStubProvider struct {
+ installStubProvider
+ gotVersion, gotOld string
+ updateSpec provider.LaunchSpec
+ updateErr error
+ mutate func(dir string) error
+ started chan struct{}
+ blockUntilCanceled bool
+}
+
+func (p *updateStubProvider) Update(ctx context.Context, dir, version, oldVersion string, report func(provider.Progress)) (provider.LaunchSpec, error) {
+ p.gotVersion, p.gotOld = version, oldVersion
+ if report != nil {
+ report(provider.Progress{Step: "shop.install.downloading", Fraction: 0.5})
+ }
+ if p.mutate != nil {
+ if err := p.mutate(dir); err != nil {
+ return provider.LaunchSpec{}, err
+ }
+ }
+ if p.started != nil {
+ close(p.started)
+ }
+ if p.blockUntilCanceled {
+ <-ctx.Done()
+ return provider.LaunchSpec{}, ctx.Err()
+ }
+ return p.updateSpec, p.updateErr
+}
+
+func modpackTestService(t *testing.T, prov provider.Provider, status mcmanagerv1.ServerStatus, providerVersion string) (*ServerService, *store.Memory, appdata.Paths) {
+ t.Helper()
+ paths := appdata.New(t.TempDir())
+ if err := os.MkdirAll(paths.ServerDir("s1"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ cacheJava(t, paths.JRECache(), 21)
+ st := store.NewMemory()
+ _ = st.Put(&store.Server{
+ ID: "s1", Name: "Pack", ProviderID: "ftb", ModLayout: "mods",
+ McVersion: "1.21.1", Loader: "neoforge", ProviderVersion: providerVersion,
+ MemoryMB: 4096, Port: 25565, Status: status,
+ JavaMajor: 21, LaunchArgs: []string{"-jar", "old-run.jar"},
+ })
+ svc := NewServerService(ServerServiceConfig{
+ Store: st,
+ Providers: testRegistry("ftb", "mods", prov),
+ Paths: paths,
+ JRE: jre.NewManager(paths.JRECache()),
+ })
+ return svc, st, paths
+}
+
+func TestUpdateModpackHappyPath(t *testing.T) {
+ prov := &updateStubProvider{updateSpec: provider.LaunchSpec{
+ JavaMajor: 21, McVersion: "1.21.4", Loader: "neoforge",
+ PackVersion: "95/300",
+ }}
+ svc, st, _ := modpackTestService(t, prov, mcmanagerv1.ServerStatus_STOPPED, "95/100")
+
+ err := svc.UpdateModpack(&mcmanagerv1.UpdateModpackRequest{Id: "s1", Version: "95/300"},
+ &fakeInstallStream{})
+ if err != nil {
+ t.Fatalf("UpdateModpack: %v", err)
+ }
+ if prov.gotVersion != "95/300" || prov.gotOld != "95/100" {
+ t.Errorf("provider got (%q, %q), want (95/300, 95/100)", prov.gotVersion, prov.gotOld)
+ }
+ rec, _ := st.Get("s1")
+ if rec.ProviderVersion != "95/300" || rec.McVersion != "1.21.4" {
+ t.Errorf("record = %+v, want new pack + MC version", rec)
+ }
+ if rec.Status != mcmanagerv1.ServerStatus_STOPPED {
+ t.Errorf("status = %v, want STOPPED", rec.Status)
+ }
+ // spec.Args empty → existing launch args kept.
+ if len(rec.LaunchArgs) != 2 || rec.LaunchArgs[1] != "old-run.jar" {
+ t.Errorf("LaunchArgs = %v, want preserved", rec.LaunchArgs)
+ }
+}
+
+func TestUpdateModpackReplacesArgsWhenProvided(t *testing.T) {
+ prov := &updateStubProvider{updateSpec: provider.LaunchSpec{
+ JavaMajor: 21, Args: []string{"@libraries/run.args"}, McVersion: "1.21.4",
+ PackVersion: "95/300",
+ }}
+ svc, st, _ := modpackTestService(t, prov, mcmanagerv1.ServerStatus_STOPPED, "95/100")
+ if err := svc.UpdateModpack(&mcmanagerv1.UpdateModpackRequest{Id: "s1", Version: "95/300"},
+ &fakeInstallStream{}); err != nil {
+ t.Fatalf("UpdateModpack: %v", err)
+ }
+ rec, _ := st.Get("s1")
+ if len(rec.LaunchArgs) != 1 || rec.LaunchArgs[0] != "@libraries/run.args" {
+ t.Errorf("LaunchArgs = %v, want replaced", rec.LaunchArgs)
+ }
+}
+
+func TestUpdateModpackRejectsRunning(t *testing.T) {
+ prov := &updateStubProvider{}
+ svc, _, _ := modpackTestService(t, prov, mcmanagerv1.ServerStatus_RUNNING, "95/100")
+ err := svc.UpdateModpack(&mcmanagerv1.UpdateModpackRequest{Id: "s1", Version: "95/300"},
+ &fakeInstallStream{})
+ if status.Code(err) != codes.FailedPrecondition {
+ t.Fatalf("code = %v, want FailedPrecondition", status.Code(err))
+ }
+}
+
+func TestUpdateModpackRejectsNonModpackServer(t *testing.T) {
+ prov := &updateStubProvider{}
+ svc, _, _ := modpackTestService(t, prov, mcmanagerv1.ServerStatus_STOPPED, "")
+ err := svc.UpdateModpack(&mcmanagerv1.UpdateModpackRequest{Id: "s1", Version: "95/300"},
+ &fakeInstallStream{})
+ if status.Code(err) != codes.FailedPrecondition {
+ t.Fatalf("code = %v, want FailedPrecondition", status.Code(err))
+ }
+}
+
+// TestUpdateModpackUnsupportedIsUnimplemented proves a provider that reports
+// ErrUpdateUnsupported (e.g. an imported pack, whose script has no update())
+// surfaces as gRPC Unimplemented, not Internal, and leaves the server STOPPED.
+func TestUpdateModpackUnsupportedIsUnimplemented(t *testing.T) {
+ prov := &updateStubProvider{updateErr: provider.ErrUpdateUnsupported}
+ svc, st, _ := modpackTestService(t, prov, mcmanagerv1.ServerStatus_STOPPED, "import/local")
+
+ err := svc.UpdateModpack(&mcmanagerv1.UpdateModpackRequest{Id: "s1", Version: "import/local"},
+ &fakeInstallStream{})
+ if status.Code(err) != codes.Unimplemented {
+ t.Fatalf("code = %v, want Unimplemented", status.Code(err))
+ }
+ rec, _ := st.Get("s1")
+ if rec.Status != mcmanagerv1.ServerStatus_STOPPED {
+ t.Errorf("status = %v, want restored STOPPED", rec.Status)
+ }
+}
+
+// TestUpdateModpackFailureLeavesInstallIntact proves an update error restores
+// STOPPED, keeps the record and the server dir — unlike Create's wipe.
+func TestUpdateModpackFailureLeavesInstallIntact(t *testing.T) {
+ prov := &updateStubProvider{
+ updateErr: errors.New("cdn exploded"),
+ mutate: func(dir string) error {
+ if err := os.WriteFile(filepath.Join(dir, "world-data.txt"), []byte("mutated"), 0o644); err != nil {
+ return err
+ }
+ return os.WriteFile(filepath.Join(dir, "new-mod.jar"), []byte("partial"), 0o644)
+ },
+ }
+ svc, st, paths := modpackTestService(t, prov, mcmanagerv1.ServerStatus_STOPPED, "95/100")
+ marker := filepath.Join(paths.ServerDir("s1"), "world-data.txt")
+ if err := os.WriteFile(marker, []byte("keep me"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ err := svc.UpdateModpack(&mcmanagerv1.UpdateModpackRequest{Id: "s1", Version: "95/300"},
+ &fakeInstallStream{})
+ if err == nil {
+ t.Fatal("UpdateModpack succeeded, want error")
+ }
+ rec, ok := st.Get("s1")
+ if !ok {
+ t.Fatal("record deleted on failure")
+ }
+ if rec.Status != mcmanagerv1.ServerStatus_STOPPED {
+ t.Errorf("status = %v, want restored STOPPED", rec.Status)
+ }
+ if rec.ProviderVersion != "95/100" {
+ t.Errorf("ProviderVersion = %q, want unchanged 95/100", rec.ProviderVersion)
+ }
+ if _, err := os.Stat(marker); err != nil {
+ t.Errorf("server dir wiped on failure: %v", err)
+ }
+ got, err := os.ReadFile(marker)
+ if err != nil || string(got) != "keep me" {
+ t.Errorf("marker after rollback = %q, %v; want original content", got, err)
+ }
+ if _, err := os.Stat(filepath.Join(paths.ServerDir("s1"), "new-mod.jar")); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("partial new file survived rollback: %v", err)
+ }
+}
+
+func TestDeleteCancelsAndWaitsForModpackUpdate(t *testing.T) {
+ started := make(chan struct{})
+ prov := &updateStubProvider{started: started, blockUntilCanceled: true}
+ svc, st, paths := modpackTestService(t, prov, mcmanagerv1.ServerStatus_STOPPED, "95/100")
+
+ updateDone := make(chan error, 1)
+ go func() {
+ updateDone <- svc.UpdateModpack(
+ &mcmanagerv1.UpdateModpackRequest{Id: "s1", Version: "95/300"},
+ &fakeInstallStream{})
+ }()
+ select {
+ case <-started:
+ case <-time.After(5 * time.Second):
+ t.Fatal("update did not start")
+ }
+
+ if _, err := svc.Delete(context.Background(), &mcmanagerv1.ServerId{Id: "s1"}); err != nil {
+ t.Fatalf("Delete: %v", err)
+ }
+ select {
+ case err := <-updateDone:
+ if err == nil {
+ t.Fatal("canceled update succeeded")
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("Delete returned before update stopped")
+ }
+ if _, ok := st.Get("s1"); ok {
+ t.Fatal("canceled update resurrected deleted server")
+ }
+ if _, err := os.Stat(paths.ServerDir("s1")); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("server directory still exists after delete: %v", err)
+ }
+}
+
+func TestStartRejectsActiveModpackUpdate(t *testing.T) {
+ started := make(chan struct{})
+ prov := &updateStubProvider{started: started, blockUntilCanceled: true}
+ svc, _, _ := modpackTestService(t, prov, mcmanagerv1.ServerStatus_STOPPED, "95/100")
+
+ updateDone := make(chan error, 1)
+ go func() {
+ updateDone <- svc.UpdateModpack(
+ &mcmanagerv1.UpdateModpackRequest{Id: "s1", Version: "95/300"},
+ &fakeInstallStream{})
+ }()
+ select {
+ case <-started:
+ case <-time.After(5 * time.Second):
+ t.Fatal("update did not start")
+ }
+
+ _, err := svc.Start(context.Background(), &mcmanagerv1.ServerId{Id: "s1"})
+ if status.Code(err) != codes.FailedPrecondition {
+ t.Fatalf("Start code = %v, want FailedPrecondition", status.Code(err))
+ }
+
+ svc.mu.Lock()
+ svc.installations["s1"].cancel()
+ svc.mu.Unlock()
+ <-updateDone
+}
+
+func TestStopCancelsAndWaitsForModpackUpdate(t *testing.T) {
+ started := make(chan struct{})
+ prov := &updateStubProvider{started: started, blockUntilCanceled: true}
+ svc, st, _ := modpackTestService(t, prov, mcmanagerv1.ServerStatus_STOPPED, "95/100")
+
+ updateDone := make(chan error, 1)
+ go func() {
+ updateDone <- svc.UpdateModpack(
+ &mcmanagerv1.UpdateModpackRequest{Id: "s1", Version: "95/300"},
+ &fakeInstallStream{})
+ }()
+ select {
+ case <-started:
+ case <-time.After(5 * time.Second):
+ t.Fatal("update did not start")
+ }
+
+ if _, err := svc.Stop(context.Background(), &mcmanagerv1.ServerId{Id: "s1"}); err != nil {
+ t.Fatalf("Stop: %v", err)
+ }
+ if err := <-updateDone; status.Code(err) != codes.Canceled {
+ t.Fatalf("UpdateModpack error = %v, want Canceled", err)
+ }
+ rec, ok := st.Get("s1")
+ if !ok {
+ t.Fatal("Stop deleted the server record")
+ }
+ if rec.Status != mcmanagerv1.ServerStatus_STOPPED {
+ t.Fatalf("status = %v, want STOPPED", rec.Status)
+ }
+ if rec.ProviderVersion != "95/100" {
+ t.Fatalf("ProviderVersion = %q, want original version", rec.ProviderVersion)
+ }
+}
diff --git a/engine/internal/grpc/settingsservice.go b/engine/internal/grpc/settingsservice.go
index 9c29c34..ab07c9e 100644
--- a/engine/internal/grpc/settingsservice.go
+++ b/engine/internal/grpc/settingsservice.go
@@ -2,9 +2,6 @@ package grpcsvc
import (
"context"
- "maps"
- "slices"
- "strings"
"time"
mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
@@ -21,10 +18,6 @@ type SettingsServiceConfig struct {
LogsRoot string
ActiveMode string // the isolation backend chosen at startup, for reporting
CloseLogs func() // close open log files before purging
- // BakedShopKeys are build-time default shop API keys (shop id -> key),
- // e.g. a CurseForge key injected via -ldflags. Reported as
- // has_builtin_key; never returned to the client.
- BakedShopKeys map[string]string
// Detector reports live Docker availability; defaults to the real probe when nil
// (injectable for tests).
Detector func(context.Context) isolation.Availability
@@ -112,58 +105,6 @@ func (s *SettingsService) GetBackendInfo(ctx context.Context, _ *mcmanagerv1.Emp
}, nil
}
-// GetShopKeys reports, per shop id, whether a user key override and/or a
-// baked-in build default exist. Key material itself never leaves the engine.
-func (s *SettingsService) GetShopKeys(_ context.Context, _ *mcmanagerv1.Empty) (*mcmanagerv1.ShopKeyList, error) {
- v, err := s.cfg.Store.Load()
- if err != nil {
- return nil, status.Errorf(codes.Internal, "load settings: %v", err)
- }
- ids := map[string]bool{}
- for id := range v.ShopKeys {
- ids[id] = true
- }
- for id, key := range s.cfg.BakedShopKeys {
- if key != "" {
- ids[id] = true
- }
- }
- out := &mcmanagerv1.ShopKeyList{}
- for _, id := range slices.Sorted(maps.Keys(ids)) {
- out.Keys = append(out.Keys, &mcmanagerv1.ShopKeyInfo{
- ShopId: id,
- HasUserKey: v.ShopKeys[id] != "",
- HasBuiltinKey: s.cfg.BakedShopKeys[id] != "",
- })
- }
- return out, nil
-}
-
-// SetShopKey persists (or clears, with an empty api_key) the user's key
-// override for one shop.
-func (s *SettingsService) SetShopKey(_ context.Context, req *mcmanagerv1.ShopKey) (*mcmanagerv1.Empty, error) {
- if strings.TrimSpace(req.ShopId) == "" {
- return nil, status.Error(codes.InvalidArgument, "shop_id is required")
- }
- v, err := s.cfg.Store.Load()
- if err != nil {
- return nil, status.Errorf(codes.Internal, "load settings: %v", err)
- }
- key := strings.TrimSpace(req.ApiKey)
- if key == "" {
- delete(v.ShopKeys, req.ShopId)
- } else {
- if v.ShopKeys == nil {
- v.ShopKeys = map[string]string{}
- }
- v.ShopKeys[req.ShopId] = key
- }
- if err := s.cfg.Store.Save(v); err != nil {
- return nil, status.Errorf(codes.Internal, "save settings: %v", err)
- }
- return &mcmanagerv1.Empty{}, nil
-}
-
// SetUseDocker persists the Docker opt-in. It takes effect on the next engine
// launch (running servers stay on the backend they were started with).
func (s *SettingsService) SetUseDocker(_ context.Context, req *mcmanagerv1.UseDocker) (*mcmanagerv1.Empty, error) {
diff --git a/engine/internal/grpc/shopservice.go b/engine/internal/grpc/shopservice.go
index cd83416..70615b2 100644
--- a/engine/internal/grpc/shopservice.go
+++ b/engine/internal/grpc/shopservice.go
@@ -39,6 +39,7 @@ type ShopService struct {
mcmanagerv1.UnimplementedShopServiceServer
shops *scripting.ShopSet
grants *scripting.GrantStore
+ config *scripting.ConfigStore
dir string // root dir where user shops are persisted
store store.Store
mods ModDirResolver
@@ -47,8 +48,8 @@ type ShopService struct {
// NewShopService builds a ShopService. dir is where imported user shop
// scripts are stored; st resolves per-server pre-filters (MC version +
// provider/loader); mods supplies the guarded target directory for installs.
-func NewShopService(shops *scripting.ShopSet, grants *scripting.GrantStore, dir string, st store.Store, mods ModDirResolver) *ShopService {
- return &ShopService{shops: shops, grants: grants, dir: dir, store: st, mods: mods}
+func NewShopService(shops *scripting.ShopSet, grants *scripting.GrantStore, config *scripting.ConfigStore, dir string, st store.Store, mods ModDirResolver) *ShopService {
+ return &ShopService{shops: shops, grants: grants, config: config, dir: dir, store: st, mods: mods}
}
func (s *ShopService) List(_ context.Context, _ *mcmanagerv1.Empty) (*mcmanagerv1.ShopList, error) {
@@ -322,10 +323,31 @@ func (s *ShopService) Remove(_ context.Context, ref *mcmanagerv1.ProviderRef) (*
if s.grants != nil {
_ = s.grants.Forget(ref.Id)
}
+ if s.config != nil {
+ _ = s.config.Forget(ref.Id)
+ }
_ = os.Remove(s.shopPath(ref.Id))
return &mcmanagerv1.Empty{}, nil
}
+func (s *ShopService) GetConfig(_ context.Context, ref *mcmanagerv1.ProviderRef) (*mcmanagerv1.ScriptConfig, error) {
+ sh, ok := s.shops.Get(ref.Id)
+ if !ok {
+ return nil, errorStatus(codes.NotFound, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, "shop not found", nil)
+ }
+ // Resolve to the canonical id so an alias reads the shared config entry.
+ return getConfigView(sh.Meta().ID, sh.Meta().Config, s.config), nil
+}
+
+func (s *ShopService) SetConfig(_ context.Context, req *mcmanagerv1.SetConfigRequest) (*mcmanagerv1.ScriptConfig, error) {
+ sh, ok := s.shops.Get(req.Id)
+ if !ok {
+ return nil, errorStatus(codes.NotFound, mcmanagerv1.ErrorCode_ERROR_CODE_UNSPECIFIED, "shop not found", nil)
+ }
+ // Resolve to the canonical id so an alias writes the shared config entry.
+ return applyConfig(sh.Meta().ID, sh.Meta().Config, s.config, req)
+}
+
func (s *ShopService) SetPermissions(_ context.Context, req *mcmanagerv1.SetPermissionsRequest) (*mcmanagerv1.ShopInfo, error) {
sh, ok := s.shops.Get(req.Id)
if !ok {
@@ -377,20 +399,33 @@ func (s *ShopService) info(sh *scripting.LuaShop) *mcmanagerv1.ShopInfo {
}
slices.Sort(granted)
return &mcmanagerv1.ShopInfo{
- Id: meta.ID,
- Name: meta.Name,
- Website: meta.Website,
- Description: meta.Description,
- Version: meta.Version,
- Author: meta.Author,
- Builtin: sh.Builtin(),
- Permissions: perms,
- Granted: granted,
- NeedsKey: meta.NeedsKey,
- Ready: sh.Ready(),
+ Id: meta.ID,
+ Name: meta.Name,
+ Website: meta.Website,
+ Description: meta.Description,
+ Version: meta.Version,
+ Author: meta.Author,
+ Builtin: sh.Builtin(),
+ Permissions: perms,
+ Granted: granted,
+ NeedsKey: meta.NeedsKey,
+ Ready: sh.Ready(),
+ ConfigOptions: configOptions(meta.Config),
+ Kinds: shopKinds(meta.Kinds),
}
}
+// shopKinds returns the shop's declared item kinds, defaulting to the common
+// {"mod","plugin"} browser when a shop declares none.
+func shopKinds(declared []string) []string {
+ if len(declared) == 0 {
+ return []string{"mod", "plugin"}
+ }
+ out := make([]string, len(declared))
+ copy(out, declared)
+ return out
+}
+
// mapShopError converts shop script failures into typed gRPC statuses.
func mapShopError(err error) error {
switch {
@@ -411,10 +446,14 @@ func mapShopError(err error) error {
// kindString maps ModKind to the script-facing string.
func kindString(k mcmanagerv1.ModKind) string {
- if k == mcmanagerv1.ModKind_PLUGIN {
+ switch k {
+ case mcmanagerv1.ModKind_PLUGIN:
return "plugin"
+ case mcmanagerv1.ModKind_MODPACK:
+ return "modpack"
+ default:
+ return "mod"
}
- return "mod"
}
// sortString maps ShopSort to the script-facing string.
diff --git a/engine/internal/modpack/export.go b/engine/internal/modpack/export.go
new file mode 100644
index 0000000..b317ea9
--- /dev/null
+++ b/engine/internal/modpack/export.go
@@ -0,0 +1,474 @@
+// Package modpack builds client-importable modpack packages from an installed
+// modpack server: a CurseForge-format zip (manifest.json + overrides/) that
+// launchers like the CurseForge app, Prism, and ATLauncher import directly,
+// carrying the server's live configs.
+package modpack
+
+import (
+ "archive/zip"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/fs"
+ "net/http"
+ "os"
+ "path"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/000hen/justhostmc/engine/internal/provider"
+ "golang.org/x/sync/errgroup"
+)
+
+// DefaultFTBAPIBase is the public FTB modpack API (same upstream ftb.lua uses).
+const DefaultFTBAPIBase = "https://api.feed-the-beast.com/v1/modpacks/public"
+
+// Options configures one export.
+type Options struct {
+ ServerDir string // installed server directory (read-only for export)
+ DestZip string // absolute output .zip path
+ PackVersion string // opaque "packId/versionId" stored on the server record
+ ServerName string // used as the pack name in manifest.json
+ ProviderID string // provider that installed the server; gates the FTB-API fallback
+ FTBAPIBase string // empty = DefaultFTBAPIBase; overridable in tests
+}
+
+// normManifest is the normalized modpack manifest providers persist at
+// .jhmc/modpack.json. Export prefers it over re-fetching the upstream source, so
+// export works for every modpack provider (and offline).
+type normManifest struct {
+ Format int `json:"format"`
+ Name string `json:"name"`
+ VersionName string `json:"version_name"`
+ MCVersion string `json:"mc_version"`
+ Loader string `json:"loader"`
+ LoaderVersion string `json:"loader_version"`
+ Files []normFile `json:"files"`
+}
+
+type normFile struct {
+ Dest string `json:"dest"`
+ Sha1 string `json:"sha1"`
+ URL string `json:"url"`
+ ProjectID flexInt64 `json:"project_id"`
+ FileID flexInt64 `json:"file_id"`
+ ClientOnly bool `json:"client_only"`
+}
+
+// normManifestRelPath is the server-dir-relative location of the persisted
+// manifest, matching mplib.MANIFEST_PATH on the Lua side.
+var normManifestRelPath = filepath.Join(".jhmc", "modpack.json")
+
+// overrideDirs are the server dirs copied verbatim into overrides/ (when they
+// exist). mods/ is handled separately so CF-covered jars aren't duplicated.
+var overrideDirs = []string{
+ "config", "defaultconfigs", "kubejs", "scripts", "resourcepacks", "shaderpacks",
+}
+
+// ftbManifest is the subset of the FTB version manifest export consumes.
+type ftbManifest struct {
+ Name string `json:"name"`
+ Targets []struct {
+ Type string `json:"type"`
+ Name string `json:"name"`
+ Version string `json:"version"`
+ } `json:"targets"`
+ Files []ftbFile `json:"files"`
+}
+
+// flexInt64 accepts both JSON numbers and numeric strings — the FTB API
+// serves curseforge ids as strings.
+type flexInt64 int64
+
+func (f *flexInt64) UnmarshalJSON(b []byte) error {
+ s := strings.Trim(string(b), `"`)
+ if s == "" || s == "null" {
+ *f = 0
+ return nil
+ }
+ n, err := strconv.ParseInt(s, 10, 64)
+ if err != nil {
+ return fmt.Errorf("not a numeric id: %s", b)
+ }
+ *f = flexInt64(n)
+ return nil
+}
+
+type ftbFile struct {
+ Path string `json:"path"`
+ Name string `json:"name"`
+ URL string `json:"url"`
+ Clientonly bool `json:"clientonly"`
+ Curseforge *struct {
+ Project flexInt64 `json:"project"`
+ File flexInt64 `json:"file"`
+ } `json:"curseforge"`
+}
+
+// dest is the file's zip-relative destination ("mods/x.jar").
+func (f ftbFile) dest() string {
+ p := strings.Trim(strings.TrimPrefix(strings.TrimSpace(f.Path), "./"), "/")
+ if p == "" {
+ return f.Name
+ }
+ return p + "/" + f.Name
+}
+
+// cfManifest is the CurseForge pack manifest.json shape.
+type cfManifest struct {
+ Minecraft struct {
+ Version string `json:"version"`
+ ModLoaders []cfModLoader `json:"modLoaders"`
+ } `json:"minecraft"`
+ ManifestType string `json:"manifestType"`
+ ManifestVersion int `json:"manifestVersion"`
+ Name string `json:"name"`
+ Version string `json:"version"`
+ Author string `json:"author"`
+ Files []cfFile `json:"files"`
+ Overrides string `json:"overrides"`
+}
+
+type cfModLoader struct {
+ ID string `json:"id"`
+ Primary bool `json:"primary"`
+}
+
+type cfFile struct {
+ ProjectID int64 `json:"projectID"`
+ FileID int64 `json:"fileID"`
+ Required bool `json:"required"`
+}
+
+func report(progress func(provider.Progress), p provider.Progress) {
+ if progress != nil {
+ progress(p)
+ }
+}
+
+// Export writes a CurseForge-format client pack zip for the modpack install in
+// o.ServerDir. When the server has a persisted .jhmc/modpack.json (every current
+// provider writes one), the manifest is built from it; otherwise, for legacy FTB
+// servers installed before manifests were persisted, it is fetched from the FTB
+// API. Either way, files with CurseForge ids (including client-only ones) become
+// manifest entries, the server's live config dirs and hand-added mods go into
+// overrides/, and client-only direct-URL files are downloaded at export time.
+func Export(ctx context.Context, client *http.Client, o Options, progress func(provider.Progress)) error {
+ report(progress, provider.Progress{Step: "shop.export.preparing", Fraction: -1})
+
+ staging, err := os.MkdirTemp("", "jhmc-export-*")
+ if err != nil {
+ return err
+ }
+ defer os.RemoveAll(staging)
+
+ var (
+ out cfManifest
+ covered map[string]bool
+ )
+ if _, statErr := os.Stat(filepath.Join(o.ServerDir, normManifestRelPath)); statErr == nil {
+ out, covered, err = buildFromManifest(ctx, client, o, staging, progress)
+ } else if o.ProviderID == "" || o.ProviderID == "ftb" {
+ out, covered, err = buildFromFTB(ctx, client, o, staging, progress)
+ } else {
+ return fmt.Errorf("no persisted modpack manifest for %q server", o.ProviderID)
+ }
+ if err != nil {
+ return err
+ }
+
+ report(progress, provider.Progress{Step: "shop.export.zipping", Fraction: -1})
+ return writeZip(o, out, staging, covered)
+}
+
+// buildFromManifest constructs the CurseForge manifest from the server's
+// persisted .jhmc/modpack.json. CurseForge-hosted files become manifest entries;
+// client-only direct-URL files are downloaded into staging (they never lived on
+// the server); server-side files are shipped from the live server dir by
+// writeZip, so nothing is done for them here.
+func buildFromManifest(ctx context.Context, client *http.Client, o Options, staging string, progress func(provider.Progress)) (cfManifest, map[string]bool, error) {
+ raw, err := os.ReadFile(filepath.Join(o.ServerDir, normManifestRelPath))
+ if err != nil {
+ return cfManifest{}, nil, err
+ }
+ var nm normManifest
+ if err := json.Unmarshal(raw, &nm); err != nil {
+ return cfManifest{}, nil, fmt.Errorf("read modpack manifest: %w", err)
+ }
+
+ name := o.ServerName
+ if name == "" {
+ name = nm.Name
+ }
+ out := cfManifest{
+ ManifestType: "minecraftModpack",
+ ManifestVersion: 1,
+ Name: name,
+ Version: nm.VersionName,
+ Overrides: "overrides",
+ }
+ out.Minecraft.Version = nm.MCVersion
+ if nm.Loader != "" {
+ id := nm.Loader
+ if nm.LoaderVersion != "" {
+ id += "-" + nm.LoaderVersion
+ }
+ out.Minecraft.ModLoaders = []cfModLoader{{ID: id, Primary: true}}
+ }
+ if out.Minecraft.Version == "" || len(out.Minecraft.ModLoaders) == 0 {
+ return cfManifest{}, nil, fmt.Errorf("modpack manifest has no minecraft version or loader")
+ }
+
+ covered := map[string]bool{}
+ var downloads []stagedDL
+ for _, f := range nm.Files {
+ if f.Dest == "" {
+ continue
+ }
+ switch {
+ case f.ProjectID != 0 && f.FileID != 0:
+ out.Files = append(out.Files, cfFile{
+ ProjectID: int64(f.ProjectID),
+ FileID: int64(f.FileID),
+ Required: true,
+ })
+ covered[f.Dest] = true
+ case f.ClientOnly && f.URL != "":
+ downloads = append(downloads, stagedDL{dest: f.Dest, url: f.URL, name: path.Base(f.Dest)})
+ }
+ }
+ if err := downloadStaged(ctx, client, downloads, staging, progress); err != nil {
+ return cfManifest{}, nil, err
+ }
+ return out, covered, nil
+}
+
+// buildFromFTB is the legacy path for FTB servers installed before manifests
+// were persisted: it re-fetches the pack version manifest from the FTB API.
+func buildFromFTB(ctx context.Context, client *http.Client, o Options, staging string, progress func(provider.Progress)) (cfManifest, map[string]bool, error) {
+ pack, ver, ok := strings.Cut(o.PackVersion, "/")
+ if !ok || pack == "" || ver == "" {
+ return cfManifest{}, nil, fmt.Errorf("invalid pack version %q", o.PackVersion)
+ }
+ base := o.FTBAPIBase
+ if base == "" {
+ base = DefaultFTBAPIBase
+ }
+ manifest, err := fetchManifest(ctx, client, fmt.Sprintf("%s/modpack/%s/%s", base, pack, ver))
+ if err != nil {
+ return cfManifest{}, nil, err
+ }
+
+ out := cfManifest{
+ ManifestType: "minecraftModpack",
+ ManifestVersion: 1,
+ Name: o.ServerName,
+ Version: manifest.Name,
+ Overrides: "overrides",
+ }
+ var loaderOK bool
+ for _, t := range manifest.Targets {
+ switch t.Type {
+ case "game":
+ out.Minecraft.Version = t.Version
+ case "modloader":
+ out.Minecraft.ModLoaders = []cfModLoader{
+ {ID: strings.ToLower(t.Name) + "-" + t.Version, Primary: true},
+ }
+ loaderOK = true
+ }
+ }
+ if out.Minecraft.Version == "" || !loaderOK {
+ return cfManifest{}, nil, fmt.Errorf("pack manifest has no game/modloader target")
+ }
+
+ // CF-hosted files (server-side AND client-only) become manifest entries;
+ // their local copies must not be duplicated into overrides.
+ covered := map[string]bool{}
+ var downloads []stagedDL
+ for _, f := range manifest.Files {
+ if f.Name == "" {
+ continue
+ }
+ switch {
+ case f.Curseforge != nil && f.Curseforge.Project != 0 && f.Curseforge.File != 0:
+ out.Files = append(out.Files, cfFile{
+ ProjectID: int64(f.Curseforge.Project),
+ FileID: int64(f.Curseforge.File),
+ Required: true,
+ })
+ covered[f.dest()] = true
+ case f.Clientonly && f.URL != "":
+ downloads = append(downloads, stagedDL{dest: f.dest(), url: f.URL, name: f.Name})
+ }
+ }
+ if err := downloadStaged(ctx, client, downloads, staging, progress); err != nil {
+ return cfManifest{}, nil, err
+ }
+ return out, covered, nil
+}
+
+// stagedDL is one client-only direct-URL file to download into the export
+// staging dir (later shipped under overrides/).
+type stagedDL struct {
+ dest string // server-dir-relative destination
+ url string
+ name string // label for progress
+}
+
+// downloadStaged fetches client-only direct-URL files into staging in parallel,
+// reporting progress. Files were never installed server-side, so they are pulled
+// fresh at export time.
+func downloadStaged(ctx context.Context, client *http.Client, dls []stagedDL, staging string, progress func(provider.Progress)) error {
+ if len(dls) == 0 {
+ return nil
+ }
+ g, gctx := errgroup.WithContext(ctx)
+ g.SetLimit(6)
+ total := len(dls)
+ results := make(chan string, total)
+ for _, f := range dls {
+ g.Go(func() error {
+ full := filepath.Join(staging, filepath.FromSlash(f.dest))
+ if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
+ return err
+ }
+ if err := downloadTo(gctx, client, f.url, full); err != nil {
+ return fmt.Errorf("%s: %w", f.dest, err)
+ }
+ results <- f.name
+ return nil
+ })
+ }
+ go func() { _ = g.Wait(); close(results) }()
+ done := 0
+ for name := range results {
+ done++
+ report(progress, provider.Progress{Step: "shop.install.downloading",
+ Fraction: float64(done) / float64(total), LogLine: name})
+ }
+ return g.Wait()
+}
+
+func fetchManifest(ctx context.Context, client *http.Client, url string) (*ftbManifest, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("GET %s: unexpected status %s", url, resp.Status)
+ }
+ var m ftbManifest
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 32<<20)).Decode(&m); err != nil {
+ return nil, fmt.Errorf("decode pack manifest: %v", err)
+ }
+ return &m, nil
+}
+
+func downloadTo(ctx context.Context, client *http.Client, url, dest string) error {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return err
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("GET %s: unexpected status %s", url, resp.Status)
+ }
+ f, err := os.Create(dest)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ _, err = io.Copy(f, resp.Body)
+ return err
+}
+
+// writeZip streams manifest.json, the staged client-only files, the server's
+// override dirs, and uncovered mod jars into the destination zip.
+func writeZip(o Options, manifest cfManifest, staging string, covered map[string]bool) error {
+ zf, err := os.Create(o.DestZip)
+ if err != nil {
+ return err
+ }
+ defer zf.Close()
+ zw := zip.NewWriter(zf)
+
+ mj, err := zw.Create("manifest.json")
+ if err != nil {
+ return err
+ }
+ enc := json.NewEncoder(mj.(io.Writer))
+ enc.SetIndent("", " ")
+ if err := enc.Encode(manifest); err != nil {
+ return err
+ }
+
+ addFile := func(zipPath, fsPath string) error {
+ w, err := zw.Create(zipPath)
+ if err != nil {
+ return err
+ }
+ f, err := os.Open(fsPath)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ _, err = io.Copy(w, f)
+ return err
+ }
+ addTree := func(root, zipPrefix string, skip func(rel string) bool) error {
+ return filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ if err != nil || d.IsDir() {
+ return err
+ }
+ rel, err := filepath.Rel(root, p)
+ if err != nil {
+ return err
+ }
+ relSlash := filepath.ToSlash(rel)
+ if skip != nil && skip(relSlash) {
+ return nil
+ }
+ return addFile(path.Join(zipPrefix, relSlash), p)
+ })
+ }
+
+ // Staged client-only downloads.
+ if _, err := os.Stat(staging); err == nil {
+ if err := addTree(staging, "overrides", nil); err != nil {
+ return err
+ }
+ }
+ // Live server config-ish dirs.
+ for _, dir := range overrideDirs {
+ root := filepath.Join(o.ServerDir, dir)
+ if _, err := os.Stat(root); err != nil {
+ continue
+ }
+ if err := addTree(root, "overrides/"+dir, nil); err != nil {
+ return err
+ }
+ }
+ // Hand-added mods (anything the CF manifest doesn't already deliver).
+ modsRoot := filepath.Join(o.ServerDir, "mods")
+ if _, err := os.Stat(modsRoot); err == nil {
+ if err := addTree(modsRoot, "overrides/mods", func(rel string) bool {
+ return covered["mods/"+rel]
+ }); err != nil {
+ return err
+ }
+ }
+
+ return zw.Close()
+}
diff --git a/engine/internal/modpack/export_live_test.go b/engine/internal/modpack/export_live_test.go
new file mode 100644
index 0000000..68e80d0
--- /dev/null
+++ b/engine/internal/modpack/export_live_test.go
@@ -0,0 +1,40 @@
+package modpack
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/000hen/justhostmc/engine/internal/provider"
+)
+
+// TestExportLiveServer is an opt-in diagnostic: it exports a real installed
+// modpack server against the real FTB API. Runs only when
+// JHMC_LIVE_EXPORT_DIR (server directory) and JHMC_LIVE_EXPORT_PACK
+// ("packId/versionId") are set.
+func TestExportLiveServer(t *testing.T) {
+ dir := os.Getenv("JHMC_LIVE_EXPORT_DIR")
+ pack := os.Getenv("JHMC_LIVE_EXPORT_PACK")
+ if dir == "" || pack == "" {
+ t.Skip("JHMC_LIVE_EXPORT_DIR / JHMC_LIVE_EXPORT_PACK not set")
+ }
+ dest := filepath.Join(t.TempDir(), "live-export.zip")
+ err := Export(context.Background(), http.DefaultClient, Options{
+ ServerDir: dir,
+ DestZip: dest,
+ PackVersion: pack,
+ ServerName: "Live Export",
+ }, func(p provider.Progress) {
+ if p.Step != "" {
+ fmt.Printf("[step] %s %.2f\n", p.Step, p.Fraction)
+ }
+ })
+ if err != nil {
+ t.Fatalf("Export: %v", err)
+ }
+ fi, _ := os.Stat(dest)
+ fmt.Printf("zip size: %d\n", fi.Size())
+}
diff --git a/engine/internal/modpack/export_manifest_test.go b/engine/internal/modpack/export_manifest_test.go
new file mode 100644
index 0000000..8d4491a
--- /dev/null
+++ b/engine/internal/modpack/export_manifest_test.go
@@ -0,0 +1,143 @@
+package modpack
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// persistedFixture builds a non-FTB modpack server: a server dir carrying a
+// persisted .jhmc/modpack.json plus live files, and a server that serves the one
+// client-only direct-URL file. The FTB API is deliberately not wired — a correct
+// export must never reach it when the manifest is present.
+func persistedFixture(t *testing.T) (Options, string) {
+ t.Helper()
+ mux := http.NewServeMux()
+ mux.HandleFunc("/blob/look.zip", func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte("client-only-bytes"))
+ })
+ mux.HandleFunc("/modpack/", func(w http.ResponseWriter, _ *http.Request) {
+ t.Error("FTB API must not be called when a persisted manifest exists")
+ http.Error(w, "unexpected", http.StatusInternalServerError)
+ })
+ srv := httptest.NewServer(mux)
+ t.Cleanup(srv.Close)
+
+ serverDir := t.TempDir()
+ mustWrite := func(rel, content string) {
+ full := filepath.Join(serverDir, filepath.FromSlash(rel))
+ if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(full, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ manifest := fmt.Sprintf(`{
+ "format": 1,
+ "name": "Persisted Pack",
+ "version_name": "2.0.0",
+ "mc_version": "1.21.1",
+ "loader": "neoforge",
+ "loader_version": "21.1.77",
+ "files": [
+ { "dest": "mods/server-mod.jar", "sha1": "a", "project_id": 111, "file_id": 1111 },
+ { "dest": "mods/client-mod.jar", "client_only": true, "project_id": 222, "file_id": 2222 },
+ { "dest": "resourcepacks/look.zip", "client_only": true, "url": "%s/blob/look.zip" },
+ { "dest": "config/pack.toml", "url": "IGNORED-server-file-from-disk" }
+ ]
+ }`, srv.URL)
+ mustWrite(".jhmc/modpack.json", manifest)
+ mustWrite("config/pack.toml", "edited-on-server") // server-side → from disk
+ mustWrite("mods/server-mod.jar", "cf-covered") // covered by CF entry → excluded
+ mustWrite("mods/local-extra.jar", "hand-added") // not in manifest → included
+ mustWrite("world/level.dat", "world") // excluded
+
+ dest := filepath.Join(t.TempDir(), "out.zip")
+ return Options{
+ ServerDir: serverDir,
+ DestZip: dest,
+ PackVersion: "999/1", // must be ignored in favor of the persisted manifest
+ ServerName: "Persisted Server",
+ ProviderID: "curseforge_modpacks",
+ FTBAPIBase: srv.URL,
+ }, dest
+}
+
+func TestExportFromPersistedManifest(t *testing.T) {
+ opts, dest := persistedFixture(t)
+ if err := Export(context.Background(), http.DefaultClient, opts, nil); err != nil {
+ t.Fatalf("Export: %v", err)
+ }
+ files := readZip(t, dest)
+
+ var m struct {
+ ManifestType string `json:"manifestType"`
+ Name string `json:"name"`
+ Version string `json:"version"`
+ Overrides string `json:"overrides"`
+ Minecraft struct {
+ Version string `json:"version"`
+ ModLoaders []struct {
+ ID string `json:"id"`
+ Primary bool `json:"primary"`
+ } `json:"modLoaders"`
+ } `json:"minecraft"`
+ Files []struct {
+ ProjectID int64 `json:"projectID"`
+ FileID int64 `json:"fileID"`
+ Required bool `json:"required"`
+ } `json:"files"`
+ }
+ if err := json.Unmarshal([]byte(files["manifest.json"]), &m); err != nil {
+ t.Fatalf("manifest.json: %v (%q)", err, files["manifest.json"])
+ }
+ if m.ManifestType != "minecraftModpack" || m.Name != "Persisted Server" ||
+ m.Version != "2.0.0" || m.Overrides != "overrides" {
+ t.Errorf("header = type=%q name=%q version=%q overrides=%q",
+ m.ManifestType, m.Name, m.Version, m.Overrides)
+ }
+ if m.Minecraft.Version != "1.21.1" || len(m.Minecraft.ModLoaders) != 1 ||
+ m.Minecraft.ModLoaders[0].ID != "neoforge-21.1.77" || !m.Minecraft.ModLoaders[0].Primary {
+ t.Errorf("minecraft = %+v", m.Minecraft)
+ }
+ // Both the server-side and the client-only CF-hosted mods are listed.
+ if len(m.Files) != 2 {
+ t.Fatalf("files = %+v, want 2 CF entries", m.Files)
+ }
+ seen := map[int64]int64{}
+ for _, f := range m.Files {
+ if !f.Required {
+ t.Errorf("file %d not required", f.ProjectID)
+ }
+ seen[f.ProjectID] = f.FileID
+ }
+ if seen[111] != 1111 || seen[222] != 2222 {
+ t.Errorf("CF ids = %v", seen)
+ }
+
+ // Overrides: live config + hand-added mod + downloaded client-only file;
+ // the CF-covered mod must not be duplicated; excluded dirs stay out.
+ if files["overrides/config/pack.toml"] != "edited-on-server" {
+ t.Errorf("server config = %q", files["overrides/config/pack.toml"])
+ }
+ if files["overrides/mods/local-extra.jar"] != "hand-added" {
+ t.Error("hand-added mod missing")
+ }
+ if _, ok := files["overrides/mods/server-mod.jar"]; ok {
+ t.Error("CF-covered mod duplicated into overrides")
+ }
+ if files["overrides/resourcepacks/look.zip"] != "client-only-bytes" {
+ t.Errorf("client-only direct file = %q", files["overrides/resourcepacks/look.zip"])
+ }
+ for name := range files {
+ if name == "overrides/world/level.dat" {
+ t.Errorf("banned path in zip: %s", name)
+ }
+ }
+}
diff --git a/engine/internal/modpack/export_test.go b/engine/internal/modpack/export_test.go
new file mode 100644
index 0000000..24601cf
--- /dev/null
+++ b/engine/internal/modpack/export_test.go
@@ -0,0 +1,215 @@
+package modpack
+
+import (
+ "archive/zip"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/000hen/justhostmc/engine/internal/provider"
+)
+
+// fixtureManifest mirrors the FTB version-manifest fields Export consumes.
+const fixtureManifest = `{
+ "name": "1.5.0",
+ "targets": [
+ { "type": "game", "version": "1.21.1" },
+ { "type": "modloader", "name": "neoforge", "version": "21.1.77" }
+ ],
+ "files": [
+ { "path": "./mods/", "name": "server-mod.jar", "clientonly": false,
+ "curseforge": { "project": "111", "file": "1111" } },
+ { "path": "./mods/", "name": "client-mod.jar", "clientonly": true,
+ "curseforge": { "project": 222, "file": 2222 } },
+ { "path": "./config/", "name": "pack.toml", "clientonly": false,
+ "url": "IGNORED-server-file-comes-from-disk" },
+ { "path": "./resourcepacks/", "name": "look.zip", "clientonly": true,
+ "url": "%s/blob/look.zip" }
+ ]
+}`
+
+func exportFixture(t *testing.T) (Options, string) {
+ t.Helper()
+ mux := http.NewServeMux()
+ var base string
+ mux.HandleFunc("/modpack/95/300", func(w http.ResponseWriter, _ *http.Request) {
+ fmt.Fprintf(w, fixtureManifest, base)
+ })
+ mux.HandleFunc("/blob/look.zip", func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte("client-only-bytes"))
+ })
+ srv := httptest.NewServer(mux)
+ base = srv.URL
+ t.Cleanup(srv.Close)
+
+ serverDir := t.TempDir()
+ mustWrite := func(rel, content string) {
+ full := filepath.Join(serverDir, filepath.FromSlash(rel))
+ if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(full, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ mustWrite("config/pack.toml", "edited-on-server")
+ mustWrite("config/nested/extra.json", "{}")
+ mustWrite("kubejs/server_scripts/recipes.js", "// kubejs")
+ mustWrite("mods/server-mod.jar", "cf-covered-jar") // covered by CF entry → excluded
+ mustWrite("mods/local-extra.jar", "hand-added-jar") // not in manifest → included
+ mustWrite("world/level.dat", "world") // excluded
+ mustWrite("logs/latest.log", "log") // excluded
+ mustWrite("libraries/dep.jar", "lib") // excluded
+ mustWrite("server.properties", "server-port=25565") // excluded
+ mustWrite("eula.txt", "eula=true") // excluded
+ mustWrite("neoforge-installer.jar", "root installer") // excluded (root jar)
+
+ dest := filepath.Join(t.TempDir(), "out.zip")
+ return Options{
+ ServerDir: serverDir,
+ DestZip: dest,
+ PackVersion: "95/300",
+ ServerName: "My Pack Server",
+ FTBAPIBase: srv.URL,
+ }, dest
+}
+
+func readZip(t *testing.T, dest string) map[string]string {
+ t.Helper()
+ zr, err := zip.OpenReader(dest)
+ if err != nil {
+ t.Fatalf("open zip: %v", err)
+ }
+ defer zr.Close()
+ out := map[string]string{}
+ for _, f := range zr.File {
+ rc, err := f.Open()
+ if err != nil {
+ t.Fatalf("open %s: %v", f.Name, err)
+ }
+ b, _ := io.ReadAll(rc)
+ rc.Close()
+ out[f.Name] = string(b)
+ }
+ return out
+}
+
+func TestExportBuildsCurseForgeManifest(t *testing.T) {
+ opts, dest := exportFixture(t)
+ if err := Export(context.Background(), http.DefaultClient, opts, nil); err != nil {
+ t.Fatalf("Export: %v", err)
+ }
+ files := readZip(t, dest)
+
+ var m struct {
+ ManifestType string `json:"manifestType"`
+ ManifestVersion int `json:"manifestVersion"`
+ Name string `json:"name"`
+ Version string `json:"version"`
+ Overrides string `json:"overrides"`
+ Minecraft struct {
+ Version string `json:"version"`
+ ModLoaders []struct {
+ ID string `json:"id"`
+ Primary bool `json:"primary"`
+ } `json:"modLoaders"`
+ } `json:"minecraft"`
+ Files []struct {
+ ProjectID int64 `json:"projectID"`
+ FileID int64 `json:"fileID"`
+ Required bool `json:"required"`
+ } `json:"files"`
+ }
+ if err := json.Unmarshal([]byte(files["manifest.json"]), &m); err != nil {
+ t.Fatalf("manifest.json: %v (%q)", err, files["manifest.json"])
+ }
+ if m.ManifestType != "minecraftModpack" || m.ManifestVersion != 1 {
+ t.Errorf("manifest type/version = %s/%d", m.ManifestType, m.ManifestVersion)
+ }
+ if m.Name != "My Pack Server" || m.Version != "1.5.0" || m.Overrides != "overrides" {
+ t.Errorf("name/version/overrides = %q/%q/%q", m.Name, m.Version, m.Overrides)
+ }
+ if m.Minecraft.Version != "1.21.1" ||
+ len(m.Minecraft.ModLoaders) != 1 || m.Minecraft.ModLoaders[0].ID != "neoforge-21.1.77" ||
+ !m.Minecraft.ModLoaders[0].Primary {
+ t.Errorf("minecraft block = %+v", m.Minecraft)
+ }
+ // Both the server-side AND the clientonly CF-hosted mods are listed.
+ if len(m.Files) != 2 {
+ t.Fatalf("files = %+v, want 2 CF entries", m.Files)
+ }
+ seen := map[int64]int64{}
+ for _, f := range m.Files {
+ if !f.Required {
+ t.Errorf("file %d not required", f.ProjectID)
+ }
+ seen[f.ProjectID] = f.FileID
+ }
+ if seen[111] != 1111 || seen[222] != 2222 {
+ t.Errorf("CF ids = %v", seen)
+ }
+}
+
+func TestExportOverridesContents(t *testing.T) {
+ opts, dest := exportFixture(t)
+ if err := Export(context.Background(), http.DefaultClient, opts, nil); err != nil {
+ t.Fatalf("Export: %v", err)
+ }
+ files := readZip(t, dest)
+
+ if files["overrides/config/pack.toml"] != "edited-on-server" {
+ t.Errorf("server-edited config missing or wrong: %q", files["overrides/config/pack.toml"])
+ }
+ if _, ok := files["overrides/config/nested/extra.json"]; !ok {
+ t.Error("nested config missing")
+ }
+ if _, ok := files["overrides/kubejs/server_scripts/recipes.js"]; !ok {
+ t.Error("kubejs missing")
+ }
+ if files["overrides/mods/local-extra.jar"] != "hand-added-jar" {
+ t.Error("hand-added mod missing from overrides")
+ }
+ if _, ok := files["overrides/mods/server-mod.jar"]; ok {
+ t.Error("CF-covered mod duplicated into overrides")
+ }
+ // Client-only direct-URL file downloaded at export time.
+ if files["overrides/resourcepacks/look.zip"] != "client-only-bytes" {
+ t.Errorf("clientonly direct file = %q", files["overrides/resourcepacks/look.zip"])
+ }
+ for name := range files {
+ for _, banned := range []string{"overrides/world/", "overrides/logs/", "overrides/libraries/",
+ "overrides/server.properties", "overrides/eula.txt", "overrides/neoforge-installer.jar"} {
+ if strings.HasPrefix(name, banned) {
+ t.Errorf("banned path in zip: %s", name)
+ }
+ }
+ }
+}
+
+func TestExportEmitsProgressSteps(t *testing.T) {
+ opts, dest := exportFixture(t)
+ var steps []string
+ err := Export(context.Background(), http.DefaultClient, opts, func(p provider.Progress) {
+ if p.Step != "" {
+ steps = append(steps, p.Step)
+ }
+ })
+ if err != nil {
+ t.Fatalf("Export: %v", err)
+ }
+ joined := strings.Join(steps, ",")
+ if !strings.Contains(joined, "shop.export.preparing") ||
+ !strings.Contains(joined, "shop.export.zipping") {
+ t.Errorf("steps = %v", steps)
+ }
+ if _, err := os.Stat(dest); err != nil {
+ t.Errorf("dest zip missing: %v", err)
+ }
+}
diff --git a/engine/internal/provider/errors.go b/engine/internal/provider/errors.go
index 4c9e367..2e619b6 100644
--- a/engine/internal/provider/errors.go
+++ b/engine/internal/provider/errors.go
@@ -11,4 +11,6 @@ var (
ErrChecksumMismatch = errors.New("downloaded file failed checksum verification")
// ErrInstallerFailed means an installer (Forge/NeoForge) did not complete.
ErrInstallerFailed = errors.New("server installer failed")
+ // ErrUpdateUnsupported means the provider has no update() entry point.
+ ErrUpdateUnsupported = errors.New("provider does not support update")
)
diff --git a/engine/internal/provider/provider.go b/engine/internal/provider/provider.go
index 78d50f0..5a50f3d 100644
--- a/engine/internal/provider/provider.go
+++ b/engine/internal/provider/provider.go
@@ -19,6 +19,16 @@ type Progress struct {
type LaunchSpec struct {
JavaMajor int // required Java feature version: 8 / 17 / 21 …
Args []string // JVM/program args, e.g. ["-jar", "server.jar", "nogui"]
+ // McVersion, when non-empty, is the concrete Minecraft version the install
+ // resolved to; it overrides the request's version on the server record (a
+ // modpack provider takes an opaque "packId/versionId" and resolves the real
+ // MC version here). Loader is the effective mod loader ("fabric"/"forge"/…).
+ McVersion string
+ Loader string
+ // PackVersion is the opaque provider pack version ("packId/versionId") a
+ // modpack provider echoes back so it can be persisted for later update and
+ // export; empty for normal providers.
+ PackVersion string
}
// JavaResolver resolves (downloading if needed) a java.exe for a Java major
@@ -36,6 +46,14 @@ type Provider interface {
Install(ctx context.Context, dir, version string, progress func(Progress)) (LaunchSpec, error)
}
+// Updater is optionally implemented by providers that can move an installed
+// server to another version in place (e.g. a modpack manifest diff).
+// Implementations return ErrUpdateUnsupported when the underlying script has
+// no update() entry point.
+type Updater interface {
+ Update(ctx context.Context, dir, version, oldVersion string, progress func(Progress)) (LaunchSpec, error)
+}
+
// report sends progress if a sink is set; it keeps call sites terse.
func report(progress func(Progress), p Progress) {
if progress != nil {
diff --git a/engine/internal/scripting/automation/manager.go b/engine/internal/scripting/automation/manager.go
index a802a2e..fd0f018 100644
--- a/engine/internal/scripting/automation/manager.go
+++ b/engine/internal/scripting/automation/manager.go
@@ -24,6 +24,7 @@ type ManagerConfig struct {
Players PlayerManager
Events PlayerEvents
KV scripting.KV
+ Config *scripting.ConfigStore
}
// Manager owns the set of automation scripts and the goroutines backing the
@@ -54,6 +55,21 @@ func NewManager(cfg ManagerConfig) *Manager {
// Logs returns the engine-wide automation log ring buffer (for StreamLog).
func (m *Manager) Logs() *scriptlog.LogBuffer { return m.logs }
+// configFor resolves the typed config values a script sees as jhmc.config,
+// merging declared defaults with stored overrides. Returns nil (no jhmc.config)
+// when the script declares no config and none is stored.
+func (m *Manager) configFor(meta scripting.Meta) map[string]string {
+ var stored map[string]string
+ if m.cfg.Config != nil {
+ stored = m.cfg.Config.Values(meta.ID)
+ }
+ eff := scripting.EffectiveConfig(meta.Config, stored)
+ if len(eff) == 0 {
+ return nil
+ }
+ return eff
+}
+
// AddSource compiles an automation script and registers it (disabled). builtin
// marks first-party scripts, whose declared permissions are granted by default.
func (m *Manager) AddSource(ctx context.Context, source string, builtin bool) (*Automation, error) {
@@ -212,6 +228,7 @@ func (m *Manager) start(a *Automation, granted scripting.GrantSet) (*runner, err
Granted: granted,
KV: m.cfg.KV,
ScriptID: a.meta.ID,
+ Config: m.configFor(a.meta),
})
L := scripting.NewSandbox(ctx)
L.SetGlobal("jhmc", inv.NewJHMC(L))
diff --git a/engine/internal/scripting/builtin/import.lua b/engine/internal/scripting/builtin/import.lua
new file mode 100644
index 0000000..3aad430
--- /dev/null
+++ b/engine/internal/scripting/builtin/import.lua
@@ -0,0 +1,68 @@
+-- Local modpack import provider: installs a server from a modpack file the user
+-- picked on their machine (a CurseForge client pack zip or a Modrinth .mrpack).
+-- Hidden from the create-server UI — the ImportModpack RPC stages the file into
+-- the new server dir at .jhmc/import.zip and drives this provider. It detects the
+-- format and reuses the shared mplib install routines, so an imported server
+-- carries the same normalized manifest as a shop-installed one (Export works).
+-- There is no update() — a local file has no upstream version to diff against.
+
+meta = {
+ id = "import",
+ name = "Imported Modpack",
+ website = "",
+ description = "Installs a server from a local CurseForge or Modrinth modpack file.",
+ version = "1.0.0",
+ author = "JustHostMC",
+ mod_layout = "mods",
+ hidden = true,
+ permissions = {
+ { kind = "network", reason = "Download the pack's mods and the loader installer." },
+ { kind = "install", reason = "Resolve a JRE and run the Forge/NeoForge installer's --installServer." },
+ { kind = "fs_server", reason = "Unpack the modpack and detect the launch command." },
+ },
+ config = {
+ { key = "curseforge_api_key", type = "secret", name = "CurseForge API key",
+ description = "Required only when importing a CurseForge pack with CurseForge-hosted mods", required = false },
+ },
+}
+
+local STAGED = ".jhmc/import.zip"
+
+function versions()
+ return {}
+end
+
+local function key(ctx)
+ local cfg = ctx.config or {}
+ return cfg.curseforge_api_key or ""
+end
+
+function install(ctx)
+ local entries = jhmc.zip_entries(STAGED)
+ local has = {}
+ for _, e in ipairs(entries) do has[e] = true end
+
+ ctx.step("install.progress.resolving_version", -1)
+ local spec
+ if has["manifest.json"] then
+ local k = key(ctx)
+ if k == "" then
+ error("this CurseForge modpack needs a CurseForge API key to resolve its mods (set it in the provider settings)")
+ end
+ spec = mplib.install_cf_pack(ctx, STAGED, k)
+ elseif has["modrinth.index.json"] then
+ spec = mplib.install_mrpack(ctx, STAGED)
+ else
+ error("not a recognized modpack file: expected a CurseForge manifest.json or a Modrinth modrinth.index.json")
+ end
+
+ jhmc.fs.remove(STAGED)
+
+ ctx.step("install.progress.done", 1)
+ local version = (spec.version_name and spec.version_name ~= "") and spec.version_name or "local"
+ spec.version_name = nil
+ -- A non-empty pack_version enables the Export action; the "import" provider id
+ -- is how the app keeps the Update action hidden (no upstream to diff against).
+ spec.pack_version = "import/" .. version
+ return spec
+end
diff --git a/engine/internal/scripting/builtin_lib/modpack.lua b/engine/internal/scripting/builtin_lib/modpack.lua
new file mode 100644
index 0000000..4e26e29
--- /dev/null
+++ b/engine/internal/scripting/builtin_lib/modpack.lua
@@ -0,0 +1,522 @@
+-- Shared modpack helpers exposed as the global `mplib`. Providers that install a
+-- modpack (FTB, CurseForge, Modrinth, local import) build on these instead of
+-- copying the loader-install steps and manifest bookkeeping. Loaded into every
+-- sandbox by prepare(); side-effect-free at load time (defines functions only,
+-- no network or filesystem access).
+
+local M = {}
+
+local FABRIC_META = "https://meta.fabricmc.net/v2"
+local FORGE_MAVEN = "https://maven.minecraftforge.net/net/minecraftforge/forge"
+local NEOFORGE_MAVEN = "https://maven.neoforged.net/releases/net/neoforged/neoforge"
+
+-- Where the normalized modpack manifest is persisted inside a server dir. Export
+-- and update read it back so they work without re-fetching the upstream source.
+local MANIFEST_DIR = ".jhmc"
+local MANIFEST_PATH = ".jhmc/modpack.json"
+
+M.MANIFEST_PATH = MANIFEST_PATH
+
+-- join_path turns a { path = "./mods/", name = "x.jar" } pair into a clean
+-- relative destination, rejecting any parent-directory segment. Host fs calls
+-- also confine writes to the server dir, so this is defense in depth.
+local function join_path(path, name)
+ local p = (path or ""):gsub("\\", "/")
+ p = p:gsub("^%./", ""):gsub("^/+", "")
+ if p ~= "" and not p:match("/$") then
+ p = p .. "/"
+ end
+ local dest = p .. (name or "")
+ for seg in dest:gmatch("[^/]+") do
+ if seg == ".." then
+ error("unsafe file path in modpack: " .. dest)
+ end
+ end
+ return dest
+end
+M.join_path = join_path
+
+-- safe_path validates an already-joined relative path (e.g. a Modrinth file
+-- "path" field) the same way join_path validates its output, returning it
+-- cleaned.
+local function safe_path(p)
+ p = (p or ""):gsub("\\", "/"):gsub("^%./", ""):gsub("^/+", "")
+ for seg in p:gmatch("[^/]+") do
+ if seg == ".." then
+ error("unsafe file path in modpack: " .. p)
+ end
+ end
+ return p
+end
+M.safe_path = safe_path
+
+-- cf_resolve_item builds a download_all entry for a CurseForge-hosted file whose
+-- real URL is resolved inside the batch via the download-url endpoint (403 there
+-- means the author disallows third-party downloads).
+local function cf_resolve_item(dest, sha1, project, file, key)
+ return {
+ dest = dest,
+ sha1 = sha1,
+ resolve = {
+ url = "https://api.curseforge.com/v1/mods/" .. project ..
+ "/files/" .. file .. "/download-url",
+ headers = { ["x-api-key"] = key },
+ },
+ }
+end
+M.cf_resolve_item = cf_resolve_item
+
+-- find_args_file walks libraries/ for a generated win_args.txt. jhmc.fs.glob is
+-- backed by Go's filepath.Glob (no recursive "**"), so probe nesting depths.
+local function find_args_file()
+ local prefix = "libraries"
+ for _ = 1, 8 do
+ prefix = prefix .. "/*"
+ local hits = jhmc.fs.glob(prefix .. "/win_args.txt")
+ if hits[1] then
+ return hits[1]
+ end
+ end
+ return nil
+end
+M.find_args_file = find_args_file
+
+-- detect_launch prefers a generated win_args.txt arg file under libraries/, else
+-- a runnable non-installer jar matching one of jar_patterns.
+local function detect_launch(jar_patterns)
+ local args_file = find_args_file()
+ if args_file then
+ return { "@" .. args_file, "nogui" }
+ end
+ for _, pat in ipairs(jar_patterns) do
+ for _, jar in ipairs(jhmc.fs.glob(pat)) do
+ if not jar:lower():find("installer") then
+ return { "-jar", jar, "nogui" }
+ end
+ end
+ end
+ error("no win_args.txt or server jar after install")
+end
+M.detect_launch = detect_launch
+
+-- fabric_installer returns the newest stable Fabric installer version (the loader
+-- version itself is pinned by the pack).
+local function fabric_installer()
+ local entries = jhmc.http_json(FABRIC_META .. "/versions/installer")
+ for _, e in ipairs(entries) do
+ if e.stable and (e.version or "") ~= "" then return e.version end
+ end
+ for _, e in ipairs(entries) do
+ if (e.version or "") ~= "" then return e.version end
+ end
+ error("version not found: fabric installer")
+end
+
+local function install_fabric(ctx, mc, loader_version)
+ local installer = fabric_installer()
+ local url = FABRIC_META .. "/versions/loader/" .. mc .. "/" .. loader_version ..
+ "/" .. installer .. "/server/jar"
+ ctx.step("install.progress.downloading_server", 0)
+ ctx.log("server.jar")
+ jhmc.download(url, { dest = "server.jar" })
+ return { "-jar", "server.jar", "nogui" }
+end
+M.install_fabric = install_fabric
+
+-- strip_mc_prefix removes a leading "-" from a loader version, so a pack that
+-- pins forge as either "47.2.0" or "1.20.1-47.2.0" yields the same coordinate.
+local function strip_mc_prefix(version, mc)
+ local pfx = mc .. "-"
+ if version:sub(1, #pfx) == pfx then
+ return version:sub(#pfx + 1)
+ end
+ return version
+end
+M.strip_mc_prefix = strip_mc_prefix
+
+local function install_forge(ctx, mc, forge_version, java_major)
+ local full = mc .. "-" .. strip_mc_prefix(forge_version, mc)
+ local url = FORGE_MAVEN .. "/" .. full .. "/forge-" .. full .. "-installer.jar"
+ ctx.step("install.progress.downloading_installer", 0)
+ ctx.log("forge-" .. full .. "-installer.jar")
+ jhmc.download(url, { dest = "installer.jar" })
+ ctx.step("install.progress.running_installer", -1)
+ ctx.log("java -jar installer.jar --installServer")
+ jhmc.run_jar({ java_major = java_major, args = { "-jar", "installer.jar", "--installServer" }, dir = "." })
+ return detect_launch({ "forge*.jar", "server.jar" })
+end
+M.install_forge = install_forge
+
+local function install_neoforge(ctx, neoforge_version, java_major)
+ local url = NEOFORGE_MAVEN .. "/" .. neoforge_version ..
+ "/neoforge-" .. neoforge_version .. "-installer.jar"
+ ctx.step("install.progress.downloading_installer", 0)
+ ctx.log("neoforge-" .. neoforge_version .. "-installer.jar")
+ jhmc.download(url, { dest = "installer.jar" })
+ ctx.step("install.progress.running_installer", -1)
+ ctx.log("java -jar installer.jar --installServer")
+ jhmc.run_jar({ java_major = java_major, args = { "-jar", "installer.jar", "--installServer" }, dir = "." })
+ return detect_launch({ "neoforge*.jar", "forge*.jar", "server.jar" })
+end
+M.install_neoforge = install_neoforge
+
+-- install_loader installs the pinned mod loader and returns the launch args.
+local function install_loader(ctx, name, version, mc, java_major)
+ if name == "fabric" then
+ return install_fabric(ctx, mc, version)
+ elseif name == "forge" then
+ return install_forge(ctx, mc, version, java_major)
+ elseif name == "neoforge" then
+ return install_neoforge(ctx, version, java_major)
+ end
+ error("unsupported modloader: " .. name)
+end
+M.install_loader = install_loader
+
+-- to_download_item turns one normalized file entry into a jhmc.download_all item.
+-- Directly-hosted files carry a url; CurseForge-hosted ones (project_id +
+-- file_id, no url) resolve their real URL in the batch and need an API key.
+local function to_download_item(f, key)
+ if (f.url or "") ~= "" then
+ return { dest = f.dest, sha1 = f.sha1, url = f.url }
+ end
+ if f.project_id and f.file_id then
+ if (key or "") == "" then
+ error("install failed: file " .. tostring(f.dest) ..
+ " is hosted on CurseForge and needs a CurseForge API key (set it in the provider settings)")
+ end
+ return cf_resolve_item(f.dest, f.sha1, f.project_id, f.file_id, key)
+ end
+ error("install failed: file " .. tostring(f.dest) .. " has no download source")
+end
+M.to_download_item = to_download_item
+
+-- download_files downloads the server-side (non-client_only) files of a
+-- normalized manifest in one parallel batch. The missing-key check runs up
+-- front, before anything downloads.
+local function download_files(ctx, files, key)
+ local items = {}
+ for _, f in ipairs(files or {}) do
+ if type(f) == "table" and not f.client_only and (f.dest or "") ~= "" then
+ items[#items + 1] = to_download_item(f, key)
+ end
+ end
+ if #items == 0 then return end
+ ctx.step("shop.install.downloading", 0)
+ jhmc.download_all(items)
+end
+M.download_files = download_files
+
+-- index_by_dest turns a normalized files array into a dest -> entry map.
+local function index_by_dest(files)
+ local by_dest = {}
+ for _, f in ipairs(files or {}) do
+ if type(f) == "table" and (f.dest or "") ~= "" then
+ by_dest[f.dest] = f
+ end
+ end
+ return by_dest
+end
+M.index_by_dest = index_by_dest
+
+-- server_index is index_by_dest restricted to server-side (non-client_only)
+-- files — the set that actually lives on disk, and the correct input for an
+-- update diff so a file that was client-only in the old version is treated as
+-- new rather than assumed present.
+local function server_index(files)
+ local by_dest = {}
+ for _, f in ipairs(files or {}) do
+ if type(f) == "table" and not f.client_only and (f.dest or "") ~= "" then
+ by_dest[f.dest] = f
+ end
+ end
+ return by_dest
+end
+M.server_index = server_index
+
+-- diff_apply reconciles an installed set of files (old_files: dest -> normalized
+-- entry) with a target set (new_files). Files the target dropped are deleted;
+-- new or changed server files are downloaded in one batch. opts.changed(old,
+-- new) decides whether an existing dest must be re-downloaded (default: sha1
+-- differs); opts.to_item(entry) maps a target entry to a download_all item.
+local function diff_apply(ctx, old_files, new_files, opts)
+ local changed = opts.changed or function(old, new)
+ return (old.sha1 or "") ~= (new.sha1 or "")
+ end
+ local to_item = opts.to_item
+
+ -- Delete files the new version dropped (guarded by existence: client-only
+ -- entries were never written to the server dir).
+ for dest in pairs(old_files) do
+ if not new_files[dest] and jhmc.fs.exists(dest) then
+ ctx.log("- " .. dest)
+ jhmc.fs.remove(dest)
+ end
+ end
+
+ -- Download new files and files whose pack version changed.
+ local items = {}
+ for dest, f in pairs(new_files) do
+ if not f.client_only then
+ local old = old_files[dest]
+ if not old or changed(old, f) then
+ items[#items + 1] = to_item(f)
+ end
+ end
+ end
+ if #items == 0 then return end
+ ctx.step("shop.install.downloading", 0)
+ jhmc.download_all(items)
+end
+M.diff_apply = diff_apply
+
+-- write_manifest persists the normalized modpack manifest into the server dir.
+local function write_manifest(tbl)
+ jhmc.fs.mkdir(MANIFEST_DIR)
+ jhmc.fs.write(MANIFEST_PATH, jhmc.json_encode(tbl))
+end
+M.write_manifest = write_manifest
+
+-- read_manifest loads the normalized manifest, or returns nil when absent.
+local function read_manifest()
+ if not jhmc.fs.exists(MANIFEST_PATH) then
+ return nil
+ end
+ return jhmc.json_decode(jhmc.fs.read(MANIFEST_PATH))
+end
+M.read_manifest = read_manifest
+
+-- ── CurseForge client pack (manifest.json + overrides/) ─────────────────────
+
+local CF_API = "https://api.curseforge.com"
+
+-- parse_loader splits a CurseForge modLoader id ("forge-47.2.0") into loader
+-- name and version.
+local function parse_loader(id)
+ local name, ver = tostring(id):match("^([^-]+)-(.+)$")
+ if not name then
+ return string.lower(tostring(id)), nil
+ end
+ return string.lower(name), ver
+end
+M.parse_loader = parse_loader
+
+local function cf_post(url, body_tbl, key)
+ if (key or "") == "" then
+ error("this modpack is hosted on CurseForge and needs a CurseForge API key (set it in the provider settings)")
+ end
+ local res = jhmc.http({
+ url = url,
+ method = "POST",
+ body = jhmc.json_encode(body_tbl),
+ headers = { ["x-api-key"] = key, ["Content-Type"] = "application/json" },
+ })
+ if res.status < 200 or res.status >= 300 then
+ error("curseforge: HTTP " .. res.status .. " for " .. url)
+ end
+ return jhmc.json_decode(res.body)
+end
+
+local function cf_sha1(f)
+ for _, h in ipairs(f.hashes or {}) do
+ if h.algo == 1 then return h.value end -- HashAlgo 1 = Sha1
+ end
+ return nil
+end
+
+-- cf_pack_meta reads a CurseForge client pack's manifest.json from a zip already
+-- on disk, resolves every listed file's real name/hash/url via one batch call,
+-- and returns { name, version, mc, loader_name, loader_version, files } with
+-- files in mplib's normalized shape. No filesystem writes — install/update layer
+-- their own steps on top. CurseForge manifests carry only project+file ids, so a
+-- key is required to learn the filenames.
+local function cf_pack_meta(zip_rel, key)
+ local manifest = jhmc.json_decode(jhmc.zip_read(zip_rel, "manifest.json"))
+ if type(manifest) ~= "table" or type(manifest.minecraft) ~= "table" then
+ error("not a CurseForge modpack: manifest.json missing the minecraft block")
+ end
+ local mc = manifest.minecraft.version
+ if not mc or mc == "" then
+ error("CurseForge pack has no Minecraft version")
+ end
+ local loader_name, loader_version
+ for _, ml in ipairs(manifest.minecraft.modLoaders or {}) do
+ if ml.primary or not loader_name then
+ loader_name, loader_version = parse_loader(ml.id)
+ end
+ end
+ if not loader_name then
+ error("CurseForge pack has no mod loader")
+ end
+
+ -- Resolve names/hashes/urls for all files in one batch request.
+ local file_ids = {}
+ for _, f in ipairs(manifest.files or {}) do
+ if f.fileID then
+ file_ids[#file_ids + 1] = f.fileID
+ end
+ end
+ local details = {}
+ if #file_ids > 0 then
+ local body = cf_post(CF_API .. "/v1/mods/files", { fileIds = file_ids }, key)
+ for _, d in ipairs(body.data or {}) do
+ details[tostring(d.id)] = d
+ end
+ end
+
+ local files = {}
+ for _, f in ipairs(manifest.files or {}) do
+ local d = details[tostring(f.fileID)]
+ if d then
+ -- CurseForge client packs place all listed mods under mods/.
+ local entry = {
+ dest = "mods/" .. d.fileName,
+ sha1 = cf_sha1(d),
+ project_id = f.projectID,
+ file_id = f.fileID,
+ }
+ if (d.downloadUrl or "") ~= "" then
+ entry.url = d.downloadUrl
+ end
+ files[#files + 1] = entry
+ elseif f.required ~= false then
+ error("CurseForge pack references a file that is no longer available (project " ..
+ tostring(f.projectID) .. ", file " .. tostring(f.fileID) .. ")")
+ end
+ end
+
+ return {
+ name = manifest.name or "",
+ version = manifest.version or "",
+ mc = mc,
+ loader_name = loader_name,
+ loader_version = loader_version,
+ files = files,
+ }
+end
+M.cf_pack_meta = cf_pack_meta
+
+-- install_cf_pack installs a CurseForge client pack whose zip is already on disk
+-- at zip_rel: it downloads the listed mods, splats overrides/ into the server
+-- root, installs the pinned loader, and persists the normalized manifest. The
+-- returned launch spec has no pack_version — the caller sets it.
+local function install_cf_pack(ctx, zip_rel, key)
+ local m = cf_pack_meta(zip_rel, key)
+ download_files(ctx, m.files, key)
+ jhmc.unzip(zip_rel, ".", { prefix = "overrides/" })
+
+ local java_major = jhmc.java_major_for(m.mc)
+ local args = install_loader(ctx, m.loader_name, m.loader_version, m.mc, java_major)
+
+ write_manifest({
+ format = 1,
+ name = m.name,
+ version_name = m.version,
+ mc_version = m.mc,
+ loader = m.loader_name,
+ loader_version = m.loader_version,
+ files = m.files,
+ })
+ return {
+ java_major = java_major,
+ args = args,
+ mc_version = m.mc,
+ loader = m.loader_name,
+ version_name = m.version, -- used by the import provider to label the pack
+ }
+end
+M.install_cf_pack = install_cf_pack
+
+-- ── Modrinth pack (.mrpack: modrinth.index.json + overrides/) ───────────────
+
+-- mrpack_meta reads a .mrpack's modrinth.index.json (the mrpack is a zip already
+-- on disk) and returns { name, version, mc, loader_name, loader_version, files }.
+-- Files unsupported on the server are kept but flagged client_only so export can
+-- round-trip them; install/update skip them. Keyless — Modrinth files carry
+-- direct download URLs.
+local function mrpack_meta(zip_rel)
+ local idx = jhmc.json_decode(jhmc.zip_read(zip_rel, "modrinth.index.json"))
+ if type(idx) ~= "table" or type(idx.dependencies) ~= "table" then
+ error("not a Modrinth modpack: modrinth.index.json missing or malformed")
+ end
+ local deps = idx.dependencies
+ local mc = deps.minecraft
+ if not mc or mc == "" then
+ error("Modrinth pack has no Minecraft version")
+ end
+ local loader_name, loader_version
+ if deps["fabric-loader"] then
+ loader_name, loader_version = "fabric", deps["fabric-loader"]
+ elseif deps["neoforge"] then
+ loader_name, loader_version = "neoforge", deps["neoforge"]
+ elseif deps["forge"] then
+ loader_name, loader_version = "forge", deps["forge"]
+ elseif deps["quilt-loader"] then
+ error("Quilt modpacks are not supported yet")
+ else
+ error("Modrinth pack declares no supported mod loader")
+ end
+
+ local files = {}
+ for _, f in ipairs(idx.files or {}) do
+ local server_env = (f.env and f.env.server) or "required"
+ local entry = {
+ dest = safe_path(f.path),
+ sha1 = f.hashes and f.hashes.sha1,
+ url = f.downloads and f.downloads[1],
+ }
+ if server_env == "unsupported" then
+ entry.client_only = true
+ end
+ files[#files + 1] = entry
+ end
+
+ return {
+ name = idx.name or "",
+ version = idx.versionId or "",
+ mc = mc,
+ loader_name = loader_name,
+ loader_version = loader_version,
+ files = files,
+ }
+end
+M.mrpack_meta = mrpack_meta
+
+-- unzip_overrides splats a pack's overrides/ then server-overrides/ into the
+-- server root; server-overrides win because they are extracted last.
+local function unzip_overrides(zip_rel)
+ jhmc.unzip(zip_rel, ".", { prefix = "overrides/" })
+ jhmc.unzip(zip_rel, ".", { prefix = "server-overrides/" })
+end
+M.unzip_overrides = unzip_overrides
+
+-- install_mrpack installs a Modrinth pack whose .mrpack is already on disk at
+-- zip_rel. The returned launch spec has no pack_version — the caller sets it.
+local function install_mrpack(ctx, zip_rel)
+ local m = mrpack_meta(zip_rel)
+ download_files(ctx, m.files, nil)
+ unzip_overrides(zip_rel)
+
+ local java_major = jhmc.java_major_for(m.mc)
+ local args = install_loader(ctx, m.loader_name, m.loader_version, m.mc, java_major)
+
+ write_manifest({
+ format = 1,
+ name = m.name,
+ version_name = m.version,
+ mc_version = m.mc,
+ loader = m.loader_name,
+ loader_version = m.loader_version,
+ files = m.files,
+ })
+ return {
+ java_major = java_major,
+ args = args,
+ mc_version = m.mc,
+ loader = m.loader_name,
+ version_name = m.version, -- used by the import provider to label the pack
+ }
+end
+M.install_mrpack = install_mrpack
+
+mplib = M
diff --git a/engine/internal/scripting/builtin_shops_live_test.go b/engine/internal/scripting/builtin_shops_live_test.go
index 52b86bd..da342f1 100644
--- a/engine/internal/scripting/builtin_shops_live_test.go
+++ b/engine/internal/scripting/builtin_shops_live_test.go
@@ -14,8 +14,10 @@ func TestModrinthLive(t *testing.T) {
if os.Getenv("JHMC_INTEGRATION") != "1" {
t.Skip("set JHMC_INTEGRATION=1 to run live-API tests")
}
- ss := NewShopSet(NewHost(nil, nil, nil), nil, nil)
- if err := LoadBuiltinShops(context.Background(), ss); err != nil {
+ host := NewHost(nil, nil, nil)
+ ss := NewShopSet(host, nil, nil)
+ reg := NewRegistry(host, nil)
+ if _, err := LoadBuiltinSources(context.Background(), reg, ss, nil); err != nil {
t.Fatal(err)
}
sh, _ := ss.Get("modrinth")
diff --git a/engine/internal/scripting/builtin_shops_test.go b/engine/internal/scripting/builtin_shops_test.go
index 7430b1f..2a8d43d 100644
--- a/engine/internal/scripting/builtin_shops_test.go
+++ b/engine/internal/scripting/builtin_shops_test.go
@@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
+ "strings"
"sync/atomic"
"testing"
@@ -40,8 +41,11 @@ func newBuiltinShops(t *testing.T, handler http.Handler) *ShopSet {
}
return ""
})
- if err := LoadBuiltinShops(context.Background(), ss); err != nil {
- t.Fatalf("LoadBuiltinShops: %v", err)
+ // The shops now live in dual-role source scripts, registered alongside a
+ // (here unused) provider registry.
+ reg := NewRegistry(host, nil)
+ if _, err := LoadBuiltinSources(context.Background(), reg, ss, nil); err != nil {
+ t.Fatalf("LoadBuiltinSources: %v", err)
}
return ss
}
@@ -353,3 +357,141 @@ func TestCurseForgeVersionsMapsFiles(t *testing.T) {
t.Fatalf("deps: %+v", v.Dependencies)
}
}
+
+// ftbHandler fakes the FTB v1 API: browse endpoints return pack-id lists that
+// the shop hydrates from /modpack/{id}.
+func ftbHandler() http.Handler {
+ pack := func(id int, name string) map[string]any {
+ return map[string]any{
+ "id": id, "name": name, "synopsis": "a pack",
+ "description": "# " + name, "installs": 1000 + id,
+ "art": []map[string]any{
+ {"type": "splash", "url": "http://ftb/splash.png"},
+ {"type": "square", "url": "http://ftb/square.png"},
+ },
+ "authors": []map[string]any{{"name": "FTB Team"}},
+ "versions": []map[string]any{
+ {"id": 10, "name": "1.0.0", "type": "Release"},
+ {"id": 11, "name": "1.1.0", "type": "Beta"},
+ },
+ }
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ p := r.URL.Path
+ switch {
+ case strings.HasSuffix(p, "/modpack/featured/20"):
+ _ = json.NewEncoder(w).Encode(map[string]any{"packs": []int{101}, "total": 1})
+ case strings.HasSuffix(p, "/modpack/popular/installs/20"):
+ _ = json.NewEncoder(w).Encode(map[string]any{"packs": []int{202}, "total": 1})
+ case strings.Contains(p, "/modpack/search/"):
+ _ = json.NewEncoder(w).Encode(map[string]any{"packs": []int{303}, "total": 1})
+ case strings.HasSuffix(p, "/modpack/101"):
+ _ = json.NewEncoder(w).Encode(pack(101, "Featured Pack"))
+ case strings.HasSuffix(p, "/modpack/202"):
+ _ = json.NewEncoder(w).Encode(pack(202, "Popular Pack"))
+ case strings.HasSuffix(p, "/modpack/303"):
+ _ = json.NewEncoder(w).Encode(pack(303, "Search Pack"))
+ default:
+ http.NotFound(w, r)
+ }
+ })
+}
+
+func TestFTBShopMeta(t *testing.T) {
+ ss := newBuiltinShops(t, http.NotFoundHandler())
+ sh, ok := ss.Get("ftb")
+ if !ok {
+ t.Fatal("ftb shop not registered")
+ }
+ m := sh.Meta()
+ if m.NeedsKey || len(m.Kinds) != 1 || m.Kinds[0] != "modpack" {
+ t.Fatalf("ftb meta: needsKey=%v kinds=%v", m.NeedsKey, m.Kinds)
+ }
+ if !sh.Ready() {
+ t.Fatal("ftb should be ready (no key needed)")
+ }
+}
+
+func TestFTBHomeHydratesSections(t *testing.T) {
+ ss := newBuiltinShops(t, ftbHandler())
+ sh, _ := ss.Get("ftb")
+ sections, err := sh.Home(context.Background(), ShopQuery{Kind: "modpack"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(sections) != 2 {
+ t.Fatalf("sections = %d, want 2", len(sections))
+ }
+ f := sections[0]
+ if f.TitleKey != "shop.home.featured" || len(f.Projects) != 1 {
+ t.Fatalf("featured section: %+v", f)
+ }
+ c := f.Projects[0]
+ if c.ID != "101" || c.Title != "Featured Pack" || c.ProjectType != "modpack" ||
+ c.IconURL != "http://ftb/square.png" || c.Author != "FTB Team" {
+ t.Fatalf("featured card: %+v", c)
+ }
+ if sections[1].TitleKey != "shop.home.popular" || sections[1].Projects[0].ID != "202" {
+ t.Fatalf("popular section: %+v", sections[1])
+ }
+}
+
+func TestFTBSearchHydrates(t *testing.T) {
+ ss := newBuiltinShops(t, ftbHandler())
+ sh, _ := ss.Get("ftb")
+ page, err := sh.Search(context.Background(), ShopQuery{Query: "pack", Kind: "modpack", Limit: 20})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if page.Total != 1 || len(page.Projects) != 1 || page.Projects[0].ID != "303" {
+ t.Fatalf("page: total=%d projects=%+v", page.Total, page.Projects)
+ }
+}
+
+func TestFTBSearchOffsetStopsPagination(t *testing.T) {
+ ss := newBuiltinShops(t, ftbHandler())
+ sh, _ := ss.Get("ftb")
+ page, err := sh.Search(context.Background(), ShopQuery{Query: "pack", Offset: 20, Limit: 20})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(page.Projects) != 0 {
+ t.Fatalf("offset page should be empty, got %+v", page.Projects)
+ }
+}
+
+func TestFTBDetailAndVersions(t *testing.T) {
+ ss := newBuiltinShops(t, ftbHandler())
+ sh, _ := ss.Get("ftb")
+
+ d, err := sh.Detail(context.Background(), "101")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if d.Project.Title != "Featured Pack" || d.BodyFormat != "markdown" || d.Body != "# Featured Pack" {
+ t.Fatalf("detail: %+v", d)
+ }
+
+ vs, err := sh.Versions(context.Background(), "101", "", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(vs) != 2 {
+ t.Fatalf("versions = %d, want 2", len(vs))
+ }
+ // Newest-first: Beta 1.1.0 (id 11) before Release 1.0.0 (id 10).
+ if vs[0].ID != "11" || vs[0].VersionNumber != "1.1.0" || vs[0].Channel != "beta" {
+ t.Fatalf("v0: %+v", vs[0])
+ }
+ if vs[1].ID != "10" || vs[1].Channel != "release" {
+ t.Fatalf("v1: %+v", vs[1])
+ }
+}
+
+func TestFTBNotDistributable(t *testing.T) {
+ ss := newBuiltinShops(t, ftbHandler())
+ sh, _ := ss.Get("ftb")
+ if _, err := sh.ResolveFile(context.Background(), "101", "11", "", ""); !errors.Is(err, ErrShopNotDistributable) {
+ t.Fatalf("want ErrShopNotDistributable, got %v", err)
+ }
+}
diff --git a/engine/internal/scripting/builtin_shops/curseforge.lua b/engine/internal/scripting/builtin_sources/curseforge.lua
similarity index 58%
rename from engine/internal/scripting/builtin_shops/curseforge.lua
rename to engine/internal/scripting/builtin_sources/curseforge.lua
index a5e6b8f..a2ee46f 100644
--- a/engine/internal/scripting/builtin_shops/curseforge.lua
+++ b/engine/internal/scripting/builtin_sources/curseforge.lua
@@ -1,27 +1,36 @@
--- CurseForge mod shop. Talks to the CurseForge for Studios REST API
--- (https://docs.curseforge.com/rest-api/), which requires an x-api-key header
--- (meta.needs_key): the engine injects the key via ctx.config.api_key.
--- GET /v1/mods/search gameId=432, classId 6=mods 5=bukkit plugins
+-- CurseForge source: one script, two roles. The `shop` role browses/searches
+-- the CurseForge for Studios REST API (https://docs.curseforge.com/rest-api/)
+-- for mods, bukkit plugins and modpacks; the hidden `provider` role installs a
+-- CurseForge modpack as a self-contained server. Both roles share one meta.id
+-- ("curseforge") and one stored config entry: the x-api-key, declared once as
+-- meta.config.api_key (secret). The old split ids "curseforge_modpacks" resolve
+-- here via meta.aliases so existing modpack servers keep updating.
+-- GET /v1/mods/search gameId=432, classId 6=mods 5=bukkit plugins 4471=modpacks
-- GET /v1/categories class-specific search filters
--- GET /v1/mods/{id} detail card
--- GET /v1/mods/{id}/description full description (HTML)
--- GET /v1/mods/{id}/files gameVersion + modLoaderType filters
--- GET /v1/mods/{id}/files/{fileId} one file
+-- GET /v1/mods/{id} detail card
+-- GET /v1/mods/{id}/description full description (HTML)
+-- GET /v1/mods/{id}/files gameVersion + modLoaderType filters
+-- GET /v1/mods/{id}/files/{fileId} one file
-- GET /v1/mods/{id}/files/{fileId}/download-url fallback when downloadUrl is null
--- POST /v1/mods batch cards (dependency titles)
--- POST /v1/mods/featured featured/popular/recentlyUpdated
--- Page size caps at 50 and index+pageSize <= 10000.
+-- POST /v1/mods batch cards (dependency titles)
+-- POST /v1/mods/featured featured/popular/recentlyUpdated
meta = {
id = "curseforge",
name = "CurseForge",
website = "https://www.curseforge.com",
- description = "Browse and install mods and plugins from CurseForge.",
+ description = "Browse and install mods, plugins and modpacks from CurseForge.",
version = "1.0.0",
author = "JustHostMC",
- needs_key = true,
+ aliases = { "curseforge_modpacks" },
+ config = {
+ { key = "api_key", type = "secret", name = "CurseForge API key",
+ description = "Required to browse, resolve and download CurseForge files", required = false },
+ },
permissions = {
- { kind = "network", reason = "Query the CurseForge API to browse, search and download mods" },
+ { kind = "network", reason = "Query the CurseForge API to browse, search and download mods and modpacks" },
+ { kind = "install", reason = "Resolve a JRE and run the Forge/NeoForge installer's --installServer for a modpack." },
+ { kind = "fs_server", reason = "Write an installed modpack's mods/configs and detect the launch command." },
},
}
@@ -29,6 +38,7 @@ local API = "https://api.curseforge.com"
local GAME_MINECRAFT = 432
local CLASS_MODS = 6
local CLASS_BUKKIT_PLUGINS = 5
+local CLASS_MODPACKS = 4471
local TTL_BROWSE = 120
local TTL_DETAIL = 600
@@ -45,7 +55,7 @@ local function urlencode(s)
end))
end
-local api_key -- set per call from ctx.config
+local api_key -- set per shop call from ctx.config
local function check(res, url)
if res.status == 404 then error("curseforge: not found: " .. url) end
@@ -74,6 +84,7 @@ local function post(url, body_tbl)
end
local function class_id(kind)
+ if kind == "modpack" then return CLASS_MODPACKS end
if kind == "plugin" then return CLASS_BUKKIT_PLUGINS end
return CLASS_MODS
end
@@ -103,7 +114,8 @@ local function project_card(m, kind)
end
-- search_url builds /v1/mods/search. modLoaderType must be paired with a
--- gameVersion, and bukkit plugins have no loader dimension at all.
+-- gameVersion, and bukkit plugins have no loader dimension. Modpacks pin their
+-- own MC version and loader, so no version/loader dimension is applied.
local function search_url(ctx, sort_field, offset, limit)
local url = API .. "/v1/mods/search?gameId=" .. GAME_MINECRAFT
.. "&classId=" .. class_id(ctx.kind)
@@ -112,7 +124,7 @@ local function search_url(ctx, sort_field, offset, limit)
if (ctx.query or "") ~= "" then
url = url .. "&searchFilter=" .. urlencode(ctx.query)
end
- if (ctx.mc_version or "") ~= "" then
+ if ctx.kind ~= "modpack" and (ctx.mc_version or "") ~= "" then
url = url .. "&gameVersion=" .. urlencode(ctx.mc_version)
local lt = ctx.kind ~= "plugin" and LOADERS[ctx.loader or ""] or nil
if lt then url = url .. "&modLoaderType=" .. lt end
@@ -123,7 +135,7 @@ local function search_url(ctx, sort_field, offset, limit)
return url
end
-function categories(ctx)
+local function do_categories(ctx)
api_key = ctx.config.api_key
local class = class_id(ctx.kind or "mod")
local body = get(API .. "/v1/categories?gameId=" .. GAME_MINECRAFT
@@ -143,7 +155,7 @@ function categories(ctx)
return { categories = out }
end
-function search(ctx)
+local function do_search(ctx)
api_key = ctx.config.api_key
local sort_field = SORTS[ctx.sort] or SORTS.relevance
local body = get(search_url(ctx, sort_field, ctx.offset or 0, ctx.limit or 20), TTL_BROWSE)
@@ -155,8 +167,22 @@ function search(ctx)
return { projects = projects, total = total }
end
-function home(ctx)
+local function do_home(ctx)
api_key = ctx.config.api_key
+ -- Modpacks: the featured POST is a mod/plugin endpoint, so browse popular +
+ -- recently-updated through search instead.
+ if ctx.kind == "modpack" then
+ local function section(title_key, sort)
+ local body = get(search_url(ctx, sort, 0, 12), TTL_BROWSE)
+ local projects = {}
+ for _, m in ipairs(body.data or {}) do
+ projects[#projects + 1] = project_card(m, "modpack")
+ end
+ return { title_key = title_key, projects = projects }
+ end
+ return { sections = { section("shop.home.popular", SORTS.downloads),
+ section("shop.home.updated", SORTS.updated) } }
+ end
-- Featured is a POST (uncached); fall back to plain popular search if the
-- endpoint misbehaves for this game/class combination.
local ok, body = pcall(post, API .. "/v1/mods/featured",
@@ -190,7 +216,7 @@ function home(ctx)
return { sections = sections }
end
-function detail(ctx)
+local function do_detail(ctx)
api_key = ctx.config.api_key
local m = get(API .. "/v1/mods/" .. urlencode(ctx.project_id), TTL_DETAIL).data
local desc = get(API .. "/v1/mods/" .. urlencode(ctx.project_id) .. "/description", TTL_DETAIL).data
@@ -206,7 +232,7 @@ function detail(ctx)
end
end
return {
- project = project_card(m),
+ project = project_card(m, ctx.kind),
body = desc,
body_format = "html",
gallery = gallery,
@@ -224,7 +250,8 @@ end
local CHANNELS = { [1] = "release", [2] = "beta", [3] = "alpha" }
--- files_url builds /v1/mods/{id}/files with the compatibility filters.
+-- files_url builds /v1/mods/{id}/files with the compatibility filters. For a
+-- modpack ctx (no mc_version/loader) it degrades to the unfiltered pack files.
local function files_url(ctx)
local url = API .. "/v1/mods/" .. urlencode(ctx.project_id) .. "/files?pageSize=50"
if (ctx.mc_version or "") ~= "" then
@@ -253,7 +280,7 @@ local function dep_titles(ids)
return titles
end
-function versions(ctx)
+local function do_versions(ctx)
api_key = ctx.config.api_key
local body = get(files_url(ctx), TTL_BROWSE)
@@ -310,7 +337,7 @@ function versions(ctx)
return { versions = out }
end
-function resolve_file(ctx)
+local function do_resolve_file(ctx)
api_key = ctx.config.api_key
local f
if (ctx.version_id or "") ~= "" then
@@ -339,3 +366,145 @@ function resolve_file(ctx)
sha1 = sha1_of(f),
}
end
+
+shop = {
+ kinds = { "mod", "plugin", "modpack" },
+ needs_key = true,
+ home = do_home,
+ categories = do_categories,
+ search = do_search,
+ detail = do_detail,
+ versions = do_versions,
+ resolve_file = do_resolve_file,
+}
+
+-- Provider role: installs a CurseForge modpack from its client pack
+-- (manifest.json + overrides/). Driven by the shop with an opaque
+-- "/" version. The API key comes from the shared
+-- ctx.config.api_key.
+local function provider_key(ctx)
+ local cfg = ctx.config or {}
+ return cfg.api_key or ""
+end
+
+-- pack_zip_url resolves the direct download URL for a CurseForge pack file,
+-- falling back to the dedicated download-url endpoint when downloadUrl is null.
+local function pack_zip_url(project, file, k)
+ local res = jhmc.http({
+ url = API .. "/v1/mods/" .. project .. "/files/" .. file,
+ headers = { ["x-api-key"] = k },
+ })
+ if res.status < 200 or res.status >= 300 then
+ error("curseforge: HTTP " .. res.status .. " resolving pack file " .. project .. "/" .. file)
+ end
+ local f = jhmc.json_decode(res.body).data or {}
+ local url = f.downloadUrl
+ if not url or url == "" then
+ local r2 = jhmc.http({
+ url = API .. "/v1/mods/" .. project .. "/files/" .. file .. "/download-url",
+ headers = { ["x-api-key"] = k },
+ })
+ if r2.status >= 200 and r2.status < 300 then
+ url = jhmc.json_decode(r2.body).data
+ end
+ end
+ if not url or url == "" then
+ error("curseforge: modpack file not distributable (author disabled third-party downloads)")
+ end
+ return url
+end
+
+-- fetch_pack downloads the pack zip for "/" to .jhmc/pack.zip.
+local function fetch_pack(ctx, project, file, k)
+ local url = pack_zip_url(project, file, k)
+ ctx.step("install.progress.downloading_server", 0)
+ ctx.log("modpack.zip")
+ jhmc.fs.mkdir(".jhmc")
+ jhmc.download(url, { dest = ".jhmc/pack.zip" })
+end
+
+local function provider_parse_version(v)
+ local project, file = tostring(v):match("^([^/]+)/([^/]+)$")
+ if not project or not file then
+ error("invalid modpack version id: " .. tostring(v))
+ end
+ return project, file
+end
+
+local function provider_install(ctx)
+ local project, file = provider_parse_version(ctx.version)
+ local k = provider_key(ctx)
+ if k == "" then
+ error("this modpack is hosted on CurseForge and needs a CurseForge API key (set it in the shop settings)")
+ end
+
+ ctx.step("install.progress.resolving_version", -1)
+ fetch_pack(ctx, project, file, k)
+
+ local spec = mplib.install_cf_pack(ctx, ".jhmc/pack.zip", k)
+ jhmc.fs.remove(".jhmc/pack.zip")
+
+ ctx.step("install.progress.done", 1)
+ spec.pack_version = tostring(ctx.version)
+ return spec
+end
+
+local function provider_update(ctx)
+ local project, file = provider_parse_version(ctx.version)
+ local oproject = provider_parse_version(ctx.old_version)
+ if project ~= oproject then
+ error("update must stay within the same modpack (" .. oproject .. " -> " .. project .. ")")
+ end
+ local k = provider_key(ctx)
+ if k == "" then
+ error("this modpack is hosted on CurseForge and needs a CurseForge API key (set it in the shop settings)")
+ end
+ local old = mplib.read_manifest()
+ if not old then
+ error("cannot update: this server has no saved modpack manifest")
+ end
+
+ ctx.step("install.progress.resolving_version", -1)
+ fetch_pack(ctx, project, file, k)
+ local m = mplib.cf_pack_meta(".jhmc/pack.zip", k)
+
+ mplib.diff_apply(ctx, mplib.server_index(old.files or {}), mplib.server_index(m.files), {
+ changed = function(a, b) return tostring(a.file_id or "") ~= tostring(b.file_id or "") end,
+ to_item = function(x) return mplib.to_download_item(x, k) end,
+ })
+ jhmc.unzip(".jhmc/pack.zip", ".", { prefix = "overrides/" })
+
+ local java_major = jhmc.java_major_for(m.mc)
+ local args
+ if m.loader_name ~= old.loader or m.loader_version ~= old.loader_version or m.mc ~= old.mc_version then
+ args = mplib.install_loader(ctx, m.loader_name, m.loader_version, m.mc, java_major)
+ end
+
+ mplib.write_manifest({
+ format = 1,
+ name = m.name,
+ version_name = m.version,
+ mc_version = m.mc,
+ loader = m.loader_name,
+ loader_version = m.loader_version,
+ files = m.files,
+ })
+ jhmc.fs.remove(".jhmc/pack.zip")
+
+ ctx.step("install.progress.done", 1)
+ return {
+ java_major = java_major,
+ args = args,
+ mc_version = m.mc,
+ loader = m.loader_name,
+ pack_version = tostring(ctx.version),
+ }
+end
+
+provider = {
+ hidden = true,
+ mod_layout = "mods",
+ versions = function() return {} end,
+ install = provider_install,
+ update = provider_update,
+}
diff --git a/engine/internal/scripting/builtin_sources/ftb.lua b/engine/internal/scripting/builtin_sources/ftb.lua
new file mode 100644
index 0000000..9ded336
--- /dev/null
+++ b/engine/internal/scripting/builtin_sources/ftb.lua
@@ -0,0 +1,370 @@
+-- Feed The Beast source: one script, two roles. The `shop` role browses/searches
+-- the keyless FTB v1 API (https://api.feed-the-beast.com/v1/modpacks/public) for
+-- modpacks; the hidden `provider` role installs an FTB modpack as a
+-- self-contained server, resolving CurseForge-hosted files with a CurseForge API
+-- key. Both roles share meta.id ("ftb"). The provider's key is CurseForge's, kept
+-- under its own config key "curseforge_api_key" (distinct from the CurseForge
+-- source's api_key) so existing stored values and the fallback wiring survive.
+-- GET /modpack/featured/{n} -> { packs = [id...], total }
+-- GET /modpack/popular/installs/{n} -> { packs = [id...], total }
+-- GET /modpack/search/{n}?term=... -> { packs = [id...], total }
+-- GET /modpack/{id} -> pack detail
+-- GET /modpack/{id}/{versionId} -> version manifest (provider install)
+
+meta = {
+ id = "ftb",
+ name = "FTB Modpacks",
+ website = "https://www.feed-the-beast.com",
+ description = "Browse and install Feed The Beast modpacks as new servers.",
+ version = "1.0.0",
+ author = "JustHostMC",
+ config = {
+ { key = "curseforge_api_key", type = "secret", name = "CurseForge API key",
+ description = "Used for pack files hosted on CurseForge", required = false },
+ },
+ permissions = {
+ { kind = "network", reason = "Query the FTB API to browse and install modpacks, and download their files and loader installer." },
+ { kind = "install", reason = "Resolve a JRE and run the Forge/NeoForge installer's --installServer." },
+ { kind = "fs_server", reason = "Write the pack's mods/configs and detect the launch command." },
+ },
+}
+
+local BASE = "https://api.feed-the-beast.com/v1/modpacks/public"
+
+-- Cache TTLs (seconds): browse lists refresh often; pack detail leans on ETag
+-- revalidation for longer.
+local TTL_BROWSE = 120
+local TTL_DETAIL = 600
+
+-- Per-section hydration cap: browsing endpoints return up to 20 ids, but each
+-- card costs one detail fetch, so bound it.
+local HYDRATE_CAP = 10
+
+local function urlencode(s)
+ return (string.gsub(s, "[^%w%-%._~]", function(c)
+ return string.format("%%%02X", string.byte(c))
+ end))
+end
+
+-- get fetches url through the ETag disk cache and decodes the JSON body.
+local function get(url, ttl)
+ local res = jhmc.http_cache({ url = url, ttl = ttl })
+ if res.status == 404 or res.status == 410 then
+ error("ftb: not found: " .. url)
+ end
+ if res.status < 200 or res.status >= 300 then
+ error("ftb: HTTP " .. res.status .. " for " .. url)
+ end
+ return jhmc.json_decode(res.body)
+end
+
+-- square_art returns the pack's square artwork url, falling back to the first
+-- artwork of any kind.
+local function square_art(p)
+ local first = ""
+ for _, a in ipairs(p.art or {}) do
+ if type(a) == "table" and a.url and a.url ~= "" then
+ if first == "" then first = a.url end
+ if a.type == "square" then return a.url end
+ end
+ end
+ return first
+end
+
+-- authors_str joins the pack's author display names.
+local function authors_str(p)
+ local names = {}
+ for _, a in ipairs(p.authors or {}) do
+ if type(a) == "table" and a.name and a.name ~= "" then
+ names[#names + 1] = a.name
+ end
+ end
+ return table.concat(names, ", ")
+end
+
+-- card builds a project card from a hydrated pack detail.
+local function card(p)
+ return {
+ project_id = tostring(p.id),
+ title = p.name,
+ summary = p.synopsis,
+ icon_url = square_art(p),
+ author = authors_str(p),
+ downloads = p.installs,
+ project_type = "modpack",
+ }
+end
+
+-- channel_of maps an FTB version type ("Release"/"Beta"/"Alpha"/…) onto the
+-- shop's release-channel vocabulary.
+local function channel_of(t)
+ t = string.lower(t or "")
+ if t == "beta" then return "beta" end
+ if t == "alpha" then return "alpha" end
+ return "release"
+end
+
+-- hydrate_ids fetches pack detail for up to cap ids from a { packs = [...] }
+-- browse response and returns their cards. Individual failures are skipped so
+-- one bad pack does not blank a whole section.
+local function hydrate_ids(resp, cap)
+ local projects = {}
+ local ids = (type(resp) == "table" and resp.packs) or {}
+ for i, id in ipairs(ids) do
+ if i > cap then break end
+ local ok, p = pcall(get, BASE .. "/modpack/" .. urlencode(tostring(id)), TTL_DETAIL)
+ if ok and type(p) == "table" and p.name then
+ projects[#projects + 1] = card(p)
+ end
+ end
+ return projects
+end
+
+local function do_home(ctx)
+ local featured = hydrate_ids(get(BASE .. "/modpack/featured/20", TTL_BROWSE), HYDRATE_CAP)
+ local popular = hydrate_ids(get(BASE .. "/modpack/popular/installs/20", TTL_BROWSE), HYDRATE_CAP)
+ return { sections = {
+ { title_key = "shop.home.featured", projects = featured },
+ { title_key = "shop.home.popular", projects = popular },
+ } }
+end
+
+local function do_search(ctx)
+ -- The FTB search endpoint returns only a single top-N page, so pagination
+ -- beyond the first request ends here rather than repeating results.
+ if (ctx.offset or 0) > 0 then
+ return { projects = {}, total = 0 }
+ end
+ local limit = ctx.limit or 20
+ local resp = get(BASE .. "/modpack/search/" .. limit .. "?term=" .. urlencode(ctx.query or ""), TTL_BROWSE)
+ local projects = hydrate_ids(resp, limit)
+ local total = (type(resp) == "table" and resp.total) or #projects
+ return { projects = projects, total = total }
+end
+
+local function do_detail(ctx)
+ local p = get(BASE .. "/modpack/" .. urlencode(ctx.project_id), TTL_DETAIL)
+ return {
+ project = card(p),
+ body = p.description or "",
+ body_format = "markdown",
+ gallery = {},
+ links = {
+ website = "https://www.feed-the-beast.com/modpacks/" .. tostring(p.id),
+ },
+ game_versions = {},
+ loaders = {},
+ -- The version list omits per-version targets; the create flow resolves the
+ -- concrete MC version + loader at install time.
+ updated = "",
+ }
+end
+
+local function do_versions(ctx)
+ local p = get(BASE .. "/modpack/" .. urlencode(ctx.project_id), TTL_DETAIL)
+ local list = p.versions or {}
+ local out = {}
+ -- Present newest-first (the API lists versions oldest-first).
+ for i = #list, 1, -1 do
+ local v = list[i]
+ if type(v) == "table" and v.id ~= nil then
+ out[#out + 1] = {
+ id = tostring(v.id),
+ name = v.name,
+ version_number = v.name,
+ channel = channel_of(v.type),
+ date = "",
+ }
+ end
+ end
+ return { versions = out }
+end
+
+local function do_resolve_file(ctx)
+ -- Required by the shop contract but never reached by the modpack flow: a pack
+ -- is installed as a whole server by this script's provider role.
+ error("not distributable: FTB modpacks install as a new server")
+end
+
+shop = {
+ kinds = { "modpack" },
+ needs_key = false,
+ home = do_home,
+ search = do_search,
+ detail = do_detail,
+ versions = do_versions,
+ resolve_file = do_resolve_file,
+}
+
+-- Provider role: installs an FTB modpack as a self-contained server from its
+-- version manifest. Driven by the shop with an opaque "/"
+-- version. CurseForge-hosted files use the configured curseforge_api_key.
+local FTB_API = "https://api.feed-the-beast.com/v1/modpacks/public"
+
+-- curseforge_key returns the configured CurseForge API key ("" when unset). It is
+-- seeded from the shared CurseForge shop key by cmd/engine wiring when the user
+-- leaves it blank.
+local function curseforge_key(ctx)
+ local cfg = ctx.config or {}
+ return cfg.curseforge_api_key or ""
+end
+
+-- read_targets extracts the Minecraft version and mod loader (name + pinned
+-- version) from the manifest's targets array.
+local function read_targets(manifest)
+ local mc, loader_name, loader_version
+ for _, t in ipairs(manifest.targets or {}) do
+ if type(t) == "table" then
+ if t.type == "game" then
+ mc = t.version
+ elseif t.type == "modloader" then
+ loader_name = string.lower(t.name or "")
+ loader_version = t.version
+ end
+ end
+ end
+ return mc, loader_name, loader_version
+end
+
+-- normalize_files maps the FTB manifest's files into mplib's normalized entries.
+-- Client-only files are kept but flagged so export can carry them while install
+-- and update skip them.
+local function normalize_files(manifest)
+ local out = {}
+ for _, f in ipairs(manifest.files or {}) do
+ if type(f) == "table" and (f.name or "") ~= "" then
+ local entry = { dest = mplib.join_path(f.path, f.name), sha1 = f.sha1 }
+ if (f.url or "") ~= "" then
+ entry.url = f.url
+ elseif type(f.curseforge) == "table" and f.curseforge.project and f.curseforge.file then
+ entry.project_id = f.curseforge.project
+ entry.file_id = f.curseforge.file
+ end
+ if f.clientonly then
+ entry.client_only = true
+ end
+ out[#out + 1] = entry
+ end
+ end
+ return out
+end
+
+-- persist writes the normalized manifest consumed by export and update.
+local function persist(manifest, ver, files, mc, loader_name, loader_version)
+ local version_name = (manifest.name and manifest.name ~= "") and manifest.name or ver
+ mplib.write_manifest({
+ format = 1,
+ name = manifest.name or "",
+ version_name = version_name,
+ mc_version = mc,
+ loader = loader_name,
+ loader_version = loader_version,
+ files = files,
+ })
+end
+
+local function provider_install(ctx)
+ local pack, ver = tostring(ctx.version):match("^([^/]+)/([^/]+)$")
+ if not pack or not ver then
+ error("invalid modpack version id: " .. tostring(ctx.version))
+ end
+
+ ctx.step("install.progress.resolving_version", -1)
+ local manifest = jhmc.http_json(FTB_API .. "/modpack/" .. pack .. "/" .. ver)
+ if type(manifest) ~= "table" then
+ error("ftb: bad manifest for " .. tostring(ctx.version))
+ end
+
+ local mc, loader_name, loader_version = read_targets(manifest)
+ if not mc or mc == "" then
+ error("ftb: modpack has no Minecraft version target")
+ end
+ if not loader_name or loader_name == "" then
+ error("ftb: modpack has no modloader target")
+ end
+
+ local files = normalize_files(manifest)
+ mplib.download_files(ctx, files, curseforge_key(ctx))
+
+ local java_major = jhmc.java_major_for(mc)
+ local args = mplib.install_loader(ctx, loader_name, loader_version, mc, java_major)
+
+ persist(manifest, ver, files, mc, loader_name, loader_version)
+
+ ctx.step("install.progress.done", 1)
+ return {
+ java_major = java_major,
+ args = args,
+ mc_version = mc,
+ loader = loader_name,
+ pack_version = tostring(ctx.version),
+ }
+end
+
+-- provider_update moves an installed pack to another version of the same pack:
+-- files only the old version listed are deleted, new/changed ones downloaded, and
+-- the loader reinstalled only when its pinned target changed.
+local function provider_update(ctx)
+ local pack, ver = tostring(ctx.version):match("^([^/]+)/([^/]+)$")
+ local opack, over = tostring(ctx.old_version):match("^([^/]+)/([^/]+)$")
+ if not pack or not ver then
+ error("invalid modpack version id: " .. tostring(ctx.version))
+ end
+ if not opack or not over then
+ error("invalid modpack version id: " .. tostring(ctx.old_version))
+ end
+ if pack ~= opack then
+ error("update must stay within the same pack (" .. opack .. " -> " .. pack .. ")")
+ end
+
+ ctx.step("install.progress.resolving_version", -1)
+ local old_manifest = jhmc.http_json(FTB_API .. "/modpack/" .. opack .. "/" .. over)
+ local new_manifest = jhmc.http_json(FTB_API .. "/modpack/" .. pack .. "/" .. ver)
+ if type(old_manifest) ~= "table" or type(new_manifest) ~= "table" then
+ error("ftb: bad manifest for update " .. tostring(ctx.old_version) ..
+ " -> " .. tostring(ctx.version))
+ end
+
+ local mc, loader_name, loader_version = read_targets(new_manifest)
+ if not mc or mc == "" then
+ error("ftb: modpack has no Minecraft version target")
+ end
+ if not loader_name or loader_name == "" then
+ error("ftb: modpack has no modloader target")
+ end
+
+ local old_files = normalize_files(old_manifest)
+ local new_files = normalize_files(new_manifest)
+ local key = curseforge_key(ctx)
+ mplib.diff_apply(ctx, mplib.server_index(old_files), mplib.server_index(new_files), {
+ to_item = function(f) return mplib.to_download_item(f, key) end,
+ })
+
+ local omc, oloader_name, oloader_version = read_targets(old_manifest)
+ local java_major = jhmc.java_major_for(mc)
+ local args
+ if loader_name ~= oloader_name or loader_version ~= oloader_version or mc ~= omc then
+ args = mplib.install_loader(ctx, loader_name, loader_version, mc, java_major)
+ end
+
+ persist(new_manifest, ver, new_files, mc, loader_name, loader_version)
+
+ ctx.step("install.progress.done", 1)
+ return {
+ java_major = java_major,
+ -- args is nil when the loader target is unchanged; the engine keeps the
+ -- server's existing launch args in that case.
+ args = args,
+ mc_version = mc,
+ loader = loader_name,
+ pack_version = tostring(ctx.version),
+ }
+end
+
+provider = {
+ hidden = true,
+ mod_layout = "mods",
+ versions = function() return {} end,
+ install = provider_install,
+ update = provider_update,
+}
diff --git a/engine/internal/scripting/builtin_shops/modrinth.lua b/engine/internal/scripting/builtin_sources/modrinth.lua
similarity index 54%
rename from engine/internal/scripting/builtin_shops/modrinth.lua
rename to engine/internal/scripting/builtin_sources/modrinth.lua
index 930f8d8..02661aa 100644
--- a/engine/internal/scripting/builtin_shops/modrinth.lua
+++ b/engine/internal/scripting/builtin_sources/modrinth.lua
@@ -1,27 +1,34 @@
--- Modrinth mod shop. Talks to the Modrinth v2 API (https://docs.modrinth.com/api/):
--- GET /search query, facets (JSON array-of-arrays), index, offset, limit<=100
--- GET /project/{id} detail: body (Markdown), gallery, links, stats
--- GET /project/{id}/version loaders=[...] game_versions=[...] filters
--- GET /version/{id} one version
--- GET /projects?ids=[...] batch cards (dependency titles)
--- Read access is keyless; the host sets the identifying User-Agent Modrinth
--- requires. Rate limit is 300 requests/minute.
+-- Modrinth source: one script, two roles. The `shop` role browses/searches the
+-- keyless Modrinth v2 API (https://docs.modrinth.com/api/) for mods, plugins and
+-- modpacks; the hidden `provider` role installs a Modrinth modpack (.mrpack) as a
+-- self-contained server. Both roles share one meta.id ("modrinth"). The old split
+-- id "modrinth_modpacks" resolves here via meta.aliases so existing modpack
+-- servers keep updating. Read access is keyless; the host sets the identifying
+-- User-Agent Modrinth requires.
+-- GET /search query, facets (JSON array-of-arrays), index, offset, limit<=100
+-- GET /project/{id} detail: body (Markdown), gallery, links, stats
+-- GET /project/{id}/version loaders=[...] game_versions=[...] filters
+-- GET /version/{id} one version
+-- GET /projects?ids=[...] batch cards (dependency titles)
meta = {
id = "modrinth",
name = "Modrinth",
website = "https://modrinth.com",
- description = "Browse and install mods and plugins from Modrinth.",
+ description = "Browse and install mods, plugins and modpacks from Modrinth.",
version = "1.0.0",
author = "JustHostMC",
+ aliases = { "modrinth_modpacks" },
permissions = {
- { kind = "network", reason = "Query the Modrinth API to browse, search and download mods" },
+ { kind = "network", reason = "Query the Modrinth API to browse, search and download mods and modpacks" },
+ { kind = "install", reason = "Resolve a JRE and run the Forge/NeoForge installer's --installServer for a modpack." },
+ { kind = "fs_server", reason = "Write an installed modpack's mods/configs and detect the launch command." },
},
}
local API = "https://api.modrinth.com/v2"
--- Cache TTLs (seconds): browse pages refresh often, detail pages can lean on
+-- Cache TTLs (seconds): browse pages refresh often; detail pages can lean on
-- ETag revalidation for longer.
local TTL_BROWSE = 120
local TTL_DETAIL = 600
@@ -45,7 +52,7 @@ local function get(url, ttl)
return jhmc.json_decode(res.body)
end
--- loader_facets returns the Modrinth loader names for one of our loader ids.
+-- loader_names returns the Modrinth loader names for one of our loader ids.
-- Paper servers also run Spigot/Bukkit plugins, Spigot runs Bukkit plugins.
local function loader_names(loader, kind)
if loader == "" then return {} end
@@ -57,17 +64,24 @@ local function loader_names(loader, kind)
return { loader }
end
--- facets builds the JSON facet expression: inner array = OR, outer = AND.
+-- facets builds the JSON facet expression: inner array = OR, outer = AND. A
+-- modpack browse pins only project_type and any chosen categories (packs carry
+-- their own MC version and loader), while mods/plugins add loader + version.
local function facets(ctx)
- local groups = { '["project_type:mod"]' }
- local loaders = loader_names(ctx.loader or "", ctx.kind or "mod")
- if #loaders > 0 then
- local parts = {}
- for _, l in ipairs(loaders) do parts[#parts + 1] = '"categories:' .. l .. '"' end
- groups[#groups + 1] = "[" .. table.concat(parts, ",") .. "]"
- end
- if (ctx.mc_version or "") ~= "" then
- groups[#groups + 1] = '["versions:' .. ctx.mc_version .. '"]'
+ local groups
+ if ctx.kind == "modpack" then
+ groups = { '["project_type:modpack"]' }
+ else
+ groups = { '["project_type:mod"]' }
+ local loaders = loader_names(ctx.loader or "", ctx.kind or "mod")
+ if #loaders > 0 then
+ local parts = {}
+ for _, l in ipairs(loaders) do parts[#parts + 1] = '"categories:' .. l .. '"' end
+ groups[#groups + 1] = "[" .. table.concat(parts, ",") .. "]"
+ end
+ if (ctx.mc_version or "") ~= "" then
+ groups[#groups + 1] = '["versions:' .. ctx.mc_version .. '"]'
+ end
end
if #(ctx.categories or {}) > 0 then
local parts = {}
@@ -79,7 +93,7 @@ local function facets(ctx)
return "[" .. table.concat(groups, ",") .. "]"
end
-local function project_card(hit)
+local function project_card(hit, kind)
return {
project_id = hit.project_id or hit.id,
slug = hit.slug,
@@ -90,7 +104,7 @@ local function project_card(hit)
downloads = hit.downloads,
follows = hit.follows or hit.followers,
categories = hit.display_categories or hit.categories,
- project_type = hit.project_type,
+ project_type = kind == "modpack" and "modpack" or hit.project_type,
}
end
@@ -103,12 +117,12 @@ local function run_search(ctx, index, offset, limit)
local body = get(url, TTL_BROWSE)
local projects = {}
for _, hit in ipairs(body.hits or {}) do
- projects[#projects + 1] = project_card(hit)
+ projects[#projects + 1] = project_card(hit, ctx.kind)
end
return projects, body.total_hits or 0
end
-function home(ctx)
+local function do_home(ctx)
local popular = run_search(ctx, "downloads", 0, 12)
local recommended = run_search(ctx, "follows", 0, 12)
local updated = run_search(ctx, "updated", 0, 12)
@@ -123,18 +137,19 @@ end
local SORTS = { relevance = "relevance", downloads = "downloads", follows = "follows",
newest = "newest", updated = "updated" }
-function search(ctx)
+local function do_search(ctx)
local projects, total = run_search(ctx, SORTS[ctx.sort] or "relevance",
ctx.offset or 0, ctx.limit or 20)
return { projects = projects, total = total }
end
-function detail(ctx)
+local function do_detail(ctx)
local p = get(API .. "/project/" .. urlencode(ctx.project_id), TTL_DETAIL)
local gallery = {}
for _, g in ipairs(p.gallery or {}) do
gallery[#gallery + 1] = { url = g.url, title = g.title, description = g.description }
end
+ local kindpath = ctx.kind == "modpack" and "modpack" or "mod"
return {
project = {
project_id = p.id,
@@ -145,13 +160,13 @@ function detail(ctx)
downloads = p.downloads,
follows = p.followers,
categories = p.categories,
- project_type = p.project_type,
+ project_type = ctx.kind == "modpack" and "modpack" or p.project_type,
},
body = p.body,
body_format = "markdown",
gallery = gallery,
links = {
- website = "https://modrinth.com/mod/" .. (p.slug or p.id),
+ website = "https://modrinth.com/" .. kindpath .. "/" .. (p.slug or p.id),
source = p.source_url,
issues = p.issues_url,
wiki = p.wiki_url,
@@ -164,7 +179,8 @@ function detail(ctx)
}
end
--- versions_url builds /project/{id}/version with loader/game_version filters.
+-- versions_url builds /project/{id}/version with loader/game_version filters. A
+-- modpack ctx carries no loader/mc_version, so it degrades to all pack versions.
local function versions_url(ctx)
local url = API .. "/project/" .. urlencode(ctx.project_id) .. "/version"
local sep = "?"
@@ -205,7 +221,7 @@ local function dep_titles(ids)
return titles
end
-function versions(ctx)
+local function do_versions(ctx)
local list = get(versions_url(ctx), TTL_BROWSE)
-- Collect unique required dependency ids for one batch title lookup.
@@ -256,7 +272,7 @@ function versions(ctx)
return { versions = out }
end
-function resolve_file(ctx)
+local function do_resolve_file(ctx)
local v
if (ctx.version_id or "") ~= "" then
v = get(API .. "/version/" .. urlencode(ctx.version_id), TTL_DETAIL)
@@ -276,3 +292,109 @@ function resolve_file(ctx)
sha512 = f.hashes and f.hashes.sha512,
}
end
+
+shop = {
+ kinds = { "mod", "plugin", "modpack" },
+ needs_key = false,
+ home = do_home,
+ search = do_search,
+ detail = do_detail,
+ versions = do_versions,
+ resolve_file = do_resolve_file,
+}
+
+-- Provider role: installs a Modrinth modpack (.mrpack) as a self-contained
+-- server. Driven by the shop with an opaque "/" version.
+-- Modrinth read access is keyless.
+local function provider_parse_version(v)
+ local project, version_id = tostring(v):match("^([^/]+)/([^/]+)$")
+ if not project or not version_id then
+ error("invalid modpack version id: " .. tostring(v))
+ end
+ return project, version_id
+end
+
+-- fetch_pack downloads the .mrpack for version_id to .jhmc/pack.mrpack.
+local function fetch_pack(ctx, version_id)
+ local res = jhmc.http({ url = API .. "/version/" .. version_id })
+ if res.status < 200 or res.status >= 300 then
+ error("modrinth: HTTP " .. res.status .. " resolving version " .. version_id)
+ end
+ local f = primary_file(jhmc.json_decode(res.body))
+ if not f or not f.url or f.url == "" then
+ error("modrinth: version has no downloadable file")
+ end
+ ctx.step("install.progress.downloading_server", 0)
+ ctx.log(f.filename or "modpack.mrpack")
+ jhmc.fs.mkdir(".jhmc")
+ jhmc.download(f.url, { dest = ".jhmc/pack.mrpack", sha1 = f.hashes and f.hashes.sha1 })
+end
+
+local function provider_install(ctx)
+ local _, version_id = provider_parse_version(ctx.version)
+
+ ctx.step("install.progress.resolving_version", -1)
+ fetch_pack(ctx, version_id)
+
+ local spec = mplib.install_mrpack(ctx, ".jhmc/pack.mrpack")
+ jhmc.fs.remove(".jhmc/pack.mrpack")
+
+ ctx.step("install.progress.done", 1)
+ spec.pack_version = tostring(ctx.version)
+ return spec
+end
+
+local function provider_update(ctx)
+ local project, version_id = provider_parse_version(ctx.version)
+ local oproject = provider_parse_version(ctx.old_version)
+ if project ~= oproject then
+ error("update must stay within the same modpack (" .. oproject .. " -> " .. project .. ")")
+ end
+ local old = mplib.read_manifest()
+ if not old then
+ error("cannot update: this server has no saved modpack manifest")
+ end
+
+ ctx.step("install.progress.resolving_version", -1)
+ fetch_pack(ctx, version_id)
+ local m = mplib.mrpack_meta(".jhmc/pack.mrpack")
+
+ mplib.diff_apply(ctx, mplib.server_index(old.files or {}), mplib.server_index(m.files), {
+ to_item = function(x) return mplib.to_download_item(x, nil) end,
+ })
+ mplib.unzip_overrides(".jhmc/pack.mrpack")
+
+ local java_major = jhmc.java_major_for(m.mc)
+ local args
+ if m.loader_name ~= old.loader or m.loader_version ~= old.loader_version or m.mc ~= old.mc_version then
+ args = mplib.install_loader(ctx, m.loader_name, m.loader_version, m.mc, java_major)
+ end
+
+ mplib.write_manifest({
+ format = 1,
+ name = m.name,
+ version_name = m.version,
+ mc_version = m.mc,
+ loader = m.loader_name,
+ loader_version = m.loader_version,
+ files = m.files,
+ })
+ jhmc.fs.remove(".jhmc/pack.mrpack")
+
+ ctx.step("install.progress.done", 1)
+ return {
+ java_major = java_major,
+ args = args,
+ mc_version = m.mc,
+ loader = m.loader_name,
+ pack_version = tostring(ctx.version),
+ }
+end
+
+provider = {
+ hidden = true,
+ mod_layout = "mods",
+ versions = function() return {} end,
+ install = provider_install,
+ update = provider_update,
+}
diff --git a/engine/internal/scripting/builtinlib.go b/engine/internal/scripting/builtinlib.go
new file mode 100644
index 0000000..1b82a1c
--- /dev/null
+++ b/engine/internal/scripting/builtinlib.go
@@ -0,0 +1,60 @@
+package scripting
+
+import (
+ "embed"
+ "fmt"
+ "sort"
+ "strings"
+
+ lua "github.com/yuin/gopher-lua"
+)
+
+// builtin_lib holds shared Lua helper modules (e.g. mplib) replayed into every
+// sandbox by prepare(), so provider/shop scripts can build on them instead of
+// copying the code. It is a separate embed from builtin/ (which holds runnable
+// provider scripts) so LoadBuiltins never picks these up as providers.
+//
+//go:embed builtin_lib/*.lua
+var builtinLibFS embed.FS
+
+type builtinLib struct {
+ name string
+ src string
+}
+
+// builtinLibSources is the ordered set of shared-library sources, read once at
+// init. Loading them must be side-effect-free (define functions/constants only —
+// no network or filesystem access), because they run on every script prepare().
+var builtinLibSources = mustLoadBuiltinLibs()
+
+func mustLoadBuiltinLibs() []builtinLib {
+ entries, err := builtinLibFS.ReadDir("builtin_lib")
+ if err != nil {
+ panic(fmt.Sprintf("read builtin_lib: %v", err))
+ }
+ var libs []builtinLib
+ for _, e := range entries {
+ if e.IsDir() || !strings.HasSuffix(e.Name(), ".lua") {
+ continue
+ }
+ src, err := builtinLibFS.ReadFile("builtin_lib/" + e.Name())
+ if err != nil {
+ panic(fmt.Sprintf("read builtin_lib/%s: %v", e.Name(), err))
+ }
+ libs = append(libs, builtinLib{name: e.Name(), src: string(src)})
+ }
+ sort.Slice(libs, func(i, j int) bool { return libs[i].name < libs[j].name })
+ return libs
+}
+
+// loadBuiltinLibs replays every shared-library source into L. Called after the
+// jhmc table is installed and before the script's own source runs, so scripts
+// see the library globals (the libs reference jhmc only at call time).
+func loadBuiltinLibs(L *lua.LState) error {
+ for _, lib := range builtinLibSources {
+ if err := L.DoString(lib.src); err != nil {
+ return fmt.Errorf("load lib %s: %w", lib.name, err)
+ }
+ }
+ return nil
+}
diff --git a/engine/internal/scripting/configinjection_test.go b/engine/internal/scripting/configinjection_test.go
new file mode 100644
index 0000000..f192551
--- /dev/null
+++ b/engine/internal/scripting/configinjection_test.go
@@ -0,0 +1,153 @@
+package scripting
+
+import (
+ "context"
+ "errors"
+ "path/filepath"
+ "testing"
+)
+
+// cfgShopSrc echoes its typed config back through a search result so tests can
+// assert what the adapter injected: title = api_key, summary = region.
+const cfgShopSrc = `
+meta = {
+ id = "cfgshop",
+ name = "Cfg Shop",
+ version = "1.0",
+ needs_key = true,
+ permissions = { { kind = "network", reason = "x" } },
+ config = {
+ { key = "region", type = "string", name = "Region", default = "us" },
+ { key = "api_key", type = "secret", name = "API key" },
+ },
+}
+function home(ctx) return { sections = {} } end
+function search(ctx)
+ return { projects = { { project_id = "p",
+ title = ctx.config.api_key or "",
+ summary = ctx.config.region or "" } }, total = 0 }
+end
+function detail(ctx) return { project = { project_id = "p" } } end
+function versions(ctx) return { versions = {} } end
+function resolve_file(ctx) error("not distributable") end
+`
+
+func cfgShop(t *testing.T, keyFn func(string) string) (*LuaShop, *ConfigStore) {
+ t.Helper()
+ cs := NewConfigStore(filepath.Join(t.TempDir(), "shop-config.json"))
+ ss := NewShopSet(NewHost(nil, nil, nil), nil, keyFn)
+ ss.SetConfigStore(cs)
+ s, err := ss.AddSource(context.Background(), cfgShopSrc, true)
+ if err != nil {
+ t.Fatalf("AddSource: %v", err)
+ }
+ return s, cs
+}
+
+// echoedConfig runs search and returns (api_key, region) as the script saw them.
+func echoedConfig(t *testing.T, s *LuaShop) (apiKey, region string) {
+ t.Helper()
+ page, err := s.Search(context.Background(), ShopQuery{Query: "q", Limit: 10})
+ if err != nil {
+ t.Fatalf("search: %v", err)
+ }
+ if len(page.Projects) != 1 {
+ t.Fatalf("projects: %+v", page.Projects)
+ }
+ return page.Projects[0].Title, page.Projects[0].Summary
+}
+
+func TestShopConfigDefaultsAndOverride(t *testing.T) {
+ s, cs := cfgShop(t, func(string) string { return "chainkey" })
+
+ // Declared default is applied when nothing is stored.
+ if _, region := echoedConfig(t, s); region != "us" {
+ t.Fatalf("default region = %q, want us", region)
+ }
+ // A stored override wins over the declared default.
+ if err := cs.Set("cfgshop", "region", "eu"); err != nil {
+ t.Fatal(err)
+ }
+ if _, region := echoedConfig(t, s); region != "eu" {
+ t.Fatalf("overridden region = %q, want eu", region)
+ }
+}
+
+func TestShopApiKeyPrecedence(t *testing.T) {
+ // A stored api_key override wins over the settings/baked chain key; the chain
+ // key (baked build default) only fills in when no config value is stored.
+ s, cs := cfgShop(t, func(string) string { return "chainkey" })
+ _ = cs.Set("cfgshop", "api_key", "storedkey")
+ if key, _ := echoedConfig(t, s); key != "storedkey" {
+ t.Fatalf("api_key = %q, want storedkey (stored config wins)", key)
+ }
+
+ // With no stored key, the chain key fills in.
+ s3, _ := cfgShop(t, func(string) string { return "chainkey" })
+ if key, _ := echoedConfig(t, s3); key != "chainkey" {
+ t.Fatalf("api_key = %q, want chainkey (baked fallback)", key)
+ }
+
+ // With no chain key, a stored api_key fills in and makes the shop Ready.
+ s2, cs2 := cfgShop(t, func(string) string { return "" })
+ if s2.Ready() {
+ t.Fatal("shop must not be ready before a key is configured")
+ }
+ _ = cs2.Set("cfgshop", "api_key", "storedkey")
+ if !s2.Ready() {
+ t.Fatal("stored api_key must make the shop ready")
+ }
+ if key, _ := echoedConfig(t, s2); key != "storedkey" {
+ t.Fatalf("api_key = %q, want storedkey", key)
+ }
+}
+
+func TestShopNotReadyWithoutKey(t *testing.T) {
+ s, _ := cfgShop(t, func(string) string { return "" })
+ if s.Ready() {
+ t.Fatal("keyless needs_key shop must not be ready")
+ }
+ if _, err := s.Search(context.Background(), ShopQuery{Query: "q", Limit: 10}); !errors.Is(err, ErrShopKeyMissing) {
+ t.Fatalf("search err = %v, want ErrShopKeyMissing", err)
+ }
+}
+
+// cfgProvSrc echoes its config flag into the launch spec args.
+const cfgProvSrc = `
+meta = { id = "cfgprov", name = "Cfg Prov", mod_layout = "none",
+ config = { { key = "flag", type = "string", name = "Flag", default = "def" } } }
+function versions() return { "1.0" } end
+function install(ctx)
+ return { java_major = 8, args = { ctx.config.flag or "nil" } }
+end
+`
+
+func TestProviderConfigInjection(t *testing.T) {
+ cs := NewConfigStore(filepath.Join(t.TempDir(), "provider-config.json"))
+ r := NewRegistry(NewHost(nil, nil, nil), nil)
+ r.SetConfigStore(cs)
+ e, err := r.AddSource(context.Background(), cfgProvSrc, true)
+ if err != nil {
+ t.Fatalf("AddSource: %v", err)
+ }
+
+ spec, err := e.Provider.Install(context.Background(), t.TempDir(), "1.0", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(spec.Args) != 1 || spec.Args[0] != "def" {
+ t.Fatalf("default args = %v, want [def]", spec.Args)
+ }
+
+ // A stored override is picked up live (configFn resolves per call).
+ if err := cs.Set("cfgprov", "flag", "xyz"); err != nil {
+ t.Fatal(err)
+ }
+ spec, err = e.Provider.Install(context.Background(), t.TempDir(), "1.0", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if spec.Args[0] != "xyz" {
+ t.Fatalf("overridden args = %v, want [xyz]", spec.Args)
+ }
+}
diff --git a/engine/internal/scripting/configstore.go b/engine/internal/scripting/configstore.go
new file mode 100644
index 0000000..ca9ff77
--- /dev/null
+++ b/engine/internal/scripting/configstore.go
@@ -0,0 +1,132 @@
+package scripting
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "sync"
+)
+
+// ConfigStore persists per-script typed config values (key -> value) as a small
+// JSON file, one map per script id. It is the config analog of GrantStore.
+// Secrets are stored plaintext — the same trust model as settings.json shop keys.
+type ConfigStore struct {
+ path string
+ mu sync.RWMutex
+ data map[string]map[string]string // script id -> key -> value
+}
+
+// NewConfigStore loads (or starts) the config file at path.
+func NewConfigStore(path string) *ConfigStore {
+ cs := &ConfigStore{path: path, data: map[string]map[string]string{}}
+ if b, err := os.ReadFile(path); err == nil {
+ _ = json.Unmarshal(b, &cs.data)
+ }
+ return cs
+}
+
+func (c *ConfigStore) save() error {
+ if err := os.MkdirAll(filepath.Dir(c.path), 0o755); err != nil {
+ return err
+ }
+ b, err := json.MarshalIndent(c.data, "", " ")
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(c.path, b, 0o644)
+}
+
+// Values returns a copy of the stored key->value overrides for id (an empty map
+// when none). The caller may freely mutate the result.
+func (c *ConfigStore) Values(id string) map[string]string {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ out := make(map[string]string, len(c.data[id]))
+ for k, v := range c.data[id] {
+ out[k] = v
+ }
+ return out
+}
+
+// Set stores one config override and persists. An empty value clears the
+// override (and drops the id entirely once it has no values left).
+func (c *ConfigStore) Set(id, key, value string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if value == "" {
+ m, ok := c.data[id]
+ if !ok {
+ return nil
+ }
+ delete(m, key)
+ if len(m) == 0 {
+ delete(c.data, id)
+ }
+ return c.save()
+ }
+ m := c.data[id]
+ if m == nil {
+ m = map[string]string{}
+ c.data[id] = m
+ }
+ m[key] = value
+ return c.save()
+}
+
+// Forget drops all stored config for an id (e.g. when a script is removed).
+func (c *ConfigStore) Forget(id string) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if _, ok := c.data[id]; !ok {
+ return nil
+ }
+ delete(c.data, id)
+ return c.save()
+}
+
+// fallbackConfigReader overlays a lazily-computed default onto a single script's
+// config key when that key has no stored value. It lets one script reuse another
+// subsystem's setting (e.g. the ftb provider falling back to the shared
+// CurseForge shop key) without persisting a copy of the secret.
+type fallbackConfigReader struct {
+ inner ConfigReader
+ id string
+ key string
+ fallback func() string
+}
+
+// NewFallbackConfigReader wraps inner so that Values(id)[key] falls back to
+// fallback() whenever the stored value is empty. Every other id and key passes
+// through unchanged.
+func NewFallbackConfigReader(inner ConfigReader, id, key string, fallback func() string) ConfigReader {
+ return fallbackConfigReader{inner: inner, id: id, key: key, fallback: fallback}
+}
+
+func (f fallbackConfigReader) Values(id string) map[string]string {
+ vals := f.inner.Values(id)
+ if id == f.id && vals[f.key] == "" {
+ if v := f.fallback(); v != "" {
+ if vals == nil {
+ vals = map[string]string{}
+ }
+ vals[f.key] = v
+ }
+ }
+ return vals
+}
+
+// EffectiveConfig merges author-declared defaults with stored overrides into the
+// final key->value map handed to a script (its ctx.config / jhmc.config). Stored
+// values win over declared defaults.
+func EffectiveConfig(options []ConfigOption, stored map[string]string) map[string]string {
+ out := make(map[string]string, len(options)+len(stored))
+ for _, opt := range options {
+ if opt.Default != "" {
+ out[opt.Key] = opt.Default
+ }
+ }
+ for k, v := range stored {
+ out[k] = v
+ }
+ return out
+}
diff --git a/engine/internal/scripting/configstore_test.go b/engine/internal/scripting/configstore_test.go
new file mode 100644
index 0000000..7272aeb
--- /dev/null
+++ b/engine/internal/scripting/configstore_test.go
@@ -0,0 +1,83 @@
+package scripting
+
+import (
+ "path/filepath"
+ "testing"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+)
+
+func TestConfigStoreRoundTrip(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "config.json")
+ cs := NewConfigStore(path)
+
+ if v := cs.Values("s1"); len(v) != 0 {
+ t.Fatalf("empty store returned %v", v)
+ }
+ if err := cs.Set("s1", "region", "eu"); err != nil {
+ t.Fatal(err)
+ }
+ if err := cs.Set("s1", "token", "abc"); err != nil {
+ t.Fatal(err)
+ }
+
+ // Reload from disk to prove persistence.
+ got := NewConfigStore(path).Values("s1")
+ if got["region"] != "eu" || got["token"] != "abc" {
+ t.Fatalf("reloaded values = %v", got)
+ }
+
+ // Values returns a copy: mutating it must not affect the store.
+ got["region"] = "mutated"
+ if cs.Values("s1")["region"] != "eu" {
+ t.Fatal("Values did not return a copy")
+ }
+}
+
+func TestConfigStoreClearAndForget(t *testing.T) {
+ cs := NewConfigStore(filepath.Join(t.TempDir(), "config.json"))
+ _ = cs.Set("s1", "a", "1")
+ _ = cs.Set("s1", "b", "2")
+
+ // Empty value clears one key.
+ if err := cs.Set("s1", "a", ""); err != nil {
+ t.Fatal(err)
+ }
+ got := cs.Values("s1")
+ if _, ok := got["a"]; ok || got["b"] != "2" {
+ t.Fatalf("after clearing a: %v", got)
+ }
+
+ // Forget drops everything for the id.
+ if err := cs.Forget("s1"); err != nil {
+ t.Fatal(err)
+ }
+ if len(cs.Values("s1")) != 0 {
+ t.Fatal("Forget left data")
+ }
+ // Clearing a key on an unknown id is a no-op, not an error.
+ if err := cs.Set("gone", "x", ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestEffectiveConfig(t *testing.T) {
+ opts := []ConfigOption{
+ {Key: "region", Type: mcmanagerv1.ConfigOptionType_CONFIG_OPTION_STRING, Default: "us"},
+ {Key: "count", Type: mcmanagerv1.ConfigOptionType_CONFIG_OPTION_NUMBER, Default: "3"},
+ {Key: "empty", Type: mcmanagerv1.ConfigOptionType_CONFIG_OPTION_STRING}, // no default
+ }
+ // Declared defaults only; an option without a default does not appear.
+ eff := EffectiveConfig(opts, nil)
+ if eff["region"] != "us" || eff["count"] != "3" {
+ t.Fatalf("defaults: %v", eff)
+ }
+ if _, ok := eff["empty"]; ok {
+ t.Fatal("option without a default must not appear")
+ }
+ // Stored overrides win over declared defaults.
+ eff = EffectiveConfig(opts, map[string]string{"region": "eu", "empty": "x"})
+ if eff["region"] != "eu" || eff["count"] != "3" || eff["empty"] != "x" {
+ t.Fatalf("override: %v", eff)
+ }
+}
diff --git a/engine/internal/scripting/export.go b/engine/internal/scripting/export.go
index d2875a5..0cc4b5f 100644
--- a/engine/internal/scripting/export.go
+++ b/engine/internal/scripting/export.go
@@ -29,6 +29,9 @@ type InvocationConfig struct {
ScriptID string
// BaseDir confines jhmc.fs; empty disables filesystem access.
BaseDir string
+ // Config supplies the script's typed config values (surfaced as jhmc.config);
+ // nil when the script declares no config or none is stored.
+ Config map[string]string
}
// NewInvocation builds an invocation from cfg.
@@ -44,6 +47,7 @@ func NewInvocation(cfg InvocationConfig) *Invocation {
kv: cfg.KV,
scriptID: cfg.ScriptID,
baseDir: cfg.BaseDir,
+ config: cfg.Config,
}}
}
diff --git a/engine/internal/scripting/ftbprovider_test.go b/engine/internal/scripting/ftbprovider_test.go
new file mode 100644
index 0000000..8a6e2b0
--- /dev/null
+++ b/engine/internal/scripting/ftbprovider_test.go
@@ -0,0 +1,149 @@
+package scripting
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+)
+
+// newFTBProvider loads the builtin providers on a host whose HTTP traffic is
+// redirected to handler, and returns the ftb entry.
+func newFTBProvider(t *testing.T, handler http.Handler) *Entry {
+ t.Helper()
+ srv := httptest.NewServer(handler)
+ t.Cleanup(srv.Close)
+ u, _ := url.Parse(srv.URL)
+ client := &http.Client{Transport: rewriteTransport{target: u}}
+ host := NewHost(client, nil, nil)
+ r := NewRegistry(host, nil)
+ if err := LoadBuiltins(context.Background(), r); err != nil {
+ t.Fatalf("LoadBuiltins: %v", err)
+ }
+ // FTB is now a dual-role source (modpack shop + hidden provider).
+ ss := NewShopSet(host, nil, nil)
+ if _, err := LoadBuiltinSources(context.Background(), r, ss, nil); err != nil {
+ t.Fatalf("LoadBuiltinSources: %v", err)
+ }
+ e, ok := r.Get("ftb")
+ if !ok {
+ t.Fatal("ftb provider not registered")
+ }
+ return e
+}
+
+func TestFTBProviderIsHiddenWithKeyConfig(t *testing.T) {
+ e := newFTBProvider(t, http.NotFoundHandler())
+ if !e.Meta.Hidden {
+ t.Fatal("ftb provider should be hidden")
+ }
+ if e.Meta.ModLayout != "mods" {
+ t.Fatalf("mod_layout = %q, want mods", e.Meta.ModLayout)
+ }
+ var hasKey bool
+ for _, c := range e.Meta.Config {
+ if c.Key == "curseforge_api_key" && c.Type == mcmanagerv1.ConfigOptionType_CONFIG_OPTION_SECRET {
+ hasKey = true
+ }
+ }
+ if !hasKey {
+ t.Fatalf("ftb should declare a curseforge_api_key secret option, config=%+v", e.Meta.Config)
+ }
+}
+
+func TestFTBProviderVersionsEmpty(t *testing.T) {
+ e := newFTBProvider(t, http.NotFoundHandler())
+ vs, err := e.Provider.Versions(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(vs) != 0 {
+ t.Fatalf("versions = %v, want empty", vs)
+ }
+}
+
+func TestFTBProviderRejectsBadVersionID(t *testing.T) {
+ e := newFTBProvider(t, http.NotFoundHandler())
+ if _, err := e.Provider.Install(context.Background(), t.TempDir(), "no-slash", nil); err == nil ||
+ !strings.Contains(err.Error(), "invalid modpack version id") {
+ t.Fatalf("want invalid-version error, got %v", err)
+ }
+}
+
+// ftbManifestHandler serves one modpack version manifest at /modpack/1/2.
+func ftbManifestHandler(manifest map[string]any) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "/modpack/1/2") {
+ _ = json.NewEncoder(w).Encode(manifest)
+ return
+ }
+ http.NotFound(w, r)
+ })
+}
+
+func TestFTBProviderUnsupportedLoader(t *testing.T) {
+ e := newFTBProvider(t, ftbManifestHandler(map[string]any{
+ "targets": []map[string]any{
+ {"type": "game", "version": "1.20.1"},
+ {"type": "modloader", "name": "quilt", "version": "0.1"},
+ },
+ "files": []any{},
+ }))
+ if _, err := e.Provider.Install(context.Background(), t.TempDir(), "1/2", nil); err == nil ||
+ !strings.Contains(err.Error(), "unsupported modloader") {
+ t.Fatalf("want unsupported-modloader error, got %v", err)
+ }
+}
+
+func TestFTBProviderMissingTargets(t *testing.T) {
+ e := newFTBProvider(t, ftbManifestHandler(map[string]any{
+ "targets": []map[string]any{{"type": "game", "version": "1.20.1"}},
+ "files": []any{},
+ }))
+ if _, err := e.Provider.Install(context.Background(), t.TempDir(), "1/2", nil); err == nil ||
+ !strings.Contains(err.Error(), "modloader target") {
+ t.Fatalf("want missing-modloader error, got %v", err)
+ }
+}
+
+func TestFTBProviderCurseForgeNeedsKey(t *testing.T) {
+ // A CurseForge-hosted file with no configured key must fail with a clear,
+ // actionable message rather than silently skipping the mod.
+ e := newFTBProvider(t, ftbManifestHandler(map[string]any{
+ "targets": []map[string]any{
+ {"type": "game", "version": "1.20.1"},
+ {"type": "modloader", "name": "forge", "version": "47.2.0"},
+ },
+ "files": []map[string]any{
+ {"name": "secret.jar", "path": "./mods/", "curseforge": map[string]any{"project": 1, "file": 2}},
+ },
+ }))
+ if _, err := e.Provider.Install(context.Background(), t.TempDir(), "1/2", nil); err == nil ||
+ !strings.Contains(err.Error(), "CurseForge API key") {
+ t.Fatalf("want CurseForge-key error, got %v", err)
+ }
+}
+
+func TestFallbackConfigReader(t *testing.T) {
+ base := NewConfigStore(filepath.Join(t.TempDir(), "c.json"))
+ reader := NewFallbackConfigReader(base, "ftb", "curseforge_api_key", func() string { return "shopkey" })
+
+ if got := reader.Values("ftb")["curseforge_api_key"]; got != "shopkey" {
+ t.Fatalf("unset key should fall back, got %q", got)
+ }
+ if err := base.Set("ftb", "curseforge_api_key", "userkey"); err != nil {
+ t.Fatal(err)
+ }
+ if got := reader.Values("ftb")["curseforge_api_key"]; got != "userkey" {
+ t.Fatalf("stored value should win, got %q", got)
+ }
+ if _, ok := reader.Values("other")["curseforge_api_key"]; ok {
+ t.Fatal("fallback leaked to a different id")
+ }
+}
diff --git a/engine/internal/scripting/host.go b/engine/internal/scripting/host.go
index 46e127e..9a962bb 100644
--- a/engine/internal/scripting/host.go
+++ b/engine/internal/scripting/host.go
@@ -62,8 +62,28 @@ type invocation struct {
report func(provider.Progress)
lastErr error // structured error stashed before a Lua RaiseError, for mapping
- kv KV // jhmc.store backend (nil where no store is wired, e.g. providers)
- scriptID string // id scoping jhmc.store access
+ kv KV // jhmc.store backend (nil where no store is wired, e.g. providers)
+ scriptID string // id scoping jhmc.store access
+ config map[string]string // typed config values surfaced as ctx.config / jhmc.config (nil = none)
+
+ // providerRole resolves versions/install/update from a global `provider`
+ // role table first (a multi-role source script) before falling back to the
+ // top-level globals (the legacy single-role layout).
+ providerRole bool
+}
+
+// providerFn resolves a provider entry point, preferring a function in the
+// global `provider` role table (when this invocation runs a source script) and
+// falling back to a top-level global (the legacy layout).
+func (inv *invocation) providerFn(L *lua.LState, name string) lua.LValue {
+ if inv.providerRole {
+ if tbl, ok := L.GetGlobal("provider").(*lua.LTable); ok {
+ if f := tbl.RawGetString(name); f.Type() == lua.LTFunction {
+ return f
+ }
+ }
+ }
+ return L.GetGlobal(name)
}
func (inv *invocation) emit(p provider.Progress) {
@@ -72,6 +92,16 @@ func (inv *invocation) emit(p provider.Progress) {
}
}
+// configTable builds a Lua table of the invocation's typed config values for a
+// script's ctx.config (empty table when the invocation carries no config).
+func (inv *invocation) configTable(L *lua.LState) *lua.LTable {
+ t := L.NewTable()
+ for k, v := range inv.config {
+ t.RawSetString(k, lua.LString(v))
+ }
+ return t
+}
+
// require raises a Lua error (caught by PCall) when kind is not granted.
func (inv *invocation) require(L *lua.LState, kind mcmanagerv1.PermissionKind) {
if !inv.granted.Has(kind) {
@@ -91,6 +121,10 @@ func (inv *invocation) fail(L *lua.LState, err error) {
func (inv *invocation) prepare(src string) (*lua.LState, error) {
L := newSandbox(inv.ctx)
L.SetGlobal("jhmc", inv.newJHMC(L))
+ if err := loadBuiltinLibs(L); err != nil {
+ L.Close()
+ return nil, err
+ }
if err := L.DoString(src); err != nil {
L.Close()
return nil, fmt.Errorf("load script: %w", err)
@@ -139,7 +173,7 @@ func (inv *invocation) versions(src string) ([]string, error) {
}
defer L.Close()
- fn := L.GetGlobal("versions")
+ fn := inv.providerFn(L, "versions")
if fn.Type() != lua.LTFunction {
return nil, fmt.Errorf("script defines no versions() function")
}
@@ -161,21 +195,9 @@ func (inv *invocation) versions(src string) ([]string, error) {
return out, nil
}
-// install loads src and calls install(ctx), returning the launch spec. dir is
-// the server directory; downloads and fs access are confined to it.
-func (inv *invocation) install(src, dir, version string) (provider.LaunchSpec, error) {
- inv.baseDir = dir
- L, err := inv.prepare(src)
- if err != nil {
- return provider.LaunchSpec{}, err
- }
- defer L.Close()
-
- fn := L.GetGlobal("install")
- if fn.Type() != lua.LTFunction {
- return provider.LaunchSpec{}, fmt.Errorf("script defines no install() function")
- }
-
+// installCtxTable builds the ctx table shared by install(ctx) and update(ctx):
+// dir/version, the step/log progress bridges, and the script config.
+func (inv *invocation) installCtxTable(L *lua.LState, dir, version string) *lua.LTable {
ictx := L.NewTable()
ictx.RawSetString("dir", lua.LString(dir))
ictx.RawSetString("version", lua.LString(version))
@@ -189,17 +211,17 @@ func (inv *invocation) install(src, dir, version string) (provider.LaunchSpec, e
inv.emit(provider.Progress{LogLine: L.CheckString(1)})
return 0
}))
+ ictx.RawSetString("config", inv.configTable(L))
+ return ictx
+}
- if err := L.CallByParam(lua.P{Fn: fn, NRet: 1, Protect: true}, ictx); err != nil {
- return provider.LaunchSpec{}, inv.mapErr(err)
- }
- ret := L.Get(-1)
- L.Pop(1)
+// parseLaunchSpec converts the table returned by install()/update() into a
+// LaunchSpec.
+func parseLaunchSpec(ret lua.LValue, fnName string) (provider.LaunchSpec, error) {
spec, ok := ret.(*lua.LTable)
if !ok {
- return provider.LaunchSpec{}, fmt.Errorf("install() must return a launch spec table")
+ return provider.LaunchSpec{}, fmt.Errorf("%s() must return a launch spec table", fnName)
}
-
major := 0
if n, ok := spec.RawGetString("java_major").(lua.LNumber); ok {
major = int(n)
@@ -210,7 +232,60 @@ func (inv *invocation) install(src, dir, version string) (provider.LaunchSpec, e
args = append(args, lua.LVAsString(v))
})
}
- return provider.LaunchSpec{JavaMajor: major, Args: args}, nil
+ return provider.LaunchSpec{
+ JavaMajor: major,
+ Args: args,
+ McVersion: strField(spec, "mc_version"),
+ Loader: strField(spec, "loader"),
+ PackVersion: strField(spec, "pack_version"),
+ }, nil
+}
+
+// install loads src and calls install(ctx), returning the launch spec. dir is
+// the server directory; downloads and fs access are confined to it.
+func (inv *invocation) install(src, dir, version string) (provider.LaunchSpec, error) {
+ inv.baseDir = dir
+ L, err := inv.prepare(src)
+ if err != nil {
+ return provider.LaunchSpec{}, err
+ }
+ defer L.Close()
+
+ fn := inv.providerFn(L, "install")
+ if fn.Type() != lua.LTFunction {
+ return provider.LaunchSpec{}, fmt.Errorf("script defines no install() function")
+ }
+ ictx := inv.installCtxTable(L, dir, version)
+ if err := L.CallByParam(lua.P{Fn: fn, NRet: 1, Protect: true}, ictx); err != nil {
+ return provider.LaunchSpec{}, inv.mapErr(err)
+ }
+ ret := L.Get(-1)
+ L.Pop(1)
+ return parseLaunchSpec(ret, "install")
+}
+
+// update loads src and calls update(ctx) — the optional in-place move of an
+// installed server to another version. ctx additionally carries old_version.
+func (inv *invocation) update(src, dir, version, oldVersion string) (provider.LaunchSpec, error) {
+ inv.baseDir = dir
+ L, err := inv.prepare(src)
+ if err != nil {
+ return provider.LaunchSpec{}, err
+ }
+ defer L.Close()
+
+ fn := inv.providerFn(L, "update")
+ if fn.Type() != lua.LTFunction {
+ return provider.LaunchSpec{}, provider.ErrUpdateUnsupported
+ }
+ ictx := inv.installCtxTable(L, dir, version)
+ ictx.RawSetString("old_version", lua.LString(oldVersion))
+ if err := L.CallByParam(lua.P{Fn: fn, NRet: 1, Protect: true}, ictx); err != nil {
+ return provider.LaunchSpec{}, inv.mapErr(err)
+ }
+ ret := L.Get(-1)
+ L.Pop(1)
+ return parseLaunchSpec(ret, "update")
}
// mapErr recovers the structured error stashed by fail(), falling back to the
diff --git a/engine/internal/scripting/hostfuncs.go b/engine/internal/scripting/hostfuncs.go
index bf64b47..4eae8f9 100644
--- a/engine/internal/scripting/hostfuncs.go
+++ b/engine/internal/scripting/hostfuncs.go
@@ -14,11 +14,15 @@ import (
"net/http"
"os"
"os/exec"
+ "path"
"path/filepath"
"strings"
"sync"
+ "sync/atomic"
"time"
+ "golang.org/x/sync/errgroup"
+
mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
"github.com/000hen/justhostmc/engine/internal/dl"
"github.com/000hen/justhostmc/engine/internal/httpcache"
@@ -39,6 +43,7 @@ func (inv *invocation) newJHMC(L *lua.LState) *lua.LTable {
reg("http_json", inv.httpJSON)
reg("http_cache", inv.httpCached)
reg("download", inv.download)
+ reg("download_all", inv.downloadAll)
reg("sha256", inv.sha256File)
reg("unzip", inv.unzip)
reg("run_jar", inv.runJar)
@@ -76,6 +81,17 @@ func (inv *invocation) newJHMC(L *lua.LState) *lua.LTable {
fs.RawSetString("remove", L.NewFunction(inv.fsRemove))
t.RawSetString("fs", fs)
+ // jhmc.config exposes the script's typed config values. It is the config
+ // surface for automation scripts (which have no per-call ctx table); present
+ // only when a config map was supplied for this invocation.
+ if inv.config != nil {
+ cfg := L.NewTable()
+ for k, v := range inv.config {
+ cfg.RawSetString(k, lua.LString(v))
+ }
+ t.RawSetString("config", cfg)
+ }
+
return t
}
@@ -307,6 +323,156 @@ func (inv *invocation) download(L *lua.LState) int {
return 1
}
+// batchItem is one download_all entry, fully resolved on the Lua thread so the
+// worker goroutines never touch the Lua state.
+type batchItem struct {
+ dest, full, url string
+ resolveURL string
+ resolveHeaders map[string]string
+ newHash func() hash.Hash // nil = no checksum
+ want string
+}
+
+// downloadAll backs jhmc.download_all(items, opts): a parallel batch download
+// with per-file completion progress. Items carry either a direct url or a
+// resolve endpoint (GET returning {"data": ""}, the CurseForge
+// download-url convention). The first error cancels the batch.
+func (inv *invocation) downloadAll(L *lua.LState) int {
+ inv.require(L, mcmanagerv1.PermissionKind_PERMISSION_NETWORK)
+ itemsTbl := L.CheckTable(1)
+ concurrency := 6
+ if opts, ok := L.Get(2).(*lua.LTable); ok {
+ if n, ok := opts.RawGetString("concurrency").(lua.LNumber); ok && int(n) > 0 {
+ concurrency = min(int(n), 16)
+ }
+ }
+
+ var items []batchItem
+ var parseErr error
+ itemsTbl.ForEach(func(_, v lua.LValue) {
+ if parseErr != nil {
+ return
+ }
+ entry, ok := v.(*lua.LTable)
+ if !ok {
+ parseErr = fmt.Errorf("download_all: item is not a table")
+ return
+ }
+ it := batchItem{dest: strField(entry, "dest"), url: strField(entry, "url")}
+ if it.dest == "" {
+ parseErr = fmt.Errorf("download_all: item.dest is required")
+ return
+ }
+ it.full = inv.resolvePath(L, it.dest) // raises via fail on escape
+ if s := strField(entry, "sha256"); s != "" {
+ it.newHash, it.want = sha256.New, strings.ToLower(s)
+ } else if s := strField(entry, "sha1"); s != "" {
+ it.newHash, it.want = sha1.New, strings.ToLower(s)
+ }
+ if res, ok := entry.RawGetString("resolve").(*lua.LTable); ok {
+ it.resolveURL = strField(res, "url")
+ if hdrs, ok := res.RawGetString("headers").(*lua.LTable); ok {
+ it.resolveHeaders = map[string]string{}
+ hdrs.ForEach(func(k, hv lua.LValue) {
+ it.resolveHeaders[k.String()] = hv.String()
+ })
+ }
+ }
+ if it.url == "" && it.resolveURL == "" {
+ parseErr = fmt.Errorf("download_all: %s has neither url nor resolve.url", it.dest)
+ return
+ }
+ items = append(items, it)
+ })
+ if parseErr != nil {
+ inv.fail(L, parseErr)
+ return 0
+ }
+ if len(items) == 0 {
+ return 0
+ }
+
+ total := len(items)
+ var done atomic.Int64
+ // gRPC stream sends are not safe for concurrent use; serialize emission.
+ var emitMu sync.Mutex
+ emit := func(p provider.Progress) {
+ emitMu.Lock()
+ inv.emit(p)
+ emitMu.Unlock()
+ }
+
+ g, ctx := errgroup.WithContext(inv.ctx)
+ g.SetLimit(concurrency)
+ for _, it := range items {
+ g.Go(func() error {
+ url := it.url
+ if url == "" {
+ u, err := resolveDownloadURL(ctx, &inv.host.client, it.resolveURL, it.resolveHeaders)
+ if err != nil {
+ return fmt.Errorf("%s: %w", it.dest, err)
+ }
+ url = u
+ }
+ var h hash.Hash
+ if it.newHash != nil {
+ h = it.newHash()
+ }
+ // Per-byte progress is intentionally dropped: fractions from
+ // parallel workers would interleave; completion counts are stable.
+ sum, _, err := dl.Download(ctx, &inv.host.client, url, it.full, h, nil)
+ if err != nil {
+ return fmt.Errorf("%s: %w", it.dest, err)
+ }
+ if it.want != "" && !strings.EqualFold(sum, it.want) {
+ return fmt.Errorf("%s: %w (got %s want %s)", it.dest, provider.ErrChecksumMismatch, sum, it.want)
+ }
+ emit(provider.Progress{Step: "shop.install.downloading",
+ Fraction: float64(done.Add(1)) / float64(total), LogLine: path.Base(it.dest)})
+ return nil
+ })
+ }
+ if err := g.Wait(); err != nil {
+ inv.fail(L, err)
+ return 0
+ }
+ return 0
+}
+
+// resolveDownloadURL fetches a JSON endpoint whose "data" field is the real
+// download URL (the CurseForge /download-url convention).
+func resolveDownloadURL(ctx context.Context, client *http.Client, url string, headers map[string]string) (string, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("User-Agent", scriptUserAgent)
+ for k, v := range headers {
+ req.Header.Set(k, v)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode == http.StatusForbidden {
+ return "", fmt.Errorf("CurseForge denied downloading (the author disallows third-party downloads)")
+ }
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("GET %s: unexpected status %s", url, resp.Status)
+ }
+ var out struct {
+ Data string `json:"data"`
+ }
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&out); err != nil {
+ return "", fmt.Errorf("resolve %s: %v", url, err)
+ }
+ if out.Data == "" {
+ return "", fmt.Errorf("resolve %s: empty download url", url)
+ }
+ return out.Data, nil
+}
+
// -- filesystem (confined to the server dir) ----------------------------------
func (inv *invocation) requireFS(L *lua.LState) {
@@ -590,12 +756,20 @@ func (inv *invocation) jsonEncode(L *lua.LState) int {
}
// unzip extracts a zip (relative path within the server dir) into destDir
-// (also within the server dir), guarding against zip-slip.
+// (also within the server dir), guarding against zip-slip. An optional third
+// arg { prefix = "overrides/" } extracts only entries under prefix, stripping
+// it from each destination — used to splat a pack's overrides/ tree into the
+// server root.
func (inv *invocation) unzip(L *lua.LState) int {
inv.requireFS(L)
zipPath := inv.resolvePath(L, L.CheckString(1))
destDir := inv.resolvePath(L, L.CheckString(2))
+ var prefix string
+ if opts, ok := L.Get(3).(*lua.LTable); ok {
+ prefix = strField(opts, "prefix")
+ }
+
zr, err := zip.OpenReader(zipPath)
if err != nil {
inv.fail(L, err)
@@ -605,7 +779,17 @@ func (inv *invocation) unzip(L *lua.LState) int {
dest := filepath.Clean(destDir)
for _, f := range zr.File {
- target := filepath.Clean(filepath.Join(dest, f.Name))
+ name := filepath.ToSlash(f.Name)
+ if prefix != "" {
+ if !strings.HasPrefix(name, prefix) {
+ continue
+ }
+ name = name[len(prefix):]
+ if name == "" {
+ continue // the prefix directory entry itself
+ }
+ }
+ target := filepath.Clean(filepath.Join(dest, name))
if r, err := filepath.Rel(dest, target); err != nil || r == ".." || strings.HasPrefix(r, ".."+string(filepath.Separator)) {
inv.fail(L, fmt.Errorf("%w: %s", ErrPathEscape, f.Name))
return 0
diff --git a/engine/internal/scripting/hostfuncs_download_all_test.go b/engine/internal/scripting/hostfuncs_download_all_test.go
new file mode 100644
index 0000000..eb562bc
--- /dev/null
+++ b/engine/internal/scripting/hostfuncs_download_all_test.go
@@ -0,0 +1,220 @@
+package scripting
+
+import (
+ "context"
+ "crypto/sha1"
+ "encoding/hex"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/000hen/justhostmc/engine/internal/provider"
+)
+
+// downloadAllScript wraps a Lua install() body that calls jhmc.download_all.
+func downloadAllScript(body string) string {
+ return fmt.Sprintf(`
+meta = { id = "batch", name = "Batch", mod_layout = "mods",
+ permissions = { { kind = "network", reason = "test" } } }
+function versions() return {} end
+function install(ctx)
+%s
+ return { java_major = 21, args = { "-jar", "s.jar" } }
+end
+`, body)
+}
+
+func installBatch(t *testing.T, script, dir string, progress func(provider.Progress)) error {
+ t.Helper()
+ r := NewRegistry(NewHost(nil, nil, nil), nil)
+ e, err := r.AddSource(context.Background(), script, true) // builtin → network granted
+ if err != nil {
+ t.Fatalf("AddSource: %v", err)
+ }
+ _, err = e.Provider.Install(context.Background(), dir, "1.0", progress)
+ return err
+}
+
+// TestDownloadAllDownloadsConcurrently proves N slow files complete in roughly
+// one slot's time, land at their dests with the right bytes, and emit one
+// completion progress line per file.
+func TestDownloadAllDownloadsConcurrently(t *testing.T) {
+ const n = 6
+ var inflight, peak atomic.Int64
+ mux := http.NewServeMux()
+ mux.HandleFunc("/f/", func(w http.ResponseWriter, r *http.Request) {
+ cur := inflight.Add(1)
+ defer inflight.Add(-1)
+ for {
+ old := peak.Load()
+ if cur <= old || peak.CompareAndSwap(old, cur) {
+ break
+ }
+ }
+ time.Sleep(150 * time.Millisecond)
+ _, _ = w.Write([]byte("body-" + strings.TrimPrefix(r.URL.Path, "/f/")))
+ })
+ srv := httptest.NewServer(mux)
+ t.Cleanup(srv.Close)
+
+ items := make([]string, 0, n)
+ for i := range n {
+ items = append(items, fmt.Sprintf(`{ dest = "mods/f%d.txt", url = %q }`, i, fmt.Sprintf("%s/f/%d", srv.URL, i)))
+ }
+ script := downloadAllScript(` jhmc.download_all({ ` + strings.Join(items, ", ") + ` })`)
+
+ dir := t.TempDir()
+ var mu sync.Mutex
+ var logs []string
+ start := time.Now()
+ err := installBatch(t, script, dir, func(p provider.Progress) {
+ if p.LogLine != "" {
+ mu.Lock()
+ logs = append(logs, p.LogLine)
+ mu.Unlock()
+ }
+ })
+ elapsed := time.Since(start)
+ if err != nil {
+ t.Fatalf("install: %v", err)
+ }
+ for i := range n {
+ b, err := os.ReadFile(filepath.Join(dir, "mods", fmt.Sprintf("f%d.txt", i)))
+ if err != nil || string(b) != fmt.Sprintf("body-%d", i) {
+ t.Errorf("f%d.txt content = %q err=%v", i, b, err)
+ }
+ }
+ if peak.Load() < 2 {
+ t.Errorf("peak concurrency = %d, want >= 2", peak.Load())
+ }
+ if elapsed > 700*time.Millisecond {
+ t.Errorf("elapsed = %v, want well under serial 6*150ms + overhead", elapsed)
+ }
+ if len(logs) != n {
+ t.Errorf("completion log lines = %d (%v), want %d", len(logs), logs, n)
+ }
+}
+
+// TestDownloadAllResolveChain proves a resolve item fetches the JSON endpoint
+// (with headers) and downloads the URL in its data field.
+func TestDownloadAllResolveChain(t *testing.T) {
+ mux := http.NewServeMux()
+ var gotKey atomic.Value
+ var base string
+ mux.HandleFunc("/resolve", func(w http.ResponseWriter, r *http.Request) {
+ gotKey.Store(r.Header.Get("x-api-key"))
+ fmt.Fprintf(w, `{"data":%q}`, base+"/real")
+ })
+ mux.HandleFunc("/real", func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte("resolved-body"))
+ })
+ srv := httptest.NewServer(mux)
+ base = srv.URL
+ t.Cleanup(srv.Close)
+
+ script := downloadAllScript(fmt.Sprintf(
+ ` jhmc.download_all({ { dest = "mods/r.jar", resolve = { url = %q, headers = { ["x-api-key"] = "sekrit" } } } })`,
+ srv.URL+"/resolve"))
+ dir := t.TempDir()
+ if err := installBatch(t, script, dir, nil); err != nil {
+ t.Fatalf("install: %v", err)
+ }
+ if b, _ := os.ReadFile(filepath.Join(dir, "mods", "r.jar")); string(b) != "resolved-body" {
+ t.Errorf("resolved file content = %q", b)
+ }
+ if gotKey.Load() != "sekrit" {
+ t.Errorf("resolve header = %v, want sekrit", gotKey.Load())
+ }
+}
+
+// TestDownloadAllFirstErrorCancels proves one failing item fails the whole
+// call, names the dest, and cancels in-flight downloads instead of waiting for
+// them to finish.
+func TestDownloadAllFirstErrorCancels(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/bad", func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, "nope", http.StatusNotFound)
+ })
+ mux.HandleFunc("/slow", func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-time.After(10 * time.Second):
+ case <-r.Context().Done():
+ }
+ })
+ srv := httptest.NewServer(mux)
+ t.Cleanup(srv.Close)
+
+ script := downloadAllScript(fmt.Sprintf(` jhmc.download_all({
+ { dest = "mods/slow.jar", url = %q },
+ { dest = "mods/bad.jar", url = %q },
+ })`, srv.URL+"/slow", srv.URL+"/bad"))
+
+ start := time.Now()
+ err := installBatch(t, script, t.TempDir(), nil)
+ if err == nil {
+ t.Fatal("install succeeded, want error")
+ }
+ if !strings.Contains(err.Error(), "bad.jar") {
+ t.Errorf("error %q does not name the failing dest", err)
+ }
+ if elapsed := time.Since(start); elapsed > 5*time.Second {
+ t.Errorf("elapsed = %v; in-flight download was not canceled", elapsed)
+ }
+}
+
+// TestDownloadAllChecksumMismatch proves a wrong sha1 fails the batch with the
+// checksum sentinel.
+func TestDownloadAllChecksumMismatch(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte("actual-bytes"))
+ }))
+ t.Cleanup(srv.Close)
+
+ wrong := sha1.Sum([]byte("other-bytes"))
+ script := downloadAllScript(fmt.Sprintf(
+ ` jhmc.download_all({ { dest = "mods/c.jar", url = %q, sha1 = %q } })`,
+ srv.URL, hex.EncodeToString(wrong[:])))
+ err := installBatch(t, script, t.TempDir(), nil)
+ if err == nil || !strings.Contains(err.Error(), "checksum") {
+ t.Fatalf("err = %v, want checksum mismatch", err)
+ }
+}
+
+// TestDownloadAllProgressFractions proves fractions are completed/total.
+func TestDownloadAllProgressFractions(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte("x"))
+ }))
+ t.Cleanup(srv.Close)
+
+ script := downloadAllScript(fmt.Sprintf(` jhmc.download_all({
+ { dest = "a.txt", url = %[1]q }, { dest = "b.txt", url = %[1]q },
+ { dest = "c.txt", url = %[1]q }, { dest = "d.txt", url = %[1]q },
+ }, { concurrency = 1 })`, srv.URL))
+
+ var fractions []float64
+ err := installBatch(t, script, t.TempDir(), func(p provider.Progress) {
+ if p.LogLine != "" && p.Fraction >= 0 {
+ fractions = append(fractions, p.Fraction)
+ }
+ })
+ if err != nil {
+ t.Fatalf("install: %v", err)
+ }
+ want := []float64{0.25, 0.5, 0.75, 1}
+ if len(fractions) != len(want) {
+ t.Fatalf("fractions = %v, want %v", fractions, want)
+ }
+ for i := range want {
+ if fractions[i] != want[i] {
+ t.Errorf("fractions[%d] = %v, want %v (all: %v)", i, fractions[i], want[i], fractions)
+ }
+ }
+}
diff --git a/engine/internal/scripting/luaprovider.go b/engine/internal/scripting/luaprovider.go
index 9529ebe..d220c8e 100644
--- a/engine/internal/scripting/luaprovider.go
+++ b/engine/internal/scripting/luaprovider.go
@@ -11,12 +11,14 @@ import (
// and Install run the script's versions()/install() in a fresh sandbox each
// call, with the script's currently-granted permissions enforced.
type LuaProvider struct {
- meta Meta
- source string
- host *Host
- builtin bool
- assetDir string // dir with files bundled alongside the script (custom jar), if any
- grantsFn func() GrantSet
+ meta Meta
+ source string
+ host *Host
+ builtin bool
+ assetDir string // dir with files bundled alongside the script (custom jar), if any
+ roleTable bool // true when the script declares a global `provider` role table
+ grantsFn func() GrantSet
+ configFn func() map[string]string
}
// newLuaProvider parses a script's meta (in a throwaway sandbox) and returns the
@@ -28,11 +30,12 @@ func newLuaProvider(ctx context.Context, host *Host, source string, builtin bool
return nil, err
}
defer L.Close()
- meta, err := parseMeta(L)
+ meta, err := parseProviderMeta(L)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrScriptInvalid, err)
}
- return &LuaProvider{meta: meta, source: source, host: host, builtin: builtin, assetDir: assetDir}, nil
+ roleTbl := roleTable(L, "provider") != nil
+ return &LuaProvider{meta: meta, source: source, host: host, builtin: builtin, assetDir: assetDir, roleTable: roleTbl}, nil
}
// Meta returns the script's declared metadata.
@@ -45,14 +48,35 @@ func (p *LuaProvider) grants() GrantSet {
return nil
}
+// config resolves the values the script sees as ctx.config / jhmc.config:
+// declared defaults merged with stored overrides. Returns nil (no config) when
+// the script declares none and none is stored.
+func (p *LuaProvider) config() map[string]string {
+ var stored map[string]string
+ if p.configFn != nil {
+ stored = p.configFn()
+ }
+ if len(p.meta.Config) == 0 && len(stored) == 0 {
+ return nil
+ }
+ return EffectiveConfig(p.meta.Config, stored)
+}
+
// Versions implements provider.Provider.
func (p *LuaProvider) Versions(ctx context.Context) ([]string, error) {
- inv := &invocation{ctx: ctx, host: p.host, granted: p.grants(), assetDir: p.assetDir}
+ inv := &invocation{ctx: ctx, host: p.host, granted: p.grants(), assetDir: p.assetDir, config: p.config(), providerRole: p.roleTable}
return inv.versions(p.source)
}
// Install implements provider.Provider.
func (p *LuaProvider) Install(ctx context.Context, dir, version string, progress func(provider.Progress)) (provider.LaunchSpec, error) {
- inv := &invocation{ctx: ctx, host: p.host, granted: p.grants(), report: progress, assetDir: p.assetDir}
+ inv := &invocation{ctx: ctx, host: p.host, granted: p.grants(), report: progress, assetDir: p.assetDir, config: p.config(), providerRole: p.roleTable}
return inv.install(p.source, dir, version)
}
+
+// Update implements provider.Updater; scripts without an update() function
+// yield provider.ErrUpdateUnsupported.
+func (p *LuaProvider) Update(ctx context.Context, dir, version, oldVersion string, progress func(provider.Progress)) (provider.LaunchSpec, error) {
+ inv := &invocation{ctx: ctx, host: p.host, granted: p.grants(), report: progress, assetDir: p.assetDir, config: p.config(), providerRole: p.roleTable}
+ return inv.update(p.source, dir, version, oldVersion)
+}
diff --git a/engine/internal/scripting/luaprovider_test.go b/engine/internal/scripting/luaprovider_test.go
index 1b6a83a..81d6a53 100644
--- a/engine/internal/scripting/luaprovider_test.go
+++ b/engine/internal/scripting/luaprovider_test.go
@@ -125,6 +125,111 @@ func TestHostVersionsAndInstall(t *testing.T) {
}
}
+// TestInstallLaunchSpecReadsMcVersionAndLoader verifies a provider that resolves
+// a concrete version/loader inside install() surfaces them on the LaunchSpec —
+// the hook a modpack provider uses to override an opaque "packId/versionId".
+func TestInstallLaunchSpecReadsMcVersionAndLoader(t *testing.T) {
+ script := `
+meta = { id = "resolv", name = "Resolv", mod_layout = "mods" }
+function versions() return {} end
+function install(ctx)
+ return { java_major = 21, args = { "-jar", "server.jar", "nogui" },
+ mc_version = "1.20.1", loader = "forge" }
+end
+`
+ r := NewRegistry(NewHost(nil, nil, nil), nil)
+ e, err := r.AddSource(context.Background(), script, true)
+ if err != nil {
+ t.Fatalf("AddSource: %v", err)
+ }
+ spec, err := e.Provider.Install(context.Background(), t.TempDir(), "pack/42", nil)
+ if err != nil {
+ t.Fatalf("Install: %v", err)
+ }
+ if spec.McVersion != "1.20.1" {
+ t.Errorf("McVersion = %q, want 1.20.1", spec.McVersion)
+ }
+ if spec.Loader != "forge" {
+ t.Errorf("Loader = %q, want forge", spec.Loader)
+ }
+}
+
+// TestInstallLaunchSpecReadsPackVersion verifies a modpack provider can persist
+// its opaque "packId/versionId" through the launch spec.
+func TestInstallLaunchSpecReadsPackVersion(t *testing.T) {
+ script := `
+meta = { id = "packy", name = "Packy", mod_layout = "mods" }
+function versions() return {} end
+function install(ctx)
+ return { java_major = 21, args = { "-jar", "server.jar", "nogui" },
+ mc_version = "1.20.1", loader = "neoforge",
+ pack_version = tostring(ctx.version) }
+end
+`
+ r := NewRegistry(NewHost(nil, nil, nil), nil)
+ e, err := r.AddSource(context.Background(), script, true)
+ if err != nil {
+ t.Fatalf("AddSource: %v", err)
+ }
+ spec, err := e.Provider.Install(context.Background(), t.TempDir(), "95/12695", nil)
+ if err != nil {
+ t.Fatalf("Install: %v", err)
+ }
+ if spec.PackVersion != "95/12695" {
+ t.Errorf("PackVersion = %q, want 95/12695", spec.PackVersion)
+ }
+}
+
+// TestUpdatePassesVersionsAndParsesSpec verifies update(ctx) receives both the
+// new and old opaque versions and its return parses like install's.
+func TestUpdatePassesVersionsAndParsesSpec(t *testing.T) {
+ script := `
+meta = { id = "updy", name = "Updy", mod_layout = "mods" }
+function versions() return {} end
+function install(ctx) return { java_major = 21, args = { "a" } } end
+function update(ctx)
+ return { java_major = 21, args = { "-jar", "s.jar" },
+ mc_version = "1.21.1", loader = "neoforge",
+ pack_version = tostring(ctx.version) .. "|was|" .. tostring(ctx.old_version) }
+end
+`
+ r := NewRegistry(NewHost(nil, nil, nil), nil)
+ e, err := r.AddSource(context.Background(), script, true)
+ if err != nil {
+ t.Fatalf("AddSource: %v", err)
+ }
+ up, ok := e.Provider.(provider.Updater)
+ if !ok {
+ t.Fatal("LuaProvider does not implement provider.Updater")
+ }
+ spec, err := up.Update(context.Background(), t.TempDir(), "95/200", "95/100", nil)
+ if err != nil {
+ t.Fatalf("Update: %v", err)
+ }
+ if spec.PackVersion != "95/200|was|95/100" {
+ t.Errorf("PackVersion = %q, want versions threaded through", spec.PackVersion)
+ }
+}
+
+// TestUpdateUnsupportedWithoutFunction proves a script lacking update() maps to
+// the sentinel instead of a generic Lua error.
+func TestUpdateUnsupportedWithoutFunction(t *testing.T) {
+ script := `
+meta = { id = "noup", name = "NoUp", mod_layout = "mods" }
+function versions() return {} end
+function install(ctx) return { java_major = 21, args = { "a" } } end
+`
+ r := NewRegistry(NewHost(nil, nil, nil), nil)
+ e, err := r.AddSource(context.Background(), script, true)
+ if err != nil {
+ t.Fatalf("AddSource: %v", err)
+ }
+ up := e.Provider.(provider.Updater)
+ if _, err := up.Update(context.Background(), t.TempDir(), "95/200", "95/100", nil); !errors.Is(err, provider.ErrUpdateUnsupported) {
+ t.Fatalf("Update err = %v, want ErrUpdateUnsupported", err)
+ }
+}
+
// TestUngrantedNetworkDenied proves a non-builtin script with no grants cannot
// reach the network.
func TestUngrantedNetworkDenied(t *testing.T) {
diff --git a/engine/internal/scripting/meta.go b/engine/internal/scripting/meta.go
index 72603aa..048b903 100644
--- a/engine/internal/scripting/meta.go
+++ b/engine/internal/scripting/meta.go
@@ -2,6 +2,7 @@ package scripting
import (
"fmt"
+ "strconv"
"strings"
mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
@@ -15,6 +16,26 @@ type Permission struct {
Reason string
}
+// ConfigOption is one author-declared typed config field (a meta.config entry).
+// The same shape backs every scriptable subsystem (providers, automation
+// scripts, parsers and shops).
+type ConfigOption struct {
+ Key string
+ Type mcmanagerv1.ConfigOptionType
+ Name string
+ Description string
+ Default string // string-encoded; validated to parse for number/boolean
+ Required bool
+}
+
+// configTypeByName maps a lowercase meta.config `type` string to its enum.
+var configTypeByName = map[string]mcmanagerv1.ConfigOptionType{
+ "string": mcmanagerv1.ConfigOptionType_CONFIG_OPTION_STRING,
+ "number": mcmanagerv1.ConfigOptionType_CONFIG_OPTION_NUMBER,
+ "boolean": mcmanagerv1.ConfigOptionType_CONFIG_OPTION_BOOLEAN,
+ "secret": mcmanagerv1.ConfigOptionType_CONFIG_OPTION_SECRET,
+}
+
// Meta is the author-declared header every provider/automation script carries.
type Meta struct {
ID string
@@ -33,6 +54,20 @@ type Meta struct {
// NeedsKey marks a shop script whose source requires an API key
// (shops only); the shop is not Ready until one is configured.
NeedsKey bool
+ // Kinds lists the item kinds a shop serves ("mod"/"plugin"/"modpack");
+ // shops only. Empty means the default {"mod","plugin"} (applied by the
+ // shop service, not here, so parseMeta stays subsystem-agnostic).
+ Kinds []string
+ // Hidden marks a provider not offered in the create-server UI — its install
+ // is driven elsewhere (e.g. a modpack shop); providers only.
+ Hidden bool
+ // Config lists the author-declared typed config options (all subsystems).
+ Config []ConfigOption
+ // Aliases lists prior ids this script also answers to, so servers persisted
+ // under an old id (e.g. "curseforge_modpacks") resolve to this canonical
+ // entry after a merge. Registry/ShopSet redirect an alias id to this id and
+ // never list an alias as a separate entry.
+ Aliases []string
}
// DeclaredKinds returns just the permission kinds the script declares.
@@ -74,6 +109,47 @@ func parseMeta(L *lua.LState) (Meta, error) {
m.NeedsKey = bool(b)
}
+ if b, ok := tbl.RawGetString("hidden").(lua.LBool); ok {
+ m.Hidden = bool(b)
+ }
+
+ if kinds, ok := tbl.RawGetString("kinds").(*lua.LTable); ok {
+ ks, kerr := parseKinds(kinds)
+ if kerr != nil {
+ return Meta{}, kerr
+ }
+ m.Kinds = ks
+ }
+
+ if aliases, ok := tbl.RawGetString("aliases").(*lua.LTable); ok {
+ seen := map[string]bool{m.ID: true}
+ var aerr error
+ aliases.ForEach(func(_, av lua.LValue) {
+ if aerr != nil {
+ return
+ }
+ s, ok := av.(lua.LString)
+ if !ok {
+ aerr = fmt.Errorf("meta.aliases entries must be strings")
+ return
+ }
+ alias := strings.TrimSpace(string(s))
+ if !validProviderID(alias) {
+ aerr = fmt.Errorf("meta.aliases has invalid id %q", alias)
+ return
+ }
+ if seen[alias] {
+ aerr = fmt.Errorf("meta.aliases has duplicate id %q", alias)
+ return
+ }
+ seen[alias] = true
+ m.Aliases = append(m.Aliases, alias)
+ })
+ if aerr != nil {
+ return Meta{}, aerr
+ }
+ }
+
if formats, ok := tbl.RawGetString("formats").(*lua.LTable); ok {
formats.ForEach(func(_, fv lua.LValue) {
if s, ok := fv.(lua.LString); ok && strings.TrimSpace(string(s)) != "" {
@@ -106,9 +182,162 @@ func parseMeta(L *lua.LState) (Meta, error) {
}
}
+ if cfg, ok := tbl.RawGetString("config").(*lua.LTable); ok {
+ var cerr error
+ seen := map[string]bool{}
+ cfg.ForEach(func(_, cv lua.LValue) {
+ if cerr != nil {
+ return
+ }
+ ctbl, ok := cv.(*lua.LTable)
+ if !ok {
+ cerr = fmt.Errorf("meta.config entries must be tables")
+ return
+ }
+ key := strField(ctbl, "key")
+ if key == "" {
+ cerr = fmt.Errorf("meta.config entry is missing a key")
+ return
+ }
+ if !validProviderID(key) {
+ cerr = fmt.Errorf("meta.config key %q must contain only letters, digits, '-' or '_'", key)
+ return
+ }
+ if seen[key] {
+ cerr = fmt.Errorf("meta.config key %q is declared more than once", key)
+ return
+ }
+ seen[key] = true
+ typeName := strings.ToLower(strField(ctbl, "type"))
+ if typeName == "" {
+ typeName = "string"
+ }
+ ct, ok := configTypeByName[typeName]
+ if !ok {
+ cerr = fmt.Errorf("meta.config key %q has unknown type %q", key, typeName)
+ return
+ }
+ def := strField(ctbl, "default")
+ if err := validateConfigDefault(ct, def); err != nil {
+ cerr = fmt.Errorf("meta.config key %q: %w", key, err)
+ return
+ }
+ var required bool
+ if b, ok := ctbl.RawGetString("required").(lua.LBool); ok {
+ required = bool(b)
+ }
+ m.Config = append(m.Config, ConfigOption{
+ Key: key,
+ Type: ct,
+ Name: strField(ctbl, "name"),
+ Description: strField(ctbl, "description"),
+ Default: def,
+ Required: required,
+ })
+ })
+ if cerr != nil {
+ return Meta{}, cerr
+ }
+ }
+
return m, nil
}
+// parseKinds reads a Lua array of shop-kind strings, validating each.
+func parseKinds(kinds *lua.LTable) ([]string, error) {
+ var out []string
+ var kerr error
+ kinds.ForEach(func(_, kv lua.LValue) {
+ if kerr != nil {
+ return
+ }
+ s, ok := kv.(lua.LString)
+ if !ok {
+ kerr = fmt.Errorf("kinds entries must be strings")
+ return
+ }
+ kind := strings.ToLower(strings.TrimSpace(string(s)))
+ if !validShopKind(kind) {
+ kerr = fmt.Errorf("kinds has unknown kind %q", kind)
+ return
+ }
+ out = append(out, kind)
+ })
+ return out, kerr
+}
+
+// roleTable returns the global role sub-table (`shop` or `provider`) a script
+// declares, or nil when it uses the legacy top-level-function layout.
+func roleTable(L *lua.LState, role string) *lua.LTable {
+ if tbl, ok := L.GetGlobal(role).(*lua.LTable); ok {
+ return tbl
+ }
+ return nil
+}
+
+// parseShopMeta parses the shared meta and layers on the shop role's scoped
+// fields (kinds, needs_key) when a global `shop` table is present. A legacy
+// script (no `shop` table) keeps reading those fields from meta.
+func parseShopMeta(L *lua.LState) (Meta, error) {
+ m, err := parseMeta(L)
+ if err != nil {
+ return Meta{}, err
+ }
+ if tbl := roleTable(L, "shop"); tbl != nil {
+ if b, ok := tbl.RawGetString("needs_key").(lua.LBool); ok {
+ m.NeedsKey = bool(b)
+ }
+ if kinds, ok := tbl.RawGetString("kinds").(*lua.LTable); ok {
+ ks, kerr := parseKinds(kinds)
+ if kerr != nil {
+ return Meta{}, fmt.Errorf("shop.%w", kerr)
+ }
+ m.Kinds = ks
+ }
+ }
+ return m, nil
+}
+
+// parseProviderMeta parses the shared meta and layers on the provider role's
+// scoped fields (hidden, mod_layout) when a global `provider` table is present.
+// A legacy script (no `provider` table) keeps reading those fields from meta.
+func parseProviderMeta(L *lua.LState) (Meta, error) {
+ m, err := parseMeta(L)
+ if err != nil {
+ return Meta{}, err
+ }
+ if tbl := roleTable(L, "provider"); tbl != nil {
+ if b, ok := tbl.RawGetString("hidden").(lua.LBool); ok {
+ m.Hidden = bool(b)
+ }
+ if s, ok := tbl.RawGetString("mod_layout").(lua.LString); ok {
+ if v := strings.ToLower(strings.TrimSpace(string(s))); v != "" {
+ m.ModLayout = v
+ }
+ }
+ }
+ return m, nil
+}
+
+// validateConfigDefault checks that a declared default parses for the typed
+// options (number/boolean); string/secret accept any default.
+func validateConfigDefault(t mcmanagerv1.ConfigOptionType, def string) error {
+ if def == "" {
+ return nil
+ }
+ switch t {
+ case mcmanagerv1.ConfigOptionType_CONFIG_OPTION_NUMBER:
+ if _, err := strconv.ParseFloat(def, 64); err != nil {
+ return fmt.Errorf("default %q is not a number", def)
+ }
+ case mcmanagerv1.ConfigOptionType_CONFIG_OPTION_BOOLEAN:
+ if _, err := strconv.ParseBool(def); err != nil {
+ return fmt.Errorf("default %q is not a boolean", def)
+ }
+ }
+ return nil
+}
+
// validProviderID reports whether id is a safe path component (letters, digits,
// '-', '_'), so it can be used directly as a directory name by Import/Remove.
func validProviderID(id string) bool {
@@ -122,6 +351,15 @@ func validProviderID(id string) bool {
return id != ""
}
+// validShopKind reports whether k is a recognized shop item kind.
+func validShopKind(k string) bool {
+ switch k {
+ case "mod", "plugin", "modpack":
+ return true
+ }
+ return false
+}
+
// strField reads a string field from a Lua table, returning "" if absent.
func strField(tbl *lua.LTable, key string) string {
if s, ok := tbl.RawGetString(key).(lua.LString); ok {
diff --git a/engine/internal/scripting/metaconfig_test.go b/engine/internal/scripting/metaconfig_test.go
new file mode 100644
index 0000000..f2fe7e5
--- /dev/null
+++ b/engine/internal/scripting/metaconfig_test.go
@@ -0,0 +1,68 @@
+package scripting
+
+import (
+ "context"
+ "testing"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+)
+
+// metaFrom parses just the meta table of a script source (no functions needed).
+func metaFrom(t *testing.T, src string) (Meta, error) {
+ t.Helper()
+ inv := &invocation{ctx: context.Background(), host: NewHost(nil, nil, nil)}
+ L, err := inv.prepare(src)
+ if err != nil {
+ return Meta{}, err
+ }
+ defer L.Close()
+ return parseMeta(L)
+}
+
+func TestParseMetaConfigValid(t *testing.T) {
+ m, err := metaFrom(t, `
+meta = { id = "x", config = {
+ { key = "region", type = "string", name = "Region", description = "d", default = "us", required = true },
+ { key = "count", type = "number", default = "5" },
+ { key = "flag", type = "boolean", default = "true" },
+ { key = "token", type = "secret" },
+ { key = "plain" },
+} }`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(m.Config) != 5 {
+ t.Fatalf("config len = %d, want 5", len(m.Config))
+ }
+ r := m.Config[0]
+ if r.Key != "region" || r.Type != mcmanagerv1.ConfigOptionType_CONFIG_OPTION_STRING ||
+ r.Name != "Region" || r.Description != "d" || r.Default != "us" || !r.Required {
+ t.Fatalf("region option: %+v", r)
+ }
+ if m.Config[1].Type != mcmanagerv1.ConfigOptionType_CONFIG_OPTION_NUMBER ||
+ m.Config[2].Type != mcmanagerv1.ConfigOptionType_CONFIG_OPTION_BOOLEAN ||
+ m.Config[3].Type != mcmanagerv1.ConfigOptionType_CONFIG_OPTION_SECRET {
+ t.Fatalf("types: %+v", m.Config)
+ }
+ // A missing type defaults to string.
+ if m.Config[4].Type != mcmanagerv1.ConfigOptionType_CONFIG_OPTION_STRING {
+ t.Fatalf("plain option type = %v", m.Config[4].Type)
+ }
+}
+
+func TestParseMetaConfigRejectsBad(t *testing.T) {
+ cases := map[string]string{
+ "unknown type": `meta = { id = "x", config = { { key = "k", type = "colour" } } }`,
+ "dup key": `meta = { id = "x", config = { { key = "k" }, { key = "k" } } }`,
+ "missing key": `meta = { id = "x", config = { { type = "string" } } }`,
+ "bad key char": `meta = { id = "x", config = { { key = "a.b" } } }`,
+ "bad number": `meta = { id = "x", config = { { key = "k", type = "number", default = "abc" } } }`,
+ "bad boolean": `meta = { id = "x", config = { { key = "k", type = "boolean", default = "maybe" } } }`,
+ "not a table": `meta = { id = "x", config = { "nope" } }`,
+ }
+ for name, src := range cases {
+ if _, err := metaFrom(t, src); err == nil {
+ t.Errorf("%s: expected an error, got none", name)
+ }
+ }
+}
diff --git a/engine/internal/scripting/metakinds_test.go b/engine/internal/scripting/metakinds_test.go
new file mode 100644
index 0000000..478b0f7
--- /dev/null
+++ b/engine/internal/scripting/metakinds_test.go
@@ -0,0 +1,68 @@
+package scripting
+
+import "testing"
+
+func TestParseMetaKinds(t *testing.T) {
+ m, err := metaFrom(t, `meta = { id = "x", kinds = { "modpack" } }`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(m.Kinds) != 1 || m.Kinds[0] != "modpack" {
+ t.Fatalf("kinds = %v, want [modpack]", m.Kinds)
+ }
+}
+
+func TestParseMetaKindsNormalizesAndAllowsAll(t *testing.T) {
+ m, err := metaFrom(t, `meta = { id = "x", kinds = { "MOD", " Plugin ", "modpack" } }`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{"mod", "plugin", "modpack"}
+ if len(m.Kinds) != len(want) {
+ t.Fatalf("kinds = %v, want %v", m.Kinds, want)
+ }
+ for i, k := range want {
+ if m.Kinds[i] != k {
+ t.Fatalf("kinds[%d] = %q, want %q", i, m.Kinds[i], k)
+ }
+ }
+}
+
+func TestParseMetaKindsRejectsUnknown(t *testing.T) {
+ if _, err := metaFrom(t, `meta = { id = "x", kinds = { "widget" } }`); err == nil {
+ t.Fatal("expected an error for an unknown kind")
+ }
+ if _, err := metaFrom(t, `meta = { id = "x", kinds = { 3 } }`); err == nil {
+ t.Fatal("expected an error for a non-string kind")
+ }
+}
+
+func TestParseMetaKindsAbsentIsEmpty(t *testing.T) {
+ // The default {"mod","plugin"} is applied by the shop service, not parseMeta,
+ // so an absent meta.kinds parses to an empty slice.
+ m, err := metaFrom(t, `meta = { id = "x" }`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(m.Kinds) != 0 {
+ t.Fatalf("kinds = %v, want empty", m.Kinds)
+ }
+}
+
+func TestParseMetaHidden(t *testing.T) {
+ m, err := metaFrom(t, `meta = { id = "x", hidden = true }`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !m.Hidden {
+ t.Fatal("hidden should be true")
+ }
+
+ m2, err := metaFrom(t, `meta = { id = "x" }`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if m2.Hidden {
+ t.Fatal("hidden should default to false")
+ }
+}
diff --git a/engine/internal/scripting/modpack_cf_test.go b/engine/internal/scripting/modpack_cf_test.go
new file mode 100644
index 0000000..f92e4a8
--- /dev/null
+++ b/engine/internal/scripting/modpack_cf_test.go
@@ -0,0 +1,167 @@
+package scripting
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "testing"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+)
+
+// builtinProvider loads the embedded providers and returns one by id.
+func builtinProvider(t *testing.T, id string) *Entry {
+ t.Helper()
+ host := NewHost(http.DefaultClient, nil, nil)
+ r := NewRegistry(host, nil)
+ if err := LoadBuiltins(context.Background(), r); err != nil {
+ t.Fatalf("LoadBuiltins: %v", err)
+ }
+ // Modpack providers now live in dual-role source scripts.
+ ss := NewShopSet(host, nil, nil)
+ if _, err := LoadBuiltinSources(context.Background(), r, ss, nil); err != nil {
+ t.Fatalf("LoadBuiltinSources: %v", err)
+ }
+ e, ok := r.Get(id)
+ if !ok {
+ t.Fatalf("%s provider not registered", id)
+ }
+ return e
+}
+
+func TestCurseForgeModpacksProviderHidden(t *testing.T) {
+ e := builtinProvider(t, "curseforge_modpacks")
+ if !e.Meta.Hidden {
+ t.Error("curseforge_modpacks provider should be hidden")
+ }
+ if e.Meta.ModLayout != "mods" {
+ t.Errorf("mod_layout = %q, want mods", e.Meta.ModLayout)
+ }
+ // The merged CurseForge source declares its key once as meta.config.api_key,
+ // shared by both roles.
+ var hasKey bool
+ for _, c := range e.Meta.Config {
+ if c.Key == "api_key" && c.Type == mcmanagerv1.ConfigOptionType_CONFIG_OPTION_SECRET {
+ hasKey = true
+ }
+ }
+ if !hasKey {
+ t.Errorf("should declare an api_key secret, config=%+v", e.Meta.Config)
+ }
+}
+
+func TestCurseForgeModpacksShopIsModpackKind(t *testing.T) {
+ ss := newBuiltinShops(t, http.NotFoundHandler())
+ sh, ok := ss.Get("curseforge_modpacks")
+ if !ok {
+ t.Fatal("curseforge_modpacks shop not registered")
+ }
+ if !sh.Meta().NeedsKey {
+ t.Error("curseforge_modpacks shop should need a key")
+ }
+ var isModpack bool
+ for _, k := range sh.Meta().Kinds {
+ if k == "modpack" {
+ isModpack = true
+ }
+ }
+ if !isModpack {
+ t.Errorf("kinds = %v, want to contain modpack", sh.Meta().Kinds)
+ }
+}
+
+// TestCFPackMeta covers parsing a CurseForge client pack's manifest.json and
+// resolving its file names/hashes/urls through the batch files endpoint.
+func TestCFPackMeta(t *testing.T) {
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodPost && r.URL.Path == "/v1/mods/files" {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "data": []map[string]any{
+ {"id": 100, "modId": 10, "fileName": "cool-1.0.jar",
+ "downloadUrl": "http://edge/cool-1.0.jar",
+ "hashes": []map[string]any{{"algo": 1, "value": "aaa"}}},
+ {"id": 200, "modId": 20, "fileName": "neat-2.0.jar",
+ "downloadUrl": nil, // author-restricted → resolved later via download-url
+ "hashes": []map[string]any{{"algo": 1, "value": "bbb"}}},
+ },
+ })
+ return
+ }
+ http.NotFound(w, r)
+ })
+ srv := httptest.NewServer(handler)
+ t.Cleanup(srv.Close)
+ u, _ := url.Parse(srv.URL)
+ client := &http.Client{Transport: rewriteTransport{target: u}}
+
+ dir := t.TempDir()
+ manifest := `{
+ "minecraft": { "version": "1.20.1", "modLoaders": [{"id":"forge-47.2.0","primary":true}] },
+ "manifestType": "minecraftModpack", "name": "Test Pack", "version": "1.0.0",
+ "files": [
+ {"projectID":10,"fileID":100,"required":true},
+ {"projectID":20,"fileID":200,"required":true}
+ ],
+ "overrides": "overrides"
+ }`
+ writeTestJar(t, filepath.Join(dir, ".jhmc", "pack.zip"), map[string]string{"manifest.json": manifest})
+
+ inv := &invocation{
+ ctx: context.Background(),
+ host: NewHost(client, nil, nil),
+ baseDir: dir,
+ granted: GrantSet{
+ mcmanagerv1.PermissionKind_PERMISSION_NETWORK: true,
+ mcmanagerv1.PermissionKind_PERMISSION_FS_SERVER: true,
+ },
+ }
+ src := `
+function check()
+ local m = mplib.cf_pack_meta(".jhmc/pack.zip", "KEY")
+ assert(m.mc == "1.20.1", "mc " .. tostring(m.mc))
+ assert(m.loader_name == "forge" and m.loader_version == "47.2.0", "loader")
+ assert(m.name == "Test Pack" and m.version == "1.0.0", "name/version")
+ assert(#m.files == 2, "files " .. #m.files)
+ local by = {}
+ for _, f in ipairs(m.files) do by[f.dest] = f end
+ local a = by["mods/cool-1.0.jar"]
+ assert(a and a.url == "http://edge/cool-1.0.jar", "cool url")
+ assert(tostring(a.project_id) == "10" and tostring(a.file_id) == "100", "cool ids")
+ assert(a.sha1 == "aaa", "cool sha1")
+ local b = by["mods/neat-2.0.jar"]
+ assert(b ~= nil, "neat present")
+ assert(b.url == nil or b.url == "", "neat has no direct url")
+ assert(b.sha1 == "bbb", "neat sha1")
+ assert(tostring(b.project_id) == "20", "neat project")
+end`
+ if err := runInv(t, inv, src); err != nil {
+ t.Fatalf("script failed: %v", err)
+ }
+}
+
+// TestCFPackMetaRequiresKey verifies the manifest lookup fails clearly without a
+// CurseForge API key.
+func TestCFPackMetaRequiresKey(t *testing.T) {
+ dir := t.TempDir()
+ manifest := `{
+ "minecraft": { "version": "1.20.1", "modLoaders": [{"id":"forge-47.2.0","primary":true}] },
+ "name": "P", "version": "1", "files": [{"projectID":10,"fileID":100}]
+ }`
+ writeTestJar(t, filepath.Join(dir, ".jhmc", "pack.zip"), map[string]string{"manifest.json": manifest})
+ inv := &invocation{
+ ctx: context.Background(),
+ host: NewHost(http.DefaultClient, nil, nil),
+ baseDir: dir,
+ granted: GrantSet{
+ mcmanagerv1.PermissionKind_PERMISSION_NETWORK: true,
+ mcmanagerv1.PermissionKind_PERMISSION_FS_SERVER: true,
+ },
+ }
+ err := runInv(t, inv, `function check() mplib.cf_pack_meta(".jhmc/pack.zip", "") end`)
+ if err == nil {
+ t.Fatal("expected an error without an API key")
+ }
+}
diff --git a/engine/internal/scripting/modpack_import_test.go b/engine/internal/scripting/modpack_import_test.go
new file mode 100644
index 0000000..c63168b
--- /dev/null
+++ b/engine/internal/scripting/modpack_import_test.go
@@ -0,0 +1,75 @@
+package scripting
+
+import (
+ "context"
+ "errors"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+ "github.com/000hen/justhostmc/engine/internal/provider"
+)
+
+func TestImportProviderHidden(t *testing.T) {
+ e := builtinProvider(t, "import")
+ if !e.Meta.Hidden {
+ t.Error("import provider should be hidden")
+ }
+ if e.Meta.ModLayout != "mods" {
+ t.Errorf("mod_layout = %q, want mods", e.Meta.ModLayout)
+ }
+ var hasKey bool
+ for _, c := range e.Meta.Config {
+ if c.Key == "curseforge_api_key" && c.Type == mcmanagerv1.ConfigOptionType_CONFIG_OPTION_SECRET {
+ hasKey = true
+ }
+ }
+ if !hasKey {
+ t.Errorf("import should declare a curseforge_api_key secret, config=%+v", e.Meta.Config)
+ }
+}
+
+// stageImportZip writes the staged import file the "import" provider reads.
+func stageImportZip(t *testing.T, dir string, entries map[string]string) {
+ t.Helper()
+ writeTestJar(t, filepath.Join(dir, ".jhmc", "import.zip"), entries)
+}
+
+func TestImportProviderRejectsUnknownFormat(t *testing.T) {
+ dir := t.TempDir()
+ stageImportZip(t, dir, map[string]string{"random.txt": "x"})
+ e := builtinProvider(t, "import")
+ _, err := e.Provider.Install(context.Background(), dir, "import/local", nil)
+ if err == nil || !strings.Contains(err.Error(), "not a recognized modpack") {
+ t.Fatalf("want unrecognized-format error, got %v", err)
+ }
+}
+
+func TestImportProviderCurseForgeNeedsKey(t *testing.T) {
+ dir := t.TempDir()
+ stageImportZip(t, dir, map[string]string{
+ "manifest.json": `{"minecraft":{"version":"1.20.1","modLoaders":[{"id":"forge-47.2.0","primary":true}]},"name":"P","version":"1","files":[]}`,
+ })
+ e := builtinProvider(t, "import")
+ _, err := e.Provider.Install(context.Background(), dir, "import/local", nil)
+ if err == nil || !strings.Contains(err.Error(), "CurseForge API key") {
+ t.Fatalf("want CurseForge-key error, got %v", err)
+ }
+}
+
+// TestImportProviderUpdateUnsupported confirms the import provider yields
+// ErrUpdateUnsupported — imported packs can be exported but not updated (a local
+// file has no upstream to diff against), which is how the RPC answers
+// Unimplemented for them.
+func TestImportProviderUpdateUnsupported(t *testing.T) {
+ e := builtinProvider(t, "import")
+ up, ok := e.Provider.(provider.Updater)
+ if !ok {
+ t.Fatal("Lua providers expose Update; import should report it unsupported at runtime")
+ }
+ _, err := up.Update(context.Background(), t.TempDir(), "import/local", "import/local", nil)
+ if !errors.Is(err, provider.ErrUpdateUnsupported) {
+ t.Fatalf("import Update err = %v, want ErrUpdateUnsupported", err)
+ }
+}
diff --git a/engine/internal/scripting/modpack_mrpack_test.go b/engine/internal/scripting/modpack_mrpack_test.go
new file mode 100644
index 0000000..9e6e5ff
--- /dev/null
+++ b/engine/internal/scripting/modpack_mrpack_test.go
@@ -0,0 +1,122 @@
+package scripting
+
+import (
+ "net/http"
+ "path/filepath"
+ "testing"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+)
+
+func TestModrinthModpacksProviderHidden(t *testing.T) {
+ e := builtinProvider(t, "modrinth_modpacks")
+ if !e.Meta.Hidden {
+ t.Error("modrinth_modpacks provider should be hidden")
+ }
+ if e.Meta.ModLayout != "mods" {
+ t.Errorf("mod_layout = %q, want mods", e.Meta.ModLayout)
+ }
+}
+
+func TestModrinthModpacksShopIsModpackKind(t *testing.T) {
+ ss := newBuiltinShops(t, http.NotFoundHandler())
+ sh, ok := ss.Get("modrinth_modpacks")
+ if !ok {
+ t.Fatal("modrinth_modpacks shop not registered")
+ }
+ if sh.Meta().NeedsKey {
+ t.Error("modrinth_modpacks shop is keyless")
+ }
+ var isModpack bool
+ for _, k := range sh.Meta().Kinds {
+ if k == "modpack" {
+ isModpack = true
+ }
+ }
+ if !isModpack {
+ t.Errorf("kinds = %v, want to contain modpack", sh.Meta().Kinds)
+ }
+}
+
+// TestMrpackMeta covers parsing modrinth.index.json: loader detection, direct
+// download URLs, and env.server=="unsupported" files flagged client_only rather
+// than installed.
+func TestMrpackMeta(t *testing.T) {
+ dir := t.TempDir()
+ index := `{
+ "formatVersion": 1, "game": "minecraft", "versionId": "1.2.0", "name": "MR Pack",
+ "files": [
+ { "path": "mods/sodium.jar", "hashes": {"sha1":"s1","sha512":"x"},
+ "env": {"client":"required","server":"required"}, "downloads": ["http://cdn/sodium.jar"], "fileSize": 100 },
+ { "path": "mods/iris.jar", "hashes": {"sha1":"s2"},
+ "env": {"client":"required","server":"unsupported"}, "downloads": ["http://cdn/iris.jar"], "fileSize": 50 }
+ ],
+ "dependencies": { "minecraft": "1.20.1", "fabric-loader": "0.15.7" }
+ }`
+ writeTestJar(t, filepath.Join(dir, ".jhmc", "pack.mrpack"),
+ map[string]string{"modrinth.index.json": index})
+
+ inv := fsInv(dir)
+ src := `
+function check()
+ local m = mplib.mrpack_meta(".jhmc/pack.mrpack")
+ assert(m.mc == "1.20.1", "mc " .. tostring(m.mc))
+ assert(m.loader_name == "fabric" and m.loader_version == "0.15.7", "loader")
+ assert(m.name == "MR Pack" and m.version == "1.2.0", "name/version")
+ assert(#m.files == 2, "files " .. #m.files)
+ local by = {}
+ for _, f in ipairs(m.files) do by[f.dest] = f end
+ local s = by["mods/sodium.jar"]
+ assert(s and s.url == "http://cdn/sodium.jar" and s.sha1 == "s1", "sodium")
+ assert(not s.client_only, "sodium is a server file")
+ local i = by["mods/iris.jar"]
+ assert(i and i.client_only, "iris unsupported-on-server must be client_only")
+end`
+ if err := runInv(t, inv, src); err != nil {
+ t.Fatalf("script failed: %v", err)
+ }
+}
+
+func TestMrpackQuiltUnsupported(t *testing.T) {
+ dir := t.TempDir()
+ index := `{
+ "formatVersion": 1, "name": "Q", "versionId": "1",
+ "files": [], "dependencies": { "minecraft": "1.20.1", "quilt-loader": "0.20.0" }
+ }`
+ writeTestJar(t, filepath.Join(dir, ".jhmc", "pack.mrpack"),
+ map[string]string{"modrinth.index.json": index})
+ inv := fsInv(dir)
+ err := runInv(t, inv, `function check() mplib.mrpack_meta(".jhmc/pack.mrpack") end`)
+ if err == nil {
+ t.Fatal("expected Quilt to be rejected")
+ }
+}
+
+// fsInvNet is fsInv plus the network grant, for pack routines that download.
+func fsInvNet(dir string) *invocation {
+ inv := fsInv(dir)
+ inv.granted[mcmanagerv1.PermissionKind_PERMISSION_NETWORK] = true
+ return inv
+}
+
+// TestMrpackServerOverridesWin verifies overrides/ then server-overrides/ are
+// both extracted, with server-overrides winning on conflict.
+func TestMrpackServerOverridesWin(t *testing.T) {
+ dir := t.TempDir()
+ writeTestJar(t, filepath.Join(dir, ".jhmc", "pack.mrpack"), map[string]string{
+ "modrinth.index.json": `{"dependencies":{"minecraft":"1.20.1","fabric-loader":"0.15.7"}}`,
+ "overrides/config/a.toml": "client-value",
+ "server-overrides/config/a.toml": "server-value",
+ "overrides/config/only-client.txt": "c",
+ })
+ inv := fsInvNet(dir)
+ src := `
+function check()
+ mplib.unzip_overrides(".jhmc/pack.mrpack")
+ assert(jhmc.fs.read("config/a.toml") == "server-value", "server-overrides must win")
+ assert(jhmc.fs.exists("config/only-client.txt"), "plain override extracted")
+end`
+ if err := runInv(t, inv, src); err != nil {
+ t.Fatalf("script failed: %v", err)
+ }
+}
diff --git a/engine/internal/scripting/modpacklib_test.go b/engine/internal/scripting/modpacklib_test.go
new file mode 100644
index 0000000..64d73b6
--- /dev/null
+++ b/engine/internal/scripting/modpacklib_test.go
@@ -0,0 +1,188 @@
+package scripting
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ mcmanagerv1 "github.com/000hen/justhostmc/engine/gen/mcmanager/v1"
+)
+
+// fsInv returns an invocation rooted at dir with the fs_server grant, for
+// exercising mplib helpers that read and write the server directory.
+func fsInv(dir string) *invocation {
+ return &invocation{
+ ctx: context.Background(),
+ host: NewHost(nil, nil, nil),
+ baseDir: dir,
+ granted: GrantSet{mcmanagerv1.PermissionKind_PERMISSION_FS_SERVER: true},
+ }
+}
+
+func TestModpackLibGlobalAndJoinPath(t *testing.T) {
+ inv := &invocation{ctx: context.Background(), host: NewHost(nil, nil, nil)}
+ src := `
+function check()
+ assert(type(mplib) == "table", "mplib global missing")
+ assert(mplib.join_path("./mods/", "a.jar") == "mods/a.jar", "join")
+ assert(mplib.join_path("", "a.jar") == "a.jar", "join empty path")
+ assert(mplib.join_path("config\\sub", "b.toml") == "config/sub/b.toml", "join backslash")
+ local ok = pcall(function() mplib.join_path("../evil", "x") end)
+ assert(not ok, "traversal must be rejected")
+end`
+ if err := runInv(t, inv, src); err != nil {
+ t.Fatalf("script failed: %v", err)
+ }
+}
+
+// TestModpackManifestPersisted validates the exact on-disk shape of
+// .jhmc/modpack.json — the contract the Go export path reads back.
+func TestModpackManifestPersisted(t *testing.T) {
+ dir := t.TempDir()
+ inv := fsInv(dir)
+ src := `
+function check()
+ assert(mplib.read_manifest() == nil, "manifest absent before write")
+ mplib.write_manifest({
+ format = 1,
+ name = "All the Mods 9",
+ version_name = "0.2.60",
+ mc_version = "1.20.1",
+ loader = "forge",
+ loader_version = "47.2.20",
+ files = {
+ { dest = "mods/direct.jar", sha1 = "aa", url = "https://example/direct.jar" },
+ { dest = "mods/cf.jar", sha1 = "bb", project_id = 123, file_id = 456 },
+ { dest = "mods/client.jar", client_only = true, project_id = 1, file_id = 2 },
+ },
+ })
+ local back = mplib.read_manifest()
+ assert(back ~= nil and back.name == "All the Mods 9", "round-trip name")
+ assert(#back.files == 3, "round-trip file count")
+end`
+ if err := runInv(t, inv, src); err != nil {
+ t.Fatalf("script failed: %v", err)
+ }
+
+ // Assert the on-disk JSON matches the schema the Go export consumes.
+ raw, err := os.ReadFile(filepath.Join(dir, ".jhmc", "modpack.json"))
+ if err != nil {
+ t.Fatalf("read manifest: %v", err)
+ }
+ var m struct {
+ Format int `json:"format"`
+ Name string `json:"name"`
+ VersionName string `json:"version_name"`
+ MCVersion string `json:"mc_version"`
+ Loader string `json:"loader"`
+ LoaderVersion string `json:"loader_version"`
+ Files []struct {
+ Dest string `json:"dest"`
+ Sha1 string `json:"sha1"`
+ URL string `json:"url"`
+ ProjectID int64 `json:"project_id"`
+ FileID int64 `json:"file_id"`
+ ClientOnly bool `json:"client_only"`
+ } `json:"files"`
+ }
+ if err := json.Unmarshal(raw, &m); err != nil {
+ t.Fatalf("unmarshal manifest: %v", err)
+ }
+ if m.Format != 1 || m.MCVersion != "1.20.1" || m.Loader != "forge" || m.LoaderVersion != "47.2.20" {
+ t.Fatalf("manifest header wrong: %+v", m)
+ }
+ if len(m.Files) != 3 {
+ t.Fatalf("files = %d, want 3", len(m.Files))
+ }
+ byDest := map[string]int{}
+ for i, f := range m.Files {
+ byDest[f.Dest] = i
+ }
+ if f := m.Files[byDest["mods/direct.jar"]]; f.URL != "https://example/direct.jar" || f.Sha1 != "aa" {
+ t.Fatalf("direct file wrong: %+v", f)
+ }
+ if f := m.Files[byDest["mods/cf.jar"]]; f.ProjectID != 123 || f.FileID != 456 {
+ t.Fatalf("cf file wrong: %+v", f)
+ }
+ if f := m.Files[byDest["mods/client.jar"]]; !f.ClientOnly {
+ t.Fatalf("client file should be client_only: %+v", f)
+ }
+}
+
+func TestModpackToDownloadItem(t *testing.T) {
+ inv := &invocation{ctx: context.Background(), host: NewHost(nil, nil, nil)}
+ src := `
+function check()
+ local u = mplib.to_download_item({ dest = "mods/a.jar", sha1 = "abc", url = "http://x/a.jar" }, "")
+ assert(u.url == "http://x/a.jar" and u.dest == "mods/a.jar" and u.sha1 == "abc", "direct item")
+
+ local c = mplib.to_download_item({ dest = "mods/b.jar", sha1 = "d", project_id = 1, file_id = 2 }, "KEY")
+ assert(c.resolve.url:find("/mods/1/files/2/download%-url"), "cf resolve url: " .. c.resolve.url)
+ assert(c.resolve.headers["x-api-key"] == "KEY", "cf key header")
+
+ local ok, err = pcall(function()
+ mplib.to_download_item({ dest = "mods/c.jar", project_id = 1, file_id = 2 }, "")
+ end)
+ assert(not ok, "missing key must error")
+ assert(tostring(err):find("CurseForge API key"), "error should mention the key: " .. tostring(err))
+end`
+ if err := runInv(t, inv, src); err != nil {
+ t.Fatalf("script failed: %v", err)
+ }
+}
+
+// TestModpackDiffApplyDeletes covers diff_apply's delete path with no downloads:
+// files the new version dropped are removed, unchanged ones are kept.
+func TestModpackDiffApplyDeletes(t *testing.T) {
+ dir := t.TempDir()
+ inv := fsInv(dir)
+ src := `
+function check()
+ local ctx = { log = function() end, step = function() end }
+ jhmc.fs.write("mods/keep.jar", "K")
+ jhmc.fs.write("mods/drop.jar", "D")
+ local old = {
+ ["mods/keep.jar"] = { dest = "mods/keep.jar", sha1 = "1" },
+ ["mods/drop.jar"] = { dest = "mods/drop.jar", sha1 = "1" },
+ }
+ local new = { ["mods/keep.jar"] = { dest = "mods/keep.jar", sha1 = "1" } }
+ mplib.diff_apply(ctx, old, new, {
+ to_item = function() error("no downloads expected") end,
+ })
+ assert(jhmc.fs.exists("mods/keep.jar"), "kept file must remain")
+ assert(not jhmc.fs.exists("mods/drop.jar"), "dropped file must be deleted")
+end`
+ if err := runInv(t, inv, src); err != nil {
+ t.Fatalf("script failed: %v", err)
+ }
+}
+
+func TestUnzipPrefix(t *testing.T) {
+ dir := t.TempDir()
+ writeTestJar(t, filepath.Join(dir, "pack.zip"), map[string]string{
+ "manifest.json": `{"name":"x"}`,
+ "overrides/config/a.toml": "A",
+ "overrides/mods/m.jar": "M",
+ })
+ inv := fsInv(dir)
+ src := `
+function check()
+ -- Plain unzip extracts everything verbatim.
+ jhmc.unzip("pack.zip", "full")
+ assert(jhmc.fs.exists("full/manifest.json"), "full manifest")
+ assert(jhmc.fs.exists("full/overrides/config/a.toml"), "full override")
+
+ -- Prefixed unzip extracts only overrides/, stripping the prefix.
+ jhmc.unzip("pack.zip", "srv", { prefix = "overrides/" })
+ assert(jhmc.fs.exists("srv/config/a.toml"), "stripped config")
+ assert(jhmc.fs.read("srv/config/a.toml") == "A", "stripped content")
+ assert(jhmc.fs.exists("srv/mods/m.jar"), "stripped mod")
+ assert(not jhmc.fs.exists("srv/manifest.json"), "manifest excluded by prefix")
+ assert(not jhmc.fs.exists("srv/overrides/config/a.toml"), "prefix not stripped")
+end`
+ if err := runInv(t, inv, src); err != nil {
+ t.Fatalf("script failed: %v", err)
+ }
+}
diff --git a/engine/internal/scripting/parser.go b/engine/internal/scripting/parser.go
index 7635be3..d09a05f 100644
--- a/engine/internal/scripting/parser.go
+++ b/engine/internal/scripting/parser.go
@@ -38,6 +38,7 @@ type LuaParser struct {
host *Host
builtin bool
grantsFn func() GrantSet
+ configFn func() map[string]string
}
// newLuaParser compiles source in a throwaway sandbox, validates its meta and
@@ -72,11 +73,25 @@ func (p *LuaParser) grants() GrantSet {
return nil
}
+// config resolves the values the script sees as ctx.config / jhmc.config:
+// declared defaults merged with stored overrides. Returns nil (no config) when
+// the script declares none and none is stored.
+func (p *LuaParser) config() map[string]string {
+ var stored map[string]string
+ if p.configFn != nil {
+ stored = p.configFn()
+ }
+ if len(p.meta.Config) == 0 && len(stored) == 0 {
+ return nil
+ }
+ return EffectiveConfig(p.meta.Config, stored)
+}
+
// Parse runs the script's parse(ctx) against one jar (path relative to
// serverDir). matched=false means the parser did not recognize the jar
// (returned nil); an error means the parser recognized-and-failed or is broken.
func (p *LuaParser) Parse(ctx context.Context, serverDir, jarRel string) (meta ModMeta, matched bool, err error) {
- inv := &invocation{ctx: ctx, host: p.host, granted: p.grants(), baseDir: serverDir}
+ inv := &invocation{ctx: ctx, host: p.host, granted: p.grants(), baseDir: serverDir, config: p.config()}
return inv.parseMod(p.source, jarRel)
}
@@ -95,6 +110,7 @@ func (inv *invocation) parseMod(src, jarRel string) (ModMeta, bool, error) {
}
ctxTbl := L.NewTable()
ctxTbl.RawSetString("jar", lua.LString(jarRel))
+ ctxTbl.RawSetString("config", inv.configTable(L))
if err := L.CallByParam(lua.P{Fn: fn, NRet: 1, Protect: true}, ctxTbl); err != nil {
return ModMeta{}, false, inv.mapErr(err)
}
diff --git a/engine/internal/scripting/parserregistry.go b/engine/internal/scripting/parserregistry.go
index b9aef11..e88c820 100644
--- a/engine/internal/scripting/parserregistry.go
+++ b/engine/internal/scripting/parserregistry.go
@@ -13,6 +13,7 @@ import (
type ParserSet struct {
host *Host
grants Grants
+ config *ConfigStore
mu sync.RWMutex
order []string
@@ -25,6 +26,16 @@ func NewParserSet(host *Host, grants Grants) *ParserSet {
return &ParserSet{host: host, grants: grants, byID: map[string]*LuaParser{}}
}
+// SetConfigStore wires the typed-config store the set hands to its parser scripts.
+func (ps *ParserSet) SetConfigStore(cs *ConfigStore) { ps.config = cs }
+
+func (ps *ParserSet) configValues(id string) map[string]string {
+ if ps.config == nil {
+ return nil
+ }
+ return ps.config.Values(id)
+}
+
// AddSource compiles a parser script and registers it. A user parser (builtin
// false) may not take over a built-in's id.
func (ps *ParserSet) AddSource(ctx context.Context, source string, builtin bool) (*LuaParser, error) {
@@ -41,6 +52,7 @@ func (ps *ParserSet) AddSource(ctx context.Context, source string, builtin bool)
ps.order = append(ps.order, p.meta.ID)
}
p.grantsFn = func() GrantSet { return ps.EffectiveGrants(p.meta.ID) }
+ p.configFn = func() map[string]string { return ps.configValues(p.meta.ID) }
ps.byID[p.meta.ID] = p
return p, nil
}
diff --git a/engine/internal/scripting/registry.go b/engine/internal/scripting/registry.go
index e310b64..f448cf3 100644
--- a/engine/internal/scripting/registry.go
+++ b/engine/internal/scripting/registry.go
@@ -26,28 +26,59 @@ type Entry struct {
Builtin bool
}
+// ConfigReader is the read side of the typed-config store the registry injects
+// into provider scripts. *ConfigStore implements it directly; wrap it with
+// NewFallbackConfigReader to layer a lazily-computed default onto one key.
+type ConfigReader interface {
+ // Values returns the stored config overrides for a script id (a possibly
+ // empty, freely-mutable map).
+ Values(id string) map[string]string
+}
+
// Registry holds the installed providers keyed by id, in insertion order, and
// resolves each provider's effective grants (persisted grant, or — for trusted
// built-ins — all declared permissions by default).
type Registry struct {
- mu sync.RWMutex
- host *Host
- grants Grants
- order []string
- byID map[string]*Entry
+ mu sync.RWMutex
+ host *Host
+ grants Grants
+ config ConfigReader
+ order []string
+ byID map[string]*Entry
+ aliases map[string]string // old id -> canonical id (Meta.Aliases)
}
// NewRegistry builds an empty registry. host runs the scripts; grants (optional)
// supplies persisted user permission decisions.
func NewRegistry(host *Host, grants Grants) *Registry {
- return &Registry{host: host, grants: grants, byID: map[string]*Entry{}}
+ return &Registry{host: host, grants: grants, byID: map[string]*Entry{}, aliases: map[string]string{}}
+}
+
+// SetConfigStore wires the typed-config reader the registry hands to its
+// scripts. A plain *ConfigStore is the common case; a wrapper may layer defaults.
+func (r *Registry) SetConfigStore(cs ConfigReader) { r.config = cs }
+
+// configValues returns the stored config overrides for id (nil when no store).
+func (r *Registry) configValues(id string) map[string]string {
+ if r.config == nil {
+ return nil
+ }
+ return r.config.Values(id)
}
// AddSource compiles a Lua provider script (with no bundled assets) and
// registers it. builtin marks first-party scripts, whose declared permissions
// are granted by default.
func (r *Registry) AddSource(ctx context.Context, source string, builtin bool) (*Entry, error) {
- return r.add(ctx, source, builtin, "")
+ return r.addWithConfig(ctx, source, builtin, "", nil)
+}
+
+// AddSourceWithConfig registers a provider script whose typed config is read
+// from cfg instead of the registry's own store. It is used for a merged source
+// script's hidden provider role, whose config lives in the shared shop store so
+// both roles read and write one entry.
+func (r *Registry) AddSourceWithConfig(ctx context.Context, source string, builtin bool, cfg ConfigReader) (*Entry, error) {
+ return r.addWithConfig(ctx, source, builtin, "", cfg)
}
// AddProviderDir registers the provider whose script is dir/provider.lua, with
@@ -57,46 +88,79 @@ func (r *Registry) AddProviderDir(ctx context.Context, dir string, builtin bool)
if err != nil {
return nil, err
}
- return r.add(ctx, string(src), builtin, dir)
+ return r.addWithConfig(ctx, string(src), builtin, dir, nil)
}
-func (r *Registry) add(ctx context.Context, source string, builtin bool, assetDir string) (*Entry, error) {
+func (r *Registry) addWithConfig(ctx context.Context, source string, builtin bool, assetDir string, cfg ConfigReader) (*Entry, error) {
lp, err := newLuaProvider(ctx, r.host, source, builtin, assetDir)
if err != nil {
return nil, err
}
id := lp.meta.ID
- // A user (non-builtin) script must never replace a trusted built-in provider.
- if !builtin {
- if existing, ok := r.Get(id); ok && existing.Builtin {
- return nil, fmt.Errorf("%w: %q", ErrProviderIDConflict, id)
- }
- }
lp.grantsFn = func() GrantSet { return r.effectiveGrants(id, builtin, lp.meta) }
+ if cfg != nil {
+ lp.configFn = func() map[string]string { return cfg.Values(id) }
+ } else {
+ lp.configFn = func() map[string]string { return r.configValues(id) }
+ }
e := &Entry{Meta: lp.meta, Provider: lp, Builtin: builtin}
- r.put(id, e)
+ if err := r.put(id, e); err != nil {
+ return nil, err
+ }
return e, nil
}
// AddEntry registers a pre-built entry (used by tests and non-Lua providers).
-func (r *Registry) AddEntry(e *Entry) { r.put(e.Meta.ID, e) }
+func (r *Registry) AddEntry(e *Entry) error { return r.put(e.Meta.ID, e) }
-func (r *Registry) put(id string, e *Entry) {
+func (r *Registry) put(id string, e *Entry) error {
r.mu.Lock()
defer r.mu.Unlock()
- if _, ok := r.byID[id]; !ok {
+ if owner, ok := r.aliases[id]; ok {
+ return fmt.Errorf("%w: canonical id %q is already an alias for %q", ErrProviderIDConflict, id, owner)
+ }
+ existing, exists := r.byID[id]
+ if exists && existing.Builtin && !e.Builtin {
+ return fmt.Errorf("%w: %q", ErrProviderIDConflict, id)
+ }
+ for _, alias := range e.Meta.Aliases {
+ if _, ok := r.byID[alias]; ok {
+ return fmt.Errorf("%w: alias %q is already a canonical id", ErrProviderIDConflict, alias)
+ }
+ if owner, ok := r.aliases[alias]; ok && owner != id {
+ return fmt.Errorf("%w: alias %q is already assigned to %q", ErrProviderIDConflict, alias, owner)
+ }
+ }
+
+ if !exists {
r.order = append(r.order, id)
+ } else {
+ for _, alias := range existing.Meta.Aliases {
+ if r.aliases[alias] == id {
+ delete(r.aliases, alias)
+ }
+ }
}
r.byID[id] = e
+ for _, a := range e.Meta.Aliases {
+ r.aliases[a] = id
+ }
+ return nil
}
// Remove deletes a provider by id.
func (r *Registry) Remove(id string) {
r.mu.Lock()
defer r.mu.Unlock()
- if _, ok := r.byID[id]; !ok {
+ e, ok := r.byID[id]
+ if !ok {
return
}
+ for _, a := range e.Meta.Aliases {
+ if r.aliases[a] == id {
+ delete(r.aliases, a)
+ }
+ }
delete(r.byID, id)
for i, x := range r.order {
if x == id {
@@ -106,12 +170,18 @@ func (r *Registry) Remove(id string) {
}
}
-// Get returns the entry for an id.
+// Get returns the entry for an id, resolving an alias to its canonical entry.
func (r *Registry) Get(id string) (*Entry, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
- e, ok := r.byID[id]
- return e, ok
+ if e, ok := r.byID[id]; ok {
+ return e, true
+ }
+ if canonical, ok := r.aliases[id]; ok {
+ e, ok := r.byID[canonical]
+ return e, ok
+ }
+ return nil, false
}
// Provider returns just the installer for an id (convenience for the gRPC layer).
diff --git a/engine/internal/scripting/roletable_test.go b/engine/internal/scripting/roletable_test.go
new file mode 100644
index 0000000..1afb1dc
--- /dev/null
+++ b/engine/internal/scripting/roletable_test.go
@@ -0,0 +1,346 @@
+package scripting
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "testing"
+)
+
+// dualRoleSource is a minimal multi-role script: a shop role (mod+modpack) and a
+// hidden provider role, sharing one meta.id and one config option, and answering
+// to the alias "acme_modpacks".
+const dualRoleSource = `
+meta = {
+ id = "acme",
+ name = "Acme",
+ version = "1.0.0",
+ author = "t",
+ aliases = { "acme_modpacks" },
+ config = { { key = "api_key", type = "secret", name = "Key" } },
+ permissions = { { kind = "network", reason = "r" } },
+}
+shop = {
+ kinds = { "mod", "modpack" },
+ needs_key = true,
+ home = function(ctx) return { sections = {} } end,
+ search = function(ctx) return { projects = {}, total = 0 } end,
+ detail = function(ctx) return { project = {}, body = "", body_format = "markdown" } end,
+ versions = function(ctx) return { versions = {} } end,
+ resolve_file = function(ctx) return { url = "http://x", filename = "x" } end,
+}
+provider = {
+ hidden = true,
+ mod_layout = "mods",
+ versions = function() return {} end,
+ install = function(ctx) return { java_major = 17, args = { ctx.config.api_key or "" } } end,
+}
+`
+
+// loadDualRole registers dualRoleSource into a fresh registry + shop set backed
+// by a shared config store, returning all three.
+func loadDualRole(t *testing.T, cfg *ConfigStore) (*Registry, *ShopSet) {
+ t.Helper()
+ host := NewHost(nil, nil, nil)
+ reg := NewRegistry(host, nil)
+ reg.SetConfigStore(cfg)
+ ss := NewShopSet(host, nil, nil)
+ ss.SetConfigStore(cfg)
+ if _, err := ss.AddSource(context.Background(), dualRoleSource, true); err != nil {
+ t.Fatalf("shop AddSource: %v", err)
+ }
+ if _, err := reg.AddSourceWithConfig(context.Background(), dualRoleSource, true, cfg); err != nil {
+ t.Fatalf("provider AddSourceWithConfig: %v", err)
+ }
+ return reg, ss
+}
+
+// TestRoleTableRegistersBothRoles proves a single source registers into both
+// subsystems with role-scoped meta applied.
+func TestRoleTableRegistersBothRoles(t *testing.T) {
+ reg, ss := loadDualRole(t, NewConfigStore(filepath.Join(t.TempDir(), "c.json")))
+
+ sh, ok := ss.Get("acme")
+ if !ok {
+ t.Fatal("shop role not registered")
+ }
+ if !sh.Meta().NeedsKey {
+ t.Error("shop role should read needs_key from the shop table")
+ }
+ if len(sh.Meta().Kinds) != 2 {
+ t.Errorf("shop kinds = %v, want mod+modpack", sh.Meta().Kinds)
+ }
+
+ e, ok := reg.Get("acme")
+ if !ok {
+ t.Fatal("provider role not registered")
+ }
+ if !e.Meta.Hidden {
+ t.Error("provider role should read hidden from the provider table")
+ }
+ if e.Meta.ModLayout != "mods" {
+ t.Errorf("provider mod_layout = %q, want mods", e.Meta.ModLayout)
+ }
+}
+
+// TestRoleTableAliasResolves proves an old id resolves to the canonical entry in
+// both subsystems and is never listed as a separate entry.
+func TestRoleTableAliasResolves(t *testing.T) {
+ reg, ss := loadDualRole(t, NewConfigStore(filepath.Join(t.TempDir(), "c.json")))
+
+ sh, ok := ss.Get("acme_modpacks")
+ if !ok || sh.Meta().ID != "acme" {
+ t.Fatalf("shop alias did not resolve to acme: ok=%v", ok)
+ }
+ e, ok := reg.Get("acme_modpacks")
+ if !ok || e.Meta.ID != "acme" {
+ t.Fatalf("provider alias did not resolve to acme: ok=%v", ok)
+ }
+
+ if got := len(reg.List()); got != 1 {
+ t.Errorf("registry List has %d entries, want 1 (no alias dupe)", got)
+ }
+ if got := len(ss.List()); got != 1 {
+ t.Errorf("shop List has %d entries, want 1 (no alias dupe)", got)
+ }
+}
+
+func TestRegistryRejectsCanonicalAliasCollisionsWithoutChangingResolution(t *testing.T) {
+ host := NewHost(nil, nil, nil)
+ reg := NewRegistry(host, nil)
+ if _, err := reg.AddSource(context.Background(), dualRoleSource, true); err != nil {
+ t.Fatalf("register built-in: %v", err)
+ }
+
+ tests := []struct {
+ name string
+ id string
+ aliases string
+ }{
+ {name: "canonical claims existing alias", id: "acme_modpacks"},
+ {name: "alias claims existing canonical", id: "other", aliases: `aliases = { "acme" },`},
+ {name: "alias claims existing alias", id: "other", aliases: `aliases = { "acme_modpacks" },`},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ source := fmt.Sprintf(`
+meta = { id = %q, name = "Other", version = "1", author = "t", %s }
+function versions() return {} end
+function install(ctx) return { java_major = 17, args = {} } end
+`, tt.id, tt.aliases)
+ if _, err := reg.AddSource(context.Background(), source, false); !errors.Is(err, ErrProviderIDConflict) {
+ t.Fatalf("AddSource error = %v, want ErrProviderIDConflict", err)
+ }
+ assertRegistryAliasResolution(t, reg)
+ })
+ }
+}
+
+func TestShopSetRejectsCanonicalAliasCollisionsWithoutChangingResolution(t *testing.T) {
+ host := NewHost(nil, nil, nil)
+ shops := NewShopSet(host, nil, nil)
+ if _, err := shops.AddSource(context.Background(), dualRoleSource, true); err != nil {
+ t.Fatalf("register built-in: %v", err)
+ }
+
+ tests := []struct {
+ name string
+ id string
+ aliases string
+ }{
+ {name: "canonical claims existing alias", id: "acme_modpacks"},
+ {name: "alias claims existing canonical", id: "other", aliases: `aliases = { "acme" },`},
+ {name: "alias claims existing alias", id: "other", aliases: `aliases = { "acme_modpacks" },`},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ source := fmt.Sprintf(`
+meta = { id = %q, name = "Other", version = "1", author = "t", %s }
+function home(ctx) return { sections = {} } end
+function search(ctx) return { projects = {}, total = 0 } end
+function detail(ctx) return { project = {}, body = "", body_format = "markdown" } end
+function versions(ctx) return { versions = {} } end
+function resolve_file(ctx) return { url = "http://x", filename = "x" } end
+`, tt.id, tt.aliases)
+ if _, err := shops.AddSource(context.Background(), source, false); !errors.Is(err, ErrProviderIDConflict) {
+ t.Fatalf("AddSource error = %v, want ErrProviderIDConflict", err)
+ }
+ assertShopAliasResolution(t, shops)
+ })
+ }
+}
+
+func assertRegistryAliasResolution(t *testing.T, reg *Registry) {
+ t.Helper()
+ for _, id := range []string{"acme", "acme_modpacks"} {
+ e, ok := reg.Get(id)
+ if !ok || e.Meta.ID != "acme" {
+ t.Fatalf("provider %q resolution changed: ok=%v entry=%v", id, ok, e)
+ }
+ }
+ if got := len(reg.List()); got != 1 {
+ t.Fatalf("registry contains %d entries after rejected collision, want 1", got)
+ }
+}
+
+func assertShopAliasResolution(t *testing.T, shops *ShopSet) {
+ t.Helper()
+ for _, id := range []string{"acme", "acme_modpacks"} {
+ shop, ok := shops.Get(id)
+ if !ok || shop.Meta().ID != "acme" {
+ t.Fatalf("shop %q resolution changed: ok=%v shop=%v", id, ok, shop)
+ }
+ }
+ if got := len(shops.List()); got != 1 {
+ t.Fatalf("shop set contains %d entries after rejected collision, want 1", got)
+ }
+}
+
+// TestRoleTableSharedConfig proves both roles read one stored config entry keyed
+// by the canonical id.
+func TestRoleTableSharedConfig(t *testing.T) {
+ cfg := NewConfigStore(filepath.Join(t.TempDir(), "c.json"))
+ reg, ss := loadDualRole(t, cfg)
+ if err := cfg.Set("acme", "api_key", "shared-secret"); err != nil {
+ t.Fatal(err)
+ }
+
+ sh, _ := ss.Get("acme")
+ if got := sh.effectiveKey(); got != "shared-secret" {
+ t.Errorf("shop effectiveKey = %q, want shared-secret", got)
+ }
+
+ e, _ := reg.Get("acme")
+ spec, err := e.Provider.Install(context.Background(), t.TempDir(), "1/2", nil)
+ if err != nil {
+ t.Fatalf("install: %v", err)
+ }
+ if len(spec.Args) != 1 || spec.Args[0] != "shared-secret" {
+ t.Errorf("provider ctx.config.api_key = %v, want [shared-secret]", spec.Args)
+ }
+}
+
+// TestLegacySingleRoleStillLoads proves a legacy top-level-function script (no
+// role tables) still registers and reads meta-level fields.
+func TestLegacySingleRoleStillLoads(t *testing.T) {
+ const legacy = `
+meta = { id = "legacy", name = "L", version = "1", author = "t", hidden = true, mod_layout = "plugins",
+ permissions = { { kind = "network", reason = "r" } } }
+function versions() return {} end
+function install(ctx) return { java_major = 17, args = {} } end
+`
+ reg := NewRegistry(NewHost(nil, nil, nil), nil)
+ e, err := reg.AddSource(context.Background(), legacy, true)
+ if err != nil {
+ t.Fatalf("AddSource: %v", err)
+ }
+ if !e.Meta.Hidden || e.Meta.ModLayout != "plugins" {
+ t.Errorf("legacy meta-level fields lost: hidden=%v layout=%q", e.Meta.Hidden, e.Meta.ModLayout)
+ }
+ if _, err := e.Provider.Install(context.Background(), t.TempDir(), "v", nil); err != nil {
+ t.Fatalf("legacy install: %v", err)
+ }
+}
+
+// TestSourceRolesDetectsTables checks role detection for the merged sources.
+func TestSourceRolesDetectsTables(t *testing.T) {
+ host := NewHost(nil, nil, nil)
+ shop, provider, err := sourceRoles(context.Background(), host, dualRoleSource)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !shop || !provider {
+ t.Fatalf("dual role detection: shop=%v provider=%v", shop, provider)
+ }
+}
+
+func TestLoadBuiltinSourcesReturnsOnlyActualMultiRoleSourceIDs(t *testing.T) {
+ host := NewHost(nil, nil, nil)
+ reg := NewRegistry(host, nil)
+ shops := NewShopSet(host, nil, nil)
+
+ ids, err := LoadBuiltinSources(context.Background(), reg, shops, nil)
+ if err != nil {
+ t.Fatalf("LoadBuiltinSources: %v", err)
+ }
+ for _, id := range []string{"curseforge", "ftb", "modrinth"} {
+ if !ids.Contains(id) {
+ t.Errorf("multi-role source ids do not contain %q", id)
+ }
+ }
+ if ids.Contains("curseforge_modpacks") {
+ t.Error("alias curseforge_modpacks must not be tracked as a canonical multi-role source id")
+ }
+ const claimedBuiltinAlias = `
+meta = { id = "curseforge_modpacks", name = "Claim", version = "1", author = "t" }
+function home(ctx) return { sections = {} } end
+function search(ctx) return { projects = {}, total = 0 } end
+function detail(ctx) return { project = {}, body = "", body_format = "markdown" } end
+function versions(ctx) return {} end
+function resolve_file(ctx) return { url = "http://x", filename = "x" } end
+function install(ctx) return { java_major = 17, args = {} } end
+`
+ if _, err := reg.AddSource(context.Background(), claimedBuiltinAlias, false); !errors.Is(err, ErrProviderIDConflict) {
+ t.Fatalf("provider claiming built-in alias error = %v, want ErrProviderIDConflict", err)
+ }
+ if _, err := shops.AddSource(context.Background(), claimedBuiltinAlias, false); !errors.Is(err, ErrProviderIDConflict) {
+ t.Fatalf("shop claiming built-in alias error = %v, want ErrProviderIDConflict", err)
+ }
+ if entry, ok := reg.Get("curseforge_modpacks"); !ok || entry.Meta.ID != "curseforge" {
+ t.Fatalf("provider built-in alias resolution changed after rejection: ok=%v entry=%v", ok, entry)
+ }
+ if shop, ok := shops.Get("curseforge_modpacks"); !ok || shop.Meta().ID != "curseforge" {
+ t.Fatalf("shop built-in alias resolution changed after rejection: ok=%v shop=%v", ok, shop)
+ }
+
+ // Matching ids in the two registries are not enough: only one script that
+ // actually declared both roles is eligible for shared config routing.
+ const unrelatedCollision = `
+meta = { id = "coincidental", name = "Coincidental", version = "1", author = "t" }
+function home(ctx) return { sections = {} } end
+function search(ctx) return { projects = {}, total = 0 } end
+function detail(ctx) return { project = {}, body = "", body_format = "markdown" } end
+function versions(ctx) return {} end
+function resolve_file(ctx) return { url = "http://x", filename = "x" } end
+function install(ctx) return { java_major = 17, args = {} } end
+`
+ if _, err := reg.AddSource(context.Background(), unrelatedCollision, false); err != nil {
+ t.Fatalf("register unrelated provider: %v", err)
+ }
+ if _, err := shops.AddSource(context.Background(), unrelatedCollision, false); err != nil {
+ t.Fatalf("register unrelated shop: %v", err)
+ }
+ if _, ok := reg.Get("coincidental"); !ok {
+ t.Fatal("unrelated provider was not registered")
+ }
+ if _, ok := shops.Get("coincidental"); !ok {
+ t.Fatal("unrelated shop was not registered")
+ }
+ if ids.Contains("coincidental") {
+ t.Error("unrelated provider/shop id collision must not be treated as a shared-config source")
+ }
+}
+
+// TestParseMetaAliases covers alias validation.
+func TestParseMetaAliases(t *testing.T) {
+ m, err := metaFrom(t, `meta = { id = "x", aliases = { "x_old", "x_older" } }`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(m.Aliases) != 2 || m.Aliases[0] != "x_old" {
+ t.Fatalf("aliases = %v", m.Aliases)
+ }
+
+ bad := map[string]string{
+ "dup with id": `meta = { id = "x", aliases = { "x" } }`,
+ "dup alias": `meta = { id = "x", aliases = { "y", "y" } }`,
+ "invalid char": `meta = { id = "x", aliases = { "a.b" } }`,
+ "non-string": `meta = { id = "x", aliases = { 5 } }`,
+ }
+ for name, src := range bad {
+ if _, err := metaFrom(t, src); err == nil {
+ t.Errorf("%s: expected an error", name)
+ }
+ }
+}
diff --git a/engine/internal/scripting/shop.go b/engine/internal/scripting/shop.go
index b810f55..14f581d 100644
--- a/engine/internal/scripting/shop.go
+++ b/engine/internal/scripting/shop.go
@@ -156,6 +156,7 @@ type LuaShop struct {
builtin bool
grantsFn func() GrantSet
keyFn func() string // resolves the shop's API key ("" = none)
+ configFn func() map[string]string
}
// newLuaShop compiles source in a throwaway sandbox and validates its meta
@@ -167,18 +168,29 @@ func newLuaShop(ctx context.Context, host *Host, source string, builtin bool) (*
return nil, err
}
defer L.Close()
- meta, err := parseMeta(L)
+ meta, err := parseShopMeta(L)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrScriptInvalid, err)
}
for _, fn := range shopFuncs {
- if L.GetGlobal(fn).Type() != lua.LTFunction {
+ if shopFn(L, fn).Type() != lua.LTFunction {
return nil, fmt.Errorf("%w: script does not define %s(ctx)", ErrScriptInvalid, fn)
}
}
return &LuaShop{meta: meta, source: source, host: host, builtin: builtin}, nil
}
+// shopFn resolves a shop entry point, preferring a function in the global `shop`
+// role table and falling back to a top-level global (the legacy layout).
+func shopFn(L *lua.LState, name string) lua.LValue {
+ if tbl := roleTable(L, "shop"); tbl != nil {
+ if f := tbl.RawGetString(name); f.Type() == lua.LTFunction {
+ return f
+ }
+ }
+ return L.GetGlobal(name)
+}
+
// Meta returns the shop's declared metadata.
func (s *LuaShop) Meta() Meta { return s.meta }
@@ -194,8 +206,26 @@ func (s *LuaShop) Key() string {
}
// Ready reports whether the shop can serve requests (a key exists when the
-// script declares needs_key).
-func (s *LuaShop) Ready() bool { return !s.meta.NeedsKey || s.Key() != "" }
+// script declares needs_key). The key may come from the settings/baked chain or
+// a stored api_key config override.
+func (s *LuaShop) Ready() bool { return !s.meta.NeedsKey || s.effectiveKey() != "" }
+
+// storedConfig returns the shop's stored typed-config overrides (nil when none).
+func (s *LuaShop) storedConfig() map[string]string {
+ if s.configFn != nil {
+ return s.configFn()
+ }
+ return nil
+}
+
+// effectiveKey resolves the shop's API key: a stored `api_key` config override
+// wins, and the keyFn (baked build default) only fills in when config is empty.
+func (s *LuaShop) effectiveKey() string {
+ if k := s.storedConfig()["api_key"]; k != "" {
+ return k
+ }
+ return s.Key()
+}
func (s *LuaShop) grants() GrantSet {
if s.grantsFn != nil {
@@ -226,7 +256,7 @@ func (s *LuaShop) callFunction(ctx context.Context, fn string, optional bool, fi
}
defer L.Close()
- f := L.GetGlobal(fn)
+ f := shopFn(L, fn)
if f.Type() != lua.LTFunction {
if optional {
return nil, false, nil
@@ -247,7 +277,16 @@ func (s *LuaShop) callFunction(ctx context.Context, fn string, optional bool, fi
}
}
cfg := L.NewTable()
- cfg.RawSetString("api_key", lua.LString(s.Key()))
+ for k, v := range EffectiveConfig(s.meta.Config, s.storedConfig()) {
+ cfg.RawSetString(k, lua.LString(v))
+ }
+ // A stored api_key config wins for the reserved api_key; the keyFn (baked
+ // build default) only fills in when no stored value is present.
+ if _, ok := s.storedConfig()["api_key"]; !ok {
+ if key := s.Key(); key != "" {
+ cfg.RawSetString("api_key", lua.LString(key))
+ }
+ }
ctxTbl.RawSetString("config", cfg)
if err := L.CallByParam(lua.P{Fn: f, NRet: 1, Protect: true}, ctxTbl); err != nil {
diff --git a/engine/internal/scripting/shopbuiltin.go b/engine/internal/scripting/shopbuiltin.go
deleted file mode 100644
index dd1f4d9..0000000
--- a/engine/internal/scripting/shopbuiltin.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package scripting
-
-import (
- "context"
- "embed"
- "fmt"
- "strings"
-)
-
-// Built-in shop scripts are embedded in the binary (separate dir from the
-// provider/parser builtins so no loader picks up another's scripts).
-//
-//go:embed builtin_shops/*.lua
-var builtinShopsFS embed.FS
-
-// LoadBuiltinShops registers every embedded shop script as builtin.
-func LoadBuiltinShops(ctx context.Context, ss *ShopSet) error {
- entries, err := builtinShopsFS.ReadDir("builtin_shops")
- if err != nil {
- return err
- }
- for _, e := range entries {
- if !strings.HasSuffix(e.Name(), ".lua") {
- continue
- }
- src, err := builtinShopsFS.ReadFile("builtin_shops/" + e.Name())
- if err != nil {
- return fmt.Errorf("builtin shop %s: %w", e.Name(), err)
- }
- if _, err := ss.AddSource(ctx, string(src), true); err != nil {
- return fmt.Errorf("builtin shop %s: %w", e.Name(), err)
- }
- }
- return nil
-}
diff --git a/engine/internal/scripting/shopregistry.go b/engine/internal/scripting/shopregistry.go
index c7b393e..fdd3361 100644
--- a/engine/internal/scripting/shopregistry.go
+++ b/engine/internal/scripting/shopregistry.go
@@ -16,15 +16,28 @@ type ShopSet struct {
// service layer to settings + baked-in defaults.
keyFn func(shopID string) string
- mu sync.RWMutex
- order []string
- byID map[string]*LuaShop
+ config *ConfigStore
+
+ mu sync.RWMutex
+ order []string
+ byID map[string]*LuaShop
+ aliases map[string]string // old id -> canonical id (Meta.Aliases)
}
// NewShopSet builds an empty set. grants supplies persisted user permission
// decisions; keyFn may be nil (no shop keys available).
func NewShopSet(host *Host, grants Grants, keyFn func(shopID string) string) *ShopSet {
- return &ShopSet{host: host, grants: grants, keyFn: keyFn, byID: map[string]*LuaShop{}}
+ return &ShopSet{host: host, grants: grants, keyFn: keyFn, byID: map[string]*LuaShop{}, aliases: map[string]string{}}
+}
+
+// SetConfigStore wires the typed-config store the set hands to its shop scripts.
+func (ss *ShopSet) SetConfigStore(cs *ConfigStore) { ss.config = cs }
+
+func (ss *ShopSet) configValues(id string) map[string]string {
+ if ss.config == nil {
+ return nil
+ }
+ return ss.config.Values(id)
}
// AddSource compiles a shop script and registers it. A user shop (builtin
@@ -36,11 +49,31 @@ func (ss *ShopSet) AddSource(ctx context.Context, source string, builtin bool) (
}
ss.mu.Lock()
defer ss.mu.Unlock()
- if existing, ok := ss.byID[s.meta.ID]; ok && existing.builtin && !builtin {
+ id := s.meta.ID
+ if owner, ok := ss.aliases[id]; ok {
+ return nil, fmt.Errorf("%w: canonical id %q is already an alias for %q", ErrProviderIDConflict, id, owner)
+ }
+ existing, exists := ss.byID[id]
+ if exists && existing.builtin && !builtin {
return nil, fmt.Errorf("%w: %s", ErrProviderIDConflict, s.meta.ID)
}
- if _, ok := ss.byID[s.meta.ID]; !ok {
- ss.order = append(ss.order, s.meta.ID)
+ for _, alias := range s.meta.Aliases {
+ if _, ok := ss.byID[alias]; ok {
+ return nil, fmt.Errorf("%w: alias %q is already a canonical id", ErrProviderIDConflict, alias)
+ }
+ if owner, ok := ss.aliases[alias]; ok && owner != id {
+ return nil, fmt.Errorf("%w: alias %q is already assigned to %q", ErrProviderIDConflict, alias, owner)
+ }
+ }
+
+ if !exists {
+ ss.order = append(ss.order, id)
+ } else {
+ for _, alias := range existing.meta.Aliases {
+ if ss.aliases[alias] == id {
+ delete(ss.aliases, alias)
+ }
+ }
}
s.grantsFn = func() GrantSet { return ss.EffectiveGrants(s.meta.ID) }
s.keyFn = func() string {
@@ -49,25 +82,42 @@ func (ss *ShopSet) AddSource(ctx context.Context, source string, builtin bool) (
}
return ss.keyFn(s.meta.ID)
}
- ss.byID[s.meta.ID] = s
+ s.configFn = func() map[string]string { return ss.configValues(s.meta.ID) }
+ ss.byID[id] = s
+ for _, a := range s.meta.Aliases {
+ ss.aliases[a] = id
+ }
return s, nil
}
-// Get returns the shop registered under id.
+// Get returns the shop registered under id, resolving an alias to its canonical
+// shop.
func (ss *ShopSet) Get(id string) (*LuaShop, bool) {
ss.mu.RLock()
defer ss.mu.RUnlock()
- s, ok := ss.byID[id]
- return s, ok
+ if s, ok := ss.byID[id]; ok {
+ return s, true
+ }
+ if canonical, ok := ss.aliases[id]; ok {
+ s, ok := ss.byID[canonical]
+ return s, ok
+ }
+ return nil, false
}
// Remove forgets the shop id (built-ins are guarded at the service layer).
func (ss *ShopSet) Remove(id string) {
ss.mu.Lock()
defer ss.mu.Unlock()
- if _, ok := ss.byID[id]; !ok {
+ s, ok := ss.byID[id]
+ if !ok {
return
}
+ for _, a := range s.meta.Aliases {
+ if ss.aliases[a] == id {
+ delete(ss.aliases, a)
+ }
+ }
delete(ss.byID, id)
for i, x := range ss.order {
if x == id {
diff --git a/engine/internal/scripting/sourcebuiltin.go b/engine/internal/scripting/sourcebuiltin.go
new file mode 100644
index 0000000..50896aa
--- /dev/null
+++ b/engine/internal/scripting/sourcebuiltin.go
@@ -0,0 +1,100 @@
+package scripting
+
+import (
+ "context"
+ "embed"
+ "fmt"
+ "strings"
+)
+
+// Built-in "source" scripts declare more than one role in a single file: a
+// `shop` role table (browse/search) and a hidden `provider` role table (install
+// a whole modpack as a server), sharing one `meta` (id, config, permissions).
+// They live in their own embedded dir so neither the provider loader nor the
+// shop loader picks them up on its own.
+//
+//go:embed builtin_sources/*.lua
+var builtinSourcesFS embed.FS
+
+// SourceIDs is the set of canonical ids loaded from scripts that actually
+// declare both a shop role and a provider role. It deliberately excludes
+// aliases and unrelated entries that happen to use the same id in both
+// registries.
+type SourceIDs struct {
+ ids map[string]struct{}
+}
+
+// Contains reports whether id is the canonical id of a loaded multi-role
+// source script.
+func (s SourceIDs) Contains(id string) bool {
+ _, ok := s.ids[id]
+ return ok
+}
+
+// LoadBuiltinSources registers every embedded multi-role source script: its
+// shop role into shops and its provider role into providers. Both roles keep the
+// script's canonical meta.id, so one stored config entry (keyed by that id in
+// the shop config store) is shared. A script that declares no `shop`/`provider`
+// role table still registers into whichever subsystem it defines functions for.
+//
+// providerCfg is the config reader handed to the provider role so its ctx.config
+// resolves from the shared shop config store (plus any baked-key fallbacks the
+// caller layers on) rather than the provider registry's own store.
+func LoadBuiltinSources(ctx context.Context, providers *Registry, shops *ShopSet, providerCfg ConfigReader) (SourceIDs, error) {
+ sourceIDs := SourceIDs{ids: make(map[string]struct{})}
+ entries, err := builtinSourcesFS.ReadDir("builtin_sources")
+ if err != nil {
+ return SourceIDs{}, err
+ }
+ for _, e := range entries {
+ if e.IsDir() || !strings.HasSuffix(e.Name(), ".lua") {
+ continue
+ }
+ src, err := builtinSourcesFS.ReadFile("builtin_sources/" + e.Name())
+ if err != nil {
+ return SourceIDs{}, fmt.Errorf("builtin source %s: %w", e.Name(), err)
+ }
+ hasShop, hasProvider, err := sourceRoles(ctx, providers.host, string(src))
+ if err != nil {
+ return SourceIDs{}, fmt.Errorf("builtin source %s: %w", e.Name(), err)
+ }
+ var sourceID string
+ if hasShop {
+ shop, err := shops.AddSource(ctx, string(src), true)
+ if err != nil {
+ return SourceIDs{}, fmt.Errorf("builtin source %s (shop): %w", e.Name(), err)
+ }
+ sourceID = shop.Meta().ID
+ }
+ if hasProvider {
+ entry, err := providers.AddSourceWithConfig(ctx, string(src), true, providerCfg)
+ if err != nil {
+ return SourceIDs{}, fmt.Errorf("builtin source %s (provider): %w", e.Name(), err)
+ }
+ sourceID = entry.Meta.ID
+ }
+ if hasShop && hasProvider {
+ sourceIDs.ids[sourceID] = struct{}{}
+ }
+ }
+ return sourceIDs, nil
+}
+
+// sourceRoles reports which role tables a source script declares. A script with
+// neither table (a legacy single-role script placed here) is treated as both so
+// it still registers where its top-level functions apply; callers only place
+// dual-role scripts in builtin_sources, so in practice both are true.
+func sourceRoles(ctx context.Context, host *Host, source string) (shop, provider bool, err error) {
+ inv := &invocation{ctx: ctx, host: host}
+ L, err := inv.prepare(source)
+ if err != nil {
+ return false, false, err
+ }
+ defer L.Close()
+ shop = roleTable(L, "shop") != nil
+ provider = roleTable(L, "provider") != nil
+ if !shop && !provider {
+ return true, true, nil
+ }
+ return shop, provider, nil
+}
diff --git a/engine/internal/store/sqlite.go b/engine/internal/store/sqlite.go
index 3171346..eaf7cfe 100644
--- a/engine/internal/store/sqlite.go
+++ b/engine/internal/store/sqlite.go
@@ -18,13 +18,15 @@ CREATE TABLE IF NOT EXISTS servers (
provider_id TEXT NOT NULL DEFAULT '',
mod_layout TEXT NOT NULL DEFAULT 'none',
mc_version TEXT NOT NULL,
+ loader TEXT NOT NULL DEFAULT '',
memory_mb INTEGER NOT NULL,
port INTEGER NOT NULL,
status INTEGER NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
java_major INTEGER NOT NULL,
launch_args TEXT NOT NULL,
- custom_java_args TEXT NOT NULL DEFAULT ''
+ custom_java_args TEXT NOT NULL DEFAULT '',
+ provider_version TEXT NOT NULL DEFAULT ''
);`
// SQLite is a Store persisted in a SQLite database file, so the registry
@@ -60,21 +62,23 @@ func (s *SQLite) Put(srv *Server) error {
return err
}
_, err = s.db.Exec(`
- INSERT INTO servers (id, name, type, provider_id, mod_layout, mc_version, memory_mb, port, status, sort_order, java_major, launch_args, custom_java_args)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ INSERT INTO servers (id, name, type, provider_id, mod_layout, mc_version, loader, memory_mb, port, status, sort_order, java_major, launch_args, custom_java_args, provider_version)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
name=excluded.name, provider_id=excluded.provider_id, mod_layout=excluded.mod_layout,
- mc_version=excluded.mc_version, memory_mb=excluded.memory_mb, port=excluded.port,
+ mc_version=excluded.mc_version, loader=excluded.loader, memory_mb=excluded.memory_mb, port=excluded.port,
status=excluded.status, sort_order=excluded.sort_order, java_major=excluded.java_major,
- launch_args=excluded.launch_args, custom_java_args=excluded.custom_java_args`,
- srv.ID, srv.Name, 0, srv.ProviderID, modLayoutOrNone(srv.ModLayout), srv.McVersion,
- srv.MemoryMB, srv.Port, int(srv.Status), srv.SortOrder, srv.JavaMajor, string(args), srv.CustomJavaArgs)
+ launch_args=excluded.launch_args, custom_java_args=excluded.custom_java_args,
+ provider_version=excluded.provider_version`,
+ srv.ID, srv.Name, 0, srv.ProviderID, modLayoutOrNone(srv.ModLayout), srv.McVersion, srv.Loader,
+ srv.MemoryMB, srv.Port, int(srv.Status), srv.SortOrder, srv.JavaMajor, string(args), srv.CustomJavaArgs,
+ srv.ProviderVersion)
return err
}
func (s *SQLite) Get(id string) (*Server, bool) {
row := s.db.QueryRow(`
- SELECT id, name, provider_id, mod_layout, mc_version, memory_mb, port, status, sort_order, java_major, launch_args, custom_java_args
+ SELECT id, name, provider_id, mod_layout, mc_version, loader, memory_mb, port, status, sort_order, java_major, launch_args, custom_java_args, provider_version
FROM servers WHERE id = ?`, id)
srv, err := scanServer(row)
if err != nil {
@@ -85,7 +89,7 @@ func (s *SQLite) Get(id string) (*Server, bool) {
func (s *SQLite) List() []*Server {
rows, err := s.db.Query(`
- SELECT id, name, provider_id, mod_layout, mc_version, memory_mb, port, status, sort_order, java_major, launch_args, custom_java_args
+ SELECT id, name, provider_id, mod_layout, mc_version, loader, memory_mb, port, status, sort_order, java_major, launch_args, custom_java_args, provider_version
FROM servers`)
if err != nil {
return nil
@@ -122,8 +126,9 @@ func scanServer(sc rowScanner) (*Server, error) {
status int
argsJSON string
)
- if err := sc.Scan(&srv.ID, &srv.Name, &srv.ProviderID, &srv.ModLayout, &srv.McVersion, &srv.MemoryMB,
- &srv.Port, &status, &srv.SortOrder, &srv.JavaMajor, &argsJSON, &srv.CustomJavaArgs); err != nil {
+ if err := sc.Scan(&srv.ID, &srv.Name, &srv.ProviderID, &srv.ModLayout, &srv.McVersion, &srv.Loader, &srv.MemoryMB,
+ &srv.Port, &status, &srv.SortOrder, &srv.JavaMajor, &argsJSON, &srv.CustomJavaArgs,
+ &srv.ProviderVersion); err != nil {
return nil, err
}
srv.Status = mcmanagerv1.ServerStatus(status)
@@ -149,6 +154,8 @@ func ensureServerColumns(db *sql.DB) error {
`ALTER TABLE servers ADD COLUMN custom_java_args TEXT NOT NULL DEFAULT ''`,
`ALTER TABLE servers ADD COLUMN provider_id TEXT NOT NULL DEFAULT ''`,
`ALTER TABLE servers ADD COLUMN mod_layout TEXT NOT NULL DEFAULT 'none'`,
+ `ALTER TABLE servers ADD COLUMN loader TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE servers ADD COLUMN provider_version TEXT NOT NULL DEFAULT ''`,
} {
if _, err := db.Exec(stmt); err != nil {
if !strings.Contains(strings.ToLower(err.Error()), "duplicate column") {
diff --git a/engine/internal/store/sqlite_test.go b/engine/internal/store/sqlite_test.go
index b0fcd6f..1b2342b 100644
--- a/engine/internal/store/sqlite_test.go
+++ b/engine/internal/store/sqlite_test.go
@@ -51,7 +51,8 @@ func TestSQLitePersistsAcrossReopen(t *testing.T) {
t.Fatal(err)
}
_ = s1.Put(&Server{ID: "x", Name: "Persisted", ProviderID: "forge", ModLayout: "mods",
- McVersion: "1.20.1", MemoryMB: 4096, Port: 25570, Status: mcmanagerv1.ServerStatus_RUNNING,
+ McVersion: "1.20.1", ProviderVersion: "95/12695", MemoryMB: 4096, Port: 25570,
+ Status: mcmanagerv1.ServerStatus_RUNNING,
JavaMajor: 17, LaunchArgs: []string{"-jar", "forge.jar"}})
s1.Close()
@@ -66,7 +67,8 @@ func TestSQLitePersistsAcrossReopen(t *testing.T) {
t.Fatal("server not found after reopen")
}
if got.Name != "Persisted" || got.JavaMajor != 17 || got.MemoryMB != 4096 ||
- got.ProviderID != "forge" || len(got.LaunchArgs) != 2 {
+ got.ProviderID != "forge" || len(got.LaunchArgs) != 2 ||
+ got.ProviderVersion != "95/12695" {
t.Errorf("reopened server = %+v", got)
}
}
diff --git a/engine/internal/store/store.go b/engine/internal/store/store.go
index 4cddf1c..fe1db68 100644
--- a/engine/internal/store/store.go
+++ b/engine/internal/store/store.go
@@ -13,32 +13,38 @@ import (
// Server is a registered server plus the launch details the engine needs to
// start it. It carries proto enums directly to avoid an extra mapping layer.
type Server struct {
- ID string
- Name string
- ProviderID string
- ModLayout string // "plugins" | "mods" | "none"; captured from the provider at create
- McVersion string
- MemoryMB int
- Port int
- Status mcmanagerv1.ServerStatus
- SortOrder int
- JavaMajor int
- LaunchArgs []string
- CustomJavaArgs string
+ ID string
+ Name string
+ ProviderID string
+ ModLayout string // "plugins" | "mods" | "none"; captured from the provider at create
+ McVersion string
+ Loader string // effective mod loader ("fabric"/"forge"/…); empty falls back to ProviderID
+ // ProviderVersion is the opaque pack version ("packId/versionId") for
+ // modpack servers; empty otherwise. Non-empty enables update/export.
+ ProviderVersion string
+ MemoryMB int
+ Port int
+ Status mcmanagerv1.ServerStatus
+ SortOrder int
+ JavaMajor int
+ LaunchArgs []string
+ CustomJavaArgs string
}
// Proto projects a Server onto the wire type returned to the frontend.
func (s *Server) Proto() *mcmanagerv1.Server {
return &mcmanagerv1.Server{
- Id: s.ID,
- Name: s.Name,
- ProviderId: s.ProviderID,
- McVersion: s.McVersion,
- MemoryMb: int32(s.MemoryMB),
- Port: int32(s.Port),
- Status: s.Status,
- SortOrder: int32(s.SortOrder),
- CustomJavaArgs: s.CustomJavaArgs,
+ Id: s.ID,
+ Name: s.Name,
+ ProviderId: s.ProviderID,
+ McVersion: s.McVersion,
+ Loader: s.Loader,
+ ProviderVersion: s.ProviderVersion,
+ MemoryMb: int32(s.MemoryMB),
+ Port: int32(s.Port),
+ Status: s.Status,
+ SortOrder: int32(s.SortOrder),
+ CustomJavaArgs: s.CustomJavaArgs,
}
}
diff --git a/keycipher.ps1 b/keycipher.ps1
new file mode 100644
index 0000000..f582b61
--- /dev/null
+++ b/keycipher.ps1
@@ -0,0 +1,146 @@
+<#
+.SYNOPSIS
+ Single source of truth for the optional baked-in CurseForge API key ldflags.
+
+.DESCRIPTION
+ Produces the Go `-ldflags` fragment that injects an XOR-obfuscated,
+ hex-encoded CurseForge API key into the engine binary. Used by BOTH build
+ paths so every build (build.ps1 AND the dotnet/VS/MSIX build via
+ app/Engine.targets) bakes the same kind of key:
+
+ - build.ps1 dot-sources this file and calls Get-CurseForgeKeyLdflagsFragment.
+ - app/Engine.targets executes this file with -BuildEngine so reversible
+ key material never enters an MSBuild property or binlog.
+
+ When executed directly without -BuildEngine this script prints EXACTLY one
+ line to stdout:
+ * the fragment -X main.defaultCurseForgeKeyCipher= -X main.defaultCurseForgeKeyPad=
+ when $env:JHMC_CURSEFORGE_API_KEY is set, or
+ * an empty line when it is not.
+ On a validation failure it writes the reason to stderr and exits 1.
+
+ The key is XOR-obfuscated with a pad and hex-encoded so it survives ldflags
+ interpolation (CF keys contain '$' and '/') and does not sit plaintext in the
+ binary. BOTH the cipher and the pad are injected via ldflags; neither is
+ committed. The pad is generated fresh per build (48 cryptographically random
+ bytes) unless JHMC_KEY_CIPHER_PAD supplies one (hex, >= 32 bytes) for a
+ reproducible build. The engine reverses this in decodeDefaultCurseForgeKey
+ (engine/cmd/engine/keycipher.go). This is obfuscation, not encryption: anyone
+ with the built binary has both halves.
+
+ COMPATIBILITY: must run under Windows PowerShell 5.1 AND pwsh 7 (MSBuild boxes
+ may only have 5.1). Uses RandomNumberGenerator::Create().GetBytes() (not the
+ PS7 static ::Fill) and avoids PS7-only syntax (no '&&', no ternary).
+#>
+
+[CmdletBinding()]
+param(
+ [switch]$BuildEngine,
+ [string]$EngineSourceDir,
+ [string]$EngineOutput
+)
+
+function Get-KeyCipherPadBytes {
+ # Returns the XOR pad as a byte[]. Uses JHMC_KEY_CIPHER_PAD when set
+ # (validated: hex only, even length, >= 32 bytes decoded; invalid -> throw),
+ # otherwise generates 48 cryptographically random bytes fresh per call.
+ if ($env:JHMC_KEY_CIPHER_PAD) {
+ $hex = $env:JHMC_KEY_CIPHER_PAD
+ if ($hex.Length % 2 -ne 0) {
+ throw "JHMC_KEY_CIPHER_PAD is invalid: hex string must have an even length (got $($hex.Length) chars)."
+ }
+ if ($hex -notmatch '^[0-9a-fA-F]+$') {
+ throw 'JHMC_KEY_CIPHER_PAD is invalid: must contain only hex characters [0-9a-fA-F].'
+ }
+ if (($hex.Length / 2) -lt 32) {
+ throw "JHMC_KEY_CIPHER_PAD is invalid: pad must be at least 32 bytes (got $($hex.Length / 2))."
+ }
+ $bytes = for ($i = 0; $i -lt $hex.Length; $i += 2) {
+ [Convert]::ToByte($hex.Substring($i, 2), 16)
+ }
+ return [byte[]]$bytes
+ }
+ $bytes = [byte[]]::new(48)
+ $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
+ try { $rng.GetBytes($bytes) } finally { $rng.Dispose() }
+ return $bytes
+}
+
+function ConvertTo-HexString {
+ param([byte[]]$Bytes)
+ $sb = [System.Text.StringBuilder]::new()
+ foreach ($b in $Bytes) { [void]$sb.Append($b.ToString('x2')) }
+ $sb.ToString()
+}
+
+function Encode-CurseForgeKeyCipher {
+ param([string]$Key, [byte[]]$Pad)
+ $keyBytes = [System.Text.Encoding]::UTF8.GetBytes($Key)
+ $sb = [System.Text.StringBuilder]::new()
+ for ($i = 0; $i -lt $keyBytes.Length; $i++) {
+ $b = $keyBytes[$i] -bxor $Pad[$i % $Pad.Count]
+ [void]$sb.Append($b.ToString('x2'))
+ }
+ $sb.ToString()
+}
+
+function Get-CurseForgeKeyLdflagsFragment {
+ # Returns the ldflags fragment (two -X flags) when JHMC_CURSEFORGE_API_KEY is
+ # set, or an empty string when it is not. Throws on an invalid
+ # JHMC_KEY_CIPHER_PAD (via Get-KeyCipherPadBytes).
+ if (-not $env:JHMC_CURSEFORGE_API_KEY) {
+ return ''
+ }
+ $padBytes = Get-KeyCipherPadBytes
+ $padHex = ConvertTo-HexString $padBytes
+ $cipher = Encode-CurseForgeKeyCipher $env:JHMC_CURSEFORGE_API_KEY $padBytes
+ return "-X main.defaultCurseForgeKeyCipher=$cipher -X main.defaultCurseForgeKeyPad=$padHex"
+}
+
+function Invoke-DefaultEngineBuild {
+ param(
+ [Parameter(Mandatory = $true)][string]$SourceDir,
+ [Parameter(Mandatory = $true)][string]$OutputPath
+ )
+
+ $ldflags = '-s -w -buildid='
+ $keyFragment = Get-CurseForgeKeyLdflagsFragment
+ # The linker needs only the derived cipher/pad. Do not pass the plaintext
+ # source secret through to the child go process environment.
+ Remove-Item Env:JHMC_CURSEFORGE_API_KEY -ErrorAction SilentlyContinue
+ if ($keyFragment) {
+ $ldflags += " $keyFragment"
+ }
+
+ Push-Location $SourceDir
+ try {
+ & go build -trimpath -buildvcs=false -mod=readonly `
+ "-ldflags=$ldflags" -o $OutputPath ./cmd/engine
+ if ($LASTEXITCODE -ne 0) {
+ throw "go build failed with exit code $LASTEXITCODE."
+ }
+ } finally {
+ Pop-Location
+ }
+}
+
+# When executed directly (not dot-sourced), emit the fragment on one stdout line
+# and translate a validation failure into stderr + exit 1. Dot-sourcing (build.ps1)
+# sets InvocationName to '.' and skips this block, importing only the functions.
+if ($MyInvocation.InvocationName -ne '.') {
+ try {
+ if ($BuildEngine) {
+ if (-not $EngineSourceDir -or -not $EngineOutput) {
+ throw '-BuildEngine requires -EngineSourceDir and -EngineOutput.'
+ }
+ Invoke-DefaultEngineBuild -SourceDir $EngineSourceDir `
+ -OutputPath $EngineOutput
+ } else {
+ $fragment = Get-CurseForgeKeyLdflagsFragment
+ [Console]::Out.WriteLine($fragment)
+ }
+ } catch {
+ [Console]::Error.WriteLine($_.Exception.Message)
+ exit 1
+ }
+}
diff --git a/proto/mcmanager/v1/mcmanager.proto b/proto/mcmanager/v1/mcmanager.proto
index e67e3f7..3ed4734 100644
--- a/proto/mcmanager/v1/mcmanager.proto
+++ b/proto/mcmanager/v1/mcmanager.proto
@@ -43,6 +43,10 @@ message Server {
ServerStatus status = 7;
int32 sort_order = 8;
string custom_java_args = 9;
+ string loader = 10; // effective mod loader ("fabric"/"forge"/...); empty falls back to provider_id
+ // Opaque provider pack version ("packId/versionId") for modpack servers;
+ // empty for normal servers. Non-empty means update/export are available.
+ string provider_version = 11;
}
message CreateServerRequest {
@@ -64,6 +68,22 @@ message UpdateServerRequest {
string custom_java_args = 7;
}
+message UpdateModpackRequest {
+ string id = 1;
+ string version = 2; // new opaque "packId/versionId"
+}
+message ExportModpackRequest {
+ string id = 1;
+ string dest_path = 2; // absolute .zip path chosen by the user
+}
+message ImportModpackRequest {
+ string name = 1; // server name
+ string src_path = 2; // absolute path to a .zip (CurseForge pack) or .mrpack
+ int32 memory_mb = 3;
+ int32 port = 4; // 0 = auto-assign
+ string custom_java_args = 5;
+}
+
// -- i18n / message strategy --------------------------------------------------
// Dynamic, display-only messages travel as a localization KEY in the form
// "namespace.method.type" (e.g. "install.progress.downloading_server"); the
@@ -159,6 +179,8 @@ message Permission {
// which mod folder a provider uses, if any.
message ProviderCapabilities {
string mod_layout = 1; // "plugins" | "mods" | "none"
+ bool hidden = 2; // not offered in the create-server UI (install is driven elsewhere, e.g. a modpack shop)
+ bool free_form_versions = 3; // Versions() is not exhaustive; version strings are opaque ids (e.g. "packId/versionId")
}
// ProviderInfo describes an installed provider script (built-in or user-imported).
@@ -173,6 +195,7 @@ message ProviderInfo {
repeated Permission permissions = 8; // declared/requested permissions
repeated PermissionKind granted = 9; // currently-granted subset
ProviderCapabilities capabilities = 10;
+ repeated ConfigOption config_options = 11; // author-declared typed config options
}
message ProviderList {
@@ -195,6 +218,43 @@ message SetPermissionsRequest {
repeated PermissionKind granted = 2;
}
+// Types a script config option can declare (meta.config in Lua). Shared by all
+// four scriptable subsystems (providers, automation scripts, parsers, shops).
+enum ConfigOptionType {
+ CONFIG_OPTION_TYPE_UNSPECIFIED = 0;
+ CONFIG_OPTION_STRING = 1;
+ CONFIG_OPTION_NUMBER = 2;
+ CONFIG_OPTION_BOOLEAN = 3;
+ CONFIG_OPTION_SECRET = 4; // stored server-side, never returned to the client
+}
+
+// ConfigOption is one author-declared typed config field (a meta.config entry).
+message ConfigOption {
+ string key = 1; // stable key, [a-zA-Z0-9_-]+
+ ConfigOptionType type = 2;
+ string name = 3; // display label (script-authored, not localized)
+ string description = 4;
+ string default = 5; // string-encoded default
+ bool required = 6;
+}
+
+// ScriptConfigValue is one stored value. In Get replies, `value` is empty for
+// secrets and `has_value` reports presence. In Set requests an empty value
+// clears the stored override.
+message ScriptConfigValue {
+ string key = 1;
+ string value = 2;
+ bool has_value = 3;
+}
+message ScriptConfig {
+ string id = 1;
+ repeated ScriptConfigValue values = 2;
+}
+message SetConfigRequest {
+ string id = 1;
+ repeated ScriptConfigValue values = 2;
+}
+
// ScriptInfo describes an installed automation/control script.
message ScriptInfo {
string id = 1;
@@ -206,6 +266,7 @@ message ScriptInfo {
bool enabled = 7;
repeated Permission permissions = 8;
repeated PermissionKind granted = 9;
+ repeated ConfigOption config_options = 10; // author-declared typed config options
}
message ScriptList {
@@ -225,6 +286,7 @@ message ParserInfo {
repeated Permission permissions = 8; // declared/requested permissions
repeated PermissionKind granted = 9; // currently-granted subset
repeated string formats = 10; // descriptor formats it reads, e.g. "fabric.mod.json"
+ repeated ConfigOption config_options = 11; // author-declared typed config options
}
message ParserList {
@@ -464,7 +526,9 @@ enum ModKind {
MOD_KIND_UNSPECIFIED = 0;
PLUGIN = 1; // Paper/Spigot -> plugins/
MOD = 2; // Forge/NeoForge/Fabric -> mods/
+ MODPACK = 3; // shop browsing discriminator only; modpacks install a whole server, no per-server folder
}
+
// ModMetadata is what a parser script extracted from a jar's embedded
// descriptor (fabric.mod.json / mods.toml / plugin.yml / ...). parsed=false
// means no installed parser recognized the jar (UI falls back to the filename).
@@ -548,6 +612,8 @@ message ShopInfo {
repeated PermissionKind granted = 9; // currently-granted subset
bool needs_key = 10; // shop requires a per-shop API key (see SettingsService)
bool ready = 11; // false when needs_key and no key is configured
+ repeated ConfigOption config_options = 12; // author-declared typed config options
+ repeated string kinds = 13; // item kinds served: "mod"/"plugin" (default) and/or "modpack"
}
message ShopList {
repeated ShopInfo shops = 1;
@@ -720,23 +786,6 @@ message ShopInstallRequest {
repeated ShopDependencyInstall dependencies = 5; // extra downloads confirmed by the user
}
-// -- Settings: per-shop API keys ------------------------------------------------
-
-// ShopKey sets (or clears, with empty api_key) the user override for one shop.
-message ShopKey {
- string shop_id = 1;
- string api_key = 2;
-}
-// ShopKeyInfo reports key presence without ever exposing the key itself.
-message ShopKeyInfo {
- string shop_id = 1;
- bool has_user_key = 2;
- bool has_builtin_key = 3; // a baked-in default key exists in this build
-}
-message ShopKeyList {
- repeated ShopKeyInfo keys = 1;
-}
-
// -- Services -----------------------------------------------------------------
service EngineService {
@@ -749,6 +798,9 @@ service ServerService {
rpc WatchChanges(Empty) returns (stream ServerChangeEvent);
rpc Create(CreateServerRequest) returns (stream InstallProgress); // last message implies done
rpc Update(UpdateServerRequest) returns (Server);
+ rpc UpdateModpack(UpdateModpackRequest) returns (stream InstallProgress); // manifest-diff move to another pack version
+ rpc ExportModpack(ExportModpackRequest) returns (stream InstallProgress); // CurseForge client pack zip
+ rpc ImportModpack(ImportModpackRequest) returns (stream InstallProgress); // new server from a local CurseForge/Modrinth pack file
rpc Start(ServerId) returns (Empty);
rpc Stop(ServerId) returns (Empty);
rpc Delete(ServerId) returns (Empty);
@@ -772,8 +824,6 @@ service SettingsService {
rpc PurgeLogs(Empty) returns (PurgeResult); // apply the policy immediately
rpc GetBackendInfo(Empty) returns (BackendInfo);
rpc SetUseDocker(UseDocker) returns (Empty); // opt in/out; takes effect on next launch
- rpc GetShopKeys(Empty) returns (ShopKeyList); // key presence per shop (never the key itself)
- rpc SetShopKey(ShopKey) returns (Empty); // set/clear the user override for one shop
}
service PlayerService {
@@ -810,6 +860,8 @@ service ProviderService {
rpc Import(ImportProviderRequest) returns (ProviderInfo); // import a user .lua (+ optional jar)
rpc Remove(ProviderRef) returns (Empty);
rpc SetPermissions(SetPermissionsRequest) returns (ProviderInfo);
+ rpc GetConfig(ProviderRef) returns (ScriptConfig);
+ rpc SetConfig(SetConfigRequest) returns (ScriptConfig);
}
// ParserService manages the Lua parser scripts that extract mod/plugin
@@ -819,6 +871,8 @@ service ParserService {
rpc Import(ImportParserRequest) returns (ParserInfo);
rpc Remove(ProviderRef) returns (Empty);
rpc SetPermissions(SetPermissionsRequest) returns (ParserInfo);
+ rpc GetConfig(ProviderRef) returns (ScriptConfig);
+ rpc SetConfig(SetConfigRequest) returns (ScriptConfig);
}
// ShopService drives the Lua "shop" scripts that browse/search/download
@@ -835,6 +889,8 @@ service ShopService {
rpc Import(ImportShopRequest) returns (ShopInfo);
rpc Remove(ProviderRef) returns (Empty);
rpc SetPermissions(SetPermissionsRequest) returns (ShopInfo);
+ rpc GetConfig(ProviderRef) returns (ScriptConfig);
+ rpc SetConfig(SetConfigRequest) returns (ScriptConfig);
}
// ScriptService manages automation/control scripts that drive running servers
@@ -844,6 +900,8 @@ service ScriptService {
rpc Import(ImportScriptRequest) returns (ScriptInfo);
rpc SetEnabled(SetScriptEnabledRequest) returns (ScriptInfo);
rpc SetPermissions(SetPermissionsRequest) returns (ScriptInfo);
+ rpc GetConfig(ProviderRef) returns (ScriptConfig);
+ rpc SetConfig(SetConfigRequest) returns (ScriptConfig);
rpc Remove(ProviderRef) returns (Empty);
rpc StreamLog(Empty) returns (stream ScriptLogLine); // engine-wide automation log
}