From e4312ce0d35c75a5654344c360bbae3d408795e7 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:11:09 +0100 Subject: [PATCH] Connect the Elytra Reputation quest branch to native acquisition and NPC refining --- DuneRealmsGUI/build.gradle.kts | 28 +- .../java/com/dunerealms/gui/HouseBridge.java | 92 +- .../java/com/dunerealms/gui/QuestMenus.java | 3 + DuneRealmsGUI/src/main/resources/plugin.yml | 54 +- JarvisConnector/build.gradle.kts | 2 +- .../com/dunerealms/jarvis/CraftedFlight.java | 31 + .../dunerealms/jarvis/ExchangeInventory.java | 33 +- .../dunerealms/jarvis/FlightObservations.java | 58 + .../dunerealms/jarvis/ItemDesignPreview.java | 2 + .../dunerealms/jarvis/JarvisTranslator.java | 14 +- .../com/dunerealms/jarvis/NativeKitGrant.java | 5 +- .../dunerealms/jarvis/QuestObservations.java | 13 +- .../com/dunerealms/jarvis/SpiceRefiner.java | 34 + .../src/main/resources/item-templates.json | 7 + JarvisConnector/src/main/resources/plugin.yml | 2 +- .../jarvis/FlightObservationsTest.java | 17 + .../cp-v2/cp-v2-personal-progression.mjs | 2 +- .../cp-v2/cp-v2-pol-quest-catalogue.mjs | 4 +- .../public/cp-v2/cp-v2-progression-dialog.css | 2 + .../public/cp-v2/elytra-quests.mjs | 16 + .../public/item-design-model.mjs | 4 +- .../public/item-metadata-policy.mjs | 4 +- .../public/jarvis-master-keys.mjs | 3 +- .../public/tool-template-policy.mjs | 2 + website/control-panel/server.mjs | 1044 ++++++++--------- .../osticket/dev-jarvis-catalogue.json | 63 +- website/node/elytra-quest-policy.mjs | 5 + website/node/game-quest-events.mjs | 17 +- website/node/game-quests.mjs | 9 +- website/node/progression-pol-runtime.mjs | 6 +- website/node/progression-pol.mjs | 2 + website/node/progression-quests.mjs | 8 + website/tests/elytra-quests.test.mjs | 7 + website/tests/flight-observations.test.mjs | 10 + website/tests/spice-refiner.test.mjs | 3 + 35 files changed, 966 insertions(+), 640 deletions(-) create mode 100644 JarvisConnector/src/main/java/com/dunerealms/jarvis/CraftedFlight.java create mode 100644 JarvisConnector/src/main/java/com/dunerealms/jarvis/FlightObservations.java create mode 100644 JarvisConnector/src/main/java/com/dunerealms/jarvis/SpiceRefiner.java create mode 100644 JarvisConnector/src/test/java/com/dunerealms/jarvis/FlightObservationsTest.java create mode 100644 website/control-panel/public/cp-v2/elytra-quests.mjs create mode 100644 website/node/elytra-quest-policy.mjs create mode 100644 website/tests/elytra-quests.test.mjs create mode 100644 website/tests/flight-observations.test.mjs create mode 100644 website/tests/spice-refiner.test.mjs diff --git a/DuneRealmsGUI/build.gradle.kts b/DuneRealmsGUI/build.gradle.kts index 4cf7fbae..6a9701a3 100644 --- a/DuneRealmsGUI/build.gradle.kts +++ b/DuneRealmsGUI/build.gradle.kts @@ -1,14 +1,14 @@ -plugins { java } -group = "com.dunerealms" -version = "1.1.11" -repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/"); maven("https://repo.opencollab.dev/main/") } -dependencies { - compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") - compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") - testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") - testRuntimeOnly("org.junit.platform:junit-platform-launcher") -} -java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } -tasks.withType { options.encoding = "UTF-8" } -tasks.test { useJUnitPlatform() } -tasks.jar { archiveFileName.set("DunerealmsGUI.jar") } +plugins { java } +group = "com.dunerealms" +version = "1.1.12" +repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/"); maven("https://repo.opencollab.dev/main/") } +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") + compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} +java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) } +tasks.withType { options.encoding = "UTF-8" } +tasks.test { useJUnitPlatform() } +tasks.jar { archiveFileName.set("DunerealmsGUI.jar") } diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/HouseBridge.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/HouseBridge.java index c97d7d49..1432f25c 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/HouseBridge.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/HouseBridge.java @@ -1,46 +1,48 @@ -package com.dunerealms.gui; - -import com.google.gson.JsonObject; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.UUID; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; - -/** Presentation delegates to the one shared translator API; no credentials or HTTP client here. */ -final class HouseBridge { - private final Plugin translator; - private final Method house, world; - HouseBridge() { - translator = Bukkit.getPluginManager().getPlugin("JarvisTranslator"); - if (translator == null || !translator.isEnabled()) throw new IllegalStateException("JarvisTranslator is required"); - try { - house = translator.getClass().getMethod("requestHouse", UUID.class, String.class, int.class, UUID.class); - world = translator.getClass().getMethod("worldOnline", String.class); - } catch (ReflectiveOperationException missing) { throw new IllegalStateException("Translator API unavailable", missing); } - } - private Object call(Method method, Object... args) throws Exception { - if (!translator.isEnabled()) throw new IllegalStateException("Translator unavailable"); - try { return method.invoke(translator, args); } - catch (InvocationTargetException wrapped) { if (wrapped.getCause() instanceof Exception cause) throw cause; throw new IllegalStateException("Translator request failed"); } - } - JsonObject request(UUID player, String faction, int version, UUID requestId) throws Exception { return (JsonObject) call(house, player, faction, version, requestId); } - JsonObject quests(UUID player,JsonObject input)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestQuests",UUID.class,JsonObject.class),player,input);} +package com.dunerealms.gui; + +import com.google.gson.JsonObject; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +/** Presentation delegates to the one shared translator API; no credentials or HTTP client here. */ +final class HouseBridge { + private final Plugin translator; + private final Method house, world; + HouseBridge() { + translator = Bukkit.getPluginManager().getPlugin("JarvisTranslator"); + if (translator == null || !translator.isEnabled()) throw new IllegalStateException("JarvisTranslator is required"); + try { + house = translator.getClass().getMethod("requestHouse", UUID.class, String.class, int.class, UUID.class); + world = translator.getClass().getMethod("worldOnline", String.class); + } catch (ReflectiveOperationException missing) { throw new IllegalStateException("Translator API unavailable", missing); } + } + private Object call(Method method, Object... args) throws Exception { + if (!translator.isEnabled()) throw new IllegalStateException("Translator unavailable"); + try { return method.invoke(translator, args); } + catch (InvocationTargetException wrapped) { if (wrapped.getCause() instanceof Exception cause) throw cause; throw new IllegalStateException("Translator request failed"); } + } + JsonObject request(UUID player, String faction, int version, UUID requestId) throws Exception { return (JsonObject) call(house, player, faction, version, requestId); } + JsonObject quests(UUID player,JsonObject input)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestQuests",UUID.class,JsonObject.class),player,input);} void refreshKits(org.bukkit.entity.Player player)throws Exception{call(translator.getClass().getMethod("refreshKits",org.bukkit.entity.Player.class),player);} - void citizenIntroduction(org.bukkit.entity.Player player)throws Exception{call(translator.getClass().getMethod("citizenIntroduction",org.bukkit.entity.Player.class),player);} - JsonObject itemPreview(UUID player,UUID id,int revision)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestItemPreview",UUID.class,UUID.class,int.class),player,id,revision);} - org.bukkit.inventory.ItemStack buildItemPreview(org.bukkit.entity.Player player,JsonObject data,boolean panels)throws Exception{return (org.bukkit.inventory.ItemStack)call(translator.getClass().getMethod("buildItemPreview",org.bukkit.entity.Player.class,JsonObject.class,boolean.class),player,data,panels);} - JsonObject exchange(UUID player,JsonObject input)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestExchange",UUID.class,JsonObject.class),player,input);} - org.bukkit.inventory.ItemStack exchangeIcon(JsonObject row)throws Exception{return (org.bukkit.inventory.ItemStack)call(translator.getClass().getMethod("exchangeIcon",JsonObject.class),row);} - long exchangePublish(org.bukkit.entity.Player p,JsonObject permit,UUID request,org.bukkit.inventory.ItemStack expected,int slot,int amount,long price)throws Exception{return ((Number)call(translator.getClass().getMethod("exchangePublish",org.bukkit.entity.Player.class,JsonObject.class,UUID.class,org.bukkit.inventory.ItemStack.class,int.class,int.class,long.class),p,permit,request,expected,slot,amount,price)).longValue();} - int exchangeCancel(org.bukkit.entity.Player p,JsonObject permit,UUID request,long id)throws Exception{return ((Number)call(translator.getClass().getMethod("exchangeCancel",org.bukkit.entity.Player.class,JsonObject.class,UUID.class,long.class),p,permit,request,id)).intValue();} - int exchangeDeliver(org.bukkit.entity.Player p)throws Exception{return ((Number)call(translator.getClass().getMethod("exchangeDeliver",org.bukkit.entity.Player.class),p)).intValue();} - JsonObject guild(UUID player,JsonObject input)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestGuild",UUID.class,JsonObject.class),player,input);} - void dispatchGuild(org.bukkit.entity.Player player,JsonObject ticket)throws Exception{call(translator.getClass().getMethod("dispatchGuild",org.bukkit.entity.Player.class,JsonObject.class),player,ticket);} - boolean worldOnline(String name) throws Exception { return Boolean.TRUE.equals(call(world, name)); } - JsonObject organisations(UUID player)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestOrganisations",UUID.class),player);} - org.bukkit.inventory.ItemStack menuItem(org.bukkit.entity.Player player)throws Exception{return (org.bukkit.inventory.ItemStack)call(translator.getClass().getMethod("menuItem",org.bukkit.entity.Player.class),player);} - void addedItem(org.bukkit.entity.Player player,org.bukkit.inventory.ItemStack item,int slot)throws Exception{call(translator.getClass().getMethod("announceItemInventory",org.bukkit.entity.Player.class,org.bukkit.inventory.ItemStack.class,int.class),player,item,slot);} - @SuppressWarnings("unchecked") org.bukkit.inventory.ItemStack lorePreview(String kind,org.bukkit.Material material,String title,java.util.Map facts)throws Exception{return (org.bukkit.inventory.ItemStack)call(translator.getClass().getMethod("formatItemLore",org.bukkit.inventory.ItemStack.class,String.class,String.class,String.class,java.util.Map.class,String.class,String.class),new org.bukkit.inventory.ItemStack(material),kind,title,"Design preview. Not a redeemable instrument.",facts,"Issued values come from its JARVIS key.",null);} - @SuppressWarnings("unchecked") java.util.concurrent.CompletableFuture action(org.bukkit.entity.Player player,JsonObject input)throws Exception{return (java.util.concurrent.CompletableFuture)call(translator.getClass().getMethod("organisationAction",org.bukkit.entity.Player.class,JsonObject.class),player,input);} -} + java.util.UUID refinerNpc(org.bukkit.entity.Player player)throws Exception{return (java.util.UUID)call(translator.getClass().getMethod("refinerNpc",org.bukkit.entity.Player.class),player);} + void refineSpice(org.bukkit.entity.Player player,JsonObject permit)throws Exception{call(translator.getClass().getMethod("refineSpice",org.bukkit.entity.Player.class,JsonObject.class),player,permit);} + void citizenIntroduction(org.bukkit.entity.Player player)throws Exception{call(translator.getClass().getMethod("citizenIntroduction",org.bukkit.entity.Player.class),player);} + JsonObject itemPreview(UUID player,UUID id,int revision)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestItemPreview",UUID.class,UUID.class,int.class),player,id,revision);} + org.bukkit.inventory.ItemStack buildItemPreview(org.bukkit.entity.Player player,JsonObject data,boolean panels)throws Exception{return (org.bukkit.inventory.ItemStack)call(translator.getClass().getMethod("buildItemPreview",org.bukkit.entity.Player.class,JsonObject.class,boolean.class),player,data,panels);} + JsonObject exchange(UUID player,JsonObject input)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestExchange",UUID.class,JsonObject.class),player,input);} + org.bukkit.inventory.ItemStack exchangeIcon(JsonObject row)throws Exception{return (org.bukkit.inventory.ItemStack)call(translator.getClass().getMethod("exchangeIcon",JsonObject.class),row);} + long exchangePublish(org.bukkit.entity.Player p,JsonObject permit,UUID request,org.bukkit.inventory.ItemStack expected,int slot,int amount,long price)throws Exception{return ((Number)call(translator.getClass().getMethod("exchangePublish",org.bukkit.entity.Player.class,JsonObject.class,UUID.class,org.bukkit.inventory.ItemStack.class,int.class,int.class,long.class),p,permit,request,expected,slot,amount,price)).longValue();} + int exchangeCancel(org.bukkit.entity.Player p,JsonObject permit,UUID request,long id)throws Exception{return ((Number)call(translator.getClass().getMethod("exchangeCancel",org.bukkit.entity.Player.class,JsonObject.class,UUID.class,long.class),p,permit,request,id)).intValue();} + int exchangeDeliver(org.bukkit.entity.Player p)throws Exception{return ((Number)call(translator.getClass().getMethod("exchangeDeliver",org.bukkit.entity.Player.class),p)).intValue();} + JsonObject guild(UUID player,JsonObject input)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestGuild",UUID.class,JsonObject.class),player,input);} + void dispatchGuild(org.bukkit.entity.Player player,JsonObject ticket)throws Exception{call(translator.getClass().getMethod("dispatchGuild",org.bukkit.entity.Player.class,JsonObject.class),player,ticket);} + boolean worldOnline(String name) throws Exception { return Boolean.TRUE.equals(call(world, name)); } + JsonObject organisations(UUID player)throws Exception{return (JsonObject)call(translator.getClass().getMethod("requestOrganisations",UUID.class),player);} + org.bukkit.inventory.ItemStack menuItem(org.bukkit.entity.Player player)throws Exception{return (org.bukkit.inventory.ItemStack)call(translator.getClass().getMethod("menuItem",org.bukkit.entity.Player.class),player);} + void addedItem(org.bukkit.entity.Player player,org.bukkit.inventory.ItemStack item,int slot)throws Exception{call(translator.getClass().getMethod("announceItemInventory",org.bukkit.entity.Player.class,org.bukkit.inventory.ItemStack.class,int.class),player,item,slot);} + @SuppressWarnings("unchecked") org.bukkit.inventory.ItemStack lorePreview(String kind,org.bukkit.Material material,String title,java.util.Map facts)throws Exception{return (org.bukkit.inventory.ItemStack)call(translator.getClass().getMethod("formatItemLore",org.bukkit.inventory.ItemStack.class,String.class,String.class,String.class,java.util.Map.class,String.class,String.class),new org.bukkit.inventory.ItemStack(material),kind,title,"Design preview. Not a redeemable instrument.",facts,"Issued values come from its JARVIS key.",null);} + @SuppressWarnings("unchecked") java.util.concurrent.CompletableFuture action(org.bukkit.entity.Player player,JsonObject input)throws Exception{return (java.util.concurrent.CompletableFuture)call(translator.getClass().getMethod("organisationAction",org.bukkit.entity.Player.class,JsonObject.class),player,input);} +} diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/QuestMenus.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/QuestMenus.java index a3219819..92932853 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/QuestMenus.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/QuestMenus.java @@ -64,8 +64,11 @@ final class QuestMenus implements Listener { else if(row.has("cooldownUntil")&&!row.get("cooldownUntil").isJsonNull()&&row.get("cooldownUntil").getAsLong()>System.currentTimeMillis())put(screen,31,"Mission cooling down","Available after "+java.time.Instant.ofEpochMilli(row.get("cooldownUntil").getAsLong()),Material.CLOCK,null); else if(yes(row,"canStart")&&!state.equals("active")&&!state.equals("claimed")&&!state.equals("completed"))put(screen,31,"Start mission","Accept this objective through J.A.R.V.I.S.",Material.LIME_DYE,()->act(p,kind,branch,page,row,"start")); else put(screen,31,state.equals("claimed")?"Reward claimed":"Awaiting verified progress","No reward can be issued from an unverified objective",Material.GRAY_DYE,null); + if(kind.equals("pol")&&Set.of("POL-ELYTRA-REFINE","POL-ELYTRA-CONTAMINATE").contains(text(row,"id",""))&&(yes(row,"canStart")||Set.of("active","completed","claimed").contains(state)))put(screen,33,"Refine at NPC","Stand near an Arrakis Smuggler.\nTurn in the ingredients shown in this quest.",Material.ORANGE_DYE,()->refine(p,kind,data,branch,page,row)); + if(row.has("recipe")&&!row.get("recipe").isJsonNull())put(screen,22,"Revealed recipe","Craft on Arrakis · Very Rare · MK XI\nNetherite | Membrane | Netherite\nIron | Diamond | Iron\nContaminated spice | Membrane | Contaminated spice",Material.ELYTRA,null); put(screen,45,"Back","Mission branch",Material.ARROW,()->quests(p,kind,data,branch,page));put(screen,49,"Refresh","Read current progress",Material.CLOCK,()->load(p,kind,branch,text(row,"id",""),page));show(p,screen); } + private void refine(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){try{var input=new JsonObject();input.addProperty("action","prepare_refine");input.addProperty("kind","pol");input.addProperty("definitionId",text(row,"id",""));input.addProperty("requestId",UUID.randomUUID().toString());input.addProperty("npcUuid",bridge.refinerNpc(p).toString());input.addProperty("confirmed",true);request(p,input,permit->{try{bridge.refineSpice(p,permit);p.sendMessage(Component.text("Spice refined. Your quest receipt is queued for confirmation.",NamedTextColor.GREEN));load(p,kind,branch,text(row,"id",""),page);}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Refinement unavailable. Reopen the quest.":failure.getMessage(),NamedTextColor.RED));}});}catch(Exception failure){p.sendMessage(Component.text(failure.getMessage()==null?"Visit an Arrakis Smuggler first.":failure.getMessage(),NamedTextColor.RED));}} private void introduction(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){ var screen=panel(p,"Imperial Citizen briefing"); put(screen,13,"Welcome, Imperial Citizen","Your House determines normal travel authority.\nGuild travel uses boarding windows and your central bank.\nClan and company actions follow current deeds.\nBlue missions require ingame actions or item turn-ins.\nWebsite missions use your linked website account.\nRead your Mentat Report for current news and duties.",Material.WRITTEN_BOOK,null); diff --git a/DuneRealmsGUI/src/main/resources/plugin.yml b/DuneRealmsGUI/src/main/resources/plugin.yml index cb1db574..64845e0d 100644 --- a/DuneRealmsGUI/src/main/resources/plugin.yml +++ b/DuneRealmsGUI/src/main/resources/plugin.yml @@ -1,27 +1,27 @@ -name: DunerealmsGUI -main: com.dunerealms.gui.DuneGUI -version: 1.1.11 -api-version: '1.21.8' -depend: [JarvisTranslator] -softdepend: [DuneLobby, DuneCore, DuneEss, DuneNPC, Vault, floodgate, ViaVersion] -commands: - exchange: - description: Open the central bank Exchange to buy or sell items - clan: - description: Open your key-linked clan panel - company: - description: Open your key-linked company panel - polgui: - description: Open your current political office panel - guildtravel: - description: Book or cancel twenty-minute Imperial passage to your House world - drscoreboard: - description: Toggle your private Personal XP, Reputation, bank and organisation scoreboard - house: - description: Open the five-House allegiance selector - aliases: [houses] - mentat: - description: Open your current House adviser - drgui: - description: Open the DuneRealms lobby services - aliases: [navigator] +name: DunerealmsGUI +main: com.dunerealms.gui.DuneGUI +version: 1.1.12 +api-version: '1.21.8' +depend: [JarvisTranslator] +softdepend: [DuneLobby, DuneCore, DuneEss, DuneNPC, Vault, floodgate, ViaVersion] +commands: + exchange: + description: Open the central bank Exchange to buy or sell items + clan: + description: Open your key-linked clan panel + company: + description: Open your key-linked company panel + polgui: + description: Open your current political office panel + guildtravel: + description: Book or cancel twenty-minute Imperial passage to your House world + drscoreboard: + description: Toggle your private Personal XP, Reputation, bank and organisation scoreboard + house: + description: Open the five-House allegiance selector + aliases: [houses] + mentat: + description: Open your current House adviser + drgui: + description: Open the DuneRealms lobby services + aliases: [navigator] diff --git a/JarvisConnector/build.gradle.kts b/JarvisConnector/build.gradle.kts index d5fb9e86..6a89738a 100644 --- a/JarvisConnector/build.gradle.kts +++ b/JarvisConnector/build.gradle.kts @@ -1,6 +1,6 @@ plugins { java } group = "com.dunerealms" -version = "0.5.20" +version = "0.5.21" repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") } dependencies { compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/CraftedFlight.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/CraftedFlight.java new file mode 100644 index 00000000..cd598c86 --- /dev/null +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/CraftedFlight.java @@ -0,0 +1,31 @@ +package com.dunerealms.jarvis; +import org.bukkit.*; +import org.bukkit.event.*; +import org.bukkit.event.inventory.*; +import org.bukkit.event.player.PlayerRecipeDiscoverEvent; +import org.bukkit.event.server.ServerLoadEvent; +import org.bukkit.inventory.*; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.plugin.Plugin; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.*; +import java.util.List; +/** Native crafting consumes ingredients; custom spice identity and planet are revalidated. */ +final class CraftedFlight implements Listener { + static final NamespacedKey KEY=new NamespacedKey("dunerealms","elytra"),ENGINE=new NamespacedKey("executableitems","ei-id"); + CraftedFlight(Plugin plugin){Bukkit.getPluginManager().registerEvents(this,plugin);} + static boolean world(String name){return "arrakis".equals(name);} + static ItemStack result(){var item=new ItemStack(Material.ELYTRA);var m=item.getItemMeta();m.displayName(Component.text("Elytra",NamedTextColor.DARK_PURPLE).decoration(TextDecoration.ITALIC,false));m.lore(List.of(Component.text("VERY RARE | MK XI",NamedTextColor.DARK_PURPLE).decoration(TextDecoration.ITALIC,false),Component.text("S1 · FLIGHT EQUIPMENT",NamedTextColor.GRAY).decoration(TextDecoration.ITALIC,false),Component.text("Forged above the sands. Made for distant skies.",NamedTextColor.GRAY).decoration(TextDecoration.ITALIC,true))); + var p=m.getPersistentDataContainer();p.set(ENGINE,PersistentDataType.STRING,"dr_s1_elytra_crafted_v2");p.set(ItemMetadataOverlay.QUALITY,PersistentDataType.STRING,"very_rare");p.set(ItemMetadataOverlay.MARK,PersistentDataType.STRING,"11");p.set(ItemMetadataOverlay.CLASS,PersistentDataType.STRING,"flight-equipment");p.set(ItemMetadataOverlay.POLICY,PersistentDataType.STRING,ItemMetadataPolicy.VERSION);m.addEnchant(org.bukkit.enchantments.Enchantment.UNBREAKING,3,true);m.addEnchant(org.bukkit.enchantments.Enchantment.MENDING,1,true);item.setItemMeta(m);return item; + } + @EventHandler public void loaded(ServerLoadEvent e){Bukkit.removeRecipe(KEY);var r=new ShapedRecipe(KEY,result());r.shape("NMN","IDI","CMC");r.setIngredient('N',Material.NETHERITE_INGOT);r.setIngredient('M',Material.PHANTOM_MEMBRANE);r.setIngredient('I',Material.IRON_INGOT);r.setIngredient('D',Material.DIAMOND);r.setIngredient('C',Material.ORANGE_DYE);if(!Bukkit.addRecipe(r))throw new IllegalStateException("Elytra recipe registration failed");} + private static boolean ours(Recipe r){return r instanceof Keyed k&&KEY.equals(k.getKey());} + private static boolean contaminated(ItemStack item){return item!=null&&item.getType()==Material.ORANGE_DYE&&item.hasItemMeta()&&"polluted_refined_spice".equals(item.getItemMeta().getPersistentDataContainer().get(ENGINE,PersistentDataType.STRING));} + private static boolean inputs(ItemStack[] a){return a.length==9&&contaminated(a[6])&&contaminated(a[8]);} + @EventHandler(priority=EventPriority.HIGHEST) public void prepare(PrepareItemCraftEvent e){if(ours(e.getRecipe()))e.getInventory().setResult(world(e.getView().getPlayer().getWorld().getName())&&inputs(e.getInventory().getMatrix())?result():null);} + @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void craft(CraftItemEvent e){if(ours(e.getRecipe())&&(!world(e.getWhoClicked().getWorld().getName())||!inputs(e.getInventory().getMatrix()))){e.setCancelled(true);e.getInventory().setResult(null);}} + @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void automated(org.bukkit.event.block.CrafterCraftEvent e){if(ours(e.getRecipe())&&(!world(e.getBlock().getWorld().getName())||!(e.getBlock().getState() instanceof org.bukkit.block.Crafter c)||!inputs(c.getInventory().getContents())))e.setCancelled(true);} + // The dossier reveals this recipe on the final quest. Do not leak it through + // automatic recipe-book discovery while earlier steps are still locked. + @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) public void discovery(PlayerRecipeDiscoverEvent e){if(KEY.equals(e.getRecipe()))e.setCancelled(true);} +} diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/ExchangeInventory.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/ExchangeInventory.java index 59a135c2..294a8b2d 100644 --- a/JarvisConnector/src/main/java/com/dunerealms/jarvis/ExchangeInventory.java +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/ExchangeInventory.java @@ -16,7 +16,9 @@ import org.bukkit.persistence.PersistentDataType; * The website owns bank payments; this class never accesses a wallet or bank. */ final class ExchangeInventory { private final Consumer stamp; - ExchangeInventory(Consumer stamp){this.stamp=stamp;} + private final String server; + private static final List SERVERS=List.of("lobby","arrakis","caladan","giedi-prime","kaitain","sigma-draconis-iv"); + ExchangeInventory(Consumer stamp,String server){this.stamp=stamp;this.server=server;if(!SERVERS.contains(server))throw new IllegalArgumentException("Unknown native server");} static String hash(String value){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));}catch(java.security.NoSuchAlgorithmException impossible){throw new IllegalStateException(impossible);}} static ItemStack decode(String material,String payload){ ItemStack item; @@ -85,12 +87,12 @@ final class ExchangeInventory { String material=r.getString("material"),payload=r.getString("payload");if(!hash(material+"\n"+(payload==null?"":payload)).equals(r.getString("payload_hash")))throw new IllegalArgumentException("A stored Exchange item needs staff review."); ItemStack unit=decode(material,payload);stamp.accept(unit);int quantity=r.getInt("quantity");if(quantity<1||quantity>64)throw new SQLException("Invalid delivery quantity");if(!fits(p,unit,quantity))continue; try(var done=prepare(c,"UPDATE dune_exchange_deliveries SET state='delivered',delivered_at=? WHERE id=? AND buyer_uuid=? AND state='queued'")){done.setLong(1,System.currentTimeMillis());done.setString(2,r.getString("id"));done.setString(3,p.getUniqueId().toString());if(done.executeUpdate()!=1)throw new SQLException("Delivery changed");} - give(p,unit,quantity);delivered+=quantity; + give(p,unit,quantity);if(unit.getType()==Material.ELYTRA)paidFlight(c,p,UUID.fromString(r.getString("id")));delivered+=quantity; }} }return delivered; }); } - int grantKit(Player p,UUID receipt,String fingerprint,List items)throws Exception{ + int grantKit(Player p,UUID receipt,String fingerprint,List items,boolean purchased)throws Exception{ if(items.isEmpty()||items.size()>36||!fingerprint.matches("[a-f0-9]{64}"))throw new IllegalArgumentException("Invalid kit delivery"); return atomic(p,c->{ if(previous(c,receipt,p.getUniqueId(),"kit-grant",fingerprint)!=null)return 0; @@ -101,12 +103,35 @@ final class ExchangeInventory { give(p,item,item.getAmount()); count+=item.getAmount(); } - record(c,receipt,p.getUniqueId(),"kit-grant",fingerprint,0);return count; + record(c,receipt,p.getUniqueId(),"kit-grant",fingerprint,0);if(purchased&&items.stream().anyMatch(i->i.getType()==Material.ELYTRA))paidFlight(c,p,receipt);return count; }); } private static Long previous(Connection c,UUID id,UUID actor,String kind,String fingerprint)throws SQLException{ try(var q=prepare(c,"SELECT actor_uuid,kind,fingerprint,listing_id FROM dune_exchange_inventory_ops WHERE id=? FOR UPDATE")){q.setString(1,id.toString());try(var r=q.executeQuery()){if(!r.next())return null;if(!actor.toString().equals(r.getString("actor_uuid"))||!kind.equals(r.getString("kind"))||!fingerprint.equals(r.getString("fingerprint")))throw new IllegalArgumentException("This Exchange operation reference was already used.");return r.getLong("listing_id");}} } + record Refined(UUID id,boolean contaminated,long occurredAt){} + record PaidFlight(UUID id,String server,long occurredAt){} + private void paidFlight(Connection c,Player p,UUID delivery)throws SQLException{UUID id=UUID.nameUUIDFromBytes(("flight-paid:"+delivery).getBytes(StandardCharsets.UTF_8));String fingerprint=hash(p.getUniqueId()+"\n"+delivery);if(previous(c,id,p.getUniqueId(),"flight-paid",fingerprint)==null)record(c,id,p.getUniqueId(),"flight-paid",fingerprint,SERVERS.indexOf(server));} + List paidFlightReceipts(Player p)throws Exception{return atomic(p,c->{var rows=new ArrayList();try(var q=prepare(c,"SELECT id,listing_id,created_at FROM dune_exchange_inventory_ops WHERE actor_uuid=? AND kind='flight-paid' ORDER BY created_at DESC LIMIT 100")){q.setString(1,p.getUniqueId().toString());try(var r=q.executeQuery()){while(r.next()){int origin=r.getInt(2);if(origin<0||origin>=SERVERS.size())throw new SQLException("Invalid flight receipt origin");rows.add(new PaidFlight(UUID.fromString(r.getString(1)),SERVERS.get(origin),r.getLong(3)));}}}return rows;});} + Refined refine(Player p,UUID request,boolean contaminated,ItemStack output)throws Exception{ + String fingerprint=hash(p.getUniqueId()+"\nrefine-v1\n"+contaminated); + return atomic(p,c->{ + Long prior=previous(c,request,p.getUniqueId(),"refine",fingerprint); + if(prior!=null){try(var q=prepare(c,"SELECT created_at FROM dune_exchange_inventory_ops WHERE id=?")){q.setString(1,request.toString());try(var r=q.executeQuery()){if(!r.next())throw new SQLException("Refinement receipt unavailable");return new Refined(request,contaminated,r.getLong(1));}}} + var storage=p.getInventory().getStorageContents();int spice=0,scrap=0; + for(var item:storage){if(refineInput(item,contaminated))spice+=item.getAmount();if(item!=null&&item.getType()==Material.NETHERITE_SCRAP)scrap+=item.getAmount();} + if(spice<2||contaminated&&scrap<2)throw new IllegalArgumentException(contaminated?"Bring 2 refined spice and 2 netherite scraps.":"Bring 2 mined Melange spice."); + int remaining=2,metal=contaminated?2:0;for(int i=0;i0&&refineInput(item,contaminated)){remove=Math.min(remaining,item.getAmount());remaining-=remove;}else if(metal>0&&item.getType()==Material.NETHERITE_SCRAP){remove=Math.min(metal,item.getAmount());metal-=remove;}if(remove>0){item=item.clone();item.setAmount(item.getAmount()-remove);storage[i]=item.isEmpty()?null:item;}} + p.getInventory().setStorageContents(storage);stamp.accept(output);if(!fits(p,output,2))throw new IllegalArgumentException("Make room for 2 spice before refining.");give(p,output,2);record(c,request,p.getUniqueId(),"refine",fingerprint,contaminated?1:0); + try(var q=prepare(c,"SELECT created_at FROM dune_exchange_inventory_ops WHERE id=?")){q.setString(1,request.toString());try(var r=q.executeQuery()){if(!r.next())throw new SQLException("Refinement receipt unavailable");return new Refined(request,contaminated,r.getLong(1));}} + }); + } + List refinedReceipts(Player p)throws Exception{return atomic(p,c->{var results=new ArrayList();try(var q=prepare(c,"SELECT id,listing_id,created_at FROM dune_exchange_inventory_ops WHERE actor_uuid=? AND kind='refine' AND created_at>=? ORDER BY created_at DESC LIMIT 100")){q.setString(1,p.getUniqueId().toString());q.setLong(2,System.currentTimeMillis()-java.util.concurrent.TimeUnit.DAYS.toMillis(90));try(var r=q.executeQuery()){while(r.next())results.add(new Refined(UUID.fromString(r.getString(1)),r.getLong(2)==1,r.getLong(3)));}}return results;});} + private static boolean refineInput(ItemStack item,boolean contaminated){ + if(item==null||item.getType()!=Material.ORANGE_DYE||!item.hasItemMeta())return false;var data=item.getItemMeta().getPersistentDataContainer(); + String engine=data.get(new NamespacedKey("executableitems","ei-id"),PersistentDataType.STRING); + return contaminated?"refined_spice".equals(engine):(engine==null||engine.equals("spice"))&&"spice".equals(data.get(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING)); + } private static void record(Connection c,UUID id,UUID actor,String kind,String fingerprint,long listing)throws SQLException{ try(var q=prepare(c,"INSERT INTO dune_exchange_inventory_ops(id,actor_uuid,kind,fingerprint,listing_id,created_at) VALUES(?,?,?,?,?,?)")){q.setString(1,id.toString());q.setString(2,actor.toString());q.setString(3,kind);q.setString(4,fingerprint);q.setLong(5,listing);q.setLong(6,System.currentTimeMillis());q.executeUpdate();} } diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/FlightObservations.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/FlightObservations.java new file mode 100644 index 00000000..0c82549b --- /dev/null +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/FlightObservations.java @@ -0,0 +1,58 @@ +package com.dunerealms.jarvis; + +import java.util.*; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.inventory.FurnaceExtractEvent; +import org.bukkit.event.entity.*; +import org.bukkit.event.inventory.CraftItemEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.plugin.Plugin; + +/** Reuses the durable quest receipt consumer; observes successful native item acquisition. */ +final class FlightObservations implements Listener { + private final Plugin plugin;private final QuestObservations receipts;private final String server; + private final Set crafts=new HashSet<>(); + private static final NamespacedKey PLACED=new NamespacedKey("dunerealms","player_elytra_frame"),END_PROOF=new NamespacedKey("dunerealms","end_ship_elytra"); + FlightObservations(Plugin plugin,QuestObservations receipts,String server){this.plugin=plugin;this.receipts=receipts;this.server=server;Bukkit.getPluginManager().registerEvents(this,plugin);} + private boolean eligible(Player p){return p.isOnline()&&!p.isDead()&&(p.getGameMode()==GameMode.SURVIVAL||p.getGameMode()==GameMode.ADVENTURE);} + static String metric(String server,World.Environment dimension,Material item,boolean furnace){ + if(server.equals("giedi-prime")&&dimension==World.Environment.NETHER)return switch(item){case ANCIENT_DEBRIS->furnace?null:"flight_debris";case NETHERITE_SCRAP->furnace?"flight_scrap":null;case GOLD_INGOT->"flight_gold";case NETHERITE_INGOT->furnace?null:"flight_netherite";default->null;}; + if(dimension!=World.Environment.NORMAL)return null; + if(server.equals("kaitain")&&furnace&&item==Material.IRON_INGOT)return "flight_iron"; + if(!furnace&&server.equals("caladan")&&item==Material.PHANTOM_MEMBRANE)return "flight_membrane"; + if(!furnace&&server.equals("sigma-draconis-iv")&&item==Material.DIAMOND)return "flight_diamond"; + return null; + } + private static int count(Player p,Material type){int n=0;for(var i:p.getInventory().getStorageContents())if(i!=null&&i.getType()==type)n+=i.getAmount();var cursor=p.getItemOnCursor();if(cursor.getType()==type)n+=cursor.getAmount();return n;} + private void credit(Player p,String metric,int quantity,UUID id,String source){if(quantity>0&&eligible(p))receipts.flight(p,metric,Math.min(64,quantity),id,source);} + @EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void pickup(EntityPickupItemEvent e){ + if(!(e.getEntity() instanceof Player p)||!eligible(p))return;var stack=e.getItem().getItemStack();String kind=metric(server,p.getWorld().getEnvironment(),stack.getType(),false); + // Netherite is credited only by crafting. Picking up the same ingot cannot repeat that step. + if(stack.getType()==Material.NETHERITE_INGOT)kind=null; + String proof=e.getItem().getPersistentDataContainer().get(END_PROOF,PersistentDataType.STRING); + if(stack.getType()==Material.ELYTRA&&p.getWorld().getEnvironment()==World.Environment.THE_END&&proof!=null)kind="flight_elytra_acquired"; + if(kind==null)return;String objective=kind;Material type=stack.getType();int before=count(p,type),amount=stack.getAmount()-e.getRemaining();UUID world=p.getWorld().getUID(); + UUID id=UUID.nameUUIDFromBytes(("flight-pickup:"+e.getItem().getUniqueId()+":"+p.getUniqueId()+":"+objective).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + Bukkit.getScheduler().runTask(plugin,()->{if(!e.isCancelled()&&p.getWorld().getUID().equals(world))credit(p,objective,Math.min(amount,count(p,type)-before),id,objective.equals("flight_elytra_acquired")?"end":null);}); + } + @EventHandler(priority=EventPriority.MONITOR) public void furnace(FurnaceExtractEvent e){var p=e.getPlayer();if(!eligible(p))return;String kind=metric(server,p.getWorld().getEnvironment(),e.getItemType(),true);if(kind!=null)credit(p,kind,e.getItemAmount(),UUID.randomUUID(),null);} + @EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void craft(CraftItemEvent e){ + if(!(e.getWhoClicked() instanceof Player p)||!eligible(p))return;Material type=e.getRecipe().getResult().getType();String kind=type==Material.ELYTRA&&e.getRecipe() instanceof Keyed k&&CraftedFlight.KEY.equals(k.getKey())?"flight_crafted":metric(server,p.getWorld().getEnvironment(),type,false); + if(type!=Material.GOLD_INGOT&&type!=Material.NETHERITE_INGOT&&type!=Material.ELYTRA||kind==null)return; + String token=p.getUniqueId()+":"+type;if(!crafts.add(token))return;int before=count(p,type);UUID world=p.getWorld().getUID(),id=UUID.randomUUID();String objective=kind; + Bukkit.getScheduler().runTask(plugin,()->{crafts.remove(token);if(!e.isCancelled()&&p.getWorld().getUID().equals(world))credit(p,objective,count(p,type)-before,id,null);}); + } + @EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void place(EntityPlaceEvent e){if(e.getEntity() instanceof ItemFrame frame)frame.getPersistentDataContainer().set(PLACED,PersistentDataType.BYTE,(byte)1);} + @EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void fill(PlayerInteractEntityEvent e){if(e.getRightClicked() instanceof ItemFrame f&&f.getItem().isEmpty()&&e.getPlayer().getInventory().getItem(e.getHand()).getType()==Material.ELYTRA)f.getPersistentDataContainer().set(PLACED,PersistentDataType.BYTE,(byte)1);} + @EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void shipFrame(EntityDamageByEntityEvent e){ + if(!(e.getEntity() instanceof ItemFrame f)||f.getWorld().getEnvironment()!=World.Environment.THE_END||f.getItem().getType()!=Material.ELYTRA||f.getPersistentDataContainer().has(PLACED))return; + if(!(e.getDamager() instanceof Player p)||!eligible(p))return; + var location=f.getLocation();var existing=new HashSet();for(var entity:location.getWorld().getNearbyEntities(location,2,2,2))existing.add(entity.getUniqueId()); + Bukkit.getScheduler().runTask(plugin,()->{if(f.isValid()&&f.getItem().getType()==Material.ELYTRA)return;for(var entity:location.getWorld().getNearbyEntities(location,2,2,2))if(entity instanceof Item item&&!existing.contains(item.getUniqueId())&&item.getItemStack().getType()==Material.ELYTRA)item.getPersistentDataContainer().set(END_PROOF,PersistentDataType.STRING,f.getUniqueId().toString());}); + } +} + diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/ItemDesignPreview.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/ItemDesignPreview.java index 6f0726e6..7fd3b27f 100644 --- a/JarvisConnector/src/main/java/com/dunerealms/jarvis/ItemDesignPreview.java +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/ItemDesignPreview.java @@ -40,6 +40,8 @@ final class ItemDesignPreview { var enchantment=Registry.ENCHANTMENT.get(NamespacedKey.minecraft(entry.getKey()));if(enchantment==null)throw new IllegalArgumentException("Unsupported enchantment");meta.addEnchant(enchantment,value,true);actual.put(entry.getKey(),value); } var data=meta.getPersistentDataContainer(); + if(grade.itemClass().equals("flight-equipment"))data.set(new NamespacedKey("executableitems","ei-id"),PersistentDataType.STRING,id); + if(id.equals("dr_s1_elytra_merged")&&material==Material.NETHERITE_CHESTPLATE)meta.setGlider(true); if(!issued)data.set(new NamespacedKey("dunerealms","preview_only"),PersistentDataType.BYTE,(byte)1); else { data.set(new NamespacedKey("dunerealms","quality"),PersistentDataType.STRING,grade.quality());data.set(new NamespacedKey("dunerealms","equipment_mark"),PersistentDataType.STRING,grade.mark());data.set(new NamespacedKey("dunerealms","item_class"),PersistentDataType.STRING,grade.itemClass());data.set(new NamespacedKey("dunerealms","metadata_policy"),PersistentDataType.STRING,ItemMetadataPolicy.VERSION); diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/JarvisTranslator.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/JarvisTranslator.java index c5cf3354..2264ac32 100644 --- a/JarvisConnector/src/main/java/com/dunerealms/jarvis/JarvisTranslator.java +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/JarvisTranslator.java @@ -20,15 +20,19 @@ public final class JarvisTranslator extends JavaPlugin implements Listener { private GuildTransport guildTransport; private ExchangeInventory exchangeInventory; private QuestObservations questObservations; + private SpiceRefiner spiceRefiner; + public UUID refinerNpc(org.bukkit.entity.Player player){return spiceRefiner.nearby(player);} + public void refineSpice(org.bukkit.entity.Player player,JsonObject permit)throws Exception{spiceRefiner.execute(player,permit);} private ItemMetadataOverlay itemMetadata; private NativeKitGrant kitGrants; + public void recoverPaidFlight(org.bukkit.entity.Player player){try{for(var receipt:exchangeInventory.paidFlightReceipts(player))questObservations.paidElytra(player,receipt);}catch(Exception failure){getLogger().warning("Paid flight receipts remain available for retry.");}} public void refreshKits(org.bukkit.entity.Player player){if(!Bukkit.isPrimaryThread()||!player.isOnline())throw new IllegalStateException("Player unavailable");kitGrants.refresh(player);} public void citizenIntroduction(org.bukkit.entity.Player player){questObservations.introduce(player);} public JsonObject requestExchange(UUID player,JsonObject input)throws Exception{if(!isEnabled()||player==null||input==null||input.has("uuid"))throw new IllegalArgumentException("Invalid Exchange request");var request=input.deepCopy();request.addProperty("uuid",player.toString());var response=api.exchange(request);if(response.has("rejectedStatus"))return response;if(!player.toString().equals(response.get("playerUuid").getAsString())||response.get("schema").getAsInt()!=1)throw new IllegalStateException("Invalid Exchange response");return response;} public org.bukkit.inventory.ItemStack exchangeIcon(JsonObject row){return exchangeInventory.icon(row);} public long exchangePublish(org.bukkit.entity.Player p,JsonObject permit,UUID request,org.bukkit.inventory.ItemStack expected,int slot,int amount,long price)throws Exception{return exchangeInventory.publish(p,permit,request,expected,slot,amount,price,serverKey);} public int exchangeCancel(org.bukkit.entity.Player p,JsonObject permit,UUID request,long id)throws Exception{return exchangeInventory.cancel(p,permit,request,id);} - public int exchangeDeliver(org.bukkit.entity.Player p)throws Exception{return exchangeInventory.deliver(p);} + public int exchangeDeliver(org.bukkit.entity.Player p)throws Exception{var delivered=exchangeInventory.deliver(p);recoverPaidFlight(p);return delivered;} public JsonObject requestGuild(UUID player,JsonObject input)throws Exception{var q=input.deepCopy();q.addProperty("uuid",player.toString());return api.guild(q);} public void dispatchGuild(org.bukkit.entity.Player player,JsonObject ticket)throws Exception{guildTransport.dispatch(player,ticket);} private String serverKey; @@ -38,15 +42,19 @@ public final class JarvisTranslator extends JavaPlugin implements Listener { new EquipmentLoreStyle(this); new WoodcuttingSupport(this); new NetherAccess(this); + new CraftedFlight(this); WorldDefaults.start(this); TerrainAuthority.start(this); - try { itemMetadata=new ItemMetadataOverlay(this);exchangeInventory=new ExchangeInventory(item->itemMetadata.stamp(item));itemPreview=new ItemDesignPreview(new ItemMetadataPolicy(getResource("item-templates.json"))); } + serverKey=getConfig().getString("native.server-key",getDataFolder().getAbsoluteFile().getParentFile().getParentFile().getName().replace('_','-')); + try { itemMetadata=new ItemMetadataOverlay(this);exchangeInventory=new ExchangeInventory(item->itemMetadata.stamp(item),serverKey);itemPreview=new ItemDesignPreview(new ItemMetadataPolicy(getResource("item-templates.json"))); } catch (java.io.IOException invalid) { throw new IllegalStateException("Shared item metadata catalogue is unavailable",invalid); } api = new SharedGameApi(new File(getDataFolder().getParentFile(), "DuneEss/website-bridge.yml")); serverKey=getConfig().getString("native.server-key",getDataFolder().getAbsoluteFile().getParentFile().getParentFile().getName().replace('_','-')); kitGrants=new NativeKitGrant(this,exchangeInventory,itemPreview,serverKey,api); questObservations=new QuestObservations(this,api,serverKey); + new FlightObservations(this,questObservations,serverKey); + spiceRefiner=new SpiceRefiner(this,exchangeInventory,questObservations,serverKey); transport=new OrganisationTransport(this,api,serverKey); guildTransport=new GuildTransport(this,api,serverKey); actions = new NativeActions(work -> Bukkit.getScheduler().runTaskAsynchronously(this, work), @@ -70,7 +78,7 @@ public final class JarvisTranslator extends JavaPlugin implements Listener { } public JsonObject requestQuests(UUID player,JsonObject input)throws Exception { if(!isEnabled()||player==null||input==null||input.has("uuid"))throw new IllegalStateException("Invalid quest request"); - var request=input.deepCopy();request.addProperty("uuid",player.toString());return api.quests(request); + var request=input.deepCopy();request.addProperty("uuid",player.toString());if("prepare_refine".equals(request.get("action").getAsString()))request.addProperty("server",serverKey);return api.quests(request); } public JsonObject requestItemPreview(UUID player,UUID id,int revision)throws Exception { if(!isEnabled()||player==null||id==null||revision<1||revision>999999)throw new IllegalArgumentException("Choose a saved item revision"); diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKitGrant.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKitGrant.java index 2b897e11..3f7f6848 100644 --- a/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKitGrant.java +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/NativeKitGrant.java @@ -70,7 +70,8 @@ final class NativeKitGrant implements Listener { var items=new ArrayList();for(var entry:data.getAsJsonArray("items")){ var definition=entry.getAsJsonObject();int quantity=definition.get("quantity").getAsInt();if(quantity<1||quantity>64)throw new IllegalArgumentException("Invalid quantity");var item=builder.issue(definition,true);item.setAmount(quantity);items.add(item); } - int n=inventory.grantKit(player,UUID.fromString(row.get("receiptId").getAsString()),ExchangeInventory.hash(data.get("grantFingerprint").getAsString()+"\n"+id),items); + int n=inventory.grantKit(player,UUID.fromString(row.get("receiptId").getAsString()),ExchangeInventory.hash(data.get("grantFingerprint").getAsString()+"\n"+id),items,"items.kitset-purchase".equals(data.get("action").getAsString())); + if(plugin instanceof JarvisTranslator translator)translator.recoverPaidFlight(player); result.addProperty("state",n==0?"already-delivered":"delivered");result.addProperty("items",n); if(n>0)player.sendMessage("J.A.R.V.I.S. delivered "+data.get("kitName").getAsString()+("items.kitset-purchase".equals(data.get("action").getAsString())?" · purchased stillsuit kit.":" · complimentary stillsuit kit.")); }catch(Exception failure){result.addProperty("state","retained");result.addProperty("reason",failure.getMessage()==null?failure.getClass().getSimpleName():failure.getMessage());} @@ -79,7 +80,7 @@ final class NativeKitGrant implements Listener { Files.writeString(folder.resolve(request+".result.json"),results.toString());return results.toString(); } @EventHandler(priority=EventPriority.MONITOR) public void joined(PlayerJoinEvent event){ - Bukkit.getScheduler().runTaskLater(plugin,()->{if(event.getPlayer().isOnline())refresh(event.getPlayer());},20); + Bukkit.getScheduler().runTaskLater(plugin,()->{if(event.getPlayer().isOnline()){refresh(event.getPlayer());if(plugin instanceof JarvisTranslator translator)translator.recoverPaidFlight(event.getPlayer());}},20); } @EventHandler(priority=EventPriority.MONITOR) public void closed(org.bukkit.event.inventory.InventoryCloseEvent event){if(event.getPlayer() instanceof org.bukkit.entity.Player player&&pending.contains(player.getUniqueId()))Bukkit.getScheduler().runTask(plugin,()->{if(player.isOnline())refresh(player);});} @EventHandler public void left(org.bukkit.event.player.PlayerQuitEvent event){var id=event.getPlayer().getUniqueId();pending.remove(id);lastCheck.remove(id);} diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/QuestObservations.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/QuestObservations.java index b8d1f2ec..a43a5c58 100644 --- a/JarvisConnector/src/main/java/com/dunerealms/jarvis/QuestObservations.java +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/QuestObservations.java @@ -34,6 +34,17 @@ final class QuestObservations implements Listener,AutoCloseable { if(!captured.offer(event))warning(); } void introduce(Player player){if(!Bukkit.isPrimaryThread()||!player.isOnline()||closing)throw new IllegalStateException("Player unavailable");if(!captured.offer(observation(player,"citizen_introduction",UUID.randomUUID())))throw new IllegalStateException("Quest receipt queue is full");} + void flight(Player player,String kind,int quantity,UUID eventId,String source){ + flightAt(player,kind,quantity,eventId,source,System.currentTimeMillis()); + } + void flightAt(Player player,String kind,int quantity,UUID eventId,String source,long occurredAt){ + if(!Bukkit.isPrimaryThread()||closing||quantity<1||quantity>64)throw new IllegalStateException("Invalid flight receipt"); + var event=observation(player,kind,eventId);event.addProperty("occurredAt",occurredAt);event.addProperty("quantity",quantity);event.addProperty("dimension",player.getWorld().getEnvironment().name());if(source!=null)event.addProperty("source",source); + if(!captured.offer(event))throw new IllegalStateException("Quest receipt queue is full"); + } + void paidElytra(Player player,ExchangeInventory.PaidFlight receipt){ + if(!Bukkit.isPrimaryThread()||closing)throw new IllegalStateException("Player unavailable");var event=observation(player,"flight_elytra_acquired",receipt.id());event.addProperty("server",receipt.server());event.addProperty("dimension","NORMAL");event.addProperty("source","exchange");event.addProperty("quantity",1);event.addProperty("occurredAt",receipt.occurredAt());if(!captured.offer(event))throw new IllegalStateException("Quest receipt queue is full"); + } private JsonObject observation(Player p,String kind,UUID id){var event=new JsonObject();event.addProperty("eventId",id.toString());event.addProperty("uuid",p.getUniqueId().toString());event.addProperty("kind",kind);event.addProperty("server",server);event.addProperty("occurredAt",System.currentTimeMillis());return event;} @EventHandler(priority=EventPriority.LOWEST) public void beginHarvest(BlockBreakEvent e){ if(server.equals("arrakis")&&eligible(e.getPlayer())&&e.getBlock().getType()==Material.SUSPICIOUS_SAND)harvests.push(new Harvest(e,new ArrayList<>())); @@ -46,7 +57,7 @@ final class QuestObservations implements Listener,AutoCloseable { @EventHandler(priority=EventPriority.MONITOR) public void finishHarvest(BlockBreakEvent e){ var harvest=harvests.stream().filter(h->h.event()==e).findFirst().orElse(null);if(harvest==null)return;harvests.remove(harvest); if(e.isCancelled()||harvest.drops().isEmpty())return; - Bukkit.getScheduler().runTask(plugin,()->{if(e.getBlock().getType()==Material.SUSPICIOUS_SAND)return;for(var proof:harvest.drops())if(!captured.offer(proof))warning();}); + Bukkit.getScheduler().runTask(plugin,()->{if(e.getBlock().getType()==Material.SUSPICIOUS_SAND)return;for(var proof:harvest.drops()){if(!captured.offer(proof))warning();var flight=proof.deepCopy();flight.addProperty("kind","flight_spice");flight.addProperty("dimension","NORMAL");flight.addProperty("eventId",UUID.nameUUIDFromBytes(("flight:"+proof.get("eventId").getAsString()).getBytes(java.nio.charset.StandardCharsets.UTF_8)).toString());if(!captured.offer(flight))warning();}}); } private void sample(Player p){ UUID id=p.getUniqueId();long now=System.nanoTime(); diff --git a/JarvisConnector/src/main/java/com/dunerealms/jarvis/SpiceRefiner.java b/JarvisConnector/src/main/java/com/dunerealms/jarvis/SpiceRefiner.java new file mode 100644 index 00000000..e6de14a1 --- /dev/null +++ b/JarvisConnector/src/main/java/com/dunerealms/jarvis/SpiceRefiner.java @@ -0,0 +1,34 @@ +package com.dunerealms.jarvis; +import com.google.gson.JsonObject; +import java.util.*; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.plugin.Plugin; + +/** Physical NPC turn-in, with central prerequisites and Core's atomic inventory checkpoint. */ +final class SpiceRefiner implements Listener { + private final Plugin plugin;private final ExchangeInventory inventory;private final QuestObservations observations;private final String server; + private static final NamespacedKey SMUGGLER=new NamespacedKey("dunecore","smuggler"); + SpiceRefiner(Plugin plugin,ExchangeInventory inventory,QuestObservations observations,String server){this.plugin=plugin;this.inventory=inventory;this.observations=observations;this.server=server;Bukkit.getPluginManager().registerEvents(this,plugin);} + UUID nearby(Player player){ + if(!Bukkit.isPrimaryThread()||!server.equals("arrakis")||player.getWorld().getEnvironment()!=World.Environment.NORMAL||!player.getWorld().getName().equals("arrakis")||!player.isOnline()||player.isDead()||player.getGameMode()!=GameMode.SURVIVAL&&player.getGameMode()!=GameMode.ADVENTURE)throw new IllegalArgumentException("Visit an Arrakis Smuggler, then open this quest at the NPC."); + return player.getNearbyEntities(5,3,5).stream().filter(e->e instanceof WanderingTrader&&e.getPersistentDataContainer().has(SMUGGLER,PersistentDataType.BYTE)).min(Comparator.comparingDouble(e->e.getLocation().distanceSquared(player.getLocation()))).map(Entity::getUniqueId).orElseThrow(()->new IllegalArgumentException("Stand near an Arrakis Smuggler to refine spice.")); + } + void execute(Player player,JsonObject permit)throws Exception{ + UUID npc=nearby(player),request=UUID.fromString(permit.get("requestId").getAsString()); + if(!permit.get("ok").getAsBoolean()||!permit.get("allowed").getAsBoolean()||!"prepare_refine".equals(permit.get("action").getAsString())||!player.getUniqueId().toString().equals(permit.get("playerUuid").getAsString())||!server.equals(permit.get("server").getAsString())||!npc.toString().equals(permit.get("npcUuid").getAsString())||permit.get("expiresAt").getAsLong())managerAPI.getMethod("getExecutableItem",String.class).invoke(manager,id);if(definition.isEmpty())throw new IllegalStateException("Spice item definition is unavailable"); + var itemAPI=loader.loadClass("com.ssomar.score.api.executableitems.config.ExecutableItemInterface");var item=(ItemStack)itemAPI.getMethod("buildItem",int.class,Optional.class,Optional.class).invoke(definition.get(),1,Optional.empty(),Optional.of(player));if(item.getType()!=Material.ORANGE_DYE)throw new IllegalStateException("Spice item definition changed");return item; + } + private void emit(Player p,ExchangeInventory.Refined receipt){observations.flightAt(p,receipt.contaminated()?"flight_contaminated":"flight_refined",2,receipt.id(),null,receipt.occurredAt());} + @EventHandler public void join(PlayerJoinEvent e){if(!server.equals("arrakis"))return;Bukkit.getScheduler().runTaskLater(plugin,()->{var p=e.getPlayer();if(!p.isOnline()||!p.getWorld().getName().equals("arrakis"))return;try{for(var receipt:inventory.refinedReceipts(p))emit(p,receipt);}catch(Exception failure){plugin.getLogger().warning("Spice turn-in receipts remain available for retry.");}},100);} +} diff --git a/JarvisConnector/src/main/resources/item-templates.json b/JarvisConnector/src/main/resources/item-templates.json index 27895240..f98bab97 100644 --- a/JarvisConnector/src/main/resources/item-templates.json +++ b/JarvisConnector/src/main/resources/item-templates.json @@ -1383,6 +1383,13 @@ "equipmentMark": 14, "itemClass": "resource", "material": "bone" + }, + "dr_s1_elytra_crafted_v2": { + "policy": "s1-item-metadata-v1", + "quality": "very_rare", + "equipmentMark": 11, + "itemClass": "flight-equipment", + "material": "elytra" } }, "materialGrades": { diff --git a/JarvisConnector/src/main/resources/plugin.yml b/JarvisConnector/src/main/resources/plugin.yml index 098ada56..a6fde7a3 100644 --- a/JarvisConnector/src/main/resources/plugin.yml +++ b/JarvisConnector/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ name: JarvisTranslator main: com.dunerealms.jarvis.JarvisTranslator -version: 0.5.20 +version: 0.5.21 api-version: '1.21.8' description: Shared J.A.R.V.I.S. website API and native server action translator. softdepend: [SCore, ExecutableItems, ExecutableCrafting, DuneEss, ImageFrame, DecentHolograms, MedievalFactions, Towny, WorldGuard] diff --git a/JarvisConnector/src/test/java/com/dunerealms/jarvis/FlightObservationsTest.java b/JarvisConnector/src/test/java/com/dunerealms/jarvis/FlightObservationsTest.java new file mode 100644 index 00000000..a3382cf8 --- /dev/null +++ b/JarvisConnector/src/test/java/com/dunerealms/jarvis/FlightObservationsTest.java @@ -0,0 +1,17 @@ +package com.dunerealms.jarvis; +import org.bukkit.*; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +class FlightObservationsTest { + @Test void stepsRequireTheirPlanetDimensionAndProcessingAction(){ + assertEquals("flight_scrap",FlightObservations.metric("giedi-prime",World.Environment.NETHER,Material.NETHERITE_SCRAP,true)); + assertNull(FlightObservations.metric("giedi-prime",World.Environment.NORMAL,Material.NETHERITE_SCRAP,true)); + assertNull(FlightObservations.metric("giedi-prime",World.Environment.NETHER,Material.NETHERITE_SCRAP,false)); + assertEquals("flight_iron",FlightObservations.metric("kaitain",World.Environment.NORMAL,Material.IRON_INGOT,true)); + assertNull(FlightObservations.metric("kaitain",World.Environment.NORMAL,Material.IRON_INGOT,false)); + assertEquals("flight_membrane",FlightObservations.metric("caladan",World.Environment.NORMAL,Material.PHANTOM_MEMBRANE,false)); + assertEquals("flight_diamond",FlightObservations.metric("sigma-draconis-iv",World.Environment.NORMAL,Material.DIAMOND,false)); + assertNull(FlightObservations.metric("arrakis",World.Environment.NORMAL,Material.DIAMOND,false)); + assertNull(FlightObservations.metric("lobby",World.Environment.THE_END,Material.ELYTRA,false)); + } +} diff --git a/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs b/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs index 972fa283..ff6063dd 100644 --- a/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs @@ -61,7 +61,7 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api for(const row of rows){const card=button('',()=>{selected=row.id;detailOpen=true;render();});card.className='progression-mission';card.dataset.missionId=row.id;card.dataset.channel=row.channel==='website'?'website':'shared';card.setAttribute('aria-pressed',String(row.id===selected));card.setAttribute('aria-haspopup','dialog');card.append(image(questArtwork(row.channel)),el('strong',row.title),el('span',labels[row.state]||'Awaiting verification','progression-badge'));tree.append(card);} layout.append(tree);const row=rows.find(q=>q.id===selected); if(row&&detailOpen){const pane=el('aside',undefined,'progression-detail');pane.setAttribute('aria-label','Selected mission');pane.append(image(questArtwork(row.channel)),el('small',row.id),el('h3',row.title),el('small',row.channel==='website'?'Website quest':'Website / Minecraft quest')); - if(uncertain){const feedback=el('p',status.textContent,'progression-notice');feedback.setAttribute('role','alert');pane.append(feedback);}const guide=questGuidance(row);pane.append(el('h4','How to complete'),el('p',guide.objective),el('h4','Where'),el('p',guide.where));if(guide.connected===false&&row.state!=='claimed')pane.append(el('p',guide.verification,'progression-notice'));if(row.issuerName)pane.append(el('small','Questgiver · '+row.issuerName)); + if(uncertain){const feedback=el('p',status.textContent,'progression-notice');feedback.setAttribute('role','alert');pane.append(feedback);}const guide=questGuidance(row);pane.append(el('h4','How to complete'),el('p',guide.objective),el('h4','Where'),el('p',guide.where));if(guide.connected===false&&row.state!=='claimed')pane.append(el('p',guide.verification,'progression-notice'));if(row.issuerName)pane.append(el('small','Questgiver · '+row.issuerName));if(row.recipe){pane.append(el('h4','Recipe · '+row.recipe.world));const table=el('table',undefined,'progression-recipe');table.setAttribute('aria-label','Elytra crafting recipe');for(const cells of row.recipe.grid){const tr=el('tr');for(const cell of cells)tr.append(el('td',cell));table.append(tr);}pane.append(table,el('p','Very Rare · MK XI · Craft on Arrakis'));} const source=data.sources?.sources?.find(s=>s.metrics?.includes(row.metric)); const quantity=value=>row.metric?.endsWith('-minor')?(value/100).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2})+' DM':value.toLocaleString(); const dl=el('dl');for(const [label,value]of [['Progress',quantity(row.progress)+' / '+quantity(row.target)],['Status',labels[row.state]||'Awaiting verification'],['Verification',questVerification(row,source)],[data.xpType==='pol'?'Reputation':'XP',row.xp===null?'Not configured':String(row.xp)],['Participation',row.optional?'Optional':'Required']])dl.append(el('dt',label),el('dd',value));pane.append(dl); diff --git a/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs b/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs index b98bf6eb..5fea2971 100644 --- a/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs @@ -1,7 +1,9 @@ +import {ELYTRA_BRANCH,ELYTRA_QUESTS} from './elytra-quests.mjs'; // Server-owned content shared with the existing quest and POL Decision interfaces. // Reward amounts, decision costs and timings require explicit configuration. const freeze=v=>{if(v&&typeof v==='object'){Object.values(v).forEach(freeze);Object.freeze(v);}return v;}; export const POL_QUEST_BRANCHES=freeze([ + ELYTRA_BRANCH, { "id": "atreides", "office": "ATR", @@ -1099,5 +1101,5 @@ export const POL_QUEST_BRANCHES=freeze([ } ]); const gameplayMetrics=new Set(['pol-sabotage','pol-water-supply','pol-spice-transport','pol-sietch-service','pol-verified-route','pol-route-service','pol-sealed-cargo','pol-restricted-delivery','pol-alternate-route','pol-opposed-delivery','pol-ghost-cargo','pol-escort','pol-interdiction','pol-cargo-recovery','pol-protection','pol-commissioned-recovery','pol-discreet-logistics','pol-protected-delivery']); -export const POL_QUEST_DEFINITIONS=Object.freeze(POL_QUEST_BRANCHES.flatMap(b=>b.quests.map((q,index)=>Object.freeze({...q,issuer:b.issuer||({smugglers:"esmar_tuek",clan:"gurney_halleck",company:"roma_atani"})[b.id],issuerName:b.issuerName||({smugglers:"Esmar Tuek",clan:"Gurney Halleck",company:"Roma Atani"})[b.id],objective:q.objective,xp:150+index*50,executionRequirements:Object.freeze({website:true,minecraft:gameplayMetrics.has(q.metric)})})))); +export const POL_QUEST_DEFINITIONS=Object.freeze(POL_QUEST_BRANCHES.flatMap(b=>b.quests.map((q,index)=>Object.freeze({...q,issuer:b.issuer||({smugglers:"esmar_tuek",clan:"gurney_halleck",company:"roma_atani"})[b.id],issuerName:b.issuerName||({smugglers:"Esmar Tuek",clan:"Gurney Halleck",company:"Roma Atani"})[b.id],objective:q.objective,xp:q.xp??150+index*50,executionRequirements:Object.freeze({website:true,minecraft:gameplayMetrics.has(q.metric)||q.branch==='elytra'})})))); export function polBranch(id){return POL_QUEST_BRANCHES.find(b=>b.id===id||b.office===id)||null;} diff --git a/website/control-panel/public/cp-v2/cp-v2-progression-dialog.css b/website/control-panel/public/cp-v2/cp-v2-progression-dialog.css index 65785c5e..9eea2a20 100644 --- a/website/control-panel/public/cp-v2/cp-v2-progression-dialog.css +++ b/website/control-panel/public/cp-v2/cp-v2-progression-dialog.css @@ -26,3 +26,5 @@ .progression-dossier-card>strong{font-size:17px}.progression-dossier-card>span{font-size:13px;color:#c4d0bf} .progression-dossier-card:focus-visible{outline:3px solid #f9d679;outline-offset:3px} @media(max-width:600px){.progression-dialog-scroll{padding:12px}.progression-dialog .progression-detail>img{height:130px}.progression-dialog dl{grid-template-columns:minmax(90px,1fr) minmax(0,1.6fr)}.progression-dialog h3{font-size:22px}} + +.progression-recipe{width:100%;table-layout:fixed;border-collapse:separate;border-spacing:5px}.progression-recipe td{padding:12px 6px;text-align:center;border:1px solid #ae914c;background:#0d2b22;color:#efdb9c;overflow-wrap:anywhere;font-size:13px} diff --git a/website/control-panel/public/cp-v2/elytra-quests.mjs b/website/control-panel/public/cp-v2/elytra-quests.mjs new file mode 100644 index 00000000..1fba8e86 --- /dev/null +++ b/website/control-panel/public/cp-v2/elytra-quests.mjs @@ -0,0 +1,16 @@ +const rows=[ + ['SPICE','Sand and Spice','Harvest 2 raw spice on Arrakis with a Spice Harvest Shovel.','flight-spice',2,50,[]], + ['REFINE','The Refiner','On Arrakis, open this quest beside an Arrakis Smuggler and give the refiner 2 raw spice to receive 2 refined spice.','flight-refined',2,75,['SPICE']], + ['DEBRIS','Buried in Fire','Enter Harkonnen’s Nether and obtain 10 ancient debris. Eight scraps will become netherite; two are reserved for contaminated spice.','flight-debris',10,100,[]], + ['SCRAP','Out of the Furnace','In Harkonnen’s Nether, smelt the 10 ancient debris into 10 netherite scraps and take them from the furnace.','flight-scrap',10,100,['DEBRIS']], + ['GOLD','A Golden Binder','Obtain 8 gold ingots in Harkonnen’s Nether for the netherite alloy.','flight-gold',8,75,['SCRAP']], + ['NETHERITE','Forge the Alloy','In Harkonnen’s Nether, craft 2 netherite ingots: each uses 4 scraps and 4 gold ingots. Keep the remaining 2 scraps.','flight-netherite',2,150,['GOLD']], + ['CONTAMINATE','A Dangerous Catalyst','Return to an Arrakis Smuggler and open this quest. Turn in 2 refined spice and 2 netherite scraps for 2 contaminated spice.','flight-contaminated',2,100,['REFINE','SCRAP']], + ['MEMBRANES','Night Hunter','Obtain 2 phantom membranes on Caladan. Hunt phantoms after several nights without sleep.','flight-membrane',2,75,[]], + ['IRON','Imperial Iron','On Kaitain, smelt raw iron and take at least 2 iron ingots from a furnace or blast furnace.','flight-iron',2,50,[]], + ['DIAMOND','Under the Ice','Obtain a diamond on Ordos.','flight-diamond',1,100,[]], + ['CRAFT','Wings over the Desert','Return to Arrakis. Complete the preparation quests to reveal the elytra recipe. Craft the elytra there.','flight-crafted',1,250,['NETHERITE','CONTAMINATE','MEMBRANES','IRON','DIAMOND']], + ['ACQUIRE','Another Way to Fly','Alternatively, buy and receive an elytra through the Exchange, or obtain an elytra from an End ship. This completes this entire branch and grants every unclaimed branch reward once.','flight-elytra-acquired',1,0,[]] +]; +export const ELYTRA_QUESTS=Object.freeze(rows.map(([suffix,title,objective,metric,target,xp,requires])=>Object.freeze({id:'POL-ELYTRA-'+suffix,title,objective,metric,target,xp,requires:requires.map(v=>'POL-ELYTRA-'+v),requiresAny:[],branch:'elytra',season:'S01',revision:1,optional:true,verifiedOnly:true,xpType:'pol'}))); +export const ELYTRA_BRANCH=Object.freeze({id:'elytra',office:null,title:'Wings across the Realms',issuer:'esmar_tuek',issuerName:'Esmar Tuek',theme:'Five worlds, two material chains, one elytra · Reputation XP',xpType:'pol',quests:ELYTRA_QUESTS,decisions:[]}); diff --git a/website/control-panel/public/item-design-model.mjs b/website/control-panel/public/item-design-model.mjs index 7d899add..60c0139d 100644 --- a/website/control-panel/public/item-design-model.mjs +++ b/website/control-panel/public/item-design-model.mjs @@ -1,5 +1,5 @@ import {itemTemplateCatalogue} from './item-metadata-policy.mjs'; -import {TOOL_TEMPLATES,elytraTemplate} from './tool-template-policy.mjs'; +import {TOOL_TEMPLATES,CRAFTED_ELYTRA_TEMPLATE,elytraTemplate} from './tool-template-policy.mjs'; import {equipmentTemplate} from './equipment-template-policy.mjs'; import {REFIT_UPGRADE_ITEMS} from './organisation-refit-policy.mjs'; import {validateItemLore,TRIM_PATTERNS,TRIM_MATERIALS} from './kit-design-model.mjs'; @@ -8,7 +8,7 @@ import {validateItemLore,TRIM_PATTERNS,TRIM_MATERIALS} from './kit-design-model. // A design describes an item; it cannot grant ownership, mint it or run commands. export const ITEM_DESIGN_VERSION=1; const catalogue=itemTemplateCatalogue().templates; -const tools=new Map([...TOOL_TEMPLATES,...REFIT_UPGRADE_ITEMS,...['basic','merged'].map(elytraTemplate)].map(row=>[row.id,row])); +const tools=new Map([...TOOL_TEMPLATES,CRAFTED_ELYTRA_TEMPLATE,...REFIT_UPGRADE_ITEMS,...['basic','merged'].map(elytraTemplate)].map(row=>[row.id,row])); const exact=(row,keys)=>row&&typeof row==='object'&&!Array.isArray(row)&&Object.keys(row).length===keys.length&&keys.every(key=>Object.hasOwn(row,key)); const title=value=>value.replaceAll('_',' ').replace(/\b[a-z]/g,c=>c.toUpperCase()); export function itemDesignTemplate(id){ diff --git a/website/control-panel/public/item-metadata-policy.mjs b/website/control-panel/public/item-metadata-policy.mjs index c14b369f..fcdcd636 100644 --- a/website/control-panel/public/item-metadata-policy.mjs +++ b/website/control-panel/public/item-metadata-policy.mjs @@ -1,5 +1,5 @@ import {equipmentTemplate} from './equipment-template-policy.mjs'; -import {TOOL_TEMPLATES,elytraTemplate,ROCKET_TEMPLATES} from './tool-template-policy.mjs'; +import {TOOL_TEMPLATES,CRAFTED_ELYTRA_TEMPLATE,elytraTemplate,ROCKET_TEMPLATES} from './tool-template-policy.mjs'; import {EVERYDAY_ITEMS} from './mining-tool-policy.mjs'; import {REFIT_UPGRADE_ITEMS} from './organisation-refit-policy.mjs'; export const ITEM_METADATA_POLICY='s1-item-metadata-v1'; @@ -1712,7 +1712,7 @@ export function itemMetadata({quality,equipmentMark,itemClass='resource'}={}){ return {policy:ITEM_METADATA_POLICY,quality,equipmentMark,itemClass}; } export function itemTemplateCatalogue(){ - const rows=[...TOOL_TEMPLATES,...ROCKET_TEMPLATES,...REFIT_UPGRADE_ITEMS.map(t=>({...t,itemClass:'resource'})),...['basic','merged'].map(elytraTemplate), + const rows=[...TOOL_TEMPLATES,CRAFTED_ELYTRA_TEMPLATE,...ROCKET_TEMPLATES,...REFIT_UPGRADE_ITEMS.map(t=>({...t,itemClass:'resource'})),...['basic','merged'].map(elytraTemplate), ...Object.values(EVERYDAY_ITEMS).map(t=>({...t,material:t.itemClass==='menu'?'paper':'orange_dye'}))]; const qualities=['common','uncommon','rare','very_rare','legendary']; for(let mark=0;mark<=14;mark++){ diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index 5dde7833..f64d41c4 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -32,7 +32,8 @@ export const MASTER_KEY_TEMPLATES=[ action('progression.smuggler-institutions','Protected hidden smuggler institutions','staff-parent-link',[],{webIssue:false,domainAdapter:'clandestineInstitutions.provision',executionStatus:'current-owner-server-operator',effect:'Create the fixed protected clan and company under the current Esmar Tuek system identity. A verified introduction QST grants secondary quest affiliations only; never replace a player clan/company or grant PvP, bank, staff or office authority.'}), action('progression.mentor-policy','Scoped Mentat reward bonus','progression-policy',[field('season','Season'),field('policyVersion','Policy version','number',{min:3})],{webIssue:false,recordOnly:true,domainAdapter:'ensurePOLMentorPolicy',executionStatus:'recorded-system-policy',effect:'Record the bounded 10% eligible Mentat bonus through the existing POL award engine. Preserve Personal XP and earlier claims; no default DM reward.'}), action('progression.pol-funded-rewards','Funded Reputation reward delivery','quest',[],{webIssue:false,recordOnly:true,domainAdapter:'createPOLFundedRewards',executionStatus:'consumed-quest-outbox-only',effect:'Pay only explicitly configured and verified claim rewards from existing website treasury funds to the bound ordinary player bank account. Original QST identity prevents duplicate ledger entries; unfunded or invalid rewards remain queued.'}), - action('progression.game-observation','Native quest observation','quest-milestone',[field('eventId','Original native event UUID'),field('uuid','Linked Minecraft UUID'),field('kind','Fixed observation kind'),field('server','Native server'),field('occurredAt','Original event time','number',{min:1}),field('quantity','Produced spice quantity','number',{min:1,max:64,required:false})],{version:3,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestEventsAPI',executionStatus:'authenticated-game-service',effect:'Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.'}), + action('progression.game-observation','Native quest observation','quest-milestone',[field('eventId','Original native event UUID'),field('uuid','Linked Minecraft UUID'),field('kind','Fixed observation kind'),field('server','Native server'),field('occurredAt','Original event time','number',{min:1}),field('quantity','Native produced quantity','number',{min:1,max:64,required:false}),field('dimension','Native dimension','text',{required:false}),field('source','Fixed Elytra acquisition source','text',{required:false})],{version:4,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestEventsAPI',executionStatus:'authenticated-game-service',effect:'Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Fixed world/dimension flight observations feed the Reputation Elytra branch. A committed paid delivery or natural End-ship acquisition completes only this branch, awarding its remaining rewards once. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.'}), + action('progression.spice-refining','NPC spice refinement','quest-milestone',[field('uuid','Linked player UUID'),field('requestId','Original turn-in UUID'),field('definitionId','Fixed refining quest'),field('npcUuid','Nearby Arrakis Smuggler UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestsAPI.prepare_refine + SpiceRefiner + ExchangeInventory.refine',executionStatus:'authenticated-native-npc-turn-in',effect:'Revalidate the current player and quest prerequisites, then require the physical Arrakis NPC again before consuming two real raw spice, or two refined spice and two scraps. Core checkpoints inputs, two EI outputs and a recoverable receipt atomically. Existing QSM observations award no reward until verified by the Reputation quest engine.'}), action('progression.earned-dm','Verified earned DM','quest-milestone',[],{webIssue:false,recordOnly:true,domainAdapter:'bankQuestIncome + progressionRuntime.collect',executionStatus:'committed-central-bank-source',effect:'Count posted wages, Exchange sale income, incoming bank transfers and verified quest treasury credits across the player’s personal central-bank accounts during the active season. Count each bank order once and preserve cumulative earnings after spending. Exclude own-account transfers, refunds, pending payments, unrelated system grants and organisation income; never use a legacy game wallet or current balance as an earnings counter.'}), action('progression.exchange-purchase','Committed Exchange quest evidence','quest-milestone',[],{webIssue:false,recordOnly:true,domainAdapter:'createBankQuestActivities',executionStatus:'committed-central-bank-source',effect:'Read the first settled Exchange purchase in the current season into existing Personal activity keys. Pending orders, self transfers, another customer and legacy wallets never count. Reuse the original order UUID without issuing a reward from the reader.'}), action('progression.personal-activity','Verified Personal activity','quest-milestone',[field('eventId','Unique domain event'),field('accountId','Current player account'),field('minecraftUuid','Current linked player UUID'),field('seasonId','Current Personal season'),field('metric','Registered Personal objective metric'),field('quantity','Verified quantity','number',{min:1}),field('reference','Original committed evidence reference')],{webIssue:false,recordOnly:true,domainAdapter:'personalActivityEvents.record',executionStatus:'trusted-domain-producer-only',effect:'Read current immutable QSM evidence through the existing Personal quest engine. Preserve dedicated bank, forum, acquisition and Q0 proof readers. Native observations and committed bank receipts feed their registered metrics. Other missing external events remain pending; browser counters never supply authority.'}), diff --git a/website/control-panel/public/tool-template-policy.mjs b/website/control-panel/public/tool-template-policy.mjs index 25a956b5..4848a9fb 100644 --- a/website/control-panel/public/tool-template-policy.mjs +++ b/website/control-panel/public/tool-template-policy.mjs @@ -23,6 +23,8 @@ export function elytraTemplate(variant){ const merged=variant==='merged',quality=merged?'mythic':'legendary',mark=merged?14:13; return {policy:TOOL_POLICY,season:'S1',id:`dr_s1_elytra_${variant}`,name:merged?'Merged Elytra':'Basic Elytra',material:merged?'netherite_chestplate':'elytra',quality,equipmentMark:mark,itemClass:'flight-equipment',glider:merged,enchantments:merged?maximumEquipmentEnchantments(equipmentTemplate({quality,mark}),'chestplate'):{unbreaking:4,mending:1}}; } +// Versioned crafting template preserves immutable original basic Elytra designs. +export const CRAFTED_ELYTRA_TEMPLATE=Object.freeze({...elytraTemplate('basic'),id:'dr_s1_elytra_crafted_v2',quality:'very_rare',equipmentMark:11,enchantments:{unbreaking:3,mending:1}}); // Distinct instruments: ordinary spice and refined spice are never interchangeable. export const ROCKET_TEMPLATES=Object.freeze([ Object.freeze({policy:TOOL_POLICY,season:'S1',id:'dr_s1_spice_rocket_mk1',name:'Spice Rocket',material:'firework_rocket',quality:'uncommon',equipmentMark:1,itemClass:'flight-consumable',effectMultiplier:1,spiceItemId:'spice'}), diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 90d158ee..db6a4f52 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -2,540 +2,540 @@ import {createKitsetCommerce} from '../node/kitset-commerce.mjs'; import {createKitsetPurchaseAPI} from './kitset-purchase-api.mjs'; import {createGameExchangeAPI} from '../node/game-exchange.mjs'; import {createGameKitGrantsAPI} from '../node/game-kit-grants.mjs'; -import {createGameGuildAPI} from '../node/game-guild.mjs'; -import {createClanWorkspace} from '../node/clan-workspace.mjs'; -import {createGameQuestsAPI} from '../node/game-quests.mjs'; +import {createGameGuildAPI} from '../node/game-guild.mjs'; +import {createClanWorkspace} from '../node/clan-workspace.mjs'; +import {createGameQuestsAPI} from '../node/game-quests.mjs'; import {createGameQuestEventsAPI} from '../node/game-quest-events.mjs'; -import {createGameItemDesignAPI} from '../node/game-item-designs.mjs'; -import {createPOLFundedRewards} from '../node/pol-funded-rewards.mjs'; -import {ensurePOLMentorPolicy} from '../node/pol-mentor-rewards.mjs'; -import {initializePersonalActivityEvents} from '../node/personal-activity-events.mjs'; -import {createPersonalActivityAPI} from '../node/personal-activity-api.mjs'; -import {initializeSecondaryAffiliations} from '../node/clandestine-institutions.mjs'; -import {initializePOLActivityEvents} from '../node/pol-activity-events.mjs'; -import {createPOLActivityAPI} from '../node/pol-activity-api.mjs'; -import {openStarterKitDelivery} from '../node/starter-kit-delivery.mjs'; -import {initializeStarterKitEvents} from '../node/starter-kit-events.mjs'; -import {ensureStarterKitRewardPolicy} from '../node/starter-kit-rewards.mjs'; -import {createStarterKitEventAPI} from '../node/starter-kit-api.mjs'; -import {openBoardKeyRuntime} from '../node/board-key-runtime.mjs'; -import {createRebellionRewards} from '../node/rebellion-rewards.mjs'; -import {createDeedPurchases} from '../node/deed-purchases.mjs'; -import {createRebellionQuests,initializeRebellionRewards} from '../node/rebellion-quests.mjs'; -import {createRebellionAPI} from '../node/rebellion-api.mjs'; -import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs'; -import {initializePOLProgression,ensurePOLProgressionPolicy,ensurePOLRepeatablePolicy,polProgressionStore} from '../node/progression-pol.mjs'; -import {initializeSystemCharacters} from '../node/system-characters.mjs'; -import {initializeEntityState} from '../node/entity-state-keys.mjs'; -import {createDMPaint} from './dmpaint.mjs'; -import {initializePassiveOrders} from '../node/political-passive-orders.mjs'; -import {createMasterKeyGeneratorAPI} from '../node/jarvis-master-generator-api.mjs'; -import {initializeJarvisGenerator} from '../node/jarvis-master-generator.mjs'; -import {initializeServerProjects} from '../node/server-projects.mjs'; -import {PROJECT_BANK_SCHEMA} from '../node/project-banking.mjs'; -import {createServerProjectRuntime} from '../node/server-project-runtime.mjs'; -import {createServerProjectAPI} from '../node/server-project-api.mjs'; -import {GAZETTE_SCHEMA} from '../node/jarvis-gazette.mjs'; -import {ECONOMIC_SNAPSHOT_SCHEMA} from '../node/jarvis-economic-snapshots.mjs'; -import {initializeProgression} from '../node/progression-schema.mjs'; -import {ensureProgressionPolicy} from '../node/progression-policy.mjs'; -import {createProgressionRuntime} from '../node/progression-runtime.mjs'; -import {createProgressionAPI} from '../node/progression-api.mjs'; -import {createNaibCouncilAPI} from '../node/naib-council-api.mjs'; -import {NAIB_COUNCIL_SCHEMA,createNaibCouncil,reconcileNaibChairs} from '../node/naib-council.mjs'; -import {configurePromotionDelivery} from '../node/jarvis-promotions.mjs'; -import {drainPoliticalJobNotifications} from '../node/political-job-notifications.mjs'; -import {createPoliticalJobs} from '../node/political-jobs.mjs'; -import {internalMailEligible} from '../node/internal-mail.mjs'; -import {POLITICAL_JOB_SCHEMA} from '../node/political-jobs.mjs'; -import {createPoliticalJobAPI} from '../node/political-job-api.mjs'; -import {createElectionResults} from '../node/election-results.mjs'; -import {createElectionCampaignAPI} from '../node/election-campaign-api.mjs'; -import {VALIDATION_CASE_SCHEMA,createKeyValidation} from '../node/jarvis-key-validation.mjs'; -import {ensureJarvisIdentity} from '../node/jarvis-identity-provision.mjs'; -import {reconcileCrysknifeCompany} from '../node/crysknife-company.mjs'; -import {createRealmEvents} from '../node/jarvis-events.mjs'; -import {createRihlaAPI,ensureRihlaAccount,provisionRihlaAccounts} from '../node/rihla.mjs'; -import {NETWORK_LAYOUT_SCHEMA,createNetworkLayoutAPI} from '../node/organisation-network.mjs'; -import {createPoliticalActions} from '../node/political-actions.mjs'; -import {createOfficeAuctionRuntime,initializeOfficeAuctionRuntime} from '../node/office-auction-runtime.mjs'; -import {createOfficeAuctionAPI} from '../node/office-auction-api.mjs'; -import {jarvisAuctionDocument} from './jarvis-auction-shell.mjs'; -import {createJarvisManagement} from '../node/jarvis-management.mjs'; -import {createProtectedClaims} from '../node/protected-claims.mjs'; -import {createCompanyMailboxSettings} from '../node/company-mailbox-settings.mjs'; -import {createCompanyClaims} from '../node/company-claims.mjs'; +import {createGameItemDesignAPI} from '../node/game-item-designs.mjs'; +import {createPOLFundedRewards} from '../node/pol-funded-rewards.mjs'; +import {ensurePOLMentorPolicy} from '../node/pol-mentor-rewards.mjs'; +import {initializePersonalActivityEvents} from '../node/personal-activity-events.mjs'; +import {createPersonalActivityAPI} from '../node/personal-activity-api.mjs'; +import {initializeSecondaryAffiliations} from '../node/clandestine-institutions.mjs'; +import {initializePOLActivityEvents} from '../node/pol-activity-events.mjs'; +import {createPOLActivityAPI} from '../node/pol-activity-api.mjs'; +import {openStarterKitDelivery} from '../node/starter-kit-delivery.mjs'; +import {initializeStarterKitEvents} from '../node/starter-kit-events.mjs'; +import {ensureStarterKitRewardPolicy} from '../node/starter-kit-rewards.mjs'; +import {createStarterKitEventAPI} from '../node/starter-kit-api.mjs'; +import {openBoardKeyRuntime} from '../node/board-key-runtime.mjs'; +import {createRebellionRewards} from '../node/rebellion-rewards.mjs'; +import {createDeedPurchases} from '../node/deed-purchases.mjs'; +import {createRebellionQuests,initializeRebellionRewards} from '../node/rebellion-quests.mjs'; +import {createRebellionAPI} from '../node/rebellion-api.mjs'; +import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs'; +import {initializePOLProgression,ensurePOLProgressionPolicy,ensurePOLRepeatablePolicy,ensureElytraQuestPolicy,polProgressionStore} from '../node/progression-pol.mjs'; +import {initializeSystemCharacters} from '../node/system-characters.mjs'; +import {initializeEntityState} from '../node/entity-state-keys.mjs'; +import {createDMPaint} from './dmpaint.mjs'; +import {initializePassiveOrders} from '../node/political-passive-orders.mjs'; +import {createMasterKeyGeneratorAPI} from '../node/jarvis-master-generator-api.mjs'; +import {initializeJarvisGenerator} from '../node/jarvis-master-generator.mjs'; +import {initializeServerProjects} from '../node/server-projects.mjs'; +import {PROJECT_BANK_SCHEMA} from '../node/project-banking.mjs'; +import {createServerProjectRuntime} from '../node/server-project-runtime.mjs'; +import {createServerProjectAPI} from '../node/server-project-api.mjs'; +import {GAZETTE_SCHEMA} from '../node/jarvis-gazette.mjs'; +import {ECONOMIC_SNAPSHOT_SCHEMA} from '../node/jarvis-economic-snapshots.mjs'; +import {initializeProgression} from '../node/progression-schema.mjs'; +import {ensureProgressionPolicy} from '../node/progression-policy.mjs'; +import {createProgressionRuntime} from '../node/progression-runtime.mjs'; +import {createProgressionAPI} from '../node/progression-api.mjs'; +import {createNaibCouncilAPI} from '../node/naib-council-api.mjs'; +import {NAIB_COUNCIL_SCHEMA,createNaibCouncil,reconcileNaibChairs} from '../node/naib-council.mjs'; +import {configurePromotionDelivery} from '../node/jarvis-promotions.mjs'; +import {drainPoliticalJobNotifications} from '../node/political-job-notifications.mjs'; +import {createPoliticalJobs} from '../node/political-jobs.mjs'; +import {internalMailEligible} from '../node/internal-mail.mjs'; +import {POLITICAL_JOB_SCHEMA} from '../node/political-jobs.mjs'; +import {createPoliticalJobAPI} from '../node/political-job-api.mjs'; +import {createElectionResults} from '../node/election-results.mjs'; +import {createElectionCampaignAPI} from '../node/election-campaign-api.mjs'; +import {VALIDATION_CASE_SCHEMA,createKeyValidation} from '../node/jarvis-key-validation.mjs'; +import {ensureJarvisIdentity} from '../node/jarvis-identity-provision.mjs'; +import {reconcileCrysknifeCompany} from '../node/crysknife-company.mjs'; +import {createRealmEvents} from '../node/jarvis-events.mjs'; +import {createRihlaAPI,ensureRihlaAccount,provisionRihlaAccounts} from '../node/rihla.mjs'; +import {NETWORK_LAYOUT_SCHEMA,createNetworkLayoutAPI} from '../node/organisation-network.mjs'; +import {createPoliticalActions} from '../node/political-actions.mjs'; +import {createOfficeAuctionRuntime,initializeOfficeAuctionRuntime} from '../node/office-auction-runtime.mjs'; +import {createOfficeAuctionAPI} from '../node/office-auction-api.mjs'; +import {jarvisAuctionDocument} from './jarvis-auction-shell.mjs'; +import {createJarvisManagement} from '../node/jarvis-management.mjs'; +import {createProtectedClaims} from '../node/protected-claims.mjs'; +import {createCompanyMailboxSettings} from '../node/company-mailbox-settings.mjs'; +import {createCompanyClaims} from '../node/company-claims.mjs'; import {createHomeRelocation} from '../node/home-relocation.mjs'; -import {ownCompanyMailbox,ensureCompanyMailbox} from '../node/internal-mail-companies.mjs'; -import {internalMailBroker} from '../node/internal-mail.mjs'; -import {applyUnicorpRoyalMailbox} from '../node/company-royal-mail.mjs'; -import {createCompanyEmblems} from './company-emblems.mjs'; -import {ensurePoliticalOfficeCharters} from '../node/political-office-charters.mjs'; -import {createCompanyRecruitment} from '../node/company-recruitment.mjs'; -import {initializeCompanyDeeds} from '../node/company-deeds.mjs'; -import {createCompanyDeedRoute} from '../node/company-deed-route.mjs'; -import {createJarvisServices} from '../node/jarvis-api.mjs'; -import {createJarvisPayments} from '../node/jarvis-payments.mjs'; -import {standardCycle} from '../node/postbank-payments.mjs'; -import {jarvisApplicationDocument} from './jarvis-application-shell.mjs'; -import {createOrganisationSettingsRoute} from '../node/organisation-settings-route.mjs'; -import {createPublicOrganisations} from '../node/public-organisations.mjs'; -import {companyCPReferenceDocument} from './company-cp-reference.mjs'; -import {politicsCPReferenceDocument} from './politics-cp-reference.mjs'; -import {createPoliticsWorkspace} from '../node/politics-workspace.mjs'; -import {initializeCodexEquipment} from '../node/codex-equipment.mjs'; -import {openOrganisationKeyService,grantCurrentAccountKeys,ensureOriginalKeys} from '../node/organisation-key-service.mjs'; -import {CHARACTER_PREFERENCE_SCHEMA} from '../node/character-preferences.mjs'; -import {CHARACTER_SCHEMA,createCharacterChoice} from './character-choice.mjs'; -import {HOUSE_SELECTION_SCHEMA,createHouseSelection,createHouseSelectionAPI} from '../node/house-selection.mjs'; -import {createGameNativeStateAPI} from '../node/game-native-state.mjs'; -import {GAME_ORGANISATION_SCHEMA,createGameOrganisationsAPI} from '../node/game-organisations.mjs'; -import {createGameBriefing,readGameMemberships} from '../node/game-briefing.mjs'; -import {createClanKeyReceipts} from './clan-key-receipts.mjs'; -import {clanDeedAuthority} from '../node/clan-deeds.mjs'; -import {createClanDeedRoute} from './clan-deed-route.mjs'; -import {createPublicClans} from '../node/public-clans.mjs'; -import {initializeClanCharters,applyRoyalClanRollout,readClanCharter} from '../node/clan-charters.mjs'; -import {resetOwnerTestClaims} from '../node/claim-test-reset.mjs'; -import {createClaimUpgrades} from './claim-upgrades.mjs'; -import {PostbankClaimProducts} from '../node/postbank-claim-products.mjs'; -import {createPostbankAuthority} from '../node/postbank-authority.mjs'; -import {createClaimOverview} from './claim-overview.mjs'; -export const PANEL_CSP="default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://usercontent.luckperms.net https://metadata.luckperms.net wss://usersockets.luckperms.net; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://pol.dunerealms.com"; -// Company artwork is served by the canonical public asset host. -export const PANEL_SERVICE_CSP="default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://pol.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://pol.dunerealms.com"; -export const COMPANY_CSP=PANEL_CSP.replace("object-src", "frame-src 'self' https://forums.dunerealms.com https://support.dunerealms.com https://www.dunerealms.com https://luckperms.net https://wiki.dunerealms.com; object-src").replace("img-src 'self' data:","img-src 'self' data: https://www.dunerealms.com"); -import {createElectionDirectory} from './election-directory.mjs'; -import {createMenuBadges} from '../node/menu-badges.mjs'; -import {startCentralScheduler} from '../node/postbank-payments.mjs'; -import {createPostbankApi} from '../node/postbank-api.mjs'; -import {openPostbankDatabase} from '../node/postbank-db.mjs'; -import {createItemRegister} from './item-register.mjs'; -import {createKitsetAPI} from './kitset-api.mjs'; -import {initializeKitsets} from '../node/kitsets.mjs'; -import {createItemDesignAPI} from './item-design-api.mjs'; -import {initializeItemDesigns} from '../node/item-designs.mjs'; -import {createManagedTransfers} from './managed-bank-transfer.mjs'; -import {createOfficialBank} from './official-bank.mjs'; -import {createBankBeneficiaries} from './bank-beneficiaries.mjs'; -import {createBankTransfers} from './bank-transfers.mjs'; -import {createHosting} from '../node/hosting.mjs'; -import {initializeOfficeLedger,startOfficeLedger} from './election-office-ledger.mjs'; -import {createMailAccounts} from '../node/mail-accounts.mjs'; -import {createElectionVoting,startElectionClock} from './election-voting.mjs'; -import {initializeBallots} from './election-ballots.mjs'; -import {initializeRounds} from './election-rounds.mjs'; -import {createImperialCharters,initializeCharters} from './imperial-charters.mjs'; -import {createProclamations,initializeProclamations} from './proclamations.mjs'; -import {createElectoralRoll} from '../node/electoral-roll.mjs'; -import {createElectionApplications} from './election-application-route.mjs'; -import {initializeApplications} from './election-applications.mjs'; -import {createInternalMail,startInternalMailSync,initializeInternalMailAccess,syncClanMailRegistry} from '../node/internal-mail.mjs'; -import {createPoliticsPreview} from './politics-preview.mjs'; -import {createPublicGovernment} from '../node/public-government.mjs'; -import{createAdminRegistration}from '../node/admin-registration.mjs'; -import{firstLoginGate,firstLoginState,initializeFirstLogin,createFirstLoginTerms}from '../node/first-login.mjs'; -import {createContactEmail,initializeContactEmails} from '../node/contact-email.mjs'; -import {isOwnerRank} from '../node/permissions.mjs'; -import {createBanEvidence,initializeBanEvidence} from './ban-evidence.mjs'; -import {createUpgradeTokens} from './upgrade-tokens.mjs'; -import {createKitCatalogueBridge} from '../node/kit-catalogue.mjs'; -import {createKitStudio} from './kit-studio.mjs'; -import {startModerationSync} from './moderation.mjs'; -import {createKitMarket} from './kit-market.mjs'; -import {createImperialAtelier} from './imperial-atelier.mjs'; -import {createGameRanks,initializeGameRanks} from '../node/game-ranks.mjs'; -import {createBanking} from './banking.mjs'; -import {createClanShop,initializeClanShop} from './clan-shop.mjs'; -import {createQuests} from './quests.mjs'; -import {createClans,initializeClans} from './clans.mjs'; -import {createClanEmblems} from './clan-emblems.mjs'; -import {createGameTickets} from './game-tickets.mjs'; -import {createQuestRewards} from './quest-rewards.mjs'; -import {openGameMysqlPool} from '../node/game-mysql-pool.mjs'; -import {retiredTicketResponse} from '../node/retired-tickets.mjs'; -import {createGitIdentityRoute,initializeGitIdentities,startGitIdentitySync,gitProxyIdentity} from '../node/git-identity.mjs'; -import {createMailIdentityRoute,initializeMailIdentities} from '../node/mail-identity.mjs'; -import {createProfile} from '../node/profile.mjs'; -import {createWorldStatus} from '../node/world-status.mjs'; -import {createMemorials} from '../node/memorials.mjs'; -import {createMemberProfiles} from '../node/member-profiles.mjs'; -import {createAvatars} from '../node/avatar.mjs'; -import {createTailorAppearance} from '../node/tailor-appearance.mjs'; -import {createBadgeAdmin} from '../node/badge-admin.mjs'; -import {createManualSealRoute} from '../node/manual-seal-route.mjs'; -import {createCompanyAdmin} from '../node/company-admin.mjs'; -import {initializeCompanyRegistry} from '../node/company-registry.mjs'; -import {initializeShareLedger} from '../node/share-ledger.mjs'; -import {initializeSealEntitlements} from '../node/seal-entitlement-store.mjs'; -import {initializeSealCatalog,createSealCatalogAdmin} from '../node/seal-catalog-admin.mjs'; -import {initializeBadges} from '../node/community-badges.mjs'; -import {createBanRegister} from './ban-register.mjs'; -import {createRankAdmin} from '../node/rank-admin.mjs'; -import {createOverview} from './overview.mjs'; -import {createStaffManual} from './staff-manual.mjs'; -import {createLuckPerms} from './luckperms.mjs'; -import {createCommunityAdmin} from './community-admin.mjs'; -import {createExchange} from './exchange.mjs'; -import {createIntegrationSSO} from '../node/integration-sso.mjs'; -import {createBanBridge} from './ban-bridge.mjs'; -import {sharedErrorResponse} from '../node/shared-errors.mjs'; -import {initializeNews} from '../node/news.mjs'; -import {initializeStaffBureau} from '../node/staff-bureau-schema.mjs'; -import {createStaffBureauReadApi} from '../node/staff-bureau-read-api.mjs'; -import {initializeOrganisation} from '../node/organisation-model.mjs'; -import {createLifeStatus,initializeLifeStatus} from '../node/life-status.mjs'; -import {createCitizenDirectory} from '../node/citizen-directory.mjs'; -import {createOrganisationManagement} from '../node/organisation-management.mjs'; -import {initializeRanks,initializeCommunityAccess,initializeQuestAccess,initializeBankAccess,can,accessFor} from '../node/permissions.mjs'; -import {createServer} from 'node:http'; -import {companyCPDocument} from './company-cp-shell.mjs'; -import {createCompanyWorkspace} from '../node/company-workspace.mjs'; -import {clanCPDocument} from './clan-cp-shell.mjs'; -import {politicsCPDocument} from './politics-cp-shell.mjs'; -import {createV1PersonalBank} from './api-v1-personal-bank.mjs'; -import {readFile} from 'node:fs/promises'; -import {pathToFileURL} from 'node:url'; -import {accountSchema} from './imperial-accounts.mjs'; -import {openDatabase} from '../node/mysql.mjs'; -import {createAuth} from '../node/auth.mjs'; -import {identity} from '../node/auth.mjs'; -import {createHonourRoute} from '../node/honour-route.mjs'; -import {panelBodyLimit} from './request-limits.mjs'; -import {initializeHonours} from '../node/honours.mjs'; -import {createBankClientApi} from '../node/bank-clients.mjs'; -import {createInventoryHandler,createSalesHistoryHandler} from './inventory/inventory-api.mjs'; -import {createMarketBridge} from './inventory/market-bridge.mjs'; -import {createGameLink,json} from '../node/game-link.mjs'; -import {createCommunityRewards} from '../node/community-rewards.mjs'; -import {createAccountAdmin} from '../node/account-admin.mjs'; -import {createServerControl} from './server-control.mjs'; -const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8'}; -const sharedAssets=new Set(["mentat-portraits-atlas-v1.png","organisation-deed-keys-v1.png","organisation-deeds-clan-tiers-v1.png","organisation-deeds-company-tiers-v1.png","organisation-deeds-protected-v1.png","spost-logo-v1.svg","postbank-transfer-hall-v1.png","corrino-group-v4.png","corrino-group-v3.svg","corrino-charter-v2.png","corrino-founding-marks-v1.png","consortium-corrini-v1.png","corrino-charter-v1.png","corrino-founder-v1.png","imperial-postbank-v2.png","spost-company-v1.png","vaerkring-company-v1.png","imperial-postbank-v1.png","corrino-group-logo.svg","spicepost-logo-v2.svg","spicepost-logo.svg","imperial-post-seal-v2.png","imperial-post-seal.svg","imperial-post-office-v1.png","mail-stamp-imperial.svg","mail-stamp-faction.svg","mail-stamp-staff.svg","mail-stamp-clan.svg","mail-stamp-personal.svg","imperial-post-logo.svg","ornament.webp","guild.webp","minecraft-hero.webp","menu-0.webp","reward-gold-ingot-transparent-v1.png","menu-5.webp","menu-6.webp","menu-9.webp","menu-12.webp","item-23.webp","dunemark-icon-64.png","arrakis-lore-frieze.svg","jarvis-keys-deeds-screen-v1.png"]); -export function createPanel(db,settings={},dependencies={}){ - const dmpaint=createDMPaint(db); - const clanWorkspace=createClanWorkspace(db); - const itemRegister=createItemRegister(db); - const kitsets=createKitsetAPI(db,dependencies.organisationKeys,settings); - const itemDesigns=createItemDesignAPI(db,dependencies.organisationKeys,settings); - const worldStatus=dependencies.worldStatus||createWorldStatus(settings); - const origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin; - const contactEmail=createContactEmail(db,{origin,...dependencies.contactEmail}); - const internalMail=createInternalMail(db,{origin,settings,...dependencies.internalMail}); - const terms=createFirstLoginTerms(db,origin); - const auth=createAuth(db,origin,{...settings,trackFirstLogin:true,onAccountReady:async user=>{if(dependencies.bankDatabase)await ensureRihlaAccount(dependencies.bankDatabase,user.id);if(dependencies.organisationKeys)await ensureOriginalKeys(dependencies.organisationKeys,user.id);}}),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin); - const clanDeeds=createClanDeedRoute(db,{origin}),publicClans=createPublicClans(db),publicOrganisations=createPublicOrganisations(db),organisationSettings=createOrganisationSettingsRoute(db,{origin}); - const characterChoice=createCharacterChoice(db,{origin,selectionService:dependencies.organisationKeys?createHouseSelection(db,dependencies.organisationKeys,{allowChange:true,source:'website-house-selector'}):null}),clanKeyReceipts=createClanKeyReceipts(db,{keys:dependencies.organisationKeys,origin}); - const claimProducts=dependencies.bankDatabase?new PostbankClaimProducts(db,dependencies.bankDatabase,createPostbankAuthority(db,{bank:dependencies.bankDatabase}),{readCharter:id=>readClanCharter(db,id)}):null; - const claimUpgrades=createClaimUpgrades(db,claimProducts,settings); - const protectedClaims=createProtectedClaims(db,dependencies.bankDatabase||null,createPostbankAuthority(db,{bank:dependencies.bankDatabase}),settings); - const companyClaims=createCompanyClaims(db,dependencies.bankDatabase||null,createPostbankAuthority(db,{bank:dependencies.bankDatabase}),settings); +import {ownCompanyMailbox,ensureCompanyMailbox} from '../node/internal-mail-companies.mjs'; +import {internalMailBroker} from '../node/internal-mail.mjs'; +import {applyUnicorpRoyalMailbox} from '../node/company-royal-mail.mjs'; +import {createCompanyEmblems} from './company-emblems.mjs'; +import {ensurePoliticalOfficeCharters} from '../node/political-office-charters.mjs'; +import {createCompanyRecruitment} from '../node/company-recruitment.mjs'; +import {initializeCompanyDeeds} from '../node/company-deeds.mjs'; +import {createCompanyDeedRoute} from '../node/company-deed-route.mjs'; +import {createJarvisServices} from '../node/jarvis-api.mjs'; +import {createJarvisPayments} from '../node/jarvis-payments.mjs'; +import {standardCycle} from '../node/postbank-payments.mjs'; +import {jarvisApplicationDocument} from './jarvis-application-shell.mjs'; +import {createOrganisationSettingsRoute} from '../node/organisation-settings-route.mjs'; +import {createPublicOrganisations} from '../node/public-organisations.mjs'; +import {companyCPReferenceDocument} from './company-cp-reference.mjs'; +import {politicsCPReferenceDocument} from './politics-cp-reference.mjs'; +import {createPoliticsWorkspace} from '../node/politics-workspace.mjs'; +import {initializeCodexEquipment} from '../node/codex-equipment.mjs'; +import {openOrganisationKeyService,grantCurrentAccountKeys,ensureOriginalKeys} from '../node/organisation-key-service.mjs'; +import {CHARACTER_PREFERENCE_SCHEMA} from '../node/character-preferences.mjs'; +import {CHARACTER_SCHEMA,createCharacterChoice} from './character-choice.mjs'; +import {HOUSE_SELECTION_SCHEMA,createHouseSelection,createHouseSelectionAPI} from '../node/house-selection.mjs'; +import {createGameNativeStateAPI} from '../node/game-native-state.mjs'; +import {GAME_ORGANISATION_SCHEMA,createGameOrganisationsAPI} from '../node/game-organisations.mjs'; +import {createGameBriefing,readGameMemberships} from '../node/game-briefing.mjs'; +import {createClanKeyReceipts} from './clan-key-receipts.mjs'; +import {clanDeedAuthority} from '../node/clan-deeds.mjs'; +import {createClanDeedRoute} from './clan-deed-route.mjs'; +import {createPublicClans} from '../node/public-clans.mjs'; +import {initializeClanCharters,applyRoyalClanRollout,readClanCharter} from '../node/clan-charters.mjs'; +import {resetOwnerTestClaims} from '../node/claim-test-reset.mjs'; +import {createClaimUpgrades} from './claim-upgrades.mjs'; +import {PostbankClaimProducts} from '../node/postbank-claim-products.mjs'; +import {createPostbankAuthority} from '../node/postbank-authority.mjs'; +import {createClaimOverview} from './claim-overview.mjs'; +export const PANEL_CSP="default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://usercontent.luckperms.net https://metadata.luckperms.net wss://usersockets.luckperms.net; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://pol.dunerealms.com"; +// Company artwork is served by the canonical public asset host. +export const PANEL_SERVICE_CSP="default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://pol.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://pol.dunerealms.com"; +export const COMPANY_CSP=PANEL_CSP.replace("object-src", "frame-src 'self' https://forums.dunerealms.com https://support.dunerealms.com https://www.dunerealms.com https://luckperms.net https://wiki.dunerealms.com; object-src").replace("img-src 'self' data:","img-src 'self' data: https://www.dunerealms.com"); +import {createElectionDirectory} from './election-directory.mjs'; +import {createMenuBadges} from '../node/menu-badges.mjs'; +import {startCentralScheduler} from '../node/postbank-payments.mjs'; +import {createPostbankApi} from '../node/postbank-api.mjs'; +import {openPostbankDatabase} from '../node/postbank-db.mjs'; +import {createItemRegister} from './item-register.mjs'; +import {createKitsetAPI} from './kitset-api.mjs'; +import {initializeKitsets} from '../node/kitsets.mjs'; +import {createItemDesignAPI} from './item-design-api.mjs'; +import {initializeItemDesigns} from '../node/item-designs.mjs'; +import {createManagedTransfers} from './managed-bank-transfer.mjs'; +import {createOfficialBank} from './official-bank.mjs'; +import {createBankBeneficiaries} from './bank-beneficiaries.mjs'; +import {createBankTransfers} from './bank-transfers.mjs'; +import {createHosting} from '../node/hosting.mjs'; +import {initializeOfficeLedger,startOfficeLedger} from './election-office-ledger.mjs'; +import {createMailAccounts} from '../node/mail-accounts.mjs'; +import {createElectionVoting,startElectionClock} from './election-voting.mjs'; +import {initializeBallots} from './election-ballots.mjs'; +import {initializeRounds} from './election-rounds.mjs'; +import {createImperialCharters,initializeCharters} from './imperial-charters.mjs'; +import {createProclamations,initializeProclamations} from './proclamations.mjs'; +import {createElectoralRoll} from '../node/electoral-roll.mjs'; +import {createElectionApplications} from './election-application-route.mjs'; +import {initializeApplications} from './election-applications.mjs'; +import {createInternalMail,startInternalMailSync,initializeInternalMailAccess,syncClanMailRegistry} from '../node/internal-mail.mjs'; +import {createPoliticsPreview} from './politics-preview.mjs'; +import {createPublicGovernment} from '../node/public-government.mjs'; +import{createAdminRegistration}from '../node/admin-registration.mjs'; +import{firstLoginGate,firstLoginState,initializeFirstLogin,createFirstLoginTerms}from '../node/first-login.mjs'; +import {createContactEmail,initializeContactEmails} from '../node/contact-email.mjs'; +import {isOwnerRank} from '../node/permissions.mjs'; +import {createBanEvidence,initializeBanEvidence} from './ban-evidence.mjs'; +import {createUpgradeTokens} from './upgrade-tokens.mjs'; +import {createKitCatalogueBridge} from '../node/kit-catalogue.mjs'; +import {createKitStudio} from './kit-studio.mjs'; +import {startModerationSync} from './moderation.mjs'; +import {createKitMarket} from './kit-market.mjs'; +import {createImperialAtelier} from './imperial-atelier.mjs'; +import {createGameRanks,initializeGameRanks} from '../node/game-ranks.mjs'; +import {createBanking} from './banking.mjs'; +import {createClanShop,initializeClanShop} from './clan-shop.mjs'; +import {createQuests} from './quests.mjs'; +import {createClans,initializeClans} from './clans.mjs'; +import {createClanEmblems} from './clan-emblems.mjs'; +import {createGameTickets} from './game-tickets.mjs'; +import {createQuestRewards} from './quest-rewards.mjs'; +import {openGameMysqlPool} from '../node/game-mysql-pool.mjs'; +import {retiredTicketResponse} from '../node/retired-tickets.mjs'; +import {createGitIdentityRoute,initializeGitIdentities,startGitIdentitySync,gitProxyIdentity} from '../node/git-identity.mjs'; +import {createMailIdentityRoute,initializeMailIdentities} from '../node/mail-identity.mjs'; +import {createProfile} from '../node/profile.mjs'; +import {createWorldStatus} from '../node/world-status.mjs'; +import {createMemorials} from '../node/memorials.mjs'; +import {createMemberProfiles} from '../node/member-profiles.mjs'; +import {createAvatars} from '../node/avatar.mjs'; +import {createTailorAppearance} from '../node/tailor-appearance.mjs'; +import {createBadgeAdmin} from '../node/badge-admin.mjs'; +import {createManualSealRoute} from '../node/manual-seal-route.mjs'; +import {createCompanyAdmin} from '../node/company-admin.mjs'; +import {initializeCompanyRegistry} from '../node/company-registry.mjs'; +import {initializeShareLedger} from '../node/share-ledger.mjs'; +import {initializeSealEntitlements} from '../node/seal-entitlement-store.mjs'; +import {initializeSealCatalog,createSealCatalogAdmin} from '../node/seal-catalog-admin.mjs'; +import {initializeBadges} from '../node/community-badges.mjs'; +import {createBanRegister} from './ban-register.mjs'; +import {createRankAdmin} from '../node/rank-admin.mjs'; +import {createOverview} from './overview.mjs'; +import {createStaffManual} from './staff-manual.mjs'; +import {createLuckPerms} from './luckperms.mjs'; +import {createCommunityAdmin} from './community-admin.mjs'; +import {createExchange} from './exchange.mjs'; +import {createIntegrationSSO} from '../node/integration-sso.mjs'; +import {createBanBridge} from './ban-bridge.mjs'; +import {sharedErrorResponse} from '../node/shared-errors.mjs'; +import {initializeNews} from '../node/news.mjs'; +import {initializeStaffBureau} from '../node/staff-bureau-schema.mjs'; +import {createStaffBureauReadApi} from '../node/staff-bureau-read-api.mjs'; +import {initializeOrganisation} from '../node/organisation-model.mjs'; +import {createLifeStatus,initializeLifeStatus} from '../node/life-status.mjs'; +import {createCitizenDirectory} from '../node/citizen-directory.mjs'; +import {createOrganisationManagement} from '../node/organisation-management.mjs'; +import {initializeRanks,initializeCommunityAccess,initializeQuestAccess,initializeBankAccess,can,accessFor} from '../node/permissions.mjs'; +import {createServer} from 'node:http'; +import {companyCPDocument} from './company-cp-shell.mjs'; +import {createCompanyWorkspace} from '../node/company-workspace.mjs'; +import {clanCPDocument} from './clan-cp-shell.mjs'; +import {politicsCPDocument} from './politics-cp-shell.mjs'; +import {createV1PersonalBank} from './api-v1-personal-bank.mjs'; +import {readFile} from 'node:fs/promises'; +import {pathToFileURL} from 'node:url'; +import {accountSchema} from './imperial-accounts.mjs'; +import {openDatabase} from '../node/mysql.mjs'; +import {createAuth} from '../node/auth.mjs'; +import {identity} from '../node/auth.mjs'; +import {createHonourRoute} from '../node/honour-route.mjs'; +import {panelBodyLimit} from './request-limits.mjs'; +import {initializeHonours} from '../node/honours.mjs'; +import {createBankClientApi} from '../node/bank-clients.mjs'; +import {createInventoryHandler,createSalesHistoryHandler} from './inventory/inventory-api.mjs'; +import {createMarketBridge} from './inventory/market-bridge.mjs'; +import {createGameLink,json} from '../node/game-link.mjs'; +import {createCommunityRewards} from '../node/community-rewards.mjs'; +import {createAccountAdmin} from '../node/account-admin.mjs'; +import {createServerControl} from './server-control.mjs'; +const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8'}; +const sharedAssets=new Set(["mentat-portraits-atlas-v1.png","organisation-deed-keys-v1.png","organisation-deeds-clan-tiers-v1.png","organisation-deeds-company-tiers-v1.png","organisation-deeds-protected-v1.png","spost-logo-v1.svg","postbank-transfer-hall-v1.png","corrino-group-v4.png","corrino-group-v3.svg","corrino-charter-v2.png","corrino-founding-marks-v1.png","consortium-corrini-v1.png","corrino-charter-v1.png","corrino-founder-v1.png","imperial-postbank-v2.png","spost-company-v1.png","vaerkring-company-v1.png","imperial-postbank-v1.png","corrino-group-logo.svg","spicepost-logo-v2.svg","spicepost-logo.svg","imperial-post-seal-v2.png","imperial-post-seal.svg","imperial-post-office-v1.png","mail-stamp-imperial.svg","mail-stamp-faction.svg","mail-stamp-staff.svg","mail-stamp-clan.svg","mail-stamp-personal.svg","imperial-post-logo.svg","ornament.webp","guild.webp","minecraft-hero.webp","menu-0.webp","reward-gold-ingot-transparent-v1.png","menu-5.webp","menu-6.webp","menu-9.webp","menu-12.webp","item-23.webp","dunemark-icon-64.png","arrakis-lore-frieze.svg","jarvis-keys-deeds-screen-v1.png"]); +export function createPanel(db,settings={},dependencies={}){ + const dmpaint=createDMPaint(db); + const clanWorkspace=createClanWorkspace(db); + const itemRegister=createItemRegister(db); + const kitsets=createKitsetAPI(db,dependencies.organisationKeys,settings); + const itemDesigns=createItemDesignAPI(db,dependencies.organisationKeys,settings); + const worldStatus=dependencies.worldStatus||createWorldStatus(settings); + const origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin; + const contactEmail=createContactEmail(db,{origin,...dependencies.contactEmail}); + const internalMail=createInternalMail(db,{origin,settings,...dependencies.internalMail}); + const terms=createFirstLoginTerms(db,origin); + const auth=createAuth(db,origin,{...settings,trackFirstLogin:true,onAccountReady:async user=>{if(dependencies.bankDatabase)await ensureRihlaAccount(dependencies.bankDatabase,user.id);if(dependencies.organisationKeys)await ensureOriginalKeys(dependencies.organisationKeys,user.id);}}),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin); + const clanDeeds=createClanDeedRoute(db,{origin}),publicClans=createPublicClans(db),publicOrganisations=createPublicOrganisations(db),organisationSettings=createOrganisationSettingsRoute(db,{origin}); + const characterChoice=createCharacterChoice(db,{origin,selectionService:dependencies.organisationKeys?createHouseSelection(db,dependencies.organisationKeys,{allowChange:true,source:'website-house-selector'}):null}),clanKeyReceipts=createClanKeyReceipts(db,{keys:dependencies.organisationKeys,origin}); + const claimProducts=dependencies.bankDatabase?new PostbankClaimProducts(db,dependencies.bankDatabase,createPostbankAuthority(db,{bank:dependencies.bankDatabase}),{readCharter:id=>readClanCharter(db,id)}):null; + const claimUpgrades=createClaimUpgrades(db,claimProducts,settings); + const protectedClaims=createProtectedClaims(db,dependencies.bankDatabase||null,createPostbankAuthority(db,{bank:dependencies.bankDatabase}),settings); + const companyClaims=createCompanyClaims(db,dependencies.bankDatabase||null,createPostbankAuthority(db,{bank:dependencies.bankDatabase}),settings); const homeRelocation=createHomeRelocation(db,dependencies.bankDatabase||null,dependencies.organisationKeys,settings); - const claimOverview=createClaimOverview(db,settings,{organisationAuthority:async(user,id)=>({canView:(await clanDeedAuthority(db,user.id,id)).canManage}),...(claimProducts?{readEntitlement:id=>claimProducts.entitlement(id)}:{})}); - const hosting=createHosting(db,{origin});const mailAccounts=createMailAccounts(db);const mailIdentity=createMailIdentityRoute(db,{origin}),gitIdentity=createGitIdentityRoute(db,settings,origin); - const adminRegistration=createAdminRegistration(db,origin);const admin=createAccountAdmin(db,origin),profile=createProfile(db,settings,origin),avatars=createAvatars(db,settings); - const tailorAppearance=createTailorAppearance(db,dependencies.tailorAppearance); - const memorials=createMemorials(db,{...settings,PUBLIC_ORIGIN:'https://www.dunerealms.com'}); - const memberProfiles=createMemberProfiles(db,{...settings,bankDatabase:dependencies.bankDatabase}); - const honours=createHonourRoute(db,origin);const ranks=createRankAdmin(db,settings,origin);const badges=createBadgeAdmin(db,origin);const manualSeals=createManualSealRoute(db,origin);const sealCatalog=createSealCatalogAdmin(db,origin);const companyAdmin=createCompanyAdmin(db,origin);const companyDeeds=createCompanyDeedRoute(db,{keys:dependencies.organisationKeys,origin,onCompanyCreated:async({id,ownerId})=>{await dependencies.boardRuntime?.boards.refresh('company',id).catch(()=>console.error('Company board key remains pending reconciliation'));const company=await ownCompanyMailbox(db,{id:ownerId},id);if(company)await ensureCompanyMailbox(company,internalMailBroker,db);}});const companyWorkspace=createCompanyWorkspace(db),politicsWorkspace=createPoliticsWorkspace(db,{keys:dependencies.organisationKeys}); - const manual=createStaffManual(db); - const staffBureauRead=createStaffBureauReadApi(db); - const citizenDirectory=createCitizenDirectory(db);const lifeStatus=createLifeStatus(db,{origin}); - const auctionRuntime=dependencies.officeAuctionRuntime||createOfficeAuctionRuntime(db,dependencies.bankDatabase||null);const politicalActions=createPoliticalActions(db,{enabled:!!auctionRuntime,origin});const officeAuctionAPI=createOfficeAuctionAPI(db,dependencies.bankDatabase||null,auctionRuntime,settings,dependencies.officeAuctionAPI); - const progressionRuntime=dependencies.progressionRuntime||(dependencies.organisationKeys?createProgressionRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); - const progression=createProgressionAPI(db,{...progressionRuntime,origin}); - const polRuntime=dependencies.polProgressionRuntime||(dependencies.organisationKeys?createPOLProgressionRuntime(db,dependencies.organisationKeys):null); - const gameHouseSelection=createHouseSelectionAPI(db,dependencies.organisationKeys,settings,{readBriefing:createGameBriefing({personal:progressionRuntime,pol:polRuntime,bank:dependencies.bankDatabase||null,authority:createPostbankAuthority(db,{bank:dependencies.bankDatabase||null}),organisations:actor=>readGameMemberships(db,actor)})}); - const gameQuests=createGameQuestsAPI(db,settings,{personal:progressionRuntime,pol:polRuntime}); + const claimOverview=createClaimOverview(db,settings,{organisationAuthority:async(user,id)=>({canView:(await clanDeedAuthority(db,user.id,id)).canManage}),...(claimProducts?{readEntitlement:id=>claimProducts.entitlement(id)}:{})}); + const hosting=createHosting(db,{origin});const mailAccounts=createMailAccounts(db);const mailIdentity=createMailIdentityRoute(db,{origin}),gitIdentity=createGitIdentityRoute(db,settings,origin); + const adminRegistration=createAdminRegistration(db,origin);const admin=createAccountAdmin(db,origin),profile=createProfile(db,settings,origin),avatars=createAvatars(db,settings); + const tailorAppearance=createTailorAppearance(db,dependencies.tailorAppearance); + const memorials=createMemorials(db,{...settings,PUBLIC_ORIGIN:'https://www.dunerealms.com'}); + const memberProfiles=createMemberProfiles(db,{...settings,bankDatabase:dependencies.bankDatabase}); + const honours=createHonourRoute(db,origin);const ranks=createRankAdmin(db,settings,origin);const badges=createBadgeAdmin(db,origin);const manualSeals=createManualSealRoute(db,origin);const sealCatalog=createSealCatalogAdmin(db,origin);const companyAdmin=createCompanyAdmin(db,origin);const companyDeeds=createCompanyDeedRoute(db,{keys:dependencies.organisationKeys,origin,onCompanyCreated:async({id,ownerId})=>{await dependencies.boardRuntime?.boards.refresh('company',id).catch(()=>console.error('Company board key remains pending reconciliation'));const company=await ownCompanyMailbox(db,{id:ownerId},id);if(company)await ensureCompanyMailbox(company,internalMailBroker,db);}});const companyWorkspace=createCompanyWorkspace(db),politicsWorkspace=createPoliticsWorkspace(db,{keys:dependencies.organisationKeys}); + const manual=createStaffManual(db); + const staffBureauRead=createStaffBureauReadApi(db); + const citizenDirectory=createCitizenDirectory(db);const lifeStatus=createLifeStatus(db,{origin}); + const auctionRuntime=dependencies.officeAuctionRuntime||createOfficeAuctionRuntime(db,dependencies.bankDatabase||null);const politicalActions=createPoliticalActions(db,{enabled:!!auctionRuntime,origin});const officeAuctionAPI=createOfficeAuctionAPI(db,dependencies.bankDatabase||null,auctionRuntime,settings,dependencies.officeAuctionAPI); + const progressionRuntime=dependencies.progressionRuntime||(dependencies.organisationKeys?createProgressionRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); + const progression=createProgressionAPI(db,{...progressionRuntime,origin}); + const polRuntime=dependencies.polProgressionRuntime||(dependencies.organisationKeys?createPOLProgressionRuntime(db,dependencies.organisationKeys):null); + const gameHouseSelection=createHouseSelectionAPI(db,dependencies.organisationKeys,settings,{readBriefing:createGameBriefing({personal:progressionRuntime,pol:polRuntime,bank:dependencies.bankDatabase||null,authority:createPostbankAuthority(db,{bank:dependencies.bankDatabase||null}),organisations:actor=>readGameMemberships(db,actor)})}); + const gameQuests=createGameQuestsAPI(db,settings,{personal:progressionRuntime,pol:polRuntime}); const gameQuestEvents=createGameQuestEventsAPI(db,dependencies.organisationKeys,settings); - const gameItemDesigns=createGameItemDesignAPI(db,dependencies.organisationKeys,settings); - const gameNativeState=createGameNativeStateAPI(db,settings); + const gameItemDesigns=createGameItemDesignAPI(db,dependencies.organisationKeys,settings); + const gameNativeState=createGameNativeStateAPI(db,settings); const gameOrganisations=createGameOrganisationsAPI(db,dependencies.organisationKeys,settings,{bank:dependencies.bankDatabase||null}); - const gameGuild=createGameGuildAPI(db,dependencies.bankDatabase||null,dependencies.organisationKeys,settings); - const polProgression=createProgressionAPI(polProgressionStore(db),{...polRuntime,authenticate:r=>identity(r,db),origin,basePath:'/api/progression/pol'}); - const serverProjects=dependencies.serverProjects||(dependencies.organisationKeys?createServerProjectRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); - const projectsAPI=createServerProjectAPI(db,serverProjects,{origin}); - const starterKitEvents=createStarterKitEventAPI(db,dependencies.organisationKeys,settings); - const personalActivityEvents=createPersonalActivityAPI(db,dependencies.organisationKeys,settings); - const polActivityEvents=createPOLActivityAPI(db,dependencies.organisationKeys,settings); - const masterKeyGenerator=createMasterKeyGeneratorAPI(db,dependencies.organisationKeys,{origin}); - const keyValidation=createKeyValidation(db,dependencies.organisationKeys,{origin}); - const politicalJobs=createPoliticalJobAPI(db,dependencies.bankDatabase||null,settings,{promotionChannels:dependencies.promotionDelivery?.channels||[]}); - const naibCouncil=createNaibCouncilAPI(db,settings); - const electionResults=createElectionResults(db,settings); - const electionCampaigns=createElectionCampaignAPI(db,dependencies.bankDatabase||null,settings,{promotionChannels:dependencies.promotionDelivery?.channels||[]}); - const realmEvents=createRealmEvents(db,dependencies.bankDatabase||null,{origin}); - const rihla=createRihlaAPI(db,dependencies.bankDatabase||null); - const networkLayouts=createNetworkLayoutAPI(db); - const rebellionAPI=createRebellionAPI(db,dependencies.rebellionQuests||(dependencies.organisationKeys?createRebellionQuests(db,dependencies.organisationKeys):null),{origin}); - const jarvisManagement=createJarvisManagement(db,dependencies.bankDatabase||null,settings,dependencies.jarvisManagement); - const organisationManagement=createOrganisationManagement(db,{origin}); - const luckperms=createLuckPerms(db,settings,dependencies.luckperms); - const servers=createServerControl(db,settings,dependencies.serverControl); - const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}}; - const community=createCommunityAdmin(db,settings,{pool}); + const gameGuild=createGameGuildAPI(db,dependencies.bankDatabase||null,dependencies.organisationKeys,settings); + const polProgression=createProgressionAPI(polProgressionStore(db),{...polRuntime,authenticate:r=>identity(r,db),origin,basePath:'/api/progression/pol'}); + const serverProjects=dependencies.serverProjects||(dependencies.organisationKeys?createServerProjectRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); + const projectsAPI=createServerProjectAPI(db,serverProjects,{origin}); + const starterKitEvents=createStarterKitEventAPI(db,dependencies.organisationKeys,settings); + const personalActivityEvents=createPersonalActivityAPI(db,dependencies.organisationKeys,settings); + const polActivityEvents=createPOLActivityAPI(db,dependencies.organisationKeys,settings); + const masterKeyGenerator=createMasterKeyGeneratorAPI(db,dependencies.organisationKeys,{origin}); + const keyValidation=createKeyValidation(db,dependencies.organisationKeys,{origin}); + const politicalJobs=createPoliticalJobAPI(db,dependencies.bankDatabase||null,settings,{promotionChannels:dependencies.promotionDelivery?.channels||[]}); + const naibCouncil=createNaibCouncilAPI(db,settings); + const electionResults=createElectionResults(db,settings); + const electionCampaigns=createElectionCampaignAPI(db,dependencies.bankDatabase||null,settings,{promotionChannels:dependencies.promotionDelivery?.channels||[]}); + const realmEvents=createRealmEvents(db,dependencies.bankDatabase||null,{origin}); + const rihla=createRihlaAPI(db,dependencies.bankDatabase||null); + const networkLayouts=createNetworkLayoutAPI(db); + const rebellionAPI=createRebellionAPI(db,dependencies.rebellionQuests||(dependencies.organisationKeys?createRebellionQuests(db,dependencies.organisationKeys):null),{origin}); + const jarvisManagement=createJarvisManagement(db,dependencies.bankDatabase||null,settings,dependencies.jarvisManagement); + const organisationManagement=createOrganisationManagement(db,{origin}); + const luckperms=createLuckPerms(db,settings,dependencies.luckperms); + const servers=createServerControl(db,settings,dependencies.serverControl); + const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}}; + const community=createCommunityAdmin(db,settings,{pool}); const exchange=createExchange(db,pool); const kitsetCommerce=dependencies.kitsetCommerce||(dependencies.bankDatabase&&settings.DB_NAME&&settings.DUNE_INVENTORY_DATABASE_URL?createKitsetCommerce(db,dependencies.bankDatabase,settings,{gamePool:pool}):null); const kitsetPurchase=createKitsetPurchaseAPI(db,kitsetCommerce,settings); - const gameExchange=createGameExchangeAPI(db,dependencies.bankDatabase||null,pool,settings,{kitsetCommerce}); + const gameExchange=createGameExchangeAPI(db,dependencies.bankDatabase||null,pool,settings,{kitsetCommerce}); const gameKitGrants=createGameKitGrantsAPI(db,settings,{pool,commerce:kitsetCommerce}); - let clans,companyRecruitment;const jarvis=createJarvisServices(db,dependencies.bankDatabase||null,settings,{...dependencies.jarvis,organisationKeys:dependencies.organisationKeys,deedPurchases:dependencies.deedPurchases,promotionChannels:dependencies.promotionDelivery?.channels||[],invokeClans:request=>clans(request),invokeCompany:request=>companyRecruitment(request)});companyRecruitment=createCompanyRecruitment(db,{origin,requestIntegration:jarvis.companyRequests});clans=createClans(db,{origin,onClanCreated:async({id})=>{await dependencies.boardRuntime?.boards.refresh('clan',id).catch(()=>console.error('Clan board key remains pending reconciliation'));await syncClanMailRegistry(db);},onClanDeleted:()=>syncClanMailRegistry(db),requestIntegration:jarvis.requests});const gameTickets=createGameTickets(db,settings); - const companyMailboxSettings=createCompanyMailboxSettings(db,{origin}); - const clanEmblems=createClanEmblems(db,{origin}),companyEmblems=createCompanyEmblems(db,{origin}); - const questRewards=createQuestRewards(db,settings,pool); - const gameRanks=createGameRanks(db,settings); - const kitStudio=createKitStudio(db,settings,dependencies.kitStudio); - const upgradeTokens=createUpgradeTokens(db,settings,dependencies.upgradeTokens); - const publicKitCatalogue=createKitCatalogueBridge(settings,{db,commerce:kitsetCommerce}); - const kitMarket=createKitMarket(db,settings,dependencies.kitMarket); - const imperialAtelier=createImperialAtelier(db,settings,dependencies.imperialAtelier); - const bankBeneficiaries=createBankBeneficiaries(db,dependencies.bankBeneficiaries); - const officialBank=createOfficialBank(db,settings,dependencies.officialBank); - const managedTransfers=createManagedTransfers(db,settings,dependencies.managedTransfers); - const bankTransfers=createBankTransfers(db,settings,dependencies.bankTransfers); - const banking=createBanking(db,settings,dependencies.banking); - const postbank=createPostbankApi(db,dependencies.bankDatabase||null,settings,{...dependencies.postbank,organisationKeys:dependencies.organisationKeys}); - const bankClient=createBankClientApi(db,dependencies.bankClient); - const v1PersonalBank=createV1PersonalBank(banking,{enabled:process.env.DUNE_API_V1_BANK_STAGING==='true'}); - const quests=createQuests(db,settings,dependencies.quests),clanShop=createClanShop(db,settings,dependencies.clanShop); - const sso=createIntegrationSSO(db,settings); - const overview=createOverview(db);const menuBadges=createMenuBadges(db,settings); - const banBridge=createBanBridge(db,settings,dependencies.bans); - const banRegister=createBanRegister(db,settings,dependencies.bans); - const electionDirectory=createElectionDirectory(db,dependencies.electionDirectory); - const electionVoting=createElectionVoting(db,settings,dependencies.electionVoting); - const imperialCharters=createImperialCharters(db,settings); - const proclamations=createProclamations(db,settings); - const electoralRoll=createElectoralRoll(db); - const electionApplications=createElectionApplications(db,settings,dependencies.electionApplications); - const politicsPreview=createPoliticsPreview(db,settings,dependencies.politicsPreview); - const publicGovernment=createPublicGovernment(db); - const banEvidence=createBanEvidence(db,settings,dependencies.banEvidence); - const inventoryOptions={authenticate:request=>identity(request,db),verifiedMinecraftUuid:async accountId=>(await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(accountId).first())?.minecraft_uuid||null,pool,logger:dependencies.logger||console}; - const inventory=createInventoryHandler(inventoryOptions),sales=createSalesHistoryHandler(inventoryOptions); - const market=(settings.EXCHANGE_READ_TOKEN||'').length>=32?createMarketBridge({pool,readToken:settings.EXCHANGE_READ_TOKEN}):null; - return async request=>{const retiredTickets=retiredTicketResponse(request);if(retiredTickets)return retiredTickets; - const path=new URL(request.url).pathname; - if(path==='/news-format.mjs'&&['GET','HEAD'].includes(request.method))return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/news-format.mjs',import.meta.url)),{headers:{'Content-Type':'text/javascript; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); - if(path==='/api/dmpaint'||path==='/dmpaint'||path.startsWith('/dmpaint/'))return dmpaint(request); - if(path==='/api/public/government')return publicGovernment(request); - if(['/api/menu-badges','/api/staff/menu-badges'].includes(path))return menuBadges(request); - if(['/v2/cp-v2-menu-badges.mjs','/v2/cp-v2-dunemark-collection.mjs','/v2/dunemark-catalogue.mjs'].includes(path))return new Response(await readFile(new URL('./public/cp-v2/'+path.slice(4),import.meta.url)),{headers:{'Content-Type':'text/javascript; charset=utf-8','Cache-Control':'no-store'}}); - if(path==='/api/items/catalogue')return itemRegister(request); + let clans,companyRecruitment;const jarvis=createJarvisServices(db,dependencies.bankDatabase||null,settings,{...dependencies.jarvis,organisationKeys:dependencies.organisationKeys,deedPurchases:dependencies.deedPurchases,promotionChannels:dependencies.promotionDelivery?.channels||[],invokeClans:request=>clans(request),invokeCompany:request=>companyRecruitment(request)});companyRecruitment=createCompanyRecruitment(db,{origin,requestIntegration:jarvis.companyRequests});clans=createClans(db,{origin,onClanCreated:async({id})=>{await dependencies.boardRuntime?.boards.refresh('clan',id).catch(()=>console.error('Clan board key remains pending reconciliation'));await syncClanMailRegistry(db);},onClanDeleted:()=>syncClanMailRegistry(db),requestIntegration:jarvis.requests});const gameTickets=createGameTickets(db,settings); + const companyMailboxSettings=createCompanyMailboxSettings(db,{origin}); + const clanEmblems=createClanEmblems(db,{origin}),companyEmblems=createCompanyEmblems(db,{origin}); + const questRewards=createQuestRewards(db,settings,pool); + const gameRanks=createGameRanks(db,settings); + const kitStudio=createKitStudio(db,settings,dependencies.kitStudio); + const upgradeTokens=createUpgradeTokens(db,settings,dependencies.upgradeTokens); + const publicKitCatalogue=createKitCatalogueBridge(settings,{db,commerce:kitsetCommerce}); + const kitMarket=createKitMarket(db,settings,dependencies.kitMarket); + const imperialAtelier=createImperialAtelier(db,settings,dependencies.imperialAtelier); + const bankBeneficiaries=createBankBeneficiaries(db,dependencies.bankBeneficiaries); + const officialBank=createOfficialBank(db,settings,dependencies.officialBank); + const managedTransfers=createManagedTransfers(db,settings,dependencies.managedTransfers); + const bankTransfers=createBankTransfers(db,settings,dependencies.bankTransfers); + const banking=createBanking(db,settings,dependencies.banking); + const postbank=createPostbankApi(db,dependencies.bankDatabase||null,settings,{...dependencies.postbank,organisationKeys:dependencies.organisationKeys}); + const bankClient=createBankClientApi(db,dependencies.bankClient); + const v1PersonalBank=createV1PersonalBank(banking,{enabled:process.env.DUNE_API_V1_BANK_STAGING==='true'}); + const quests=createQuests(db,settings,dependencies.quests),clanShop=createClanShop(db,settings,dependencies.clanShop); + const sso=createIntegrationSSO(db,settings); + const overview=createOverview(db);const menuBadges=createMenuBadges(db,settings); + const banBridge=createBanBridge(db,settings,dependencies.bans); + const banRegister=createBanRegister(db,settings,dependencies.bans); + const electionDirectory=createElectionDirectory(db,dependencies.electionDirectory); + const electionVoting=createElectionVoting(db,settings,dependencies.electionVoting); + const imperialCharters=createImperialCharters(db,settings); + const proclamations=createProclamations(db,settings); + const electoralRoll=createElectoralRoll(db); + const electionApplications=createElectionApplications(db,settings,dependencies.electionApplications); + const politicsPreview=createPoliticsPreview(db,settings,dependencies.politicsPreview); + const publicGovernment=createPublicGovernment(db); + const banEvidence=createBanEvidence(db,settings,dependencies.banEvidence); + const inventoryOptions={authenticate:request=>identity(request,db),verifiedMinecraftUuid:async accountId=>(await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(accountId).first())?.minecraft_uuid||null,pool,logger:dependencies.logger||console}; + const inventory=createInventoryHandler(inventoryOptions),sales=createSalesHistoryHandler(inventoryOptions); + const market=(settings.EXCHANGE_READ_TOKEN||'').length>=32?createMarketBridge({pool,readToken:settings.EXCHANGE_READ_TOKEN}):null; + return async request=>{const retiredTickets=retiredTicketResponse(request);if(retiredTickets)return retiredTickets; + const path=new URL(request.url).pathname; + if(path==='/news-format.mjs'&&['GET','HEAD'].includes(request.method))return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/news-format.mjs',import.meta.url)),{headers:{'Content-Type':'text/javascript; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + if(path==='/api/dmpaint'||path==='/dmpaint'||path.startsWith('/dmpaint/'))return dmpaint(request); + if(path==='/api/public/government')return publicGovernment(request); + if(['/api/menu-badges','/api/staff/menu-badges'].includes(path))return menuBadges(request); + if(['/v2/cp-v2-menu-badges.mjs','/v2/cp-v2-dunemark-collection.mjs','/v2/dunemark-catalogue.mjs'].includes(path))return new Response(await readFile(new URL('./public/cp-v2/'+path.slice(4),import.meta.url)),{headers:{'Content-Type':'text/javascript; charset=utf-8','Cache-Control':'no-store'}}); + if(path==='/api/items/catalogue')return itemRegister(request); if(path==='/api/items/kitsets')return kitsets(request); - if(['/api/kitsets/catalogue','/api/kitsets/purchase'].includes(path))return kitsetPurchase(request); - if(path==='/api/items/designs')return itemDesigns(request); - if(path==='/api/worlds')return request.method==='GET'?worldStatus():new Response('Method not allowed',{status:405}); - const onboarding=await firstLoginGate(request,db);if(onboarding)return onboarding; - if(settings.POSTBANK_ENABLED==='true'&&path.startsWith('/api/bank/'))return postbank(request); - if(settings.POSTBANK_ENABLED==='true'&&path==='/api/v1/me/bank')return json({message:'The game-linked bank has been retired from this website.'},410); - if(path==='/api/politics/directory'){const response=await electionDirectory(request);if(request.method==='GET'&&response.ok&&progressionRuntime){try{const visitor=await identity(request,db);if(visitor)await progressionRuntime.recordPoliticalVisit(visitor);}catch{}}return response;} - if(['/api/politics/ballot/house','/api/politics/ballot/imperial','/api/politics/ballot/bene','/api/politics/ballot/guild','/api/politics/ballot/clan_delegate','/api/politics/ballot/naib_chair'].includes(path))return electionVoting(request); - if(path==='/api/account/character')return characterChoice(request); - if(path==='/internal/game/house')return gameHouseSelection(request); - if(path==='/internal/game/native-state')return gameNativeState(request); - if(path==='/internal/game/quests')return gameQuests(request); + if(['/api/kitsets/catalogue','/api/kitsets/purchase'].includes(path))return kitsetPurchase(request); + if(path==='/api/items/designs')return itemDesigns(request); + if(path==='/api/worlds')return request.method==='GET'?worldStatus():new Response('Method not allowed',{status:405}); + const onboarding=await firstLoginGate(request,db);if(onboarding)return onboarding; + if(settings.POSTBANK_ENABLED==='true'&&path.startsWith('/api/bank/'))return postbank(request); + if(settings.POSTBANK_ENABLED==='true'&&path==='/api/v1/me/bank')return json({message:'The game-linked bank has been retired from this website.'},410); + if(path==='/api/politics/directory'){const response=await electionDirectory(request);if(request.method==='GET'&&response.ok&&progressionRuntime){try{const visitor=await identity(request,db);if(visitor)await progressionRuntime.recordPoliticalVisit(visitor);}catch{}}return response;} + if(['/api/politics/ballot/house','/api/politics/ballot/imperial','/api/politics/ballot/bene','/api/politics/ballot/guild','/api/politics/ballot/clan_delegate','/api/politics/ballot/naib_chair'].includes(path))return electionVoting(request); + if(path==='/api/account/character')return characterChoice(request); + if(path==='/internal/game/house')return gameHouseSelection(request); + if(path==='/internal/game/native-state')return gameNativeState(request); + if(path==='/internal/game/quests')return gameQuests(request); if(path==='/internal/game/quest-events')return gameQuestEvents(request); - if(path==='/internal/game/item-designs')return gameItemDesigns(request); - if(path==='/internal/game/organisations')return gameOrganisations(request); + if(path==='/internal/game/item-designs')return gameItemDesigns(request); + if(path==='/internal/game/organisations')return gameOrganisations(request); if(path==='/internal/game/home-relocation')return homeRelocation.cleanupAPI(request); if(path==='/internal/game/guild')return gameGuild(request); - if(path==='/internal/game/exchange')return gameExchange(request); + if(path==='/internal/game/exchange')return gameExchange(request); if(path==='/internal/game/kit-grants')return gameKitGrants(request); - if(path==='/api/organisation-keys')return clanKeyReceipts(request); - if(path.startsWith('/api/clan-deeds/'))return clanDeeds(request); - if(/^\/api\/public\/(companies|political-houses)(?:\/|$)/.test(path))return publicOrganisations(request); - if(path==='/api/rihla')return rihla(request); - if(path==='/api/network/layout')return networkLayouts(request); - if(path==='/api/politics/my-offices'||path==='/api/politics/resign')return politicalActions(request); - if(path==='/api/jarvis/auctions'||path==='/api/jarvis/auction'||path==='/api/jarvis/auctions/bid')return officeAuctionAPI(request); - if(['/api/jarvis/generator','/api/jarvis/generator/redeem','/api/jarvis/generator/history','/api/jarvis/generator/options'].includes(path))return masterKeyGenerator(request); - if(path==='/api/jarvis/validate')return keyValidation(request); - if(path==='/api/politics/naibs'||path==='/api/politics/naibs/propose'||path==='/api/politics/naibs/vote')return naibCouncil(request); - if(path.startsWith('/api/jarvis/political-jobs'))return politicalJobs.api(request); - if(['/api/jarvis/campaigns','/api/jarvis/campaigns/public'].includes(path))return electionCampaigns(request); - if(path==='/api/jarvis/events')return realmEvents(request); - if(path==='/api/jarvis/management')return jarvisManagement(request); - if(path.startsWith('/api/jarvis/'))return jarvis.api(request); - if(path.startsWith('/api/organisations/'))return organisationSettings(request); - if(path.startsWith('/api/public/clans/'))return publicClans(request); - if(path==='/api/politics/charters')return imperialCharters(request); - if(path==='/api/politics/proclamations')return proclamations(request); - if(path==='/api/politics/electoral-roll')return electoralRoll(request); - if(path.startsWith('/api/politics/results/'))return electionResults(request); - if(path==='/api/politics/applications')return electionApplications(request); - if(path==='/api/politics/preview')return politicsPreview(request); - if(path==='/api/admin/register-user')return adminRegistration(request); - if(path==='/api/admin/life-status')return lifeStatus(request); - if(path==='/api/admin/citizens'||path.startsWith('/api/admin/citizens/'))return citizenDirectory(request); - if(path.startsWith('/api/admin/organisation/'))return organisationManagement(request); - if(path==='/api/account/email')return contactEmail(request); - if(path.startsWith('/api/people/'))return memberProfiles(request); - if(path==='/profile-login'&&request.method==='GET'){ - const username=new URL(request.url).searchParams.get('username');if(!/^[a-z0-9_]{3,32}$/.test(username||'')||!await db.prepare("SELECT id FROM site_accounts WHERE username=? AND password_hash NOT LIKE '!%'").bind(username).first())return new Response('Profile not found',{status:404}); - return Response.redirect(await identity(request,db)?'https://www.dunerealms.com/people/'+username:origin+'/?return_to='+encodeURIComponent('/profile-login?username='+username),302); - } - if(path==='/memorial-login'&&request.method==='GET'){ - const slug=new URL(request.url).searchParams.get('slug');if(!/^[a-z0-9-]{3,64}$/.test(slug||'')||!await db.prepare('SELECT slug FROM site_memorials WHERE slug=?').bind(slug).first())return new Response('Memorial not found',{status:404}); - return Response.redirect(await identity(request,db)?'https://www.dunerealms.com/memorial/'+slug:origin+'/?return_to='+encodeURIComponent('/memorial-login?slug='+slug),302); - } - if(path.startsWith('/api/memorials/')){ - const from=request.headers.get('origin'),allowed='https://www.dunerealms.com';if(from&&from!==allowed)return new Response(null,{status:403}); - const headers={'Access-Control-Allow-Origin':allowed,'Access-Control-Allow-Credentials':'true','Access-Control-Allow-Methods':'GET, POST, OPTIONS','Access-Control-Allow-Headers':'Content-Type','Vary':'Origin','Cache-Control':'no-store'}; - if(request.method==='OPTIONS')return new Response(null,{status:204,headers}); - const result=await memorials(request),out=new Headers(result.headers);for(const[k,v]of Object.entries(headers))out.set(k,v);return new Response(result.body,{status:result.status,headers:out}); - } - if(path==='/api/game/tickets')return gameTickets(request); - if(['/api/game/quest/discover','/api/quest/rewards','/api/quest/rewards/claim'].includes(path))return questRewards(request); - if(path==='/api/imperial-atelier')return imperialAtelier(request); - if(path==='/internal/kits/catalogue')return publicKitCatalogue(request); - if(['/api/kits/studio','/api/kits/server-studio'].includes(path))return kitStudio(request); - if(path==='/api/kits/upgrade-tokens')return upgradeTokens(request); - if(path.startsWith('/api/kits/'))return kitMarket(request); - if(path==='/api/ranks/game')return gameRanks(request); - if(path==='/api/bank/beneficiaries')return bankBeneficiaries(request); - if(path==='/api/bank/official')return officialBank(request); - if(path==='/api/bank/managed-transfer')return managedTransfers(request); - if(path==='/api/bank/transfer-own'||path==='/api/bank/remittance')return bankTransfers(request); - if(path==='/api/bank/client')return bankClient(request); - if(path==='/api/bank/personal'||path==='/api/bank/staff'||path==='/api/bank/faction')return banking(request); - if(path==='/api/v1/me/bank')return v1PersonalBank(request); - if(path==='/api/quests'||path.startsWith('/api/quests/'))return quests(request); - if(['/api/clans/shop','/api/clans/shop/price','/api/clans/game-context'].includes(path))return clanShop(request); - if(path.startsWith('/api/clan-emblems/'))return clanEmblems(request); - if(path.startsWith('/api/company-emblems/'))return companyEmblems(request); - if(['/api/clans/decisions/rebellion','/api/politics/decisions/rebellion'].includes(path))return rebellionAPI(request); - if(path==='/api/clans/workspace')return clanWorkspace(request); - if(path==='/api/clans'||path.startsWith('/api/clans/'))return clans(request); - if(path.startsWith('/api/hosting/'))return hosting(request); - if(path==='/api/mail/accounts')return mailAccounts(request); - if(path.startsWith('/api/internal-mail/'))return internalMail(request); - if(path==='/api/git/me')return gitIdentity(request); - if(['/api/mail/me','/api/mail/password','/api/mail/signature','/api/mail/template'].includes(path))return mailIdentity(request); - if(['/api/account/profile','/api/account/avatar','/api/account/avatar/remove'].includes(path))return profile(request); - if(path.startsWith('/api/avatars/'))return avatars(request); - if(path==='/api/tailor/appearance'||path==='/api/tailor/skin')return tailorAppearance(request); - if(path==='/api/badges')return badges(request); - if(path==='/api/seals/manual')return manualSeals(request); - if(path==='/api/seals/catalog'||path.startsWith('/api/seals/artwork/'))return sealCatalog(request); - if(path==='/api/companies/recruitment')return companyRecruitment(request); - if(path==='/api/companies/deeds'||path.startsWith('/api/companies/deeds/'))return companyDeeds(request); - if(path==='/api/companies/workspace')return companyWorkspace(request); - if(/^\/api\/companies\/[a-f0-9-]{36}\/mailbox$/i.test(path))return companyMailboxSettings(request); - if(path==='/api/politics/workspace')return politicsWorkspace(request); - if(path==='/api/companies/manage')return companyAdmin(request); - if(path.startsWith('/api/v1/staff/'))return staffBureauRead(request); - if(path==='/api/ban-register')return banRegister(request); - if(path==='/api/ban-evidence'||path==='/api/ban-evidence/file')return banEvidence(request); - if(path==='/api/public/bans'&&request.method==='GET')return banBridge.publicBans(); - if(path==='/api/overview'||path==='/api/overview/staff')return overview(request); - const sharedError=await sharedErrorResponse(request);if(sharedError)return sharedError; - if(path.startsWith('/internal/progression/personal/'))return personalActivityEvents(request); - if(path.startsWith('/internal/progression/pol/'))return polActivityEvents(request); - if(path.startsWith('/internal/equipment/'))return starterKitEvents(request); - if(path==='/internal/integrations/ban')return banBridge.handle(request); - if(path==='/sso/authorize'||path.startsWith('/internal/integrations/'))return sso(request); - if(path==='/api/v1/claims/upgrades')return claimUpgrades(request); - if(path==='/api/v1/claims/overview')return claimOverview(request); + if(path==='/api/organisation-keys')return clanKeyReceipts(request); + if(path.startsWith('/api/clan-deeds/'))return clanDeeds(request); + if(/^\/api\/public\/(companies|political-houses)(?:\/|$)/.test(path))return publicOrganisations(request); + if(path==='/api/rihla')return rihla(request); + if(path==='/api/network/layout')return networkLayouts(request); + if(path==='/api/politics/my-offices'||path==='/api/politics/resign')return politicalActions(request); + if(path==='/api/jarvis/auctions'||path==='/api/jarvis/auction'||path==='/api/jarvis/auctions/bid')return officeAuctionAPI(request); + if(['/api/jarvis/generator','/api/jarvis/generator/redeem','/api/jarvis/generator/history','/api/jarvis/generator/options'].includes(path))return masterKeyGenerator(request); + if(path==='/api/jarvis/validate')return keyValidation(request); + if(path==='/api/politics/naibs'||path==='/api/politics/naibs/propose'||path==='/api/politics/naibs/vote')return naibCouncil(request); + if(path.startsWith('/api/jarvis/political-jobs'))return politicalJobs.api(request); + if(['/api/jarvis/campaigns','/api/jarvis/campaigns/public'].includes(path))return electionCampaigns(request); + if(path==='/api/jarvis/events')return realmEvents(request); + if(path==='/api/jarvis/management')return jarvisManagement(request); + if(path.startsWith('/api/jarvis/'))return jarvis.api(request); + if(path.startsWith('/api/organisations/'))return organisationSettings(request); + if(path.startsWith('/api/public/clans/'))return publicClans(request); + if(path==='/api/politics/charters')return imperialCharters(request); + if(path==='/api/politics/proclamations')return proclamations(request); + if(path==='/api/politics/electoral-roll')return electoralRoll(request); + if(path.startsWith('/api/politics/results/'))return electionResults(request); + if(path==='/api/politics/applications')return electionApplications(request); + if(path==='/api/politics/preview')return politicsPreview(request); + if(path==='/api/admin/register-user')return adminRegistration(request); + if(path==='/api/admin/life-status')return lifeStatus(request); + if(path==='/api/admin/citizens'||path.startsWith('/api/admin/citizens/'))return citizenDirectory(request); + if(path.startsWith('/api/admin/organisation/'))return organisationManagement(request); + if(path==='/api/account/email')return contactEmail(request); + if(path.startsWith('/api/people/'))return memberProfiles(request); + if(path==='/profile-login'&&request.method==='GET'){ + const username=new URL(request.url).searchParams.get('username');if(!/^[a-z0-9_]{3,32}$/.test(username||'')||!await db.prepare("SELECT id FROM site_accounts WHERE username=? AND password_hash NOT LIKE '!%'").bind(username).first())return new Response('Profile not found',{status:404}); + return Response.redirect(await identity(request,db)?'https://www.dunerealms.com/people/'+username:origin+'/?return_to='+encodeURIComponent('/profile-login?username='+username),302); + } + if(path==='/memorial-login'&&request.method==='GET'){ + const slug=new URL(request.url).searchParams.get('slug');if(!/^[a-z0-9-]{3,64}$/.test(slug||'')||!await db.prepare('SELECT slug FROM site_memorials WHERE slug=?').bind(slug).first())return new Response('Memorial not found',{status:404}); + return Response.redirect(await identity(request,db)?'https://www.dunerealms.com/memorial/'+slug:origin+'/?return_to='+encodeURIComponent('/memorial-login?slug='+slug),302); + } + if(path.startsWith('/api/memorials/')){ + const from=request.headers.get('origin'),allowed='https://www.dunerealms.com';if(from&&from!==allowed)return new Response(null,{status:403}); + const headers={'Access-Control-Allow-Origin':allowed,'Access-Control-Allow-Credentials':'true','Access-Control-Allow-Methods':'GET, POST, OPTIONS','Access-Control-Allow-Headers':'Content-Type','Vary':'Origin','Cache-Control':'no-store'}; + if(request.method==='OPTIONS')return new Response(null,{status:204,headers}); + const result=await memorials(request),out=new Headers(result.headers);for(const[k,v]of Object.entries(headers))out.set(k,v);return new Response(result.body,{status:result.status,headers:out}); + } + if(path==='/api/game/tickets')return gameTickets(request); + if(['/api/game/quest/discover','/api/quest/rewards','/api/quest/rewards/claim'].includes(path))return questRewards(request); + if(path==='/api/imperial-atelier')return imperialAtelier(request); + if(path==='/internal/kits/catalogue')return publicKitCatalogue(request); + if(['/api/kits/studio','/api/kits/server-studio'].includes(path))return kitStudio(request); + if(path==='/api/kits/upgrade-tokens')return upgradeTokens(request); + if(path.startsWith('/api/kits/'))return kitMarket(request); + if(path==='/api/ranks/game')return gameRanks(request); + if(path==='/api/bank/beneficiaries')return bankBeneficiaries(request); + if(path==='/api/bank/official')return officialBank(request); + if(path==='/api/bank/managed-transfer')return managedTransfers(request); + if(path==='/api/bank/transfer-own'||path==='/api/bank/remittance')return bankTransfers(request); + if(path==='/api/bank/client')return bankClient(request); + if(path==='/api/bank/personal'||path==='/api/bank/staff'||path==='/api/bank/faction')return banking(request); + if(path==='/api/v1/me/bank')return v1PersonalBank(request); + if(path==='/api/quests'||path.startsWith('/api/quests/'))return quests(request); + if(['/api/clans/shop','/api/clans/shop/price','/api/clans/game-context'].includes(path))return clanShop(request); + if(path.startsWith('/api/clan-emblems/'))return clanEmblems(request); + if(path.startsWith('/api/company-emblems/'))return companyEmblems(request); + if(['/api/clans/decisions/rebellion','/api/politics/decisions/rebellion'].includes(path))return rebellionAPI(request); + if(path==='/api/clans/workspace')return clanWorkspace(request); + if(path==='/api/clans'||path.startsWith('/api/clans/'))return clans(request); + if(path.startsWith('/api/hosting/'))return hosting(request); + if(path==='/api/mail/accounts')return mailAccounts(request); + if(path.startsWith('/api/internal-mail/'))return internalMail(request); + if(path==='/api/git/me')return gitIdentity(request); + if(['/api/mail/me','/api/mail/password','/api/mail/signature','/api/mail/template'].includes(path))return mailIdentity(request); + if(['/api/account/profile','/api/account/avatar','/api/account/avatar/remove'].includes(path))return profile(request); + if(path.startsWith('/api/avatars/'))return avatars(request); + if(path==='/api/tailor/appearance'||path==='/api/tailor/skin')return tailorAppearance(request); + if(path==='/api/badges')return badges(request); + if(path==='/api/seals/manual')return manualSeals(request); + if(path==='/api/seals/catalog'||path.startsWith('/api/seals/artwork/'))return sealCatalog(request); + if(path==='/api/companies/recruitment')return companyRecruitment(request); + if(path==='/api/companies/deeds'||path.startsWith('/api/companies/deeds/'))return companyDeeds(request); + if(path==='/api/companies/workspace')return companyWorkspace(request); + if(/^\/api\/companies\/[a-f0-9-]{36}\/mailbox$/i.test(path))return companyMailboxSettings(request); + if(path==='/api/politics/workspace')return politicsWorkspace(request); + if(path==='/api/companies/manage')return companyAdmin(request); + if(path.startsWith('/api/v1/staff/'))return staffBureauRead(request); + if(path==='/api/ban-register')return banRegister(request); + if(path==='/api/ban-evidence'||path==='/api/ban-evidence/file')return banEvidence(request); + if(path==='/api/public/bans'&&request.method==='GET')return banBridge.publicBans(); + if(path==='/api/overview'||path==='/api/overview/staff')return overview(request); + const sharedError=await sharedErrorResponse(request);if(sharedError)return sharedError; + if(path.startsWith('/internal/progression/personal/'))return personalActivityEvents(request); + if(path.startsWith('/internal/progression/pol/'))return polActivityEvents(request); + if(path.startsWith('/internal/equipment/'))return starterKitEvents(request); + if(path==='/internal/integrations/ban')return banBridge.handle(request); + if(path==='/sso/authorize'||path.startsWith('/internal/integrations/'))return sso(request); + if(path==='/api/v1/claims/upgrades')return claimUpgrades(request); + if(path==='/api/v1/claims/overview')return claimOverview(request); if(path==='/api/v1/claims/home-relocation')return homeRelocation.api(request); - if(path==='/api/v1/protected-claims/overview')return protectedClaims.overview(request); - if(path==='/api/v1/protected-claims/home-block')return protectedClaims.homeBlock(request); - if(path==='/api/v1/protected-claims/upgrades')return protectedClaims.upgrades(request); - if(path==='/api/v1/company-claims/overview')return companyClaims.overview(request); - if(path==='/api/v1/company-claims/home-block')return companyClaims.homeBlock(request); - if(path==='/api/v1/company-claims/upgrades')return companyClaims.upgrades(request); - if(path==='/api/exchange/listings')return exchange(request); - if(path==='/api/projects'||path.startsWith('/api/projects/'))return projectsAPI(request); - if(path==='/api/progression/pol'||path.startsWith('/api/progression/pol/'))return polProgression(request); - if(path==='/api/progression'||path.startsWith('/api/progression/'))return progression(request); - if(path.startsWith('/api/cp/'))return community(request); - if(path.startsWith('/luckperms-editor/')){ - const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401); - if(!isOwnerRank((await accessFor(db,user)).rank)||!await can(db,user,'web.menu.luckperms')||!await can(db,user,'web.luckperms.edit'))return json({message:'LuckPerms editor access is restricted to Owners with web.luckperms.edit.'},403); - if(!['GET','HEAD'].includes(request.method))return json({message:'Method not allowed'},405); - let file=path.slice('/luckperms-editor/'.length); - if(!file||/^editor(?:\/[A-Za-z0-9_-]{3,200})?\/?$/.test(file))file='index.html'; - if(!/^[A-Za-z0-9_./-]+$/.test(file)||file.includes('..'))return json({message:'Not found'},404); - const extension=file.slice(file.lastIndexOf('.')),mime={...types,'.svg':'image/svg+xml','.png':'image/png','.ico':'image/x-icon','.woff':'font/woff','.woff2':'font/woff2','.ttf':'font/ttf','.txt':'text/plain; charset=utf-8'}[extension]; - if(!mime)return json({message:'Not found'},404); - try{return new Response(request.method==='HEAD'?null:await readFile(new URL('./native-editor/'+file,import.meta.url)),{headers:{'Content-Type':mime,'Cache-Control':'private, no-store','Content-Security-Policy':PANEL_CSP}});}catch{return json({message:'Native LuckPerms editor build is unavailable.'},404);} - } - if(path.startsWith('/api/luckperms/'))return luckperms(request); - if(path==='/api/staff/manual')return manual(request); - if(path==='/api/ranks/honour')return honours(request); - if(path==='/api/game/permissions'||path==='/api/ranks'||path.startsWith('/api/ranks/'))return ranks(request); - const menu=path==='/api/inventory'||path==='/api/exchange/sales-history'?'web.menu.inventory':(path==='/api/game-link'||path.startsWith('/api/game-link/')&&path!=='/api/game-link/consume')?'web.menu.game':path==='/api/community/rewards'?'web.menu.rewards':null; - if(menu){const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401);if(!await can(db,user,menu))return json({message:'Permission required: '+menu},403);} - if(path==='/api/servers'||path.startsWith('/api/servers/'))return servers(request); - if(path==='/api/inventory')return inventory(request); - if(path==='/api/exchange/sales-history')return sales(request); - if(path==='/internal/exchange/listings')return market?market(request):new Response('Not configured',{status:503,headers:{'Cache-Control':'no-store'}}); - if(path.startsWith('/api/admin/'))return admin(request); - if(path==='/healthz'){await db.prepare('SELECT 1 AS ok').first();return json({status:'ok'});} - if(path==='/api/welcome'&&request.method==='GET'){const allowed=new Set(['https://corp.dunerealms.com','https://www.dunerealms.com','https://dunerealms.com','https://forums.dunerealms.com','https://support.dunerealms.com','https://clans.dunerealms.com','https://wiki.dunerealms.com','https://cp.dunerealms.com']);const origin=request.headers.get('origin');if(origin&&!allowed.has(origin))return new Response(null,{status:403});const user=await identity(request,db);return new Response(JSON.stringify({username:user?.username||null}),{headers:{'Content-Type':'application/json','Cache-Control':'no-store','Vary':'Origin',...(origin?{'Access-Control-Allow-Origin':origin,'Access-Control-Allow-Credentials':'true'}:{})}});} - if(path==='/api/auth/terms')return terms(request); - if(path==='/api/auth/session'&&request.method==='GET'){const response=await auth(request),data=await response.json();if(data.user)data.user.firstLogin=await firstLoginState(db,await identity(request,db));return json(data);} - if(path.startsWith('/api/auth/'))return auth(request); - if(path==='/api/game-link'||path.startsWith('/api/game-link/'))return links(request); - if(path.startsWith('/api/community/'))return rewards(request); - if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405}); - if(/^\/kit-textures\/(?:entity\/(?:banner\/[a-z_]+|equipment\/(?:humanoid|humanoid_leggings)\/netherite)|trims\/(?:color_palettes\/[a-z_]+|entity\/(?:humanoid|humanoid_leggings)\/[a-z_]+))\.png$/.test(path)){ - try{return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+path.slice(1),import.meta.url)),{headers:{'Content-Type':'image/png','Cache-Control':'public, max-age=86400'}});}catch{return new Response('Texture not found',{status:404});} - } - if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});} - if(path==='/federal-reserve'||path==='/federal-reserve/')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/reserve-ledger.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); - // V2 shell is public; private data and writes retain their authenticated API gates. - if(path==='/company-cp-reference'||path==='/politics-cp-reference'){const source=await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8');return new Response(request.method==='HEAD'?null:(path==='/company-cp-reference'?companyCPReferenceDocument:politicsCPReferenceDocument)(source),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff',...(path==='/company-cp-reference'?{'Content-Security-Policy':COMPANY_CSP}:{})}});} - if(path==='/political-job')return new Response(request.method==='HEAD'?null:jarvisApplicationDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')).replace('cp-v2-jarvis-application.mjs','cp-v2-political-job-application.mjs'),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}}); - if(path==='/jarvis-auction')return new Response(request.method==='HEAD'?null:jarvisAuctionDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); - if(path==='/join-company')return new Response(request.method==='HEAD'?null:jarvisApplicationDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')).replace('cp-v2-jarvis-application.mjs','cp-v2-company-application.mjs'),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}}); - if(path==='/deed-purchase')return new Response(request.method==='HEAD'?null:jarvisApplicationDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')).replace('cp-v2-jarvis-application.mjs','cp-v2-deed-purchase.mjs').replace('DuneRealms · Recruitment Application','DuneRealms · Deed Purchase'),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}}); - if(path==='/jarvis-application')return new Response(request.method==='HEAD'?null:jarvisApplicationDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}}); - if(path==='/company-cp')return new Response(request.method==='HEAD'?null:companyCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Security-Policy':COMPANY_CSP,'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); - if(path==='/clan-cp')return new Response(request.method==='HEAD'?null:clanCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); - if(path==='/politics-cp')return new Response(request.method==='HEAD'?null:politicsCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); - const calendarVendorFiles=new Set(['fullcalendar.global.min.js','monarch.global.min.js','skeleton.css','monarch.css','palette.css','LICENSE.md','SOURCE.json']); - if(path.startsWith('/v2/vendor/fullcalendar/')&&['GET','HEAD'].includes(request.method)){const file=path.slice('/v2/vendor/fullcalendar/'.length);if(!calendarVendorFiles.has(file))return new Response('Not found',{status:404});const type=file.endsWith('.js')?'text/javascript':file.endsWith('.css')?'text/css':file.endsWith('.json')?'application/json':'text/plain';return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/vendor/fullcalendar/'+file,import.meta.url)),{headers:{'Content-Type':type+'; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});} - // All authored cp-v2 browser modules share this bounded public directory. - // New components must not require a second, manually maintained route list. - if(path==='/mentat-report')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/cp-v2-mentat-embed.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff','Content-Security-Policy':PANEL_CSP.replace("img-src 'self' data:;","img-src 'self' data: https://www.dunerealms.com;")}}); - if(/^\/(?:v2|cp-v2)\/cp-v2-[a-z0-9-]+\.(?:mjs|css)$/.test(path)){ - try{const bytes=await readFile(new URL('./public/cp-v2/'+path.slice(path.lastIndexOf('/')+1),import.meta.url));return new Response(request.method==='HEAD'?null:bytes,{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});}catch(error){if(error.code==='ENOENT')return new Response('Not found',{status:404});throw error;} - } - if(['/v2/faith-theme-loader.mjs','/v2/faith-theme.css','/v2/cp-v2-codex-management.mjs','/v2/cp-v2-codex-management.css','/v2/cp-v2-exchange-design.mjs','/v2/cp-v2-exchange-design.css'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice(4),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'no-store','Access-Control-Allow-Origin':'*'}}); - if(['/jarvis-master-keys.mjs','/jarvis-brand.mjs','/organisation-tabs.mjs','/organisation-tabs.css','/codex-code-format.mjs','/codex-dossier-format.mjs'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+path.slice(1),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'no-store','Access-Control-Allow-Origin':'*'}}); - if(['/v2/citizen-directory.mjs','/v2/citizen-directory.css','/v2/organisation-permissions.mjs'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice('/v2/'.length),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); - if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-authorisations.mjs','/v2/cp-v2-tax-treasury.mjs','/v2/cp-v2-reserve-ledger.mjs','/v2/cp-v2-reserve-entry.mjs','/v2/cp-v2-postbank-credit.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-code-redemption.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){ - const moduleFile=path.endsWith('.mjs')||path.endsWith('.js'); - const file=path.endsWith('.mjs')?path.slice('/v2/'.length):path.endsWith('.js')?'v2.js':path.endsWith('.css')?'v2.css':'index.html'; - return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); - } - const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1); - if(!['kitset-model.mjs','item-design-model.mjs','item-metadata-policy.mjs','mining-tool-policy.mjs','tool-template-policy.mjs','equipment-template-policy.mjs','organisation-refit-policy.mjs','action-cooldown-policy.mjs','faith-pol-policy.mjs','item-lore-model.mjs','item-lore-view.mjs','item-lore.css','organisation-editor.mjs','organisation-register.mjs','user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','starter-kit-policy.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-directory-view.mjs','clan-profile-panels.mjs','clan-titles.mjs','dynastic-address.mjs','organisation-palette.mjs','organisation-palette-model.mjs','organisation-palette.css','clan-dynasty.mjs','clan-dynasty.css','clan-deed-settings.mjs','dune-date.mjs','organisation-settings.mjs','organisation-settings.css','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); - return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}}); - }; -} -export async function startPanel(settings=process.env){ - let inventoryPool=null; - if(settings.DUNE_INVENTORY_DATABASE_URL){ - if(settings.DUNE_INVENTORY_DATABASE_URL.startsWith('mysql:'))inventoryPool=await openGameMysqlPool(settings.DUNE_INVENTORY_DATABASE_URL); - else{const {Pool}=await import('pg');inventoryPool=new Pool({connectionString:settings.DUNE_INVENTORY_DATABASE_URL,max:3,connectionTimeoutMillis:5000,idleTimeoutMillis:30000});} - inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); - } - const bankDatabase=await openPostbankDatabase(settings); - const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; - await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db); - const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]}); - const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':PANEL_SERVICE_CSP}; - const server=createServer(async(req,res)=>{try{ - req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);} - if(!req.url?.startsWith('/')||req.url.startsWith('//')){res.writeHead(400,security);res.end();return;} - const result=await handle(new Request(origin+req.url,{method:req.method,headers:req.headers,...(!['GET','HEAD'].includes(req.method)?{body:Buffer.concat(chunks)}:{})})); - const headers=new Headers(security);result.headers.forEach((value,key)=>headers.set(key,value)); - res.writeHead(result.status,Object.fromEntries(headers));res.end(Buffer.from(await result.arrayBuffer())); - }catch(error){console.error('Panel request failed:',error.code||error.name);res.writeHead(503,security);res.end('{"message":"The account panel is temporarily unavailable."}');}}); - server.headersTimeout=10000;server.requestTimeout=30000; - await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(Number(settings.CP_PORT||3003),'127.0.0.1',resolve);}); - process.once('SIGTERM',()=>{stopOfficeLedger();stopElectionClock();stopBanSync();stopInternalMail();stopCentralScheduler();server.close(async()=>{await Promise.allSettled([db.close(),bankDatabase?.close(),inventoryPool?.end(),starterKitDelivery.close()]);process.exit(0);});});console.log('Account panel listening on localhost');return server; -} -if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)await startPanel(); + if(path==='/api/v1/protected-claims/overview')return protectedClaims.overview(request); + if(path==='/api/v1/protected-claims/home-block')return protectedClaims.homeBlock(request); + if(path==='/api/v1/protected-claims/upgrades')return protectedClaims.upgrades(request); + if(path==='/api/v1/company-claims/overview')return companyClaims.overview(request); + if(path==='/api/v1/company-claims/home-block')return companyClaims.homeBlock(request); + if(path==='/api/v1/company-claims/upgrades')return companyClaims.upgrades(request); + if(path==='/api/exchange/listings')return exchange(request); + if(path==='/api/projects'||path.startsWith('/api/projects/'))return projectsAPI(request); + if(path==='/api/progression/pol'||path.startsWith('/api/progression/pol/'))return polProgression(request); + if(path==='/api/progression'||path.startsWith('/api/progression/'))return progression(request); + if(path.startsWith('/api/cp/'))return community(request); + if(path.startsWith('/luckperms-editor/')){ + const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401); + if(!isOwnerRank((await accessFor(db,user)).rank)||!await can(db,user,'web.menu.luckperms')||!await can(db,user,'web.luckperms.edit'))return json({message:'LuckPerms editor access is restricted to Owners with web.luckperms.edit.'},403); + if(!['GET','HEAD'].includes(request.method))return json({message:'Method not allowed'},405); + let file=path.slice('/luckperms-editor/'.length); + if(!file||/^editor(?:\/[A-Za-z0-9_-]{3,200})?\/?$/.test(file))file='index.html'; + if(!/^[A-Za-z0-9_./-]+$/.test(file)||file.includes('..'))return json({message:'Not found'},404); + const extension=file.slice(file.lastIndexOf('.')),mime={...types,'.svg':'image/svg+xml','.png':'image/png','.ico':'image/x-icon','.woff':'font/woff','.woff2':'font/woff2','.ttf':'font/ttf','.txt':'text/plain; charset=utf-8'}[extension]; + if(!mime)return json({message:'Not found'},404); + try{return new Response(request.method==='HEAD'?null:await readFile(new URL('./native-editor/'+file,import.meta.url)),{headers:{'Content-Type':mime,'Cache-Control':'private, no-store','Content-Security-Policy':PANEL_CSP}});}catch{return json({message:'Native LuckPerms editor build is unavailable.'},404);} + } + if(path.startsWith('/api/luckperms/'))return luckperms(request); + if(path==='/api/staff/manual')return manual(request); + if(path==='/api/ranks/honour')return honours(request); + if(path==='/api/game/permissions'||path==='/api/ranks'||path.startsWith('/api/ranks/'))return ranks(request); + const menu=path==='/api/inventory'||path==='/api/exchange/sales-history'?'web.menu.inventory':(path==='/api/game-link'||path.startsWith('/api/game-link/')&&path!=='/api/game-link/consume')?'web.menu.game':path==='/api/community/rewards'?'web.menu.rewards':null; + if(menu){const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401);if(!await can(db,user,menu))return json({message:'Permission required: '+menu},403);} + if(path==='/api/servers'||path.startsWith('/api/servers/'))return servers(request); + if(path==='/api/inventory')return inventory(request); + if(path==='/api/exchange/sales-history')return sales(request); + if(path==='/internal/exchange/listings')return market?market(request):new Response('Not configured',{status:503,headers:{'Cache-Control':'no-store'}}); + if(path.startsWith('/api/admin/'))return admin(request); + if(path==='/healthz'){await db.prepare('SELECT 1 AS ok').first();return json({status:'ok'});} + if(path==='/api/welcome'&&request.method==='GET'){const allowed=new Set(['https://corp.dunerealms.com','https://www.dunerealms.com','https://dunerealms.com','https://forums.dunerealms.com','https://support.dunerealms.com','https://clans.dunerealms.com','https://wiki.dunerealms.com','https://cp.dunerealms.com']);const origin=request.headers.get('origin');if(origin&&!allowed.has(origin))return new Response(null,{status:403});const user=await identity(request,db);return new Response(JSON.stringify({username:user?.username||null}),{headers:{'Content-Type':'application/json','Cache-Control':'no-store','Vary':'Origin',...(origin?{'Access-Control-Allow-Origin':origin,'Access-Control-Allow-Credentials':'true'}:{})}});} + if(path==='/api/auth/terms')return terms(request); + if(path==='/api/auth/session'&&request.method==='GET'){const response=await auth(request),data=await response.json();if(data.user)data.user.firstLogin=await firstLoginState(db,await identity(request,db));return json(data);} + if(path.startsWith('/api/auth/'))return auth(request); + if(path==='/api/game-link'||path.startsWith('/api/game-link/'))return links(request); + if(path.startsWith('/api/community/'))return rewards(request); + if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405}); + if(/^\/kit-textures\/(?:entity\/(?:banner\/[a-z_]+|equipment\/(?:humanoid|humanoid_leggings)\/netherite)|trims\/(?:color_palettes\/[a-z_]+|entity\/(?:humanoid|humanoid_leggings)\/[a-z_]+))\.png$/.test(path)){ + try{return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+path.slice(1),import.meta.url)),{headers:{'Content-Type':'image/png','Cache-Control':'public, max-age=86400'}});}catch{return new Response('Texture not found',{status:404});} + } + if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});} + if(path==='/federal-reserve'||path==='/federal-reserve/')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/reserve-ledger.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + // V2 shell is public; private data and writes retain their authenticated API gates. + if(path==='/company-cp-reference'||path==='/politics-cp-reference'){const source=await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8');return new Response(request.method==='HEAD'?null:(path==='/company-cp-reference'?companyCPReferenceDocument:politicsCPReferenceDocument)(source),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff',...(path==='/company-cp-reference'?{'Content-Security-Policy':COMPANY_CSP}:{})}});} + if(path==='/political-job')return new Response(request.method==='HEAD'?null:jarvisApplicationDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')).replace('cp-v2-jarvis-application.mjs','cp-v2-political-job-application.mjs'),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}}); + if(path==='/jarvis-auction')return new Response(request.method==='HEAD'?null:jarvisAuctionDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + if(path==='/join-company')return new Response(request.method==='HEAD'?null:jarvisApplicationDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')).replace('cp-v2-jarvis-application.mjs','cp-v2-company-application.mjs'),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}}); + if(path==='/deed-purchase')return new Response(request.method==='HEAD'?null:jarvisApplicationDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')).replace('cp-v2-jarvis-application.mjs','cp-v2-deed-purchase.mjs').replace('DuneRealms · Recruitment Application','DuneRealms · Deed Purchase'),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}}); + if(path==='/jarvis-application')return new Response(request.method==='HEAD'?null:jarvisApplicationDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}}); + if(path==='/company-cp')return new Response(request.method==='HEAD'?null:companyCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Security-Policy':COMPANY_CSP,'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + if(path==='/clan-cp')return new Response(request.method==='HEAD'?null:clanCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + if(path==='/politics-cp')return new Response(request.method==='HEAD'?null:politicsCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + const calendarVendorFiles=new Set(['fullcalendar.global.min.js','monarch.global.min.js','skeleton.css','monarch.css','palette.css','LICENSE.md','SOURCE.json']); + if(path.startsWith('/v2/vendor/fullcalendar/')&&['GET','HEAD'].includes(request.method)){const file=path.slice('/v2/vendor/fullcalendar/'.length);if(!calendarVendorFiles.has(file))return new Response('Not found',{status:404});const type=file.endsWith('.js')?'text/javascript':file.endsWith('.css')?'text/css':file.endsWith('.json')?'application/json':'text/plain';return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/vendor/fullcalendar/'+file,import.meta.url)),{headers:{'Content-Type':type+'; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});} + // All authored cp-v2 browser modules share this bounded public directory. + // New components must not require a second, manually maintained route list. + if(path==='/mentat-report')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/cp-v2-mentat-embed.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff','Content-Security-Policy':PANEL_CSP.replace("img-src 'self' data:;","img-src 'self' data: https://www.dunerealms.com;")}}); + if(/^\/(?:v2|cp-v2)\/cp-v2-[a-z0-9-]+\.(?:mjs|css)$/.test(path)){ + try{const bytes=await readFile(new URL('./public/cp-v2/'+path.slice(path.lastIndexOf('/')+1),import.meta.url));return new Response(request.method==='HEAD'?null:bytes,{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});}catch(error){if(error.code==='ENOENT')return new Response('Not found',{status:404});throw error;} + } + if(['/v2/faith-theme-loader.mjs','/v2/faith-theme.css','/v2/cp-v2-codex-management.mjs','/v2/cp-v2-codex-management.css','/v2/cp-v2-exchange-design.mjs','/v2/cp-v2-exchange-design.css'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice(4),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'no-store','Access-Control-Allow-Origin':'*'}}); + if(['/jarvis-master-keys.mjs','/jarvis-brand.mjs','/organisation-tabs.mjs','/organisation-tabs.css','/codex-code-format.mjs','/codex-dossier-format.mjs'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+path.slice(1),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'no-store','Access-Control-Allow-Origin':'*'}}); + if(['/v2/citizen-directory.mjs','/v2/citizen-directory.css','/v2/organisation-permissions.mjs'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice('/v2/'.length),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); + if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-authorisations.mjs','/v2/cp-v2-tax-treasury.mjs','/v2/cp-v2-reserve-ledger.mjs','/v2/cp-v2-reserve-entry.mjs','/v2/cp-v2-postbank-credit.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-code-redemption.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){ + const moduleFile=path.endsWith('.mjs')||path.endsWith('.js'); + const file=path.endsWith('.mjs')?path.slice('/v2/'.length):path.endsWith('.js')?'v2.js':path.endsWith('.css')?'v2.css':'index.html'; + return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); + } + const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1); + if(!['kitset-model.mjs','item-design-model.mjs','item-metadata-policy.mjs','mining-tool-policy.mjs','tool-template-policy.mjs','equipment-template-policy.mjs','organisation-refit-policy.mjs','action-cooldown-policy.mjs','faith-pol-policy.mjs','item-lore-model.mjs','item-lore-view.mjs','item-lore.css','organisation-editor.mjs','organisation-register.mjs','user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','starter-kit-policy.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-directory-view.mjs','clan-profile-panels.mjs','clan-titles.mjs','dynastic-address.mjs','organisation-palette.mjs','organisation-palette-model.mjs','organisation-palette.css','clan-dynasty.mjs','clan-dynasty.css','clan-deed-settings.mjs','dune-date.mjs','organisation-settings.mjs','organisation-settings.css','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); + return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}}); + }; +} +export async function startPanel(settings=process.env){ + let inventoryPool=null; + if(settings.DUNE_INVENTORY_DATABASE_URL){ + if(settings.DUNE_INVENTORY_DATABASE_URL.startsWith('mysql:'))inventoryPool=await openGameMysqlPool(settings.DUNE_INVENTORY_DATABASE_URL); + else{const {Pool}=await import('pg');inventoryPool=new Pool({connectionString:settings.DUNE_INVENTORY_DATABASE_URL,max:3,connectionTimeoutMillis:5000,idleTimeoutMillis:30000});} + inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); + } + const bankDatabase=await openPostbankDatabase(settings); + const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db); + const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]}); + const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':PANEL_SERVICE_CSP}; + const server=createServer(async(req,res)=>{try{ + req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);} + if(!req.url?.startsWith('/')||req.url.startsWith('//')){res.writeHead(400,security);res.end();return;} + const result=await handle(new Request(origin+req.url,{method:req.method,headers:req.headers,...(!['GET','HEAD'].includes(req.method)?{body:Buffer.concat(chunks)}:{})})); + const headers=new Headers(security);result.headers.forEach((value,key)=>headers.set(key,value)); + res.writeHead(result.status,Object.fromEntries(headers));res.end(Buffer.from(await result.arrayBuffer())); + }catch(error){console.error('Panel request failed:',error.code||error.name);res.writeHead(503,security);res.end('{"message":"The account panel is temporarily unavailable."}');}}); + server.headersTimeout=10000;server.requestTimeout=30000; + await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(Number(settings.CP_PORT||3003),'127.0.0.1',resolve);}); + process.once('SIGTERM',()=>{stopOfficeLedger();stopElectionClock();stopBanSync();stopInternalMail();stopCentralScheduler();server.close(async()=>{await Promise.allSettled([db.close(),bankDatabase?.close(),inventoryPool?.end(),starterKitDelivery.close()]);process.exit(0);});});console.log('Account panel listening on localhost');return server; +} +if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)await startPanel(); diff --git a/website/integrations/osticket/dev-jarvis-catalogue.json b/website/integrations/osticket/dev-jarvis-catalogue.json index ebf73476..c376fb2a 100644 --- a/website/integrations/osticket/dev-jarvis-catalogue.json +++ b/website/integrations/osticket/dev-jarvis-catalogue.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "sourceHash": "1fc53f9f18f4149014f85e2f3bf39e4cb6d15128fbaf20810b064e61dd5d6227", + "sourceHash": "a25ecf12f3252f4a690fd214cf3a201684e86311eaa759c21c4092f90883098e", "actions": [ { "id": "clan.clear-protected-rosters", @@ -1107,7 +1107,7 @@ { "id": "progression.game-observation", "label": "Progression & XP · Native quest observation", - "version": 3, + "version": 4, "keyType": "quest-milestone", "fields": [ { @@ -1150,14 +1150,69 @@ }, { "name": "quantity", - "label": "Produced spice quantity", + "label": "Native produced quantity", "type": "number", "required": false, "min": 1, "max": 64 + }, + { + "name": "dimension", + "label": "Native dimension", + "type": "text", + "required": false + }, + { + "name": "source", + "label": "Fixed Elytra acquisition source", + "type": "text", + "required": false } ], - "effect": "Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.", + "effect": "Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Fixed world/dimension flight observations feed the Reputation Elytra branch. A committed paid delivery or natural End-ship acquisition completes only this branch, awarding its remaining rewards once. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, + { + "id": "progression.spice-refining", + "label": "Progression & XP · NPC spice refinement", + "version": 1, + "keyType": "quest-milestone", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + }, + { + "name": "uuid", + "label": "Linked player UUID", + "type": "text", + "required": true + }, + { + "name": "requestId", + "label": "Original turn-in UUID", + "type": "text", + "required": true + }, + { + "name": "definitionId", + "label": "Fixed refining quest", + "type": "text", + "required": true + }, + { + "name": "npcUuid", + "label": "Nearby Arrakis Smuggler UUID", + "type": "text", + "required": true + } + ], + "effect": "Revalidate the current player and quest prerequisites, then require the physical Arrakis NPC again before consuming two real raw spice, or two refined spice and two scraps. Core checkpoints inputs, two EI outputs and a recoverable receipt atomically. Existing QSM observations award no reward until verified by the Reputation quest engine.", "fixedTargets": [], "webIssue": false, "recordOnly": true diff --git a/website/node/elytra-quest-policy.mjs b/website/node/elytra-quest-policy.mjs new file mode 100644 index 00000000..3426e84d --- /dev/null +++ b/website/node/elytra-quest-policy.mjs @@ -0,0 +1,5 @@ +import {ELYTRA_QUESTS} from '../control-panel/public/cp-v2/elytra-quests.mjs'; +export const ELYTRA_RECIPE=Object.freeze({world:'Arrakis',quality:'very_rare',equipmentMark:11,result:'Elytra',grid:[['Netherite ingot','Phantom membrane','Netherite ingot'],['Iron ingot','Diamond','Iron ingot'],['Contaminated spice','Phantom membrane','Contaminated spice']]}); +export const FLIGHT_METRICS=Object.freeze(Object.fromEntries(ELYTRA_QUESTS.map(d=>[d.metric,d.target]))); +export function applyElytraAlternative(totals){if((totals.get('flight-elytra-acquired')||0)>0)for(const [metric,target]of Object.entries(FLIGHT_METRICS))totals.set(metric,Math.max(target,totals.get(metric)||0));return totals;} +export function flightDossier(quest){if(quest.id!=='POL-ELYTRA-CRAFT')return quest;if(!quest.canStart&&!['active','completed','claimed'].includes(quest.state))return {...quest,objective:'Complete the preparation quests to reveal the elytra recipe.'};return {...quest,objective:'Craft this elytra on Arrakis using the revealed recipe.',recipe:ELYTRA_RECIPE};} diff --git a/website/node/game-quest-events.mjs b/website/node/game-quest-events.mjs index 9d022970..3c8fa3a3 100644 --- a/website/node/game-quest-events.mjs +++ b/website/node/game-quest-events.mjs @@ -1,11 +1,14 @@ import {gameAuthorized,validUuid,json} from './game-link.mjs'; import {createPersonalActivityEvents} from './personal-activity-events.mjs'; import {createPOLActivityEvents} from './pol-activity-events.mjs'; +import {createPOLProgressionRuntime} from './progression-pol-runtime.mjs'; // Only fixed native observations cross this boundary. No supplied account, // metric, progress, quantity or reward can be interpreted as quest authority. const servers=new Set(['lobby','arrakis','caladan','giedi-prime','kaitain','sigma-draconis-iv']); const metrics={arrakis_visit:'arrakduin-visit',active_minute:'arrakduin-active-minutes',equipment_use:'equipment-use',spice_harvest:'spice-harvest',citizen_introduction:'citizen-introduction'}; +const flight={flight_spice:['arrakis','NORMAL'],flight_refined:['arrakis','NORMAL'],flight_contaminated:['arrakis','NORMAL'],flight_debris:['giedi-prime','NETHER'],flight_scrap:['giedi-prime','NETHER'],flight_gold:['giedi-prime','NETHER'],flight_netherite:['giedi-prime','NETHER'],flight_membrane:['caladan','NORMAL'],flight_iron:['kaitain','NORMAL'],flight_diamond:['sigma-draconis-iv','NORMAL'],flight_crafted:['arrakis','NORMAL'],flight_elytra_acquired:null}; +for(const kind of Object.keys(flight))metrics[kind]=kind.replaceAll('_','-'); export function createGameQuestEventsAPI(db,keys,settings,{clock=Date.now,events:provided=null}={}){ const producer=Object.freeze({source:'native-quest-observation'}); const events=provided||(keys?createPersonalActivityEvents(db,keys,{clock,authorizeProducer:async actor=>actor===producer}):null); @@ -17,17 +20,21 @@ export function createGameQuestEventsAPI(db,keys,settings,{clock=Date.now,events if(request.method!=='POST'||url.search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return json({message:'A native quest observation is required.'},400); const reader=request.body?.getReader();if(!reader)return json({message:'Observation required'},400); let input;try{let size=0;const chunks=[];while(true){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>2048){await reader.cancel();return json({message:'Observation too large'},413);}chunks.push(value);}input=JSON.parse(Buffer.concat(chunks).toString());}catch{return json({message:'Invalid observation'},400);}finally{reader.releaseLock();} - const fields=['eventId','uuid','kind','server','occurredAt',...(input?.kind==='spice_harvest'?['quantity']:[])]; - if(!input||Array.isArray(input)||Object.keys(input).length!==fields.length||fields.some(f=>!Object.hasOwn(input,f))||!validUuid(input.eventId)||!validUuid(input.uuid)||!Object.hasOwn(metrics,input.kind)||!servers.has(input.server)||input.kind!=='citizen_introduction'&&(input.server==='lobby'||input.kind!=='equipment_use'&&input.server!=='arrakis')||!Number.isSafeInteger(input.occurredAt)||input.occurredAt<=0||input.occurredAt>clock()+30000)return json({message:'Invalid observation fields'},400); + const isFlight=Object.hasOwn(flight,input?.kind||''); + const fields=['eventId','uuid','kind','server','occurredAt',...(isFlight?['quantity','dimension',...(input.kind==='flight_elytra_acquired'?['source']:[])]:input?.kind==='spice_harvest'?['quantity']:[])]; + if(!input||Array.isArray(input)||Object.keys(input).length!==fields.length||fields.some(f=>!Object.hasOwn(input,f))||!validUuid(input.eventId)||!validUuid(input.uuid)||!Object.hasOwn(metrics,input.kind)||!servers.has(input.server)||!isFlight&&input.kind!=='citizen_introduction'&&(input.server==='lobby'||input.kind!=='equipment_use'&&input.server!=='arrakis')||!Number.isSafeInteger(input.occurredAt)||input.occurredAt<=0||input.occurredAt>clock()+30000)return json({message:'Invalid observation fields'},400); + if(isFlight&&(!Number.isSafeInteger(input.quantity)||input.quantity<1||input.quantity>64||!['NORMAL','NETHER','THE_END'].includes(input.dimension)||flight[input.kind]&&(flight[input.kind][0]!==input.server||flight[input.kind][1]!==input.dimension)||input.kind==='flight_elytra_acquired'&&(!['end','exchange'].includes(input.source)||input.source==='end'&&input.dimension!=='THE_END')))return json({message:'Invalid flight objective location'},400); if(input.kind==='spice_harvest'&&(!Number.isSafeInteger(input.quantity)||input.quantity<1||input.quantity>64))return json({message:'Invalid harvest quantity'},400); if(!events)return json({message:'Quest evidence is unavailable'},503); try{ const users=await db.query("SELECT a.id FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[input.uuid]); if(users.length!==1)return json({message:'Link an active personal account first.'},403); - const seasons=await db.query("SELECT season_id FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[input.occurredAt,Math.max(clock(),input.occurredAt)]); + const seasons=await db.query("SELECT season_id FROM "+(isFlight?'jarvis_pol_progression_seasons':'jarvis_progression_seasons')+" WHERE state='active' AND starts_at<=? AND ends_at>?",[input.occurredAt,Math.max(clock(),input.occurredAt)]); if(seasons.length!==1||seasons[0].season_id!=='S01')return json({message:'No matching active quest season'},409); - const evidence={eventId:input.eventId,accountId:users[0].id,minecraftUuid:input.uuid,seasonId:seasons[0].season_id,metric:metrics[input.kind],quantity:input.kind==='spice_harvest'?input.quantity:1,occurredAt:input.occurredAt,reference:'native:'+input.server+':'+input.kind+':'+input.eventId}; - const result=await events.record(producer,evidence); + const evidence={eventId:input.eventId,accountId:users[0].id,minecraftUuid:input.uuid,seasonId:seasons[0].season_id,metric:metrics[input.kind],quantity:isFlight||input.kind==='spice_harvest'?input.quantity:1,occurredAt:input.occurredAt,reference:'native:'+input.server+':'+input.kind+':'+input.eventId}; + if(isFlight&&(!db.polActivityEventsEnabled||!polEvents))return json({message:'Reputation quest evidence is unavailable'},503); + const result=await (isFlight?polEvents:events).record(producer,evidence); + if(isFlight)await createPOLProgressionRuntime(db,keys,{clock}).collect({id:users[0].id}); if(input.kind==='spice_harvest'&&db.polActivityEventsEnabled&&polEvents)await polEvents.record(producer,{...evidence,metric:'pol-repeat-spice'}); return json({ok:true,eventId:input.eventId,keyId:result.keyId,replayed:!result.created}); }catch{return json({message:'Quest evidence could not be confirmed. Retry the same observation.'},409);} diff --git a/website/node/game-quests.mjs b/website/node/game-quests.mjs index e7677931..8a313649 100644 --- a/website/node/game-quests.mjs +++ b/website/node/game-quests.mjs @@ -20,8 +20,9 @@ export function createGameQuestsAPI(db,settings,{personal=null,pol=null}={}){ let input; try{const chunks=[];let size=0;while(true){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4096){await reader.cancel();return json({message:'Quest request too large.'},413);}chunks.push(value);}input=JSON.parse(Buffer.concat(chunks).toString('utf8'));} catch{return json({message:'Invalid quest action.'},400);}finally{reader.releaseLock();} - const allowed=input?.action==='read'?['action','uuid','kind']:input?.action==='start'?['action','uuid','kind','definitionId','requestId','confirmed']:['action','uuid','kind','definitionId','requestId','revision','confirmed']; - if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!allowed.includes(k))||!['read','start','claim'].includes(input.action)||!['personal','pol'].includes(input.kind)||!validUuid(input.uuid))return json({message:'Choose a valid linked-player quest action.'},400); + const refine=input?.action==='prepare_refine'; + const allowed=input?.action==='read'?['action','uuid','kind']:refine?['action','uuid','kind','definitionId','requestId','confirmed','server','npcUuid']:input?.action==='start'?['action','uuid','kind','definitionId','requestId','confirmed']:['action','uuid','kind','definitionId','requestId','revision','confirmed']; + if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!allowed.includes(k))||!['read','start','claim','prepare_refine'].includes(input.action)||!['personal','pol'].includes(input.kind)||!validUuid(input.uuid))return json({message:'Choose a valid linked-player quest action.'},400); if(input.action!=='read'&&(input.confirmed!==true||!validUuid(input.requestId)||typeof input.definitionId!=='string'||input.definitionId.length>64||input.action==='claim'&&(!Number.isSafeInteger(input.revision)||input.revision<1)))return json({message:'Confirm the selected quest and its current reward revision.'},400); const runtime=input.kind==='pol'?pol:personal;if(!runtime?.quests)return json({message:'The central quest service is unavailable.'},503); try{ @@ -32,6 +33,10 @@ export function createGameQuestsAPI(db,settings,{personal=null,pol=null}={}){ if(input.action==='read')return json({ok:true,...journal,branches:journal.branches||(input.kind==='personal'?personalBranches:[]),kind:input.kind}); const quest=journal.quests?.find(q=>q.id===input.definitionId); if(!quest)return json({message:'This quest is not in the current mission journal.'},409); + if(refine){ + if(input.kind!=='pol'||input.server!=='arrakis'||!validUuid(input.npcUuid)||!['POL-ELYTRA-REFINE','POL-ELYTRA-CONTAMINATE'].includes(quest.id)||!quest.canStart&&!['active','completed','claimed'].includes(quest.state))return json({message:'Complete the preparation quests and visit the Arrakis refiner.'},409); + return json({ok:true,allowed:true,action:'prepare_refine',playerUuid:input.uuid.toLowerCase(),requestId:input.requestId,definitionId:quest.id,npcUuid:input.npcUuid,server:'arrakis',expiresAt:Date.now()+30000}); + } if(questChannel(quest.executionRequirements)==='website')return json({message:'Complete this website quest in your online mission journal.'},409); const result=input.action==='start'?await runtime.quests.start(actor,{definitionId:quest.id}):await runtime.quests.claim(actor,{definitionId:quest.id,revision:input.revision,requestId:input.requestId}); if(input.action==='claim')await runtime.quests.processCompletions?.({accountId:actor.id}); diff --git a/website/node/progression-pol-runtime.mjs b/website/node/progression-pol-runtime.mjs index ee967d6e..b2363126 100644 --- a/website/node/progression-pol-runtime.mjs +++ b/website/node/progression-pol-runtime.mjs @@ -7,6 +7,7 @@ import {verifiedPOLActivities} from './pol-activity-events.mjs'; import {verifiedPOLDeathTotals} from './pol-death-evidence.mjs'; import {repeatableDefinitions} from './pol-repeatable-quests.mjs'; import {createHash} from 'node:crypto'; +import {applyElytraAlternative,flightDossier} from './elytra-quest-policy.mjs'; export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyObservation=null}={}){ const observer=Object.freeze({internal:'pol-key-source-reader'}); const resolvePlayer=async id=>(await central.query("SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]))[0]||null; @@ -26,7 +27,7 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO const links=await store.query('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?'+(lock?' FOR UPDATE':''),[actor.id]);if(links.length!==1)throw Error('Current activity identity required'); const season=seasons[0],input={accountId:actor.id,minecraftUuid:links[0].minecraft_uuid.toLowerCase(),seasonId:season.season_id,startsAt:Number(season.starts_at),endsAt:Number(season.ends_at),now,lock},activity=await verifiedPOLActivities(store,keys,input); if(central.polRepeatablesEnabled){const deaths=await verifiedPOLDeathTotals(store,keys,input);for(const [metric,value]of deaths.totals)activity.totals.set(metric,value);activity.proofIds.push(...deaths.proofIds);} - return {...activity,season}; + applyElytraAlternative(activity.totals);return {...activity,season}; } const adapters={clock,authorizePlayer,authorizeIssuer,resolvePlayer, resolveAward:async(actor,definition,tx,award)=>mentorAward(tx,keys,{actor,definition,issuer:await authorizeIssuer(tx,definition),award,enabled:central.polMentorBonusEnabled}), @@ -50,13 +51,14 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO const claimedIds=result.quests.filter(q=>q.state==='claimed'&&q.keyId).map(q=>q.keyId),claimedAwards=new Map((claimedIds.length?await central.query('SELECT key_id,xp FROM jarvis_pol_quest_claims WHERE account_id=? AND key_id IN ('+claimedIds.map(()=>'?').join(',')+')',[actor.id,...claimedIds]):[]).map(r=>[r.key_id,Number(r.xp)])); const bonusPolicy=central.polMentorBonusEnabled?await currentMentorPolicy(central):null,bonusIssuers=new Map(); if(bonusPolicy){const characters=createSystemCharacters(central,keys,{authorizeOperator:async()=>false});for(const issuer of new Set(current.definitions.map(d=>d.issuer))){const identity=await characters.inspect(issuer);bonusIssuers.set(issuer,!!identity?.capabilities.includes('quest.reward-bonus'));}} - return {...result,affiliations:central.secondaryAffiliationsEnabled?await readSmugglerAffiliations(central,keys,actor.id):[],quests:result.quests.map(q=>{const d=current.definitions.find(d=>d.id===q.id),verified=typeof verifyObservation==='function'||!!proof&&(proof.totals.get(q.metric)||0)>=q.target,derived=!!d.repeatable&&q.revision===null,baseXP=derived?d.xp:q.xp,xp=claimedAwards.has(q.keyId)?claimedAwards.get(q.keyId):Number.isSafeInteger(baseXP)&&bonusPolicy&&bonusIssuers.get(d.issuer)?mentorXP(baseXP,bonusPolicy.xpBonusBps):baseXP;return {...q,baseXP,xp,mentorBonusXP:q.state==='claimed'?null:Number.isSafeInteger(xp)?xp-baseXP:0,revision:derived?1:q.revision,rewardConfigured:derived||q.rewardConfigured,canClaim:(q.canClaim||derived&&q.state==='completed')&&verified&&(!q.cooldownUntil||q.cooldownUntil<=clock()),...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};}),xpType:'pol',branches:[...POL_QUEST_BRANCHES.map(b=>({id:b.id,title:b.title,theme:b.theme})),...(central.polRepeatablesEnabled?[{id:'repeatables',title:'Ongoing duties',theme:'Verified repeating objectives'}]:[])]}; + return {...result,affiliations:central.secondaryAffiliationsEnabled?await readSmugglerAffiliations(central,keys,actor.id):[],quests:result.quests.map(q=>{const d=current.definitions.find(d=>d.id===q.id),verified=typeof verifyObservation==='function'||!!proof&&(proof.totals.get(q.metric)||0)>=q.target,derived=!!d.repeatable&&q.revision===null,baseXP=derived?d.xp:q.xp,xp=claimedAwards.has(q.keyId)?claimedAwards.get(q.keyId):Number.isSafeInteger(baseXP)&&bonusPolicy&&bonusIssuers.get(d.issuer)?mentorXP(baseXP,bonusPolicy.xpBonusBps):baseXP;return {...q,baseXP,xp,mentorBonusXP:q.state==='claimed'?null:Number.isSafeInteger(xp)?xp-baseXP:0,revision:derived?1:q.revision,rewardConfigured:derived||q.rewardConfigured,canClaim:(q.canClaim||derived&&q.state==='completed')&&verified&&(!q.cooldownUntil||q.cooldownUntil<=clock()),...(q.state==='completed'&&!verified?{state:q.keyId?'active':'not-started'}:{})};}).map(flightDossier),xpType:'pol',branches:[...POL_QUEST_BRANCHES.map(b=>({id:b.id,title:b.title,theme:b.theme})),...(central.polRepeatablesEnabled?[{id:'repeatables',title:'Ongoing duties',theme:'Verified repeating objectives'}]:[])]}; } }); async function collect(actor){ if(!await authorizePlayer(actor,central))throw Error('Current player identity required');const proof=await evidence(actor);if(!proof)return {state:'verified-key-sources',sources:[{source:'pol-activity-keys',available:false,reason:'pending-verified-producer'}]}; const digest=createHash('sha256').update(JSON.stringify(proof.proofIds)).digest('hex'); const current=await engineFor(actor);for(const [metric,value]of proof.totals)await current.engine.observe(observer,{accountId:actor.id,seasonId:proof.season.season_id,metric,value,eventId:'pol-activity:'+actor.id+':'+metric+':'+digest.slice(0,32),source:'verified-activity-key'}); + if((proof.totals.get('flight-elytra-acquired')||0)>0)await current.engine.completeVerifiedBranch(actor,'elytra'); return {state:'verified-key-sources',sources:[{source:'pol-activity-keys',available:true,verifiedEvents:proof.proofIds.length}]}; } return Object.freeze({quests,collect}); diff --git a/website/node/progression-pol.mjs b/website/node/progression-pol.mjs index dcd5cbbf..3b23da84 100644 --- a/website/node/progression-pol.mjs +++ b/website/node/progression-pol.mjs @@ -47,3 +47,5 @@ export function polPolicyKeys(keys){return { export const ensurePOLProgressionPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:POL_XP_POLICY,definitions:POL_QUEST_DEFINITIONS}); export const ensurePOLRepeatablePolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:2},definitions:repeatablePolicyDefinitions()}); + +export const ensureElytraQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:3},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='elytra')}); diff --git a/website/node/progression-quests.mjs b/website/node/progression-quests.mjs index 255453dc..4b3e33fe 100644 --- a/website/node/progression-quests.mjs +++ b/website/node/progression-quests.mjs @@ -112,6 +112,14 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au } return {completed}; }, + async completeVerifiedBranch(actor,branch){ + await player(actor);let completed=0; + for(const d of definitions.filter(d=>d.branch===branch&&!d.repeatable)){ + const view=await service.list(actor),q=view.quests.find(q=>q.id===d.id);if(!q||q.state==='claimed')continue; + if(!q.canClaim||!q.rewardConfigured)throw Error('Verified branch completion is not ready'); + await service.claim(actor,{definitionId:q.id,revision:q.revision,requestId:deterministicId('branch:'+actor.id+':'+view.season.id+':'+q.id)});completed++; + }return {completed}; + }, async processCompletions({accountId=null}={}){ if(accountId!==null&&!uuid(accountId))throw TypeError('Invalid completion account'); const jobs=await db.query("SELECT * FROM jarvis_progression_outbox WHERE purpose='mandatory-completion' AND state='queued'"+(accountId?' AND account_id=?':'')+' ORDER BY created_at,id LIMIT 20',accountId?[accountId]:[]);let completed=0,failed=0; diff --git a/website/tests/elytra-quests.test.mjs b/website/tests/elytra-quests.test.mjs new file mode 100644 index 00000000..423a4009 --- /dev/null +++ b/website/tests/elytra-quests.test.mjs @@ -0,0 +1,7 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {CRAFTED_ELYTRA_TEMPLATE,elytraTemplate} from '../control-panel/public/tool-template-policy.mjs'; +import {defaultItemDesign,validateItemDesign} from '../control-panel/public/item-design-model.mjs'; +test('new crafted Elytra grade preserves already published original Elytra definitions',()=>{for(const template of [elytraTemplate('basic'),CRAFTED_ELYTRA_TEMPLATE]){const design=defaultItemDesign(template.id);assert.equal(validateItemDesign(design).equipmentMark,template.equipmentMark);}assert.equal(elytraTemplate('basic').equipmentMark,13);assert.equal(CRAFTED_ELYTRA_TEMPLATE.equipmentMark,11);assert.equal(CRAFTED_ELYTRA_TEMPLATE.quality,'very_rare');}); +import {questAwardXP} from '../node/progression-definitions.mjs';import {systemCharacterFixture} from './system-character-fixture.mjs';import {initializePOLProgression,ensurePOLProgressionPolicy} from '../node/progression-pol.mjs';import {initializePOLActivityEvents,createPOLActivityEvents} from '../node/pol-activity-events.mjs';import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs';import {ELYTRA_QUESTS} from '../control-panel/public/cp-v2/elytra-quests.mjs';import {flightDossier} from '../node/elytra-quest-policy.mjs'; +test('elytra recipe remains outside the locked final dossier',()=>{const q={id:'POL-ELYTRA-CRAFT',state:'not-started',canStart:false};assert.equal(flightDossier(q).recipe,undefined);assert.equal(flightDossier({...q,canStart:true}).recipe.grid.length,3);assert.equal(flightDossier({...q,state:'active'}).recipe.grid.length,3);}); +test('one verified acquired Elytra completes only its Reputation branch and pays every remaining reward once',async()=>{const f=await systemCharacterFixture();try{const clock=()=>2000;await f.characters.provision(f.people.Owner,'esmar_tuek');await initializePOLProgression(f.db);await ensurePOLProgressionPolicy(f.db,f.keys,{clock});await initializePOLActivityEvents(f.db);f.db.polActivityEventsEnabled=true;const minecraftUuid=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[minecraftUuid,f.people.Member.id]);const producer={},events=createPOLActivityEvents(f.db,f.keys,{clock,authorizeProducer:async p=>p===producer}),runtime=createPOLProgressionRuntime(f.db,f.keys,{clock});await events.record(producer,{eventId:randomUUID(),accountId:f.people.Member.id,minecraftUuid,seasonId:'S01',metric:'flight-elytra-acquired',quantity:1,occurredAt:2000,reference:'verified-paid-delivery'});await runtime.collect(f.people.Member);let view=await runtime.quests.list(f.people.Member);assert.equal(view.quests.filter(q=>q.branch==='elytra'&&q.state==='claimed').length,ELYTRA_QUESTS.length);assert.equal(view.profile.totalXP,ELYTRA_QUESTS.reduce((sum,q)=>sum+questAwardXP(q,q.xp),0));assert.equal(view.quests.filter(q=>q.branch!=='elytra'&&q.state==='claimed').length,0);await runtime.collect(f.people.Member);assert.equal((await runtime.quests.list(f.people.Member)).profile.totalXP,2250);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_pol_quest_claims')).n,12);}finally{f.db.close();}}); diff --git a/website/tests/flight-observations.test.mjs b/website/tests/flight-observations.test.mjs new file mode 100644 index 00000000..6d5c38f1 --- /dev/null +++ b/website/tests/flight-observations.test.mjs @@ -0,0 +1,10 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {createGameQuestEventsAPI} from '../node/game-quest-events.mjs'; +const secret='flight-observation-test-secret-at-least-32-characters'; +test('flight receipts reject wrong world, dimension, source and forged quantities before reading an account',async()=>{let reads=0;const db={query:async()=>{reads++;return [];}};const api=createGameQuestEventsAPI(db,null,{GAME_LINK_SECRET:secret},{clock:()=>2000,events:{record(){throw Error('not expected');}}}); +const input={eventId:randomUUID(),uuid:randomUUID(),kind:'flight_scrap',server:'giedi-prime',occurredAt:2000,quantity:10,dimension:'NETHER'}; +const send=body=>api(new Request('https://cp.dunerealms.com/internal/game/quest-events',{method:'POST',headers:{authorization:'Bearer '+secret,'content-type':'application/json'},body:JSON.stringify(body)})); +for(const bad of [{server:'arrakis'},{dimension:'NORMAL'},{quantity:0},{quantity:65},{quantity:'10'},{source:'end'}])assert.equal((await send({...input,...bad})).status,400); +const alternate={...input,kind:'flight_elytra_acquired',source:'end'};assert.equal((await send(alternate)).status,400);assert.equal(reads,0); +assert.equal((await send({...alternate,dimension:'THE_END',server:'sigma-draconis-iv'})).status,403);assert.equal((await send({...alternate,source:'exchange',dimension:'NORMAL',server:'lobby'})).status,403);assert.equal(reads,2); +}); diff --git a/website/tests/spice-refiner.test.mjs b/website/tests/spice-refiner.test.mjs new file mode 100644 index 00000000..3cfe61af --- /dev/null +++ b/website/tests/spice-refiner.test.mjs @@ -0,0 +1,3 @@ +import {test} from 'node:test';import assert from 'node:assert/strict';import {createGameQuestsAPI} from '../node/game-quests.mjs'; +const uuid='11111111-1111-4111-8111-111111111111',requestId='22222222-2222-4222-8222-222222222222',npcUuid='33333333-3333-4333-8333-333333333333',secret='refiner-permit-test-secret-at-least-32-characters'; +test('refining permit binds the current player, prepared quest, NPC and Arrakis without claiming rewards',async()=>{let state='not-started',canStart=false;const api=createGameQuestsAPI({query:async()=>[{id:uuid}]},{GAME_LINK_SECRET:secret},{pol:{collect:async()=>{},quests:{list:async()=>({quests:[{id:'POL-ELYTRA-REFINE',state,canStart}]})}}});const input={action:'prepare_refine',uuid,kind:'pol',definitionId:'POL-ELYTRA-REFINE',requestId,confirmed:true,server:'arrakis',npcUuid};const send=body=>api(new Request('https://cp.dunerealms.com/internal/game/quests',{method:'POST',headers:{authorization:'Bearer '+secret,'content-type':'application/json'},body:JSON.stringify(body)}));assert.equal((await send(input)).status,409);canStart=true;const r=await send(input);assert.equal(r.status,200);const permit=await r.json();assert.equal(permit.playerUuid,uuid);assert.equal(permit.npcUuid,npcUuid);assert.equal(permit.requestId,requestId);assert.equal(permit.allowed,true);for(const bad of [{server:'kaitain'},{npcUuid:'fake'},{confirmed:false},{definitionId:'POL-ELYTRA-CRAFT'},{quantity:64}])assert.notEqual((await send({...input,...bad})).status,200);});