Build and publish a separately stacked menu transport without replacing world packs

This commit is contained in:
unimatrixgit 2026-11-29 03:14:35 +01:00
commit e19acd2549
17 changed files with 443 additions and 32 deletions

View file

@ -10,9 +10,11 @@ on:
- 'gui-common/**'
- 'citizens-common/**'
- 'network/resource-pack/shared/**'
- 'network/resource-pack/mcgui/**'
- 'network/content-assets/planet-artwork/profiles.json'
- 'tools/*gameplay*'
- 'tools/*plugin*'
- 'tools/*menu*'
jobs:
plugins:
@ -51,16 +53,17 @@ jobs:
done
printf '%s\n' "$(git rev-parse HEAD)" > plugin-artifacts/SOURCE_COMMIT
(cd plugin-artifacts && sha256sum -- *.jar SOURCE_COMMIT > SHA256SUMS)
- name: Validate gameplay assets and build pack with original GUI
- name: Validate rollout contract and build stacked menu overlay
shell: bash
run: |
set -euo pipefail
python3 tools/test_plugin_fleet_install.py -v
python3 tools/test_plugin_menu_pack.py -v
python3 tools/test_gameplay_resourcepack.py -v
python3 tools/build-gameplay-resourcepack.py --from-gui-config DuneRealmsGUI/src/main/resources/gui-pack.yml --output "plugin-artifacts/DuneRealms-Gameplay-${GITHUB_SHA}.zip"
python3 tools/build-menu-resourcepack.py --source "$GITHUB_SHA" --output "plugin-artifacts/DuneRealms-Menu-${GITHUB_SHA}.zip"
python3 tools/write-plugin-manifest.py plugin-artifacts "$GITHUB_SHA"
cp tools/install-plugin-fleet.py plugin-artifacts/
cp DuneMenus/docs/FLEET-INSTALL.md plugin-artifacts/
cp tools/install-plugin-fleet.py tools/plugin_menu_pack.py tools/publish-plugin-menu.py plugin-artifacts/
cp DuneMenus/docs/FLEET-INSTALL.md DuneMenus/docs/MENU-PACK-ROLLOUT.md plugin-artifacts/
(cd plugin-artifacts && sha256sum -- *.jar *.zip *.json *.py *.md SOURCE_COMMIT > SHA256SUMS)
- uses: actions/upload-artifact@v3
with:

View file

@ -8,7 +8,9 @@ First run a read-only plan with `--artifacts`, `--inventory`, and `--expected-so
All artifacts, descriptors, installed-file snapshots and backups are verified. Services must be fully stopped before JAR replacement; active services restart afterward, previously stopped services remain stopped. Old filenames are replaced by actual plugin identity. On an installation/start failure, original bytes and filenames are restored after verifying the service is stopped, and a rollback receipt is retained. A rollback that cannot stop the service halts without replacing active JARs. A multi-server failure may leave earlier servers installed; inspect each receipt.
An `installed-service-active` receipt proves file installation and systemd state only. It does not prove Minecraft finished loading or an NPC interaction worked. Verify server logs, enabled versions, resource-pack publication/configuration, actual GUI/NPC actions and retained progression separately before reporting rollout complete. Resource-pack hosting/configuration is not changed by this JAR installer.
An `installed-service-active` receipt proves file installation and systemd state only. It does not prove Minecraft finished loading or an NPC interaction worked. Verify server logs, enabled versions, resource-pack publication/configuration, actual GUI/NPC actions and retained progression separately before reporting rollout complete. Resource-pack publication uses the separate built publisher; required menu configuration is verified and managed by this installer as described in MENU-PACK-ROLLOUT.md.
A missing existing MCGUI runtime may be staged privately by the authorised coordinator. Inventory `privatePrerequisites.MCGUI` requires an absolute `path` and the reviewed SHA-256 `69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300`; the server entry must explicitly list `prerequisites: ["MCGUI"]`. The installer verifies plugin name MCGUI, version0.8.6 and main ai.resourcepack.ui.MCGUIPlugin before including those privately staged bytes. They are never added to the public source/release artifact. Unknown private prerequisites or different bytes/identities fail planning. The private runtime's installation and rollback follow the same stopped-service, backup and checksum path as first-party JARs.
For selected DuneMenus, inventory menuPack.url is mandatory and actual public bytes must match the built composite. Owned config bytes are hashed, backed up and restored with JAR rollback; existing unmanaged config fails closed. Per-world server.properties is never written. See MENU-PACK-ROLLOUT.md for the persistent publication and external runtime contract.

View file

@ -33,3 +33,6 @@ The example path is a parameter, not a deployment location. This task checks the
Local Java21 Gradle verification completed successfully using cached dependencies (`--offline`) after the local JDK trust store rejected online Maven TLS. `test jar verifyMenuRenderer` built the frontend and JARVIS dependency, ran their tests and rendered all15 families/152 hitboxes. Canonical CI uses Gradle9.2.1 and is reported separately by exact commit.
The build also ships the manifest-driven fleet installer and its tested rollback path. See FLEET-INSTALL.md. This is deployable tooling, not evidence that any host was changed.
The final pack acceptance supersedes intermediate gameplay ZIPs: use only the built DuneRealms-Menu-<source>.zip composite and MENU-PACK-ROLLOUT.md. Legacy world/artwork auto-offers are removed; the actual engine's external-mode readiness assumption is supplemented by an exact-pack SUCCESSFULLY_LOADED guard. Existing active hosts have no GUI runtimes installed yet; incoming first-party services and a hash-pinned private MCGUI prerequisite restore them. Source/backend implementation preservation does not claim those services were already installed live.

View file

@ -0,0 +1,23 @@
# Build-owned stacked menu delivery
The existing MCGUI0.8.6 runtime calls Player.addResourcePack with UUID.nameUUIDFromBytes("uiengine:pack"). It stacks its pack rather than clearing the server world pack. In mode external with blank public-url, offers() is false and mergedElsewhere() is true. Its has(player) method can assume readiness in that mode; our sender therefore additionally requires an actual SUCCESSFULLY_LOADED event for the exact MCGUI pack ID before opening any new menu or enabling item-card assets.
The canonical build preserves all116 entries from the pinned generated MCGUI client transport and adds exactly75 approved assets/dunerealms entries, including389 card mappings. It excludes every old baseline/world-artwork entry and all vanilla block/entity replacements. The client pack explicitly includes26.2 shaders/formats88–96. The private vendor plugin JAR is not in public source or CI artifacts.
DunerealmsGUI no longer starts legacy PlanetTexturePacks/EcologyArtwork delivery and no longer offers NetworkArtwork-v6. It offers only the separately stacked built menu overlay. Server-owned per-world resource-pack settings and bytes remain untouched. The MCGUI runtime is configured external/blank URL with telemetry, update-check and web imports disabled; no vendor upload or built-in pack server is used.
Publish through the CI-shipped publish-plugin-menu.py, first read-only, then --apply, supplying --artifacts, --expected-source, --store and --snippet. The verified web hosting contract is host91.107.196.242, store /var/lib/dunerealms-public-downloads, included snippet /etc/nginx/snippets/dunerealms-gui-download-v3.conf. The built publisher copies only DuneRealms-Menu-<source>.zip, refuses conflicting immutable bytes, preserves all existing routes, backs up the snippet, appends one exact idempotent location, runs nginx -t before reload, and restores config on test/reload failure. The permanent URL is https://www.dunerealms.com/downloads/DuneRealms-Menu-<source>.zip. Never use an expiring artifact link as client configuration.
The built fleet installer requires inventory menuPack.url equal to that permanent URL. It verifies the actual public bytes against the CI menu ZIP/manifest before stopping anything. For selected DuneMenus targets it writes only owned MCGUI/config.yml and DunerealmsGUI/menu-pack.yml, records/writes their hashes, backs up existing owned config bytes, and restores them together with JARs on failure. Unexpected unmanaged config is refused. New data directories and JAR/config files inherit plugin-directory ownership so root-staged0600 runtime bytes can be read/run by the game service without changing the private source file. No server.properties write exists in either tool.
## Verified staging fact — not installation
The authorised coordinator staged the existing reviewed MCGUI runtime privately on both verified game hosts at /opt/dunerealms/rollouts/private/MCGUI-0.8.6-69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300.jar, root-owned0600. SHA25669a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300 was rechecked after transfer. That was prerequisite staging only: no plugin installation, service restart or GUI delivery was performed at that point. No credential/key path is part of this handover.
Current fleet Paper is26.2-135/API26.2.build.135, not the historical compile API1.21.8. Existing isolated logs establish MCGUI0.8.6 startup on matchingPaper. Actual new renderer checks cover15 menu families/152 action hitboxes; connected-client transport, NPC interactions and current world textures still require rollout checks. Citizens is absent and its compatible runtime remains pending official vendor access; do not claim Citizens conversion complete.
Inventory extension:
```json
"menuPack": {"url": "https://www.dunerealms.com/downloads/DuneRealms-Menu-<exact40hexsource>.zip"}
```
Replace the placeholder with the actual built source. The coordinator retains exclusive host invocation; all persistent code/config publication goes through these committed build tools.

View file

@ -109,9 +109,11 @@ public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor {
void forgetPack(Player player) { loadedPacks.remove(player); }
boolean itemCardPackLoaded(Player player) {
String expected = getConfig().getString("resource-pack.item-card-sha1", "");
return expected.matches("[a-f0-9]{40}") && expected.equals(loadedPacks.get(player))
&& !Bedrock.is(player);
if(Bedrock.is(player))return false;
var services=getServer().getPluginManager().getPlugin("DunerealmsGUI");
if(services==null||!services.isEnabled())return false;
try{return Boolean.TRUE.equals(services.getClass().getMethod("menuAssetsLoaded",Player.class).invoke(services,player));}
catch(ReflectiveOperationException failure){return false;}
}
boolean hasOpenMenu(Player player) { return openMenus.containsKey(player.getUniqueId()); }

View file

@ -23,13 +23,13 @@ import java.util.function.Consumer;
/** Lobby presentation only. Character authority and committed keys remain central. */
public final class DuneGUI extends JavaPlugin implements Listener,CommandExecutor {
public void openOrganisationServices(Player player,String kind,String id){if(!Bukkit.isPrimaryThread()||!player.isOnline())return;organisations.openHomeNpc(player,kind.equals("clan")?"clans":"companies",id);}
public boolean menuAssetsLoaded(Player player){return MCGUIMenus.assetsLoaded(player);}
public boolean presentSuppliedMenu(Player player,String title,String html,Map<Integer,Runnable> actions,Runnable close){return MCGUIMenus.showDocument(player,title,html,actions,close);}
public void warObjective(Player player,JsonObject target,Runnable capture){if(!Bukkit.isPrimaryThread()||!isEnabled())throw new IllegalStateException("Open objectives on the server thread");organisations.warObjective(player,target,capture);}
private HouseBridge bridge;
private OrganisationMenus organisations;
private MCGUIMenus modernMenus;
private EcologyArtwork ecologyArtwork;
private QuestMenus quests;
private WarMenus warMenus;
private PolQuestNpc polQuestNpcs;
@ -76,8 +76,6 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
organisations=new OrganisationMenus(this,bridge,p->fetch(p,null,0,null,data->mentat(p,data)),p->openGuild(p,null),p->fetch(p,null,0,null,data->select(p,data,null)),p->quests.open(p),p->exchange.open(p),p->spice.open(p),p->guiPackLoaded.contains(p.getUniqueId()));
registrar=new NamespacedKey(this,"house_registrar"); com.dunerealms.npc.CitizensBridge.start(this,registrar,new NamespacedKey("dunerealms","quartermaster"),new NamespacedKey("dunerealms","quest_character"));
modernMenus=new MCGUIMenus(this);
ecologyArtwork=new EcologyArtwork(this);
new PlanetTexturePacks(this);
sidebar=new PersonalSidebar(this);nameplates=new PublicNameplates(this);
for(String command:List.of("start","spice","sellall","exchange","house","mentat","drgui","drscoreboard","guildtravel","clan","company","polgui"))Objects.requireNonNull(getCommand(command)).setExecutor(this);
@ -191,14 +189,7 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=true) public void legacyTravel(PlayerCommandPreprocessEvent e){String[] args=e.getMessage().substring(1).trim().toLowerCase(Locale.ROOT).split("\\s+");String label=args[0].replaceFirst("^[^:]+:","");if(label.equals("balance")||label.equals("bal")||label.equals("money")){e.setCancelled(true);if(!sidebar.enabled(e.getPlayer()))sidebar.toggle(e.getPlayer());refreshSidebar(e.getPlayer());return;}if(label.equals("exchange")){e.setCancelled(true);if(!SuppliedMenus.open(e.getPlayer(),"exchange"))exchange.open(e.getPlayer());return;}if(label.equals("server")||label.equals("duneess")&&args.length>1&&args[1].equals("travel")){e.setCancelled(true);if(!SuppliedMenus.open(e.getPlayer(),"travel"))openGuild(e.getPlayer(),null);}}
private void offerGuiPack(Player p){offerGuiPack(p,true);}
private void offerGuiPack(Player p,boolean force){
if(!p.isOnline()||BedrockForms.isBedrock(p))return;
var pack=guiPack(p);
if(!force&&pack.equals(offeredGuiPacks.get(p.getUniqueId())))return;
guiPackLoaded.remove(p.getUniqueId());
// Replace only the network pack, never the separately managed planet pack.
offeredGuiPacks.put(p.getUniqueId(),pack);
p.addResourcePack(NetworkArtworkPolicy.PACK_ID,pack.url(),java.util.HexFormat.of().parseHex(pack.hash()),"DuneRealms menus and item artwork",true);
if(lobby(p)){MCGUIMenus.offerPack(p);ecologyArtwork.offer(p);}
if(p.isOnline()&&!BedrockForms.isBedrock(p))MCGUIMenus.offerPack(p);
}
@EventHandler public void join(PlayerJoinEvent e){Bukkit.getScheduler().runTaskLater(this,()->{
Player p=e.getPlayer();if(!p.isOnline())return;
@ -209,9 +200,9 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
if(sidebar.enabled(p))refreshSidebar(p);
},40L);}
@EventHandler public void packStatus(PlayerResourcePackStatusEvent e){
if(!NetworkArtworkPolicy.PACK_ID.equals(e.getID()))return;
if(!MCGUIMenus.isMenuPack(e.getID()))return;
getLogger().info("GUI pack status for "+e.getPlayer().getName()+": "+e.getStatus());
if(e.getStatus()==PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED){guiPackLoaded.add(e.getPlayer().getUniqueId());e.getPlayer().sendMessage(Component.text("DuneRealms artwork loaded. Reopen your menu.",NamedTextColor.GREEN));return;}
if(e.getStatus()==PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED){e.getPlayer().sendMessage(Component.text("DuneRealms artwork loaded. Reopen your menu.",NamedTextColor.GREEN));return;}
guiPackLoaded.remove(e.getPlayer().getUniqueId());
if(Set.of("FAILED_DOWNLOAD","FAILED_RELOAD","INVALID_URL","DECLINED","DISCARDED").contains(e.getStatus().name()))offeredGuiPacks.remove(e.getPlayer().getUniqueId());
}

View file

@ -27,6 +27,10 @@ final class MCGUIMenus implements AutoCloseable, Listener {
MCGUIMenus(JavaPlugin plugin){
this.plugin=plugin;base=plugin.getDataFolder().toPath().resolve("mcgui/menu.html");
if(!plugin.getConfig().getBoolean("mcgui.enabled",true))return;
var pinFile=plugin.getDataFolder().toPath().resolve("menu-pack.yml").toFile();
var settings=org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(pinFile);
var pin=MenuPackPolicy.select(settings.getString("url"),settings.getString("sha1"),settings.getString("sha256"),settings.getString("source-commit"));
if(pin==null){plugin.getLogger().warning("Built menu-pack.yml publication pin is required; world packs were left unchanged.");return;}
engine=Bukkit.getPluginManager().getPlugin("MCGUI");if(engine==null||!engine.isEnabled())return;
try{
ClassLoader cl=engine.getClass().getClassLoader();Class<?> api=Class.forName("ai.resourcepack.ui.framework.api.UIFramework",true,cl);
@ -39,11 +43,8 @@ final class MCGUIMenus implements AutoCloseable, Listener {
for(Method m:renderer.getMethods())if(m.getName().equals("state")&&m.getParameterCount()==2)hoverState=m;
Class<?> canvas=Class.forName("ai.resourcepack.ui.framework.api.Canvas",true,cl);draw=canvas.getMethod("draw",java.awt.image.BufferedImage.class,int.class,int.class);
packId=(UUID)Class.forName("ai.resourcepack.ui.framework.pack.ResourcePack",true,cl).getField("PACK_ID").get(null);
packUrl=engine.getConfig().getString("resource-pack.public-url","");
// MC GUI external-without-URL means the pack was delivered by lobby.
if(packUrl.isBlank())packUrl="https://www.dunerealms.com/downloads/DuneRealms-MCGUI-0.8.6-1.21.11.zip";
if(!packUrl.startsWith("https://"))throw new IllegalStateException("A hosted menu pack URL is required");
packHash=java.security.MessageDigest.getInstance("SHA-1").digest(Files.readAllBytes(engine.getDataFolder().toPath().resolve("pack.zip")));
if(!engine.getConfig().getString("resource-pack.mode","").equals("external")||!engine.getConfig().getString("resource-pack.public-url","").isBlank()||engine.getConfig().getBoolean("telemetry",true))throw new IllegalStateException("MCGUI must use external merged mode with telemetry disabled");
packUrl=pin.url();packHash=HexFormat.of().parseHex(pin.sha1());
active=this;Bukkit.getPluginManager().registerEvents(this,plugin);Bukkit.getScheduler().runTaskLater(plugin,()->Bukkit.getOnlinePlayers().forEach(this::offerGameplay),60L);plugin.getLogger().info("MC GUI presentation connected for all DuneRealms menus; Jarvis callbacks retained.");
}catch(Exception failure){framework=null;plugin.getLogger().warning("MC GUI adapter unavailable: "+failure.getClass().getSimpleName());}
}
@ -53,19 +54,21 @@ final class MCGUIMenus implements AutoCloseable, Listener {
}
static boolean showDocument(Player p,String title,String html,Map<Integer,Runnable> actions,Runnable closed){
if(active==null||active.framework==null||!p.isOnline()||BedrockForms.isBedrock(p))return false;
try{if(!Boolean.TRUE.equals(active.hasPack.invoke(active.framework,p))){active.sendPack(p);return false;}
try{if(!active.gameplayReady.contains(p.getUniqueId())||!Boolean.TRUE.equals(active.hasPack.invoke(active.framework,p))){active.sendPack(p);return false;}
Session old=active.sessions.remove(p.getUniqueId());if(old!=null)old.finish();
Session next=active.new Session(p,title,"",List.of(),Map.copyOf(actions),null);
next.suppliedHtml=html;next.onClose=closed;active.sessions.put(p.getUniqueId(),next);p.closeInventory();next.schedule();
Bukkit.getScheduler().runTaskLater(active.plugin,()->{if(active.sessions.remove(p.getUniqueId(),next)){next.finish();next.onClose.run();}},2400L);return true;
}catch(Exception failure){active.plugin.getLogger().warning("Supplied menu presentation unavailable: "+failure.getClass().getSimpleName());return false;}
}
static boolean isMenuPack(UUID id){return active!=null&&id.equals(active.packId);}
static boolean assetsLoaded(Player player){if(active==null||active.framework==null)return false;try{return active.gameplayReady.contains(player.getUniqueId())&&Boolean.TRUE.equals(active.hasPack.invoke(active.framework,player));}catch(Exception failure){return false;}}
static void forget(UUID player){if(active!=null){active.closeHints.remove(player);active.gameplayReady.remove(player);active.gameplayOffered.remove(player);}}
static void offerPack(Player p){if(active!=null&&!BedrockForms.isBedrock(p))active.sendPack(p);}
private void sendPack(Player p){p.addResourcePack(packId,packUrl,packHash,"DuneRealms interactive menus",true);}
private void offerGameplay(Player p){if(p.isOnline()&&!BedrockForms.isBedrock(p)&&!p.getWorld().getName().equals("guild_lobby")&&gameplayOffered.add(p.getUniqueId()))sendPack(p);}
private void sendPack(Player p){if(p.isOnline()&&!gameplayReady.contains(p.getUniqueId())&&gameplayOffered.add(p.getUniqueId()))p.addResourcePack(packId,packUrl,packHash,"DuneRealms interactive menus",true);}
private void offerGameplay(Player p){if(p.isOnline()&&!BedrockForms.isBedrock(p))sendPack(p);}
@EventHandler public void playerJoined(PlayerJoinEvent e){Bukkit.getScheduler().runTaskLater(plugin,()->offerGameplay(e.getPlayer()),60L);}
@EventHandler public void menuPackStatus(PlayerResourcePackStatusEvent e){if(packId==null||!packId.equals(e.getID())||e.getPlayer().getWorld().getName().equals("guild_lobby"))return;var id=e.getPlayer().getUniqueId();if(e.getStatus()==PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED)gameplayReady.add(id);else if(e.getStatus()!=PlayerResourcePackStatusEvent.Status.ACCEPTED&&e.getStatus()!=PlayerResourcePackStatusEvent.Status.DOWNLOADED)gameplayReady.remove(id);}
@EventHandler public void menuPackStatus(PlayerResourcePackStatusEvent e){if(packId==null||!packId.equals(e.getID()))return;var id=e.getPlayer().getUniqueId();if(e.getStatus()==PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED)gameplayReady.add(id);else if(e.getStatus()!=PlayerResourcePackStatusEvent.Status.ACCEPTED&&e.getStatus()!=PlayerResourcePackStatusEvent.Status.DOWNLOADED) {gameplayReady.remove(id);gameplayOffered.remove(id);}}
private boolean present(Player p,String title,String description,Inventory inventory,Map<Integer,Runnable> actions,GuiSession suppliedGate){
if(framework==null||!engine.isEnabled()||!p.isOnline()||BedrockForms.isBedrock(p))return false;
if(!p.getWorld().getName().equals("guild_lobby")&&!gameplayReady.contains(p.getUniqueId()))return false;

View file

@ -0,0 +1,9 @@
package com.dunerealms.gui;
/** Immutable built menu overlay. Server-owned world packs are never selected or replaced here. */
final class MenuPackPolicy {
record Pin(String url,String sha1,String sha256,String source){}
static Pin select(String url,String sha1,String sha256,String source){
if(url==null||sha1==null||sha256==null||source==null||!source.matches("[a-f0-9]{40}")||!sha1.matches("[a-f0-9]{40}")||!sha256.matches("[a-f0-9]{64}"))return null;
return url.equals("https://www.dunerealms.com/downloads/DuneRealms-Menu-"+source+".zip")?new Pin(url,sha1,sha256,source):null;
}
}

View file

@ -0,0 +1,5 @@
package com.dunerealms.gui;
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;
class MenuPackPolicyTest {
@Test void onlyExactImmutableBuiltOverlayIsAccepted(){String source="a".repeat(40),sha="b".repeat(40),sha256="c".repeat(64);String url="https://www.dunerealms.com/downloads/DuneRealms-Menu-"+source+".zip";assertNotNull(MenuPackPolicy.select(url,sha,sha256,source));assertNull(MenuPackPolicy.select(url,sha,sha256,"d".repeat(40)));assertNull(MenuPackPolicy.select("https://www.dunerealms.com/downloads/DuneRealms-Network-Artwork-v6.zip",sha,sha256,source));assertNull(MenuPackPolicy.select(url,"bad",sha256,source));assertNull(MenuPackPolicy.select(null,sha,sha256,source));}
}

View file

@ -0,0 +1,5 @@
# MCGUI client transport input
Client resource assets generated by the existing verified MCGUI0.8.6 runtime (runtime SHA25669a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300) in the owner-provided isolated Paper26.2 environment. This is the redistributable client pack, not the private vendor plugin JAR.
Input SHA256eb7eacfbb50679b83a4da4a671cb565de2d67b02ee8525d05e345a17cdbe3721;166638bytes;116entries. Includes explicit26.2 overlays at resource-pack formats88–96. The builder preserves all transport entries and adds only the reviewed dunerealms namespace. No vanilla world material textures are supplied.

Binary file not shown.

View file

@ -0,0 +1,38 @@
"""Build the separately stacked MCGUI transport + namespaced DuneRealms menu/item overlay."""
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import zipfile
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('gameplay_pack', ROOT / 'tools/build-gameplay-resourcepack.py')
shared = importlib.util.module_from_spec(spec); spec.loader.exec_module(shared)
INPUT = ROOT / 'network/resource-pack/mcgui/transport-0.8.6.zip'
INPUT_SHA256 = 'eb7eacfbb50679b83a4da4a671cb565de2d67b02ee8525d05e345a17cdbe3721'
def build(output, source_commit, transport=INPUT):
transport = Path(transport)
if hashlib.sha256(transport.read_bytes()).hexdigest() != INPUT_SHA256:
raise ValueError('MCGUI client transport differs from reviewed input')
base = shared.entries(transport)
if not any(name.startswith('uiengine_26_2/assets/minecraft/shaders/') for name in base):
raise ValueError('Missing actual26.2 fullscreen transport')
output = Path(output); result = shared.build(transport, output)
actual = shared.entries(output)
if any(actual[name] != data for name, data in base.items()):
raise ValueError('MCGUI transport changed')
if any('/textures/block/' in name or '/textures/entity/' in name or '/models/block/' in name for name in actual):
raise ValueError('Menu overlay must not contain world material/entity replacements')
result.update(sourceCommit=source_commit, transportSha256=INPUT_SHA256, stacked=True)
output.with_suffix('.manifest.json').write_text(json.dumps(result, indent=2) + '\n')
return result
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--source', required=True)
args = parser.parse_args(); print(json.dumps(build(args.output, args.source), indent=2))

View file

@ -7,12 +7,14 @@ import argparse
import datetime
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import zipfile
from plugin_menu_pack import load_menu, menu_url, verify_public_menu, config_payloads
PRIVATE_PREREQUISITES = {
@ -26,6 +28,12 @@ def digest(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def set_owner(path, owner, mode):
Path(path).chmod(mode)
if hasattr(os, 'chown'):
os.chown(path, owner.st_uid, owner.st_gid)
def identity(path):
with zipfile.ZipFile(path) as jar:
text = jar.read('plugin.yml').decode('utf-8')
@ -72,6 +80,10 @@ def plan(artifacts, inventory, expected_source):
if identity(path) != {field: expected[field] for field in ('name', 'version', 'main')}:
raise ValueError('Private prerequisite identity differs: ' + key)
prerequisites[key] = dict(expected, source=str(path.resolve()), privatePrerequisite=True)
menu = None
if inventory.get('menuPack') is not None:
_, menu = load_menu(artifacts, expected_source)
verify_public_menu(inventory['menuPack']['url'], menu)
servers, ids, roots, units = [], set(), set(), set()
for server in inventory['servers']:
sid, unit = server['id'], server['serviceUnit']
@ -114,8 +126,23 @@ def plan(artifacts, inventory, expected_source):
name = entry['filename']
if (plugins / name).exists() and name not in old_names:
raise ValueError('Artifact filename collides with another plugin: ' + name)
configurations = []
if 'dunemenus' in wanted:
if menu is None:
raise ValueError('DuneMenus requires a verified published built menu overlay')
for relative, content in config_payloads(menu).items():
target = plugins / relative
if target.is_symlink() or target.parent.is_symlink():
raise ValueError('Menu configuration path must not be a symlink')
previous_hash = None
if target.exists():
if not target.read_text().startswith('# Managed by DuneRealms plugin CI;'):
raise ValueError('Existing unmanaged menu configuration requires review')
previous_hash = digest(target)
configurations.append({'path': relative, 'content': content,
'sha256': hashlib.sha256(content.encode()).hexdigest(), 'previousSha256': previous_hash})
servers.append({'id': sid, 'root': str(root), 'serviceUnit': unit,
'artifacts': chosen, 'previous': previous})
'artifacts': chosen, 'previous': previous, 'configurations': configurations})
ids.add(sid); roots.add(root); units.add(unit)
if not servers:
raise ValueError('Explicit fleet inventory is empty')
@ -143,6 +170,12 @@ def apply(deployment, backup_root, control=systemctl):
for old in server['previous']:
if digest(Path(server['root']) / 'plugins' / old['filename']) != old['sha256']:
raise ValueError('Installed plugin changed after planning')
for config in server.get('configurations', []):
target = Path(server['root']) / 'plugins' / config['path']
current = digest(target) if target.exists() else None
if current != config['previousSha256']:
raise ValueError('Menu configuration changed after planning')
receipts = []
for server in deployment['servers']:
unit = server['serviceUnit']; plugins = Path(server['root']) / 'plugins'
@ -152,6 +185,12 @@ def apply(deployment, backup_root, control=systemctl):
shutil.copy2(plugins / old['filename'], backup / old['filename'])
if digest(backup / old['filename']) != old['sha256']:
raise RuntimeError('Backup verification failed')
for config in server.get('configurations', []):
if config['previousSha256'] is not None:
saved = backup / 'configurations' / config['path']; saved.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(plugins / config['path'], saved)
if digest(saved) != config['previousSha256']:
raise RuntimeError('Menu configuration backup verification failed')
record = backup / 'receipt.json'; record.write_text(json.dumps(receipt, indent=2))
active = control('is-active', '--quiet', unit).returncode == 0
installed = []
@ -163,16 +202,25 @@ def apply(deployment, backup_root, control=systemctl):
raise RuntimeError('Refusing to replace plugins unless the service is fully stopped')
for entry in server['artifacts']:
fd, temporary = tempfile.mkstemp(prefix='.dune-ci-', suffix='.tmp', dir=plugins)
import os
os.close(fd)
temporary = Path(temporary)
try:
shutil.copy2(entry['source'], temporary)
if digest(temporary) != entry['sha256']:
raise RuntimeError('Staged checksum differs')
set_owner(temporary, plugins.stat(), 0o640)
temporary.replace(plugins / entry['filename']); installed.append(entry['filename'])
finally:
temporary.unlink(missing_ok=True)
for config in server.get('configurations', []):
target = plugins / config['path']; new_parent = not target.parent.exists()
target.parent.mkdir(parents=True, exist_ok=True)
if new_parent:
set_owner(target.parent, plugins.stat(), 0o750)
target.write_bytes(config['content'].encode())
set_owner(target, plugins.stat(), 0o640)
if digest(target) != config['sha256']:
raise RuntimeError('Written menu configuration hash differs')
for old in server['previous']:
if old['filename'] not in installed:
(plugins / old['filename']).unlink()
@ -192,6 +240,14 @@ def apply(deployment, backup_root, control=systemctl):
(plugins / name).unlink(missing_ok=True)
for old in server['previous']:
shutil.copy2(backup / old['filename'], plugins / old['filename'])
for config in server.get('configurations', []):
target = plugins / config['path']
if config['previousSha256'] is None:
target.unlink(missing_ok=True)
else:
shutil.copy2(backup / 'configurations' / config['path'], target)
if digest(target) != config['previousSha256']:
raise RuntimeError('Menu configuration rollback hash differs')
restarted = not active or control('start', unit).returncode == 0
receipt.update(status='rolled-back', error=str(error), rollbackStartAccepted=restarted)
record.write_text(json.dumps(receipt, indent=2)); raise

55
tools/plugin_menu_pack.py Normal file
View file

@ -0,0 +1,55 @@
"""Shared immutable client-pack verification for built publisher/installer tools."""
import hashlib
import json
import re
from pathlib import Path
import urllib.request
import zipfile
def sha(path, algorithm='sha256'):
return hashlib.new(algorithm, Path(path).read_bytes()).hexdigest()
def load_menu(artifacts, source):
if not re.fullmatch(r'[a-f0-9]{40}', source):
raise ValueError('Menu source must be an exact commit SHA')
name = 'DuneRealms-Menu-' + source + '.zip'
root = Path(artifacts)
data = json.loads((root / name.replace('.zip', '.manifest.json')).read_text())
path = root / name
if data.get('sourceCommit') != source or data.get('filename') != name or not data.get('stacked'):
raise ValueError('Menu pack source/filename/stacking contract differs')
if sha(path) != data['sha256'] or sha(path, 'sha1') != data['sha1']:
raise ValueError('Built menu pack checksum differs')
with zipfile.ZipFile(path) as archive:
names = archive.namelist()
if 'pack.mcmeta' not in names or not any(n.startswith('uiengine_26_2/assets/minecraft/shaders/') for n in names):
raise ValueError('Menu pack lacks client root/26.2 transport')
if any('/textures/block/' in n or '/textures/entity/' in n for n in names):
raise ValueError('Menu pack would replace world textures')
return path, data
def menu_url(source):
return 'https://www.dunerealms.com/downloads/DuneRealms-Menu-' + source + '.zip'
def verify_public_menu(url, data):
if url != menu_url(data['sourceCommit']):
raise ValueError('Menu URL must be the exact immutable built release URL')
with urllib.request.urlopen(url, timeout=30) as response:
if response.geturl() != url:
raise ValueError('Menu publication must not redirect')
payload = response.read(data['bytes'] + 1)
if len(payload) != data['bytes'] or hashlib.sha256(payload).hexdigest() != data['sha256']:
raise ValueError('Published menu pack bytes differ from CI build')
def config_payloads(data):
url = menu_url(data['sourceCommit'])
marker = '# Managed by DuneRealms plugin CI; immutable menu overlay.\n'
engine = marker + 'telemetry: false\nupdate-check: false\nallow-web: false\nresource-pack:\n mode: external\n public-url: ""\n bind: 127.0.0.1\n port: 0\n'
pin = marker + ''.join(key + ': ' + json.dumps(value) + '\n' for key, value in (
('url', url), ('sha1', data['sha1']), ('sha256', data['sha256']), ('source-commit', data['sourceCommit'])))
return {'MCGUI/config.yml': engine, 'DunerealmsGUI/menu-pack.yml': pin}

View file

@ -0,0 +1,83 @@
"""Publish only the selected immutable CI menu ZIP into the verified existing nginx downloads contract."""
import argparse
import datetime
import json
from pathlib import Path
import shutil
import subprocess
import tempfile
from plugin_menu_pack import load_menu, menu_url, sha
def control(*args):
return subprocess.run(args, capture_output=True, text=True, check=False)
def publish(artifacts, source, store, snippet, apply=False, run=control):
pack, data = load_menu(artifacts, source)
store, snippet = Path(store).resolve(strict=True), Path(snippet).resolve(strict=True)
if not store.is_dir() or not snippet.is_file():
raise ValueError('Verified downloads store and included snippet must already exist')
destination = store / pack.name
if destination.is_symlink() or (destination.exists() and sha(destination) != data['sha256']):
raise ValueError('Immutable publication filename has conflicting bytes')
before = snippet.read_bytes()
route = ('\n# DuneRealms CI menu overlay ' + source + '\nlocation = /downloads/' + pack.name + ' {\n'
' alias ' + json.dumps(str(destination)) + ';\n'
' add_header Cache-Control "public, max-age=31536000, immutable" always;\n'
' add_header X-Content-Type-Options "nosniff" always;\n}\n').encode()
old = before.decode('utf-8')
if 'location = /downloads/' + pack.name in old and route not in before:
raise ValueError('Existing route differs from the reviewed immutable publication')
after = before if route in before else before + route
report = {'sourceCommit': source, 'url': menu_url(source), 'sha1': data['sha1'], 'sha256': data['sha256'],
'destination': str(destination), 'snippetBeforeSha256': __import__('hashlib').sha256(before).hexdigest(),
'snippetAfterSha256': __import__('hashlib').sha256(after).hexdigest(), 'applied': False}
if not apply:
return report
if after == before and destination.exists():
report.update(applied=True, unchanged=True); return report
backup = snippet.with_name(snippet.name + '.before-menu-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ'))
backup.write_bytes(before)
if sha(backup) != report['snippetBeforeSha256']:
raise RuntimeError('Nginx snippet backup differs')
created = not destination.exists()
try:
if created:
with tempfile.NamedTemporaryFile(dir=store, prefix='.dune-menu-', suffix='.tmp', delete=False) as stream:
temp = Path(stream.name)
try:
shutil.copy2(pack, temp)
if sha(temp) != data['sha256']:
raise RuntimeError('Staged client ZIP differs')
temp.chmod(0o644); temp.replace(destination)
finally:
temp.unlink(missing_ok=True)
snippet.write_bytes(after)
if sha(snippet) != report['snippetAfterSha256']:
raise RuntimeError('Written nginx route differs')
if run('nginx', '-t').returncode:
raise RuntimeError('Nginx configuration validation failed')
if run('systemctl', 'reload', 'nginx').returncode:
raise RuntimeError('Nginx reload failed')
except Exception:
snippet.write_bytes(before)
if sha(snippet) != report['snippetBeforeSha256']:
raise RuntimeError('Nginx snippet rollback differs')
if created:
destination.unlink(missing_ok=True)
if run('nginx', '-t').returncode == 0:
run('systemctl', 'reload', 'nginx')
raise
report.update(applied=True, backup=str(backup)); return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--artifacts', required=True); parser.add_argument('--expected-source', required=True)
parser.add_argument('--store', required=True); parser.add_argument('--snippet', required=True)
parser.add_argument('--apply', action='store_true'); args = parser.parse_args()
print(json.dumps(publish(args.artifacts, args.expected_source, args.store, args.snippet, args.apply), indent=2))
if __name__ == '__main__': main()

View file

@ -2,11 +2,13 @@ import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import zipfile
sys.path.insert(0, str(Path(__file__).resolve().parent))
spec = importlib.util.spec_from_file_location('installer', Path(__file__).with_name('install-plugin-fleet.py'))
installer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(installer)

View file

@ -0,0 +1,131 @@
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import zipfile
sys.path.insert(0, str(Path(__file__).resolve().parent))
import plugin_menu_pack as contract
from test_plugin_fleet_install import Service, jar, installer
def module(name, filename):
spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename))
result = importlib.util.module_from_spec(spec); spec.loader.exec_module(result); return result
builder = module('menu_builder', 'build-menu-resourcepack.py')
publisher = module('menu_publisher', 'publish-plugin-menu.py')
SOURCE = 'a' * 40
class MenuPackTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name); self.artifacts = self.root / 'artifacts'; self.artifacts.mkdir()
self.pack = self.artifacts / ('DuneRealms-Menu-' + SOURCE + '.zip')
self.metadata = builder.build(self.pack, SOURCE)
def test_exact_transport_plus_only75_namespaced_assets_preserves_world_layers(self):
base = builder.shared.entries(builder.INPUT); actual = builder.shared.entries(self.pack)
overlay = {p.relative_to(builder.shared.SHARED).as_posix(): p.read_bytes() for p in builder.shared.SHARED.rglob('*') if p.is_file()}
self.assertEqual(len(base), 116); self.assertEqual(len(overlay), 75)
self.assertEqual({key: actual[key] for key in base}, base)
self.assertEqual(set(actual) - set(base), set(overlay))
self.assertTrue(all(name.startswith('assets/dunerealms/') for name in overlay))
self.assertFalse(any('/textures/block/' in name or '/textures/entity/' in name for name in actual))
self.assertEqual(self.metadata['cardMappings'], 389)
first = self.pack.read_bytes(); builder.build(self.pack, SOURCE)
self.assertEqual(first, self.pack.read_bytes())
def test_published_url_and_actual_bytes_are_verified(self):
class Response:
def __enter__(self): return self
def __exit__(self, *args): pass
def geturl(self): return contract.menu_url(SOURCE)
def read(self, limit): return self.payload[:limit]
response = Response(); response.payload = self.pack.read_bytes()
with patch.object(contract.urllib.request, 'urlopen', return_value=response):
contract.verify_public_menu(contract.menu_url(SOURCE), self.metadata)
response.payload = b'wrong'
with self.assertRaises(ValueError): contract.verify_public_menu(contract.menu_url(SOURCE), self.metadata)
with self.assertRaises(ValueError): contract.verify_public_menu('https://example.com/pack.zip', self.metadata)
def test_publisher_is_idempotent_and_preserves_every_existing_route(self):
store = self.root / 'downloads'; store.mkdir(); snippet = self.root / 'routes.conf'
before = b'# existing worldpack routes\nlocation = /downloads/world.zip { return 404; }\n'; snippet.write_bytes(before)
calls = []
def run(*args): calls.append(args); return subprocess.CompletedProcess(args, 0)
result = publisher.publish(self.artifacts, SOURCE, store, snippet)
self.assertFalse(result['applied']); self.assertEqual(snippet.read_bytes(), before)
publisher.publish(self.artifacts, SOURCE, store, snippet, True, run)
self.assertTrue(snippet.read_bytes().startswith(before)); self.assertEqual((store / self.pack.name).read_bytes(), self.pack.read_bytes())
after = snippet.read_bytes(); count = len(calls)
self.assertTrue(publisher.publish(self.artifacts, SOURCE, store, snippet, True, run)['unchanged'])
self.assertEqual(after, snippet.read_bytes()); self.assertEqual(count, len(calls))
(store / self.pack.name).write_bytes(b'conflict')
with self.assertRaises(ValueError): publisher.publish(self.artifacts, SOURCE, store, snippet, True, run)
def test_nginx_failure_restores_config_and_removes_only_new_pack(self):
store = self.root / 'downloads'; store.mkdir(); (store / 'world.zip').write_bytes(b'world')
snippet = self.root / 'routes.conf'; before = b'# world routes\n'; snippet.write_bytes(before)
def fail(*args): return subprocess.CompletedProcess(args, 1)
with self.assertRaises(RuntimeError): publisher.publish(self.artifacts, SOURCE, store, snippet, True, fail)
self.assertEqual(snippet.read_bytes(), before); self.assertFalse((store / self.pack.name).exists())
self.assertEqual((store / 'world.zip').read_bytes(), b'world')
def configuration_plan(self, existing=False):
root = self.root / 'server'; root.mkdir(); plugins = root / 'plugins'; plugins.mkdir()
(root / 'server.properties').write_bytes(b'resource-pack=existing-world.zip\nresource-pack-sha1=unchanged\n')
for name in ('JarvisTranslator', 'DunerealmsGUI', 'MCGUI'):
jar(plugins / (name + '.jar'), name)
jar(self.artifacts / 'DuneMenus.jar', 'DuneMenus', '2.0.1')
entry = dict(installer.identity(self.artifacts / 'DuneMenus.jar'), filename='DuneMenus.jar', sha256=installer.digest(self.artifacts / 'DuneMenus.jar'))
(self.artifacts / 'release-manifest.json').write_text(json.dumps({'sourceCommit': SOURCE, 'plugins': [entry]}))
if existing:
for relative in contract.config_payloads(self.metadata):
target = plugins / relative; target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(b'# Managed by DuneRealms plugin CI; previous release\nold: retained\n')
inventory = {'menuPack': {'url': contract.menu_url(SOURCE)}, 'servers': [{'id': 'test', 'root': str(root.resolve()), 'serviceUnit': 'test.service', 'artifacts': ['DuneMenus.jar']}]}
with patch.object(installer, 'verify_public_menu'):
deployment = installer.plan(self.artifacts, inventory, SOURCE)
return root, plugins, deployment
def test_installer_writes_verified_external_pins_and_never_changes_worldpack(self):
root, plugins, deployment = self.configuration_plan(); before = (root / 'server.properties').read_bytes()
installer.apply(deployment, self.root / 'backup', Service())
for config in deployment['servers'][0]['configurations']:
self.assertEqual(installer.digest(plugins / config['path']), config['sha256'])
engine = (plugins / 'MCGUI/config.yml').read_text()
self.assertIn('telemetry: false', engine); self.assertIn('mode: external', engine); self.assertIn('public-url: ""', engine)
self.assertEqual((root / 'server.properties').read_bytes(), before)
def test_failed_restart_rolls_back_config_bytes_together_with_jars(self):
root, plugins, deployment = self.configuration_plan(); before = (root / 'server.properties').read_bytes()
with self.assertRaises(RuntimeError): installer.apply(deployment, self.root / 'backup', Service(fail_start=True))
self.assertFalse((plugins / 'DuneMenus.jar').exists())
self.assertFalse((plugins / 'MCGUI/config.yml').exists()); self.assertFalse((plugins / 'DunerealmsGUI/menu-pack.yml').exists())
self.assertEqual((root / 'server.properties').read_bytes(), before)
def test_existing_owned_config_is_backed_up_and_restored_exactly(self):
_, plugins, deployment = self.configuration_plan(existing=True)
before = {config['path']: (plugins / config['path']).read_bytes() for config in deployment['servers'][0]['configurations']}
with self.assertRaises(RuntimeError): installer.apply(deployment, self.root / 'backup', Service(fail_start=True))
for relative, payload in before.items():
self.assertEqual((plugins / relative).read_bytes(), payload)
self.assertEqual(next((self.root / 'backup').glob('*/test/configurations/' + relative)).read_bytes(), payload)
def test_reload_failure_restores_route_after_successful_nginx_validation(self):
store = self.root / 'downloads'; store.mkdir(); snippet = self.root / 'routes.conf'
before = b'# existing routes\n'; snippet.write_bytes(before); calls = []
def run(*args):
calls.append(args)
return subprocess.CompletedProcess(args, 1 if len(calls) == 2 else 0)
with self.assertRaises(RuntimeError): publisher.publish(self.artifacts, SOURCE, store, snippet, True, run)
self.assertEqual(calls[0], ('nginx', '-t')); self.assertEqual(calls[1], ('systemctl', 'reload', 'nginx'))
self.assertEqual(snippet.read_bytes(), before); self.assertFalse((store / self.pack.name).exists())
if __name__ == '__main__': unittest.main()