diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 013a3200..821e49c5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -19,12 +19,14 @@ jobs: uses: actions/setup-node@v4 with: node-version: '22' - - name: Build the illustrated website and API - run: node scripts/build.mjs - name: Install website server dependencies run: npm install --omit=dev --no-audit --no-fund + - name: Build the illustrated website and API + run: node scripts/build.mjs - name: Test feeds and compiled pages run: node --test tests/*.test.mjs + - name: Test inventory ownership and private market bridge + run: node --test ../control-panel-inventory/tests/*.test.mjs - name: Upload website build uses: actions/upload-artifact@v4 with: diff --git a/.gitignore b/.gitignore index cc448ff8..e11197ae 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,7 @@ __pycache__/ /built-crossplay/ /DuneRealms-Velocity-Network/ /DuneRealms-Velocity-Network.zip + +# Private database credentials and manual profile recovery snapshots +/network/database/.env +**/inventory-recovery/ diff --git a/DuneEss/EXCHANGE.md b/DuneEss/EXCHANGE.md index ff5d30a5..d435d836 100644 --- a/DuneEss/EXCHANGE.md +++ b/DuneEss/EXCHANGE.md @@ -1,32 +1,30 @@ -# CHOAM exchange — DuneEss 1.0.2 +# CHOAM exchange — DuneEss 1.0.4 -Install `DuneEss-1.0.2.jar` with Vault and the existing DuneCore/DuneTerrain/DuneNPC suite on Paper 1.21.4 / Java 21. Replace the previous DuneEss JAR while the server is stopped. Existing wallet and listing tables are retained; startup adds nullable item-payload and display-name columns to the listing table. +Install matching DuneRealms-Core.jar (1.0.12) and DuneRealms-Essentials.jar (1.0.4), with Vault and existing modules on Java 21 / Paper 1.21.8. Stop all planetary servers, back up SQL/player data, replace only these plugin JARs and configure the shared PostgreSQL database on every backend before starting. Preserve all worlds/configurations. See [database setup](../network/database/README.md). ## Player controls -- `/exchange` (also `/choam` or `/market`): faction-themed standard inventory menu. Actual DuneCore faction selection controls its appearance, including Ordos and unaffiliated Guild styling. Uses vanilla inventory slots; no Java-only client UI is required. -- `/exchange sell `: reserve 1–64 held items, priced per item, maximum 1,000,000 Solaris with two decimal places. You cannot offer more than the held stack. Item names, enchantments, Dune tags and other serialized item data are preserved. Operator admin rods cannot be sold. -- `/exchange buy `: review a listing, then confirm purchase of **one** item. The inventory GUI uses the same confirmation. Self-purchases are refused. -- `/exchange mine`: view your offers; select one to confirm cancellation and reclaim all unsold items. Only the seller can cancel. Your offers span all planets regardless of the browsing filter. -- `/exchange cancel `: open the reclaim confirmation directly. -- `/exchange admin`: permission `dune.admin`, with all-planet listing inspection and a real connection check. Normal ownership rules still apply. +- `/exchange` (`/choam`, `/market`): native Java/Bedrock exchange menu. +- `/exchange sell `: list 1–64 held items, up to 1,000,000 Solari per item, two decimal places. Items are escrowed with names, enchantments, Dune metadata and item data. Administrative items are rejected. +- `/exchange buy `: inspect and confirm the purchase of one item. +- `/exchange mine`: browse your listings and reclaim unsold stock. +- `/exchange cancel `: confirm cancellation of your own listing. +- `/exchange admin`: operator inspection and database check. Ownership rules still apply. -Category filters, all-items browsing, planet filters and pagination work together. The GUI identifies its own inventories through holders, cancels item transfers and drags, and prevents queued duplicate confirmations after a screen changes. +Filters, pagination, capacity checks, stale-confirmation handling and self-purchase rejection remain supported. Missing/incompatible shared Core profiles refuse to trade; lobby inventories never enter the planetary exchange. -## Shared database +## Transactions and history -Enable PostgreSQL in `plugins/DuneCore/config.yml`, using the same database on every backend. Leave `database.use-core-database: true` in DuneEss. DuneEss first initializes the existing shared `dune_economy_balances` ledger, then initializes the exchange. Restart after configuration changes. The exchange refuses to trade against fallback local wallets or an unavailable shared economy. Menu/guide access still works when unconnected, and no demo items are sold in-game. +Every actual player trade runs through Core's owned profile connection. Listing escrow, buyer debit, seller credit, stock changes, the resulting authoritative player inventory checkpoint, and any completed sale history commit together. A normal SQL failure restores the in-memory inventory and rolls back all SQL. If the commit outcome is uncertain, the profile is quarantined and ordinary quit saving is suppressed until manual recovery. Excess item delivery aborts the transaction instead of dropping items into the world. -Payments, seller credit and stock changes share one SQL transaction with a locked listing row. Buying the final item deletes the row instead of attempting an invalid zero quantity. Insufficient funds, a missing seller wallet or another transaction failure rolls back the database changes. Legacy material-only listings remain readable. Unsold item payloads are stored in PostgreSQL. +The sales ledger `dune_exchange_sales` retains a row per completed unit purchase, including seller/buyer names and UUIDs, item/material, quantity, exact unit/total price, origin and timestamp. Cancelling or failing a trade creates no sale. Earlier sales cannot be reconstructed retroactively. Configured shared economy deposits/withdrawals now use atomic SQL arithmetic and do not fall back to stale local balances during SQL outages. -**Verification limits:** automated SQL tests use H2 in PostgreSQL compatibility mode, and GUI tests use mocked Paper events. A live PostgreSQL + Paper/Velocity/Geyser staging run has not been performed. Queries are bounded and have five-second query/connect/socket timeouts but currently run on the server thread. Bukkit inventory/player-file writes and SQL commits are separate operations: abrupt process loss between them is not an exactly-once transfer guarantee. Keep normal backups and test staging before opening a public multi-backend economy. This change does not alter the wider Core profile/transfer synchronization system. +General gameplay/container changes outside these exchange transactions still rely on autosaves and unclean-session recovery. This is not an exactly-once guarantee for every Minecraft/plugin interaction. Ender chests remain local. SQL remains synchronous with bounded timeouts; profile capacity and staging tests are documented in the database guide. -## Website +## Account page and website -The website uses 40 clearly labelled fictional offers while the game-market gateway is unavailable. Demo offers never display purchase commands. When the configured gateway returns a valid live response, it switches to read-only live listings automatically on page load or Refresh; a valid empty live response remains an empty live market. +[control-panel-inventory](../control-panel-inventory/README.md) contains the account-page armor mannequin, saved inventory and **History of sales**, plus authenticated read-only API handlers, a private market listings bridge, integration instructions and a self-contained demo preview. The CP source is not in MC, so live wiring/deployment is a handoff task. Purchases remain in-game. Existing public website demo offers remain labelled until its operator enables the supplied live bridge. -The current gateway expects an HTTPS read-only bridge in `EXCHANGE_LISTINGS_URL`, authenticated server-to-server with `EXCHANGE_READ_TOKEN`. These are runtime secrets, never browser code. No bridge or production database is provisioned by this change. The response is `{ "listings": [{ "id": 1, "material": "IRON_INGOT", "category": "ores", "origin": "giedi_prime", "seller": "Trader", "quantity": 16, "price": 90 }] }`. Category and planet IDs must match the website's documented filter IDs. The bridge reads `dune_exchange_listings`; the website never executes a purchase or writes to SQL. +## Validation -## Checks - -Run `gradle build` in DuneEss and `npm run build` / `npm test` in website. SQL coverage includes the final item, partial purchases, insufficient funds, rollback after debit, concurrent buyers, ownership, filters/pagination and validation. GUI coverage includes holder isolation, bottom-inventory transfers, drags, stale duplicate confirmation and admin permission enforcement. +Run `gradle build` in Core and DuneEss and `node --test tests/*.test.mjs` in control-panel-inventory. Core tests use mocked JDBC/Paper and exchange SQL tests use H2 PostgreSQL compatibility mode, including concurrency, rollback, sales ledger and externally owned transactions. Live PostgreSQL/Paper/Velocity/Bedrock validation is pending. diff --git a/DuneEss/build.gradle.kts b/DuneEss/build.gradle.kts index a081f0b5..0e580081 100644 --- a/DuneEss/build.gradle.kts +++ b/DuneEss/build.gradle.kts @@ -1,6 +1,6 @@ plugins { java } group = "com.example" -version = "1.0.3" +version = "1.0.4" repositories { mavenCentral() maven("https://repo.papermc.io/repository/maven-public/") @@ -16,7 +16,7 @@ dependencies { testImplementation("com.h2database:h2:2.3.232") testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") testImplementation("org.mockito:mockito-core:5.15.2") - testRuntimeOnly("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") } + testImplementation("com.github.MilkBowl:VaultAPI:1.7") { exclude(group = "org.bukkit", module = "bukkit") } testRuntimeOnly("org.junit.platform:junit-platform-launcher") } tasks.jar { diff --git a/DuneEss/src/main/java/com/example/duneess/CommunityCodes.java b/DuneEss/src/main/java/com/example/duneess/CommunityCodes.java new file mode 100644 index 00000000..4f588e43 --- /dev/null +++ b/DuneEss/src/main/java/com/example/duneess/CommunityCodes.java @@ -0,0 +1,73 @@ +package com.example.duneess; + +import com.google.gson.*; +import org.bukkit.Bukkit; +import org.bukkit.command.*; +import org.bukkit.entity.Player; +import org.bukkit.configuration.file.YamlConfiguration; +import java.io.File; +import java.net.URI; +import java.net.http.*; +import java.time.Duration; +import java.util.*; + +/** Authenticated website bridge; rewards are always credited by the UUID/month ledger. */ +final class CommunityCodes implements CommandExecutor,TabCompleter { + private final DuneEss plugin; + private final HttpClient http=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build(); + private final Set busy=new HashSet<>(); + private final Map cooldown=new HashMap<>(); + private final String endpoint,secret; + private boolean syncing; + CommunityCodes(DuneEss plugin){ + this.plugin=plugin; + File file=new File(plugin.getDataFolder(),"website-bridge.yml");if(!file.exists())plugin.saveResource("website-bridge.yml",false); + YamlConfiguration settings=YamlConfiguration.loadConfiguration(file);endpoint=settings.getString("origin","https://cp.dunerealms.com");secret=settings.getString("secret",""); + for(String name:List.of("communitycode","linkwebsite")){PluginCommand command=Objects.requireNonNull(plugin.getCommand(name));command.setExecutor(this);command.setTabCompleter(this);} + Bukkit.getScheduler().runTaskTimer(plugin,this::syncReceipts,200L,1200L); + } + private JsonObject post(String path,JsonObject body) throws Exception { + if(secret.length()<32||!endpoint.equals("https://cp.dunerealms.com"))throw new IllegalStateException("Website bridge is not configured"); + HttpRequest request=HttpRequest.newBuilder(URI.create(endpoint+path)).timeout(Duration.ofSeconds(10)).header("Authorization","Bearer "+secret).header("Content-Type","application/json").POST(HttpRequest.BodyPublishers.ofString(body.toString())).build(); + HttpResponse response=http.send(request,HttpResponse.BodyHandlers.ofString()); + if(response.body().length()>16384)throw new IllegalStateException("Unexpected bridge response"); + JsonObject data=JsonParser.parseString(response.body()).getAsJsonObject(); + if(response.statusCode()!=200)throw new IllegalStateException(data.has("message")?data.get("message").getAsString():"Website unavailable");return data; + } + @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){ + if(!(sender instanceof Player player)){sender.sendMessage(com.example.dunegui.PublicNames.text("Players only."));return true;} + boolean linking=command.getName().equals("linkwebsite"); + if(args.length!=1){player.sendMessage(com.example.dunegui.PublicNames.text(linking?"Generate a private link command at https://cp.dunerealms.com":"Public community codes: https://www.dunerealms.com/donate.html | Personal codes: https://cp.dunerealms.com | /communitycode CODE"));return true;} + String code=linking?args[0].toLowerCase(Locale.ROOT):args[0].toUpperCase(Locale.ROOT); + if(!(linking?code.matches("[a-f0-9]{32}"):code.matches("[A-Z0-9-]{4,48}"))){player.sendMessage(com.example.dunegui.PublicNames.text("Invalid code format."));return true;} + UUID uuid=player.getUniqueId();long now=System.currentTimeMillis();cooldown.entrySet().removeIf(entry->now-entry.getValue()>60000); + if(busy.contains(uuid)||now-cooldown.getOrDefault(uuid,0L)<3000){player.sendMessage(com.example.dunegui.PublicNames.text("Please wait a few seconds before trying again."));return true;} + cooldown.put(uuid,now);busy.add(uuid); + JsonObject body=new JsonObject();body.addProperty("uuid",uuid.toString());body.addProperty("name",player.getName());body.addProperty("code",code); + player.sendMessage(com.example.dunegui.PublicNames.text(linking?"Verifying website link…":"Checking community reward…")); + Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{try{ + JsonObject response=post(linking?"/api/game-link/consume":"/api/community/game/prepare",body); + Bukkit.getScheduler().runTask(plugin,()->{try{ + if(linking){player.sendMessage(com.example.dunegui.PublicNames.text("Website account linked to your Minecraft UUID. Refresh the account panel."));return;} + if(response.has("delivered")&&response.get("delivered").getAsBoolean()){player.sendMessage("This Minecraft UUID has already received that month's reward.");return;} + String month=response.get("month").getAsString(),receipt=response.get("receipt").getAsString();int amount=response.get("amount").getAsInt(); + boolean granted=((DuneEconomy)plugin.economy()).grantCommunity(uuid,month,amount,receipt); + player.sendMessage(com.example.dunegui.PublicNames.text(granted?"Community reward credited: "+amount+" Dunemarks. Thank you, everyone!":"This UUID has already claimed that month's reward. No duplicate currency credited.")); + syncReceipts(); + }catch(Exception error){plugin.getLogger().warning("Community reward could not be committed: "+error.getClass().getSimpleName());player.sendMessage(com.example.dunegui.PublicNames.text("The reward could not be confirmed. Your code remains available; try again later."));}finally{busy.remove(uuid);}}); + }catch(Exception error){Bukkit.getScheduler().runTask(plugin,()->{busy.remove(uuid);player.sendMessage(com.example.dunegui.PublicNames.text("Website request failed. Check the account panel or public code page and try again later."));});}}); + return true; + } + private void syncReceipts(){ + if(syncing||secret.length()<32)return; + Map> pending;try{pending=((DuneEconomy)plugin.economy()).pendingCommunityReceipts();}catch(Exception error){return;} + if(pending.isEmpty())return;syncing=true; + Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{List> confirmed=new ArrayList<>(); + try{for(var player:pending.entrySet())for(String receipt:player.getValue()){ + JsonObject body=new JsonObject();body.addProperty("uuid",player.getKey().toString());body.addProperty("receipt",receipt); + try{post("/api/community/game/ack",body);confirmed.add(Map.entry(player.getKey(),receipt));}catch(Exception unavailable){return;} + }}finally{Bukkit.getScheduler().runTask(plugin,()->{try{for(var row:confirmed)((DuneEconomy)plugin.economy()).acknowledgeCommunity(row.getKey(),row.getValue());}catch(Exception error){plugin.getLogger().warning("Community receipts will retry on the next sync.");}finally{syncing=false;}});} + }); + } + @Override public List onTabComplete(CommandSender sender,Command command,String alias,String[] args){return List.of();} +} diff --git a/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java b/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java index aa53852a..72d118f5 100644 --- a/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java +++ b/DuneEss/src/main/java/com/example/duneess/DuneEconomy.java @@ -33,14 +33,17 @@ final class DuneEconomy implements Economy { private final String singular, plural; private String jdbcUrl = "", dbUser = "", dbPassword = ""; private boolean databaseEnabled; + private boolean sharedDatabaseRequested; DuneEconomy(DuneEss plugin) { this.plugin = plugin; this.file = new File(plugin.getDataFolder(), "balances.yml"); this.data = YamlConfiguration.loadConfiguration(file); this.allowNegative = plugin.getConfig().getBoolean("currency.allow-negative-balances", true); - this.singular = plugin.getConfig().getString("currency.singular", "Solaris"); - this.plural = plugin.getConfig().getString("currency.plural", "Solaris"); + String configuredSingular = plugin.getConfig().getString("currency.singular", "Dunemark"); + this.singular = configuredSingular.equalsIgnoreCase("Solaris") ? "Dunemark" : configuredSingular; + String configuredPlural = plugin.getConfig().getString("currency.plural", "Dunemarks"); + this.plural = configuredPlural.equalsIgnoreCase("Solaris") ? "Dunemarks" : configuredPlural; loadDatabaseSettings(); loadBalances(); } @@ -51,6 +54,7 @@ final class DuneEconomy implements Economy { if (!coreConfig.isFile()) return; YamlConfiguration core = YamlConfiguration.loadConfiguration(coreConfig); if (!core.getBoolean("database.enabled", false)) return; + sharedDatabaseRequested = true; jdbcUrl = core.getString("database.jdbc-url", ""); dbUser = core.getString("database.username", ""); dbPassword = core.getString("database.password", ""); @@ -60,7 +64,10 @@ final class DuneEconomy implements Economy { boolean sharedDatabaseReady() { return databaseEnabled; } private Connection connect() throws SQLException { - return DriverManager.getConnection(jdbcUrl, dbUser, dbPassword); + java.util.Properties settings=new java.util.Properties(); + settings.setProperty("user",dbUser);settings.setProperty("password",dbPassword); + settings.setProperty("connectTimeout","5");settings.setProperty("socketTimeout","10"); + return DriverManager.getConnection(jdbcUrl,settings); } private void loadBalances() { @@ -85,8 +92,7 @@ final class DuneEconomy implements Economy { while (rows.next()) balances.put(rows.getObject(1, UUID.class), money(rows.getDouble(2))); } } catch (SQLException ex) { - databaseEnabled = false; - plugin.getLogger().severe("Could not open the shared Solaris database; using the migrated local ledger: " + ex.getMessage()); + plugin.getLogger().severe("Shared Solaris database unavailable; network transactions remain disabled until it recovers: " + ex.getMessage()); } } saveLocal(); @@ -144,8 +150,8 @@ final class DuneEconomy implements Economy { private synchronized void saveLocal() { for (Map.Entry entry : balances.entrySet()) data.set(entry.getKey().toString(), entry.getValue()); - try { data.save(file); } - catch (IOException ex) { plugin.getLogger().severe("Could not save Solaris balances: " + ex.getMessage()); } + try { writeCommunitySnapshot(data); } + catch (Exception ex) { plugin.getLogger().severe("Could not save Solaris balances: " + ex.getMessage()); } } private synchronized double balance(UUID id) { @@ -160,6 +166,7 @@ final class DuneEconomy implements Economy { } } } catch (SQLException ex) { plugin.getLogger().warning("Solaris balance read failed: " + ex.getMessage()); } + return 0; // Never authorize a network payment against stale local cache. } return balances.getOrDefault(id, 0.0); } @@ -176,23 +183,104 @@ final class DuneEconomy implements Economy { saveLocal(); } - synchronized void add(UUID id, double amount) { set(id, balance(id) + amount); } - synchronized void subtract(UUID id, double amount) { set(id, balance(id) - amount); } + synchronized void add(UUID id, double amount) { change(id, amount); } + synchronized void subtract(UUID id, double amount) { change(id, -amount); } + + private synchronized EconomyResponse change(UUID id, double delta) { + if (!Double.isFinite(delta)) return response(0, 0, EconomyResponse.ResponseType.FAILURE, "Invalid amount."); + if (sharedDatabaseRequested && !databaseEnabled) return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Shared economy is unavailable."); + if (!databaseEnabled) { + double next=money(balance(id)+delta); + if (!allowNegative && next<0) return response(Math.abs(delta),balance(id),EconomyResponse.ResponseType.FAILURE,"Insufficient funds."); + set(id,next); return response(Math.abs(delta),next,EconomyResponse.ResponseType.SUCCESS,null); + } + try (Connection c=connect()) { + c.setAutoCommit(false); + try { + try (PreparedStatement create=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,0) ON CONFLICT(uuid) DO NOTHING")) { + create.setObject(1,id);create.executeUpdate(); + } + double updated; + try (PreparedStatement q=c.prepareStatement("UPDATE dune_economy_balances SET balance=balance+? WHERE uuid=? AND (? OR balance+?>=0) RETURNING balance")) { + BigDecimal amount=BigDecimal.valueOf(money(delta)); + q.setBigDecimal(1,amount);q.setObject(2,id);q.setBoolean(3,allowNegative);q.setBigDecimal(4,amount); + try (ResultSet row=q.executeQuery()) { + if (!row.next()) {c.rollback();return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Insufficient funds.");} + updated=row.getDouble(1); + } + } + c.commit();balances.put(id,updated);saveLocal(); + return response(Math.abs(delta),updated,EconomyResponse.ResponseType.SUCCESS,null); + } catch(SQLException ex) {c.rollback();throw ex;} + } catch(SQLException ex) { + plugin.getLogger().warning("Shared Solaris transaction failed: "+ex.getSQLState()); + return response(Math.abs(delta),0,EconomyResponse.ResponseType.FAILURE,"Shared economy is unavailable."); + } + } + + /** One durable credit per UUID/month. A failed shared ledger never falls back to a second ledger. */ + synchronized boolean grantCommunity(UUID id,String month,int amount,String receipt) throws Exception { + if(!month.matches("20\\d\\d-(0[1-9]|1[0-2])")||amount<1||amount>10000||!receipt.matches("[a-f0-9]{64}"))throw new IllegalArgumentException("Invalid community grant"); + if(sharedDatabaseRequested&&!databaseEnabled)throw new IOException("Shared economy is unavailable"); + String key="community-claims."+id+"."+month; + if(databaseEnabled){ + try(Connection c=connect()){ + try(Statement s=c.createStatement()){s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_community_claims (uuid UUID NOT NULL, month VARCHAR(7) NOT NULL, receipt VARCHAR(64) NOT NULL, amount INTEGER NOT NULL, acked BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY(uuid,month))");} + c.setAutoCommit(false); + try{ + int inserted; + try(PreparedStatement s=c.prepareStatement("INSERT INTO dune_community_claims(uuid,month,receipt,amount) VALUES(?,?,?,?) ON CONFLICT(uuid,month) DO NOTHING")){s.setObject(1,id);s.setString(2,month);s.setString(3,receipt);s.setInt(4,amount);inserted=s.executeUpdate();} + if(inserted==0){try(PreparedStatement s=c.prepareStatement("SELECT receipt,amount FROM dune_community_claims WHERE uuid=? AND month=?")){s.setObject(1,id);s.setString(2,month);try(ResultSet r=s.executeQuery()){if(!r.next()||!receipt.equals(r.getString(1))||amount!=r.getInt(2))throw new IOException("Community receipt mismatch");}}c.commit();return false;} + double updated; + try(PreparedStatement s=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES(?,?) ON CONFLICT(uuid) DO UPDATE SET balance=dune_economy_balances.balance+EXCLUDED.balance RETURNING balance")){s.setObject(1,id);s.setBigDecimal(2,BigDecimal.valueOf(amount));try(ResultSet r=s.executeQuery()){r.next();updated=r.getDouble(1);}} + c.commit();balances.put(id,money(updated));saveLocal();return true; + }catch(Exception error){c.rollback();throw error;} + } + } + if(data.contains(key+".receipt")){if(!receipt.equals(data.getString(key+".receipt"))||amount!=data.getInt(key+".amount"))throw new IOException("Community receipt mismatch");return false;} + YamlConfiguration next=new YamlConfiguration();next.loadFromString(data.saveToString()); + double updated=money(balances.getOrDefault(id,0.0)+amount); + next.set(id.toString(),updated);next.set(key+".receipt",receipt);next.set(key+".amount",amount);next.set(key+".acked",false); + writeCommunitySnapshot(next);balances.put(id,updated);return true; + } + private void writeCommunitySnapshot(YamlConfiguration next) throws Exception { + java.nio.file.Path target=file.toPath(),temporary=target.resolveSibling("balances.yml.community-tmp"); + java.nio.file.Files.createDirectories(target.getParent()); + byte[] bytes=next.saveToString().getBytes(java.nio.charset.StandardCharsets.UTF_8); + try(java.nio.channels.FileChannel channel=java.nio.channels.FileChannel.open(temporary,java.nio.file.StandardOpenOption.CREATE,java.nio.file.StandardOpenOption.TRUNCATE_EXISTING,java.nio.file.StandardOpenOption.WRITE)){java.nio.ByteBuffer buffer=java.nio.ByteBuffer.wrap(bytes);while(buffer.hasRemaining())channel.write(buffer);channel.force(true);} + java.nio.file.Files.move(temporary,target,java.nio.file.StandardCopyOption.ATOMIC_MOVE,java.nio.file.StandardCopyOption.REPLACE_EXISTING); + data.loadFromString(next.saveToString()); + } + synchronized Map> pendingCommunityReceipts() throws Exception { + Map> pending=new HashMap<>(); + if(sharedDatabaseRequested&&!databaseEnabled)return pending; + if(databaseEnabled){try(Connection c=connect();Statement s=c.createStatement()){ + s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_community_claims (uuid UUID NOT NULL, month VARCHAR(7) NOT NULL, receipt VARCHAR(64) NOT NULL, amount INTEGER NOT NULL, acked BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY(uuid,month))"); + try(ResultSet r=s.executeQuery("SELECT uuid,receipt FROM dune_community_claims WHERE acked=FALSE LIMIT 100")){while(r.next())pending.computeIfAbsent(r.getObject(1,UUID.class),ignored->new ArrayList<>()).add(r.getString(2));} + }return pending;} + var section=data.getConfigurationSection("community-claims");if(section==null)return pending; + for(String uuid:section.getKeys(false)){var months=section.getConfigurationSection(uuid);if(months==null)continue;for(String month:months.getKeys(false)){String key=uuid+"."+month;if(!section.getBoolean(key+".acked"))pending.computeIfAbsent(UUID.fromString(uuid),ignored->new ArrayList<>()).add(section.getString(key+".receipt"));}} + return pending; + } + synchronized void acknowledgeCommunity(UUID id,String receipt) throws Exception { + if(databaseEnabled){try(Connection c=connect();PreparedStatement s=c.prepareStatement("UPDATE dune_community_claims SET acked=TRUE WHERE uuid=? AND receipt=?")){s.setObject(1,id);s.setString(2,receipt);s.executeUpdate();}return;} + YamlConfiguration next=new YamlConfiguration();next.loadFromString(data.saveToString());var months=next.getConfigurationSection("community-claims."+id);if(months==null)return; + for(String month:months.getKeys(false))if(receipt.equals(months.getString(month+".receipt")))months.set(month+".acked",true); + writeCommunitySnapshot(next); + } private EconomyResponse response(double amount, double balance, EconomyResponse.ResponseType type, String message) { return new EconomyResponse(amount, balance, type, message); } private EconomyResponse deposit(OfflinePlayer player, double amount) { if (amount < 0 || !Double.isFinite(amount)) return response(amount, getBalance(player), EconomyResponse.ResponseType.FAILURE, "Amount must be non-negative."); - set(player.getUniqueId(), getBalance(player) + amount); - return response(amount, getBalance(player), EconomyResponse.ResponseType.SUCCESS, null); + return change(player.getUniqueId(), amount); } private EconomyResponse withdraw(OfflinePlayer player, double amount) { double current = getBalance(player); if (amount < 0 || !Double.isFinite(amount)) return response(amount, current, EconomyResponse.ResponseType.FAILURE, "Amount must be non-negative."); if (!allowNegative && current < amount) return response(amount, current, EconomyResponse.ResponseType.FAILURE, "Insufficient funds."); - set(player.getUniqueId(), current - amount); - return response(amount, getBalance(player), EconomyResponse.ResponseType.SUCCESS, null); + return change(player.getUniqueId(), -amount); } @Override public boolean isEnabled() { return plugin.isEnabled(); } @@ -237,6 +325,11 @@ final class DuneEconomy implements Economy { @Override public boolean createPlayerAccount(String name) { return createPlayerAccount(Bukkit.getOfflinePlayer(name)); } @Override public boolean createPlayerAccount(OfflinePlayer player) { UUID id = player.getUniqueId(); + if (databaseEnabled) { + try (Connection c=connect();PreparedStatement q=c.prepareStatement("INSERT INTO dune_economy_balances(uuid,balance) VALUES (?,?) ON CONFLICT(uuid) DO NOTHING")) { + q.setObject(1,id);q.setBigDecimal(2,BigDecimal.valueOf(money(plugin.getConfig().getDouble("currency.starting-balance",0))));q.executeUpdate();return true; + } catch(SQLException ex) {return false;} + } if (!balances.containsKey(id)) set(id, money(plugin.getConfig().getDouble("currency.starting-balance", 0))); return true; } diff --git a/DuneEss/src/main/java/com/example/duneess/DuneEss.java b/DuneEss/src/main/java/com/example/duneess/DuneEss.java index 44e8f6c0..b65e6346 100644 --- a/DuneEss/src/main/java/com/example/duneess/DuneEss.java +++ b/DuneEss/src/main/java/com/example/duneess/DuneEss.java @@ -32,6 +32,7 @@ import java.util.*; public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCompleter, Listener { private static final List PLANETS = List.of("arrakis", "giedi_prime", "kaitain", "caladan", "sigma_draconis_iv", "spacing_guild"); private DuneEconomy economy; + String balanceLabel(Player player) { return economy.format(economy.getBalance(player)); } private ExchangeMenu exchangeMenu; private EssentialsBasics basics; private String jdbcUrl = "", dbUser = "", dbPassword = ""; @@ -43,28 +44,28 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom private static final String HELP_TITLE = ChatColor.DARK_RED + "Dune Field Guide"; private static final List> HELP_PAGES = List.of( List.of( - new HelpEntry("/duneess balance", "Check your Solaris wallet.", Material.GOLD_INGOT), + new HelpEntry("/duneess balance", "Check your Dunemarks wallet.", Material.GOLD_INGOT), new HelpEntry("/duneess sell", "Sell all tagged spice in your inventory.", Material.ORANGE_DYE), - new HelpEntry("/duneess travel", "Open the Spacing Guild planet selector.", Material.ENDER_PEARL), + new HelpEntry("/duneess travel", "Open the Vaerkring planet selector.", Material.ENDER_PEARL), new HelpEntry("/duneess travel arrakis", "Pay the fare and travel to Arrakis.", Material.MAP), new HelpEntry("/dune", "Open the Dune Navigator menu.", Material.NETHER_STAR) ), List.of( - new HelpEntry("/dune choose fremen", "Choose Fremen; replace 'fremen' with another house to choose it.", Material.WHITE_BANNER), + new HelpEntry("/dune choose fremen", "Choose Vrijduin; replace 'fremen' with another house to choose it.", Material.WHITE_BANNER), new HelpEntry("/dune kit", "Receive your faction stillsuit and spice shovel.", Material.NETHERITE_SHOVEL), new HelpEntry("/dune elytra", "Upgrade a worn stillsuit chestplate with an Elytra.", Material.ELYTRA), - new HelpEntry("/dune politics status", "View the Spacing Trust, leaders, and imperial appointments.", Material.WRITABLE_BOOK), + new HelpEntry("/dune politics status", "View the Vaerkring Trust, leaders, and Landsraad appointments.", Material.WRITABLE_BOOK), new HelpEntry("/dune water status", "View your Arrakis water-trading career.", Material.WATER_BUCKET) ), List.of( - new HelpEntry("/dune serverjobs", "Browse hourly CHOAM spice contracts.", Material.EMERALD), + new HelpEntry("/dune serverjobs", "Browse hourly Koopkring spice contracts.", Material.EMERALD), new HelpEntry("/dune job", "Browse player-posted spice contracts.", Material.BOOK), new HelpEntry("/dune job post 100", "Post a 100-spice contract; change the amount to suit your listing.", Material.PAPER), new HelpEntry("/dune water sell", "Sell water collected on Arrakis.", Material.BUCKET), new HelpEntry("/dune exchange", "Open the spice exchange menu.", Material.CHEST) ), List.of( - new HelpEntry("/duneess admin solari player amount", "Grant Solaris to an online player.", Material.GOLD_INGOT), + new HelpEntry("/duneess admin solari player amount", "Grant Dunemarks to an online player.", Material.GOLD_INGOT), new HelpEntry("/duneess admin teleport arrakis", "Force yourself to Arrakis spawn.", Material.COMPASS), new HelpEntry("/duneess admin teleport sietch", "Teleport yourself to a generated sietch.", Material.CHEST), new HelpEntry("/duneess admin teleport spiceblow", "Teleport yourself to a generated spice blow.", Material.MAGMA_BLOCK), @@ -82,6 +83,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom helpPageKey = new NamespacedKey(this, "help_page"); helpActionKey = new NamespacedKey(this, "help_action"); economy = new DuneEconomy(this); + new CommunityCodes(this); getServer().getServicesManager().register(Economy.class, economy, this, ServicePriority.Highest); getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); PluginCommand command = Objects.requireNonNull(getCommand("duneess")); @@ -93,7 +95,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom exchangeMenu = new ExchangeMenu(this); exchangeMenu.register(); for (Player player : Bukkit.getOnlinePlayers()) economy.createPlayerAccount(player); - getLogger().info("DuneRealms Essentials enabled as the Solaris Vault provider."); + getLogger().info("DuneRealms Essentials enabled as the Dunemarks Vault provider."); } @Override public void onDisable() { @@ -201,7 +203,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom } sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+"); sendBoxLine(sender, ChatColor.GRAY + "Use /duneess help menu for the visual guide."); - sendBoxLine(sender, ChatColor.GRAY + "DuneEss: Solaris and Guild travel"); + sendBoxLine(sender, ChatColor.GRAY + "DuneEss: Dunemarks and Vaerkring travel"); sendBoxLine(sender, ChatColor.GRAY + "DuneCore: factions and Arrakis"); sender.sendMessage(ChatColor.DARK_RED + "+" + "-".repeat(58) + "+"); if (sender instanceof Player player) { @@ -341,7 +343,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom ItemStack spice=new ItemStack(Material.ORANGE_DYE,quantity);ItemMeta sm=spice.getItemMeta(); sm.setDisplayName(ChatColor.GOLD+"Melange Spice");sm.getPersistentDataContainer().set(spiceKey,PersistentDataType.STRING,"spice");spice.setItemMeta(sm); if(player.getInventory().firstEmpty()<0){player.sendMessage("Make an empty inventory slot first.");return;} - if(!economy.withdrawPlayer(player,price).transactionSuccess()){player.sendMessage("Not enough Solaris, or economy unavailable.");return;} + if(!economy.withdrawPlayer(player,price).transactionSuccess()){player.sendMessage("Not enough Dunemarks, or economy unavailable.");return;} player.getInventory().addItem(spice);player.sendMessage(ChatColor.GOLD+"Bought 16 spice for "+economy.format(price)+"."); }); com.example.dunegui.NativeMenus.inventory(this,player,"Spice Seller · +35%",menu,actions); @@ -377,23 +379,23 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom } private void openTravelMenu(Player player) { - Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.DARK_AQUA + "Spacing Guild Travel"); + Inventory inventory = Bukkit.createInventory(null, 9, ChatColor.DARK_AQUA + "Vaerkring Travel"); for (int i = 0; i < PLANETS.size(); i++) { String planet = PLANETS.get(i); ItemStack item = new ItemStack(Material.ENDER_PEARL); ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(ChatColor.GOLD + planet + " — " + getConfig().getInt("currency.travel-price", 100) + " Solaris"); + meta.setDisplayName(ChatColor.GOLD + com.example.dunegui.PlanetSigils.label(planet) + " — " + getConfig().getInt("currency.travel-price", 100) + " Dunemarks"); meta.getPersistentDataContainer().set(new NamespacedKey(this, "planet"), PersistentDataType.STRING, planet); item.setItemMeta(meta); - inventory.setItem(i, item); + inventory.setItem(i, com.example.dunegui.PlanetSigils.apply(item,planet)); } java.util.Map actions=new java.util.HashMap<>(); for(int i=0;itravel(player,planet)); } - com.example.dunegui.NativeMenus.inventory(this,player,"Spacing Guild Travel",inventory,actions); + com.example.dunegui.NativeMenus.inventory(this,player,"Vaerkring Travel",inventory,actions); } @EventHandler public void onTravelMenuClick(InventoryClickEvent event) { - if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().equals(ChatColor.DARK_AQUA + "Spacing Guild Travel")) return; + if (!(event.getWhoClicked() instanceof Player player) || !event.getView().getTitle().equals(ChatColor.DARK_AQUA + "Vaerkring Travel")) return; event.setCancelled(true); ItemStack item = event.getCurrentItem(); if (item == null || !item.hasItemMeta()) return; @@ -415,7 +417,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom } if (server.isBlank()) { player.sendMessage(ChatColor.RED + "The Guild server for " + planet + " is not configured."); return; } int fare = travelFare(player, planet); - if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Solaris for the Guild fare."); return; } + if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Dunemarks for the Guild fare."); return; } if (fare > 0) economy.withdrawPlayer(player, fare); if (!sendToServer(player, server, planet) && fare > 0) economy.depositPlayer(player, fare); return; @@ -423,13 +425,13 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom World world = Bukkit.getWorld(planet); if (world == null) { player.sendMessage(ChatColor.RED + "That planet is not loaded on this server."); return; } int fare = travelFare(player, planet); - if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Solaris for the Guild fare."); return; } + if (fare > 0 && !economy.has(player, fare)) { player.sendMessage(ChatColor.RED + "Not enough Dunemarks for the Guild fare."); return; } if (fare > 0) economy.withdrawPlayer(player, fare); if (!player.teleport(world.getSpawnLocation())) { if (fare > 0) economy.depositPlayer(player, fare); - player.sendMessage(ChatColor.RED + "Guild travel failed. Your fare was returned."); + player.sendMessage(ChatColor.RED + "Vaerkring travel failed. Your fare was returned."); } else { - player.sendMessage(ChatColor.AQUA + "Spacing Guild arrival: " + planet); + player.sendMessage(ChatColor.AQUA + "Vaerkring arrival: " + planet); if (planet.equals("arrakis")) callCoreArrakisArrival(player); } } @@ -440,7 +442,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom DataOutputStream data = new DataOutputStream(bytes); data.writeUTF("Connect"); data.writeUTF(server); player.sendPluginMessage(this, "BungeeCord", bytes.toByteArray()); - player.sendMessage(ChatColor.AQUA + "Spacing Guild transfer requested: " + planet); + player.sendMessage(ChatColor.AQUA + "Vaerkring transfer requested: " + planet); return true; } catch (Exception ex) { player.sendMessage(ChatColor.RED + "Guild transfer failed. Your fare was returned."); @@ -488,7 +490,7 @@ public final class DuneEss extends JavaPlugin implements CommandExecutor, TabCom economy.depositPlayer(target, amount); sender.sendMessage(ChatColor.GREEN + "Added " + economy.format(amount) + " to " + target.getName() + "."); target.sendMessage(ChatColor.GOLD + "An admin added " + economy.format(amount) + " to your balance."); - } catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Enter a positive Solaris amount."); } + } catch (NumberFormatException ex) { sender.sendMessage(ChatColor.RED + "Enter a positive Dunemarks amount."); } return true; } if (args[1].equalsIgnoreCase("spicebloom")) { diff --git a/DuneEss/src/main/java/com/example/duneess/EssentialsBasics.java b/DuneEss/src/main/java/com/example/duneess/EssentialsBasics.java index af738885..9eff49ce 100644 --- a/DuneEss/src/main/java/com/example/duneess/EssentialsBasics.java +++ b/DuneEss/src/main/java/com/example/duneess/EssentialsBasics.java @@ -64,7 +64,7 @@ final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener choices.add(new NativeMenus.Choice("Spawn","Return to this world's spawn.",()->p.performCommand("spawn"))); choices.add(new NativeMenus.Choice("Guild servers","Travel using existing Solaris fares and permissions.",()->p.performCommand("duneess travel"))); choices.add(new NativeMenus.Choice("Solaris","Show your balance.",()->p.performCommand("duneess balance"))); - choices.add(new NativeMenus.Choice("CHOAM Exchange","Buy, list and reclaim items.",()->p.performCommand("exchange"))); + choices.add(new NativeMenus.Choice("Koopkring Exchange","Buy, list and reclaim items.",()->p.performCommand("exchange"))); choices.add(new NativeMenus.Choice("Help","Open the Dune Field Guide.",()->p.performCommand("duneess help menu"))); NativeMenus.show(plugin,p,"DuneRealms Essentials","Solaris: "+plugin.economy().format(plugin.economy().getBalance(p)),choices); } @@ -98,7 +98,7 @@ final class EssentialsBasics implements CommandExecutor, TabCompleter, Listener if(args.length!=1) throw new IllegalArgumentException("Usage: /tpa "); Player target=Bukkit.getPlayerExact(args[0]); if(target==null || target.equals(p) || !p.canSee(target)) throw new IllegalArgumentException("Choose another online player on this server."); - if(!target.getWorld().equals(p.getWorld())) throw new IllegalArgumentException("Use Guild travel to reach that player's world first."); + if(!target.getWorld().equals(p.getWorld())) throw new IllegalArgumentException("Use Vaerkring travel to reach that player's world first."); requests.put(target.getUniqueId(),new Request(p.getUniqueId(),System.nanoTime()+60_000_000_000L)); target.sendMessage(p.getName()+" requests to teleport to you. /tpaccept or /tpdeny (60 seconds)."); p.sendMessage("Teleport request sent."); diff --git a/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java b/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java index 05c3eebb..8c64d9bc 100644 --- a/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java +++ b/DuneEss/src/main/java/com/example/duneess/ExchangeMenu.java @@ -41,12 +41,12 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { command.setExecutor(this); command.setTabCompleter(this); Bukkit.getPluginManager().registerEvents(this,plugin); try { store.initialize(); ready=true; } - catch(SQLException ex) { plugin.getLogger().warning("CHOAM is offline until the shared PostgreSQL economy is connected."); } + catch(SQLException ex) { plugin.getLogger().warning("Koopkring is offline until the shared PostgreSQL economy is connected."); } } private boolean connected(Player p) { // Retry after a transient startup outage; never trade against a fallback local wallet. if(!ready) try { store.initialize(); ready=true; } catch(SQLException ignored) { } - if(!ready) p.sendMessage(ChatColor.YELLOW+"CHOAM is not connected. Ask an operator to configure DuneCore PostgreSQL and restart DuneEss. No items or Solaris were taken."); + if(!ready) p.sendMessage(ChatColor.YELLOW+"Koopkring is not connected. Ask an operator to configure DuneCore PostgreSQL and restart DuneEss. No items or Dunemarks were taken."); return ready; } private String faction(Player p) { @@ -55,7 +55,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { String house=String.valueOf(core.getClass().getMethod("factionOf",Player.class).invoke(core,p)); if(List.of("Fremen","Atreides","Harkonnen","Corrino","Ordos").contains(house)) return house; } catch(ReflectiveOperationException ignored) { } - return "Spacing Guild"; + return "Vaerkring"; } private ChatColor tint(Player p) { return switch(faction(p)) { @@ -73,8 +73,8 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { } private Screen screen(Player p,String title) { Screen s=new Screen(p.getUniqueId()); - s.title="CHOAM | "+title; - s.inventory=Bukkit.createInventory(s,54,tint(p)+"CHOAM | "+title); + s.title="Koopkring | "+title; + s.inventory=Bukkit.createInventory(s,54,tint(p)+"Koopkring | "+title); Material glass=switch(faction(p)) { case "Atreides" -> Material.CYAN_STAINED_GLASS_PANE; case "Harkonnen" -> Material.RED_STAINED_GLASS_PANE; @@ -85,6 +85,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { }; for(int i=0;i<54;i++) if(i<9||i>=45||i%9==0||i%9==8) s.inventory.setItem(i,icon(glass," ")); + s.inventory.setItem(47,com.example.dunegui.DunemarkItems.icon(ChatColor.GOLD+"Dunemarks",List.of(ChatColor.GRAY+"Wallet: "+plugin.balanceLabel(p),ChatColor.GRAY+"Display icon only; balances stay in the ledger."))); button(s,49,Material.BARRIER,"Back to Exchange",()->home(p)); return s; } private void button(Screen s,int slot,Material material,String title,Runnable action,String... lore) { @@ -96,7 +97,8 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { String category=CATEGORIES.get(i); button(s,10+i,ICONS.get(i),category.toUpperCase(Locale.ROOT),()->browse(p,category,0,false,false)); } - button(s,29,Material.EMERALD,"Buy / All Items",()->browse(p,"all",0,false,false)); + s.inventory.setItem(29,com.example.dunegui.DunemarkItems.icon(ChatColor.GOLD+"Buy / All Items",List.of(ChatColor.GRAY+"Pay with Dunemarks from your wallet."))); + s.actions.put(29,()->browse(p,"all",0,false,false)); button(s,31,Material.CHEST,"Sell Held Item",()->{ p.closeInventory(); p.sendMessage(ChatColor.YELLOW+"Hold the item to list, then /exchange sell . Example: /exchange sell 16 25"); },"Tagged Dune items and their attributes are preserved.","Price is for ONE item."); @@ -123,7 +125,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { Screen s=screen(p,"Administration"); button(s,20,Material.BOOK,"All Listings",()->browse(p,"all",0,false,true),"All planets. Read-only inspection; normal ownership rules apply."); button(s,24,Material.REDSTONE,"Check Database",()->{ - if(connected(p)) p.sendMessage(ChatColor.GREEN+"Shared CHOAM database connected."); + if(connected(p)) p.sendMessage(ChatColor.GREEN+"Shared Koopkring database connected."); }); com.example.dunegui.NativeMenus.inventory(plugin,p,s.title,s.inventory,s.actions); } @@ -152,7 +154,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { try { item=decode(row); } catch(RuntimeException ex) { item=new ItemStack(Material.PAPER); } ItemMeta meta=item.getItemMeta(); meta.setDisplayName(ChatColor.GOLD+"#"+row.id()+" "+(row.displayName()==null?row.material():row.displayName())); - meta.setLore(List.of("Quantity: "+row.quantity(),"Each: "+row.price()+" Solaris","Seller: "+row.sellerName(),"Planet: "+row.origin(), + meta.setLore(List.of("Quantity: "+row.quantity(),"Each: "+row.price()+" Dunemarks","Seller: "+row.sellerName(),"Planet: "+row.origin(), row.seller().equals(p.getUniqueId())?"Click to reclaim unsold items":"Click to review purchase")); item.setItemMeta(meta); s.inventory.setItem(slot,item); s.actions.put(slot,()->confirm(p,row.id(),row.seller().equals(p.getUniqueId()))); slot++; @@ -169,7 +171,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { if(reclaim&&!row.seller().equals(p.getUniqueId())) throw new IllegalArgumentException("You can reclaim only your own listings."); Screen s=screen(p,reclaim?"Reclaim Listing":"Confirm Purchase"); s.inventory.setItem(22,icon(decode(row).getType(),"#"+id+" "+(row.displayName()==null?row.material():row.displayName()), - "Seller: "+row.sellerName(),reclaim?"Return "+row.quantity()+" unsold items":"Buy ONE for "+row.price()+" Solaris")); + "Seller: "+row.sellerName(),reclaim?"Return "+row.quantity()+" unsold items":"Buy ONE for "+row.price()+" Dunemarks")); button(s,30,Material.LIME_CONCRETE,reclaim?"Confirm Reclaim":"Confirm Purchase",()->{ p.closeInventory(); if(reclaim) cancel(p,id); else buy(p,id); }); @@ -189,8 +191,7 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { item.setAmount(amount); Map excess=p.getInventory().addItem(item); // Capacity is checked immediately before the transaction on this same server thread. - for(ItemStack left:excess.values()) p.getWorld().dropItemNaturally(p.getLocation(),left); - p.saveData(); + if (!excess.isEmpty()) throw new IllegalArgumentException("Inventory changed; the trade was rolled back. Make room and retry."); } private void sell(Player p,int amount,BigDecimal price) throws SQLException { ExchangeStore.validate(amount,price); @@ -202,10 +203,13 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { ItemStack unit=held.clone(); unit.setAmount(1); String name=unit.hasItemMeta()&&unit.getItemMeta().hasDisplayName()?ChatColor.stripColor(unit.getItemMeta().getDisplayName()):unit.getType().name(); if(name.length()>120) name=name.substring(0,120); - store.list(p.getUniqueId(),p.getName(),origin(p),category(unit),unit.getType().name(),amount,price, - Base64.getEncoder().encodeToString(unit.serializeAsBytes()),name); - held.setAmount(held.getAmount()-amount); p.saveData(); - p.sendMessage(ChatColor.GREEN+"Listed "+amount+" "+name+" at "+price+" Solaris each."); + final String displayName=name; + atomic(p, scoped -> { + scoped.list(p.getUniqueId(),p.getName(),origin(p),category(unit),unit.getType().name(),amount,price, + Base64.getEncoder().encodeToString(unit.serializeAsBytes()),displayName); + held.setAmount(held.getAmount()-amount); + }); + p.sendMessage(ChatColor.GREEN+"Listed "+amount+" "+name+" at "+price+" Dunemarks each."); } private String origin(Player p) { String world=p.getWorld().getName().toLowerCase(Locale.ROOT).replace('-','_'); @@ -228,8 +232,11 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { execute(p,()->{ ExchangeStore.Listing before=store.find(id); ItemStack item=decode(before); if(!fits(p,item,1)) throw new IllegalArgumentException("Make room in your inventory first."); - ExchangeStore.Listing bought=store.buy(p.getUniqueId(),id); - deliver(p,item,1); p.sendMessage(ChatColor.GREEN+"Purchased one item for "+bought.price()+" Solaris."); + atomic(p, scoped -> { + scoped.buy(p.getUniqueId(),p.getName(),id); + deliver(p,item,1); + }); + p.sendMessage(ChatColor.GREEN+"Purchased one item for "+before.price()+" Dunemarks."); }); } private void cancel(Player p,long id) { @@ -237,21 +244,42 @@ final class ExchangeMenu implements Listener, CommandExecutor, TabCompleter { execute(p,()->{ ExchangeStore.Listing before=store.find(id); ItemStack item=decode(before); if(!fits(p,item,before.quantity())) throw new IllegalArgumentException("Make room for all "+before.quantity()+" items first."); - ExchangeStore.Listing cancelled=store.cancel(p.getUniqueId(),id); - deliver(p,item,cancelled.quantity()); p.sendMessage(ChatColor.GREEN+"Listing cancelled. Unsold items returned."); + atomic(p, scoped -> { + ExchangeStore.Listing cancelled=scoped.cancel(p.getUniqueId(),id); + deliver(p,item,cancelled.quantity()); + }); + p.sendMessage(ChatColor.GREEN+"Listing cancelled. Unsold items returned."); }); } + private interface Trade { void run(ExchangeStore scoped) throws SQLException; } + private void atomic(Player p, Trade trade) throws SQLException { + Plugin core=Bukkit.getPluginManager().getPlugin("DuneCore"); + if (core==null) throw new SQLException("DuneCore network profiles are required"); + try { + java.util.function.Consumer work = connection -> { + try { trade.run(ExchangeStore.bound(connection)); } + catch (SQLException ex) { throw new java.util.concurrent.CompletionException(ex); } + }; + core.getClass().getMethod("transactNetworkInventory",Player.class,java.util.function.Consumer.class).invoke(core,p,work); + } catch (ReflectiveOperationException ex) { + Throwable cause=ex instanceof java.lang.reflect.InvocationTargetException ? ex.getCause() : ex; + if (cause instanceof java.util.concurrent.CompletionException && cause.getCause()!=null) cause=cause.getCause(); + if (cause instanceof IllegalArgumentException invalid) throw invalid; + if (cause instanceof SQLException sql) throw sql; + throw new SQLException("Network inventory transaction unavailable; install matching Core and Essentials",cause); + } + } private interface Operation { void run() throws SQLException; } private void execute(Player p,Operation action) { try { action.run(); } catch(IllegalArgumentException ex) { p.sendMessage(ChatColor.YELLOW+ex.getMessage()); } catch(SQLException ex) { - ready=false; plugin.getLogger().warning("CHOAM SQL operation failed: "+ex.getSQLState()); + ready=false; plugin.getLogger().warning("Koopkring SQL operation failed: "+ex.getSQLState()); p.sendMessage(ChatColor.RED+"The market database is unavailable. Please try again later."); } } @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) { - if(!(sender instanceof Player p)) { sender.sendMessage("Open the CHOAM exchange in-game with /exchange."); return true; } + if(!(sender instanceof Player p)) { sender.sendMessage("Open the Koopkring exchange in-game with /exchange."); return true; } if(args.length==0) { home(p); return true; } String action=args[0].toLowerCase(Locale.ROOT); if(action.equals("admin")) { if(p.hasPermission("dune.admin")) admin(p); else p.sendMessage(ChatColor.RED+"Operators only."); return true; } diff --git a/DuneEss/src/main/java/com/example/duneess/ExchangeStore.java b/DuneEss/src/main/java/com/example/duneess/ExchangeStore.java index d71acead..302e4ba5 100644 --- a/DuneEss/src/main/java/com/example/duneess/ExchangeStore.java +++ b/DuneEss/src/main/java/com/example/duneess/ExchangeStore.java @@ -11,12 +11,24 @@ final class ExchangeStore { String material, int quantity, BigDecimal price, String payload, String displayName) {} private final Connections connections; ExchangeStore(Connections connections) { this.connections = connections; } + /** Reuse the Core profile transaction; only Core may commit, roll back or close it. */ + static ExchangeStore bound(Connection connection) { + Connection scoped = (Connection) java.lang.reflect.Proxy.newProxyInstance( + ExchangeStore.class.getClassLoader(), new Class[]{Connection.class}, (proxy, method, args) -> { + if (Set.of("close", "commit", "rollback", "setAutoCommit").contains(method.getName())) return null; + try { return method.invoke(connection, args); } + catch (java.lang.reflect.InvocationTargetException ex) { throw ex.getCause(); } + }); + return new ExchangeStore(() -> scoped); + } void initialize() throws SQLException { try (Connection c = connections.open(); Statement s = c.createStatement()) { s.setQueryTimeout(5); s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_exchange_listings (id BIGSERIAL PRIMARY KEY, seller UUID NOT NULL, seller_name VARCHAR(32) NOT NULL, origin VARCHAR(48) NOT NULL, category VARCHAR(24) NOT NULL, material VARCHAR(80) NOT NULL, quantity INT NOT NULL CHECK(quantity>0), price NUMERIC(20,2) NOT NULL CHECK(price>0))"); s.executeUpdate("ALTER TABLE dune_exchange_listings ADD COLUMN IF NOT EXISTS payload TEXT"); s.executeUpdate("ALTER TABLE dune_exchange_listings ADD COLUMN IF NOT EXISTS display_name VARCHAR(120)"); + s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_exchange_sales (id BIGSERIAL PRIMARY KEY, listing_id BIGINT NOT NULL, seller UUID NOT NULL, seller_name VARCHAR(32) NOT NULL, buyer UUID NOT NULL, buyer_name VARCHAR(32) NOT NULL, material VARCHAR(80) NOT NULL, display_name VARCHAR(120), quantity INTEGER NOT NULL CHECK(quantity>0), unit_price NUMERIC(20,2) NOT NULL CHECK(unit_price>0), total_price NUMERIC(20,2) NOT NULL CHECK(total_price>0), origin VARCHAR(48) NOT NULL, sold_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP)"); + s.executeUpdate("CREATE INDEX IF NOT EXISTS dune_exchange_sales_seller_id ON dune_exchange_sales(seller,id DESC)"); } } private PreparedStatement prepare(Connection c, String sql) throws SQLException { @@ -68,7 +80,8 @@ final class ExchangeStore { r.getBigDecimal("price"),r.getString("payload"),r.getString("display_name")); } /** On SQL failure, no wallet or listing changes survive. Never set quantity to zero under CHECK(quantity>0). */ - Listing buy(UUID buyer, long id) throws SQLException { + Listing buy(UUID buyer, long id) throws SQLException { return buy(buyer, "Unknown", id); } + Listing buy(UUID buyer, String buyerName, long id) throws SQLException { try(Connection c=connections.open()) { c.setAutoCommit(false); try(PreparedStatement q=prepare(c,"SELECT * FROM dune_exchange_listings WHERE id=? FOR UPDATE")) { @@ -85,6 +98,13 @@ final class ExchangeStore { credit.setBigDecimal(1,offer.price()); credit.setObject(2,offer.seller()); if(credit.executeUpdate()!=1) throw new IllegalArgumentException("Seller wallet unavailable; no payment taken."); stock.setLong(1,id); if(stock.executeUpdate()!=1) throw new SQLException("Listing changed."); + try (PreparedStatement sale = prepare(c, "INSERT INTO dune_exchange_sales(listing_id,seller,seller_name,buyer,buyer_name,material,display_name,quantity,unit_price,total_price,origin) VALUES(?,?,?,?,?,?,?,1,?,?,?)")) { + sale.setLong(1, id); sale.setObject(2, offer.seller()); sale.setString(3, offer.sellerName()); + sale.setObject(4, buyer); sale.setString(5, buyerName); + sale.setString(6, offer.material()); sale.setString(7, offer.displayName()); + sale.setBigDecimal(8, offer.price()); sale.setBigDecimal(9, offer.price()); sale.setString(10, offer.origin()); + sale.executeUpdate(); + } c.commit(); return offer; } } diff --git a/DuneEss/src/main/resources/config.yml b/DuneEss/src/main/resources/config.yml index a7cd372a..38695e3c 100644 --- a/DuneEss/src/main/resources/config.yml +++ b/DuneEss/src/main/resources/config.yml @@ -1,6 +1,6 @@ currency: - singular: Solaris - plural: Solaris + singular: Dunemark + plural: Dunemarks spice-price: 15 travel-price: 100 starting-balance: 0 diff --git a/DuneEss/src/main/resources/plugin.yml b/DuneEss/src/main/resources/plugin.yml index dd9b52c2..164f5800 100644 --- a/DuneEss/src/main/resources/plugin.yml +++ b/DuneEss/src/main/resources/plugin.yml @@ -1,12 +1,18 @@ name: DuneEss -version: 1.0.3 +version: 1.0.4 main: com.example.duneess.DuneEss api-version: '1.21.8' depend: [Vault] softdepend: [floodgate, ViaVersion, DuneCore, DuneTerrain] prefix: DuneRealms Essentials -description: DuneRealms Essentials - Dune Solaris economy, Vault provider, spice sales, and Arrakis travel +description: DuneRealms Essentials - Dunemarks economy, Vault provider, spice sales, and Arrakduin travel commands: + communitycode: + description: Claim one community currency reward per UUID and monthly goal + usage: /communitycode + linkwebsite: + description: Verify your Minecraft UUID for a website account + usage: /linkwebsite exchange: description: CHOAM interplanetary player marketplace usage: /exchange diff --git a/DuneEss/src/main/resources/website-bridge.yml b/DuneEss/src/main/resources/website-bridge.yml new file mode 100644 index 00000000..35404fc4 --- /dev/null +++ b/DuneEss/src/main/resources/website-bridge.yml @@ -0,0 +1,3 @@ +origin: https://cp.dunerealms.com +# Operator secret shared with the account panel. Never publish or put it in command arguments. +secret: '' diff --git a/DuneEss/src/test/java/com/example/duneess/CommunityLedgerTest.java b/DuneEss/src/test/java/com/example/duneess/CommunityLedgerTest.java new file mode 100644 index 00000000..7fb2514b --- /dev/null +++ b/DuneEss/src/test/java/com/example/duneess/CommunityLedgerTest.java @@ -0,0 +1,37 @@ +package com.example.duneess; + +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.file.YamlConfiguration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.*; +import java.util.*; +import java.util.logging.Logger; +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; + +class CommunityLedgerTest { + @TempDir Path directory; + DuneEss plugin(){DuneEss plugin=mock(DuneEss.class);when(plugin.getDataFolder()).thenReturn(directory.resolve("DuneEss").toFile());when(plugin.getConfig()).thenReturn(new YamlConfiguration());when(plugin.getLogger()).thenReturn(Logger.getAnonymousLogger());return plugin;} + @Test void creditsOnceAcrossRestartAndRetainsReceiptUntilAcknowledged() throws Exception { + DuneEss plugin=plugin();UUID uuid=UUID.randomUUID();OfflinePlayer player=mock(OfflinePlayer.class);when(player.getUniqueId()).thenReturn(uuid);String receipt="a".repeat(64); + DuneEconomy first=new DuneEconomy(plugin);assertTrue(first.grantCommunity(uuid,"2026-10",50,receipt));assertEquals(50,first.getBalance(player)); + first.add(uuid,10);assertEquals(60,first.getBalance(player)); + DuneEconomy restarted=new DuneEconomy(plugin);assertFalse(restarted.grantCommunity(uuid,"2026-10",50,receipt));assertEquals(60,restarted.getBalance(player));assertEquals(List.of(receipt),restarted.pendingCommunityReceipts().get(uuid)); + assertThrows(Exception.class,()->restarted.grantCommunity(uuid,"2026-10",50,"b".repeat(64))); + restarted.acknowledgeCommunity(uuid,receipt);assertTrue(new DuneEconomy(plugin).pendingCommunityReceipts().isEmpty()); + assertTrue(restarted.grantCommunity(uuid,"2026-11",50,"c".repeat(64)));assertEquals(110,restarted.getBalance(player)); + } + @Test void failedDurableWriteDoesNotCreditOrConsumeTheReward() throws Exception { + DuneEss plugin=plugin();DuneEconomy ledger=new DuneEconomy(plugin);UUID uuid=UUID.randomUUID();OfflinePlayer player=mock(OfflinePlayer.class);when(player.getUniqueId()).thenReturn(uuid); + Path blocker=directory.resolve("DuneEss/balances.yml.community-tmp");Files.createDirectory(blocker); + assertThrows(Exception.class,()->ledger.grantCommunity(uuid,"2026-10",50,"a".repeat(64)));assertEquals(0,ledger.getBalance(player));assertTrue(ledger.pendingCommunityReceipts().isEmpty()); + Files.delete(blocker);assertTrue(ledger.grantCommunity(uuid,"2026-10",50,"a".repeat(64)));assertEquals(50,ledger.getBalance(player)); + } + @Test void incompleteSharedConfigurationCannotCreateASecondLocalWallet() throws Exception { + Files.createDirectories(directory.resolve("DuneCore"));YamlConfiguration core=new YamlConfiguration();core.set("database.enabled",true);core.set("database.jdbc-url","");core.save(directory.resolve("DuneCore/config.yml").toFile()); + DuneEconomy ledger=new DuneEconomy(plugin());UUID uuid=UUID.randomUUID();OfflinePlayer player=mock(OfflinePlayer.class);when(player.getUniqueId()).thenReturn(uuid); + assertFalse(ledger.depositPlayer(player,50).transactionSuccess());assertEquals(0,ledger.getBalance(player)); + assertThrows(Exception.class,()->ledger.grantCommunity(uuid,"2026-10",50,"a".repeat(64))); + } +} diff --git a/DuneEss/src/test/java/com/example/duneess/DunemarkDenominationsTest.java b/DuneEss/src/test/java/com/example/duneess/DunemarkDenominationsTest.java new file mode 100644 index 00000000..9e3acfbc --- /dev/null +++ b/DuneEss/src/test/java/com/example/duneess/DunemarkDenominationsTest.java @@ -0,0 +1,12 @@ +package com.example.duneess; +import com.example.dunegui.DunemarkItems; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +class DunemarkDenominationsTest { + @Test void walletArtSelectsOnlySupportedDenominationsWithoutRoundingUp(){ + assertEquals(1,DunemarkItems.denomination(0)); assertEquals(1,DunemarkItems.denomination(4.99)); + assertEquals(5,DunemarkItems.denomination(5)); assertEquals(5,DunemarkItems.denomination(99.99)); + assertEquals(100,DunemarkItems.denomination(100));assertEquals(1000,DunemarkItems.denomination(4999.99)); + assertEquals(5000,DunemarkItems.denomination(5000)); + } +} diff --git a/DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java b/DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java index 7bdde66b..399f87e2 100644 --- a/DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java +++ b/DuneEss/src/test/java/com/example/duneess/ExchangeStoreTest.java @@ -98,4 +98,28 @@ class ExchangeStoreTest { assertThrows(IllegalArgumentException.class,()->listing(0,"1")); assertThrows(IllegalArgumentException.class,()->listing(65,"1")); } + @Test void committedSaleRecordsBuyerItemAndExactPaymentButFailuresDoNot() throws Exception { + long id=listing(2,"12.50");store.buy(buyer,"BuyerName",id); + try(Connection c=DriverManager.getConnection(url);Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT * FROM dune_exchange_sales")) { + assertTrue(r.next());assertEquals(seller,r.getObject("seller",UUID.class)); + assertEquals(buyer,r.getObject("buyer",UUID.class));assertEquals("BuyerName",r.getString("buyer_name")); + assertEquals(1,r.getInt("quantity"));assertEquals(new BigDecimal("12.50"),r.getBigDecimal("total_price"));assertFalse(r.next()); + } + assertThrows(IllegalArgumentException.class,()->store.buy(seller,id));store.cancel(seller,id); + try(Connection c=DriverManager.getConnection(url);Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT COUNT(*) FROM dune_exchange_sales")) { + assertTrue(r.next());assertEquals(1,r.getInt(1)); + } + } + @Test void externallyOwnedTransactionRollsBackStockWalletsAndHistoryTogether() throws Exception { + long id=listing(1,"25"); + try(Connection c=DriverManager.getConnection(url)) { + c.setAutoCommit(false);ExchangeStore.bound(c).buy(buyer,"Buyer",id); + assertFalse(c.isClosed());c.rollback(); + } + assertEquals(1,store.find(id).quantity());assertEquals(new BigDecimal("100.00"),balance(buyer)); + assertEquals(new BigDecimal("0.00"),balance(seller)); + try(Connection c=DriverManager.getConnection(url);Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT COUNT(*) FROM dune_exchange_sales")) { + assertTrue(r.next());assertEquals(0,r.getInt(1)); + } + } } diff --git a/DuneEss/src/test/java/com/example/duneess/PlanetNamesTest.java b/DuneEss/src/test/java/com/example/duneess/PlanetNamesTest.java new file mode 100644 index 00000000..ae60b604 --- /dev/null +++ b/DuneEss/src/test/java/com/example/duneess/PlanetNamesTest.java @@ -0,0 +1,15 @@ +package com.example.duneess; +import com.example.dunegui.PlanetSigils; +import com.example.dunegui.PublicNames; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +class PlanetNamesTest { + @Test void newDisplayNamesRetainSavedIdentifiersAndFullCapitalization(){ + assertEquals("Arrakduin",PlanetSigils.label("arrakis"));assertEquals("Kaladam",PlanetSigils.label("caladan")); + assertEquals("Giedermark",PlanetSigils.label("giedi_prime"));assertEquals("Kaiterhof",PlanetSigils.label("kaitain")); + assertEquals("Sigmadraken IV",PlanetSigils.label("sigma_draconis_iv")); + assertEquals("arrakis_world_id",PublicNames.text("arrakis_world_id")); + assertEquals("/duneess travel arrakis",PublicNames.text("/duneess travel arrakis")); + assertEquals("Arrakduin and Kaladam",PublicNames.text("Serevan and Pelareth")); + } +} diff --git a/DuneLobby/README.md b/DuneLobby/README.md index bd146364..a6f04945 100644 --- a/DuneLobby/README.md +++ b/DuneLobby/README.md @@ -1,4 +1,4 @@ -# Spacing Guild lobby world +# Vaerkring lobby world A separate **Minecraft Java / Paper 1.21.4 / Java 21** End-dimension lobby. The rebuilt 1.1.0 world is already built and saved in [`../worlds/Dune-Guild-Lobby-1.1.0.zip`](../worlds/Dune-Guild-Lobby-1.1.0.zip); the deterministic builder and runtime companion are here. It does not replace a planet world. diff --git a/DuneLobby/previews/README.md b/DuneLobby/previews/README.md index f2ed4bcf..b31d870a 100644 --- a/DuneLobby/previews/README.md +++ b/DuneLobby/previews/README.md @@ -9,4 +9,4 @@ Final ImageGen prompt (reference image was the preceding five-room starport concept): -> Update this Minecraft Dune Spacing Guild lobby rendering with a SIXTH room, a shady SMUGGLER EXCHANGE. Preserve every existing room: central spawn with amber Guild Navigator tank, Dune II-inspired STARPORT / TELEPORT upper left with square landing and launch pads and block-built frigate, official EXCHANGE left, NEWS upper right, RULES right, purple End atmosphere and gold/blackstone architecture. Widen framing or pull back as needed to show all six distinct connected rooms clearly. Add the new smugglers' den as a substantial enclosed annex in the lower foreground below the official Exchange, attached via a narrow dim side corridor branching off the official Exchange. It must be visibly different: lower vaulted ceiling (removed for cutaway), dark worn stone, rusty copper pipes, patchwork brown cloth awnings/screens, stacked barrels and crates, low amber lanterns, discreet violet accents. TWO separate Minecraft villager seller NPCs behind separate screened market counters: WATER SELLER next to blue glass water vessels and a cauldron, SPICE SELLER beside orange spice samples and sacks represented by brown blocks and barrels. Small clear labels over counters 'WATER' and 'SPICE'. Shady illicit back-room atmosphere but navigable and readable. Clearly label the new annex 'SMUGGLER EXCHANGE' with matching clean external architectural callout. Keep five other callouts correctly pointing to their rooms. Floor of annex is fully supported and bounded, no unsafe holes; visible corridor connection. High-quality architectural Minecraft shader concept overview, block-built geometry and pixel textures, no photoreal smooth creatures. Retain wall artwork in framed maps. One wide coherent elevated isometric roofless cutaway, clean presentation, no HUD or watermark. +> Update this Minecraft Dune Vaerkring lobby rendering with a SIXTH room, a shady SMUGGLER EXCHANGE. Preserve every existing room: central spawn with amber Guild Navigator tank, Dune II-inspired STARPORT / TELEPORT upper left with square landing and launch pads and block-built frigate, official EXCHANGE left, NEWS upper right, RULES right, purple End atmosphere and gold/blackstone architecture. Widen framing or pull back as needed to show all six distinct connected rooms clearly. Add the new smugglers' den as a substantial enclosed annex in the lower foreground below the official Exchange, attached via a narrow dim side corridor branching off the official Exchange. It must be visibly different: lower vaulted ceiling (removed for cutaway), dark worn stone, rusty copper pipes, patchwork brown cloth awnings/screens, stacked barrels and crates, low amber lanterns, discreet violet accents. TWO separate Minecraft villager seller NPCs behind separate screened market counters: WATER SELLER next to blue glass water vessels and a cauldron, SPICE SELLER beside orange spice samples and sacks represented by brown blocks and barrels. Small clear labels over counters 'WATER' and 'SPICE'. Shady illicit back-room atmosphere but navigable and readable. Clearly label the new annex 'SMUGGLER EXCHANGE' with matching clean external architectural callout. Keep five other callouts correctly pointing to their rooms. Floor of annex is fully supported and bounded, no unsafe holes; visible corridor connection. High-quality architectural Minecraft shader concept overview, block-built geometry and pixel textures, no photoreal smooth creatures. Retain wall artwork in framed maps. One wide coherent elevated isometric roofless cutaway, clean presentation, no HUD or watermark. diff --git a/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java b/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java index 27fc6fac..ae7cf906 100644 --- a/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java +++ b/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java @@ -86,9 +86,9 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec private boolean inLobby(World world) { return lobby!=null && world.equals(lobby); } private void ensureNpcs() { for(int x=-8;x<=6;x++) for(int z=-6;z<=8;z++) lobby.getChunkAt(x,z).load(); - npc("liaison","Guild Navigator Liaison",13,87,-11,Villager.Profession.CLERIC); - npc("exchange","CHOAM Exchange Broker",-82,81,23,Villager.Profession.LIBRARIAN); - npc("water","Discreet Water Seller",-78,81,110,Villager.Profession.FISHERMAN); + npc("liaison","Vaerkring Routekeeper Liaison",13,87,-11,Villager.Profession.CLERIC); + npc("exchange","Koopkring Exchange Broker",-82,81,23,Villager.Profession.LIBRARIAN); + npc("water","Discreet Welvaarder",-78,81,110,Villager.Profession.FISHERMAN); npc("spice","Discreet Spice Seller",-54,81,110,Villager.Profession.LEATHERWORKER); } private void npc(String role,String name,int x,int y,int z,Villager.Profession profession) { @@ -180,7 +180,7 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec if(role==null) return; e.setCancelled(true); if(e.getHand()!=EquipmentSlot.HAND) return; switch(role) { case "liaison" -> { if(Bukkit.getPluginCommand("duneess")!=null) e.getPlayer().performCommand("duneess travel"); else departure(e.getPlayer(),"arrakis"); } - case "exchange" -> { if(Bukkit.getPluginCommand("dune")!=null) e.getPlayer().performCommand("dune exchange"); else e.getPlayer().sendMessage(ChatColor.GOLD+"CHOAM market integration requires DuneCore on this backend."); } + case "exchange" -> { if(Bukkit.getPluginCommand("dune")!=null) e.getPlayer().performCommand("dune exchange"); else e.getPlayer().sendMessage(ChatColor.GOLD+"Koopkring market integration requires DuneCore on this backend."); } case "water","spice" -> trade(e.getPlayer(),role); } } @@ -193,7 +193,7 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec result.setItemMeta(meta); int price=Math.max(1,Math.min(64,getConfig().getInt(water?"water-price-emeralds":"spice-price-emeralds",water?4:8))); MerchantRecipe recipe=new MerchantRecipe(result,0,999,false,0,0f); recipe.addIngredient(new ItemStack(Material.EMERALD,price)); - Merchant merchant=Bukkit.createMerchant(water?"Discreet Water Seller":"Discreet Spice Seller"); merchant.setRecipes(List.of(recipe)); player.openMerchant(merchant,true); + Merchant merchant=Bukkit.createMerchant(water?"Discreet Welvaarder":"Discreet Spice Seller"); merchant.setRecipes(List.of(recipe)); player.openMerchant(merchant,true); } @EventHandler public void interact(PlayerInteractEvent e) { if(!inLobby(e.getPlayer().getWorld()) || e.getClickedBlock()==null || e.getAction()!=Action.RIGHT_CLICK_BLOCK) return; diff --git a/DuneLobby/src/main/java/com/example/dunelobby/LobbyBuilder.java b/DuneLobby/src/main/java/com/example/dunelobby/LobbyBuilder.java index f4bcf50d..f3bb2670 100644 --- a/DuneLobby/src/main/java/com/example/dunelobby/LobbyBuilder.java +++ b/DuneLobby/src/main/java/com/example/dunelobby/LobbyBuilder.java @@ -181,7 +181,7 @@ final class LobbyBuilder { for(int y=99;y<=111;y+=2) for(int s:new int[]{-1,1}) box(s<0?-4:2,y,-18,s<0?-2:4,y,-17,Material.SANDSTONE); for(int x:new int[]{-14,14}) for(int z=-25;z<=-11;z+=5) lamp(x,87,z,false); box(11,87,-12,15,88,-12,Material.WAXED_CUT_COPPER); - sign(13,88,-11,BlockFace.SOUTH,"SPACING GUILD","NAVIGATOR","Right-click liaison","for planet travel"); + sign(13,88,-11,BlockFace.SOUTH,"VAERKRING","NAVIGATOR","Right-click liaison","for planet travel"); for(int x=-18;x<=18;x++) for(int z=-5;z<=23;z++) { double r=Math.hypot(x,z-10); if((r>=11.5 && r<=12.5)||(r>=4.5&&r<=5.5)) block(x,80,z,Material.GOLD_BLOCK); @@ -276,7 +276,7 @@ final class LobbyBuilder { box(x-5,81,25,x-5,86,25,Material.DARK_OAK_LOG); box(x+5,81,25,x+5,86,25,Material.DARK_OAK_LOG); box(x-5,87,24,x+5,87,26,Material.BLACK_WOOL); block(x,83,25,Material.LANTERN); - sign(x,82,27,BlockFace.SOUTH,"CHOAM EXCHANGE","Official market","Right-click broker","to open exchange"); + sign(x,82,27,BlockFace.SOUTH,"Koopkring EXCHANGE","Official market","Right-click broker","to open exchange"); } for(int x=-84;x<=-48;x+=6) { box(x,81,54,x+2,82,56,Material.BARREL); block(x+1,83,55,Material.LANTERN); } box(-76,81,40,-70,81,44,Material.DARK_OAK_PLANKS); @@ -342,7 +342,7 @@ final class LobbyBuilder { for(int y:new int[]{83,86,89}) box(x-5,y,21,x+5,y,22,Material.WAXED_CUT_COPPER); for(int i=0;i<5;i++) displayItem(x-4+i*2,84,23,new Material[]{Material.DIAMOND,Material.GOLD_INGOT,Material.ORANGE_DYE,Material.POTION,Material.EMERALD}[i]); for(int dx:new int[]{-3,3}) { block(x+dx,83,26,Material.BREWING_STAND); block(x+dx,87,26,Material.LANTERN); } - title(x+.5,89,26.5,x==-66?"CHOAM":x==-82?"TRADE":"CONTRACTS"); + title(x+.5,89,26.5,x==-66?"Koopkring":x==-82?"TRADE":"CONTRACTS"); } for(int x:new int[]{-85,-47}) for(int z=34;z<=46;z+=4) { box(x-1,81,z-1,x+1,82,z+1,Material.DARK_OAK_PLANKS); diff --git a/DuneLobby/src/main/resources/config.yml b/DuneLobby/src/main/resources/config.yml index 4e7fcbdb..5389c1eb 100644 --- a/DuneLobby/src/main/resources/config.yml +++ b/DuneLobby/src/main/resources/config.yml @@ -19,7 +19,7 @@ rules: - Follow the server's faction and trading rules. - Ask staff before building outside authorised areas. news: - - Welcome to the Spacing Guild. + - Welcome to the Vaerkring. - Five planetary departures are available in the starport. - Official trade is in the Exchange. Discreet trade is down the side passage. - These are lobby notices; configure live news separately. diff --git a/DuneLobby/src/main/resources/plugin.yml b/DuneLobby/src/main/resources/plugin.yml index af8be68e..7b81eb1b 100644 --- a/DuneLobby/src/main/resources/plugin.yml +++ b/DuneLobby/src/main/resources/plugin.yml @@ -6,7 +6,7 @@ load: POSTWORLD softdepend: [floodgate, ViaVersion, ImageFrame, DuneEss, DuneCore] commands: lobby: - description: Return to the Spacing Guild lobby + description: Return to the Vaerkring lobby permission: dunelobby.visit dunelobby: description: Guild lobby administration diff --git a/DuneLobby/tools/inspect_world.py b/DuneLobby/tools/inspect_world.py index 9f269ac8..6d1321db 100644 --- a/DuneLobby/tools/inspect_world.py +++ b/DuneLobby/tools/inspect_world.py @@ -86,7 +86,7 @@ def render(data, output): scale, x0, z0, margin, top = 6, -122, -96, 38, 125 image = Image.new('RGB', (1380, 1515), '#100f1c') draw = ImageDraw.Draw(image) - draw.text((38, 24), 'SPACING GUILD | SAVED WORLD PLAN', fill='#e5bd72', font=font(36)) + draw.text((38, 24), 'VAERKRING | SAVED WORLD PLAN', fill='#e5bd72', font=font(36)) draw.text((40, 77), 'Actual Minecraft blocks at floor level; roofs removed for this plan. North is up.', fill='#b3adc2', font=font(19)) for z in range(-96, 129): for x in range(-122, 94): diff --git a/DuneLobby/tools/prepare_boards.py b/DuneLobby/tools/prepare_boards.py index 5fca958f..640162e6 100644 --- a/DuneLobby/tools/prepare_boards.py +++ b/DuneLobby/tools/prepare_boards.py @@ -27,7 +27,7 @@ if __name__ == '__main__': 'SOLARIS / SPICE / CONTRACTS', 'Speak to the Exchange Broker.', 'Planetary markets follow server rules.', 'Discreet supplies: follow the side passage.']) board('news.png', 'GUILD DISPATCH', 'NEWS & ARRIVALS', [ - 'Welcome aboard the Spacing Guild.', 'Five worlds. One starport.', + 'Welcome aboard the Vaerkring.', 'Five worlds. One starport.', 'Landing apron: arrivals. Launch pads: departures.', 'Read the lecterns for current notices.', 'Official exchange and discreet market are open.']) board('rules.png', 'GUILD CHARTER', 'SAFE PASSAGE FOR EVERY TRAVELLER', [ diff --git a/DuneNPC/src/main/java/com/example/dunenpc/DuneNPC.java b/DuneNPC/src/main/java/com/example/dunenpc/DuneNPC.java index 8ff6e924..47c9a20e 100644 --- a/DuneNPC/src/main/java/com/example/dunenpc/DuneNPC.java +++ b/DuneNPC/src/main/java/com/example/dunenpc/DuneNPC.java @@ -89,7 +89,7 @@ public final class DuneNPC extends JavaPlugin implements Listener, CommandExecut } private void spawnNavigator(Location location) { location.getWorld().spawn(location, Villager.class, villager -> { - villager.setCustomName(ChatColor.LIGHT_PURPLE + "Spacing Guild Navigator"); + villager.setCustomName(ChatColor.LIGHT_PURPLE + "Vaerkring Navigator"); villager.setCustomNameVisible(true); villager.setProfession(Villager.Profession.CLERIC); villager.setAI(false); villager.setInvulnerable(true); villager.setSilent(true); villager.setPersistent(true); villager.getPersistentDataContainer().set(guildKey, PersistentDataType.BYTE, (byte) 1); @@ -106,7 +106,7 @@ public final class DuneNPC extends JavaPlugin implements Listener, CommandExecut if (args.length > 0 && args[0].equalsIgnoreCase("smuggle")) { smugglers.command(player, args); return true; } if (args.length > 0 && args[0].equalsIgnoreCase("guildnpc")) { if (!player.hasPermission("dune.admin")) { player.sendMessage("Admin only."); return true; } - spawnNavigator(player.getLocation()); player.sendMessage("Guild Navigator placed."); return true; + spawnNavigator(player.getLocation()); player.sendMessage("Vaerkring Routekeeper placed."); return true; } if (!player.isOp()) { player.sendMessage(ChatColor.RED + "Operators only. Right-click an Arrakis Smuggler for missions."); return true; } if (args.length == 0 || args[0].equalsIgnoreCase("admin")) { openAdmin(player); return true; } @@ -126,14 +126,14 @@ public final class DuneNPC extends JavaPlugin implements Listener, CommandExecut for (WanderingTrader trader : world.getEntitiesByClass(WanderingTrader.class)) if (trader.getPersistentDataContainer().has(new NamespacedKey("dunecore", "smuggler"), PersistentDataType.BYTE)) traders++; } - player.sendMessage(ChatColor.GOLD + "DuneNPC: " + guild + " loaded Guild Navigators, " + traders + " loaded smugglers, " + smugglers.activeCount() + " open contracts."); + player.sendMessage(ChatColor.GOLD + "DuneNPC: " + guild + " loaded Vaerkring Routekeepers, " + traders + " loaded smugglers, " + smugglers.activeCount() + " open contracts."); } void openAdmin(Player player) { if (!player.isOp()) { player.sendMessage(ChatColor.RED + "Operators only."); return; } Menu menu = new Menu(); menu.inventory = Bukkit.createInventory(menu, 27, ChatColor.GOLD + "DuneNPC | NPC Administration"); for (int slot = 0; slot < 27; slot++) menu.inventory.setItem(slot, icon(Material.BLACK_STAINED_GLASS_PANE, " ")); - menu.inventory.setItem(10, icon(Material.VILLAGER_SPAWN_EGG, "Place Guild Navigator", "Spawn at your position; opens Guild travel.")); + menu.inventory.setItem(10, icon(Material.VILLAGER_SPAWN_EGG, "Place Vaerkring Routekeeper", "Spawn at your position; opens Vaerkring travel.")); menu.inventory.setItem(12, icon(Material.WANDERING_TRADER_SPAWN_EGG, "Place Arrakis Smuggler", "Spawn at your position on Arrakis.")); menu.inventory.setItem(14, icon(Material.WRITABLE_BOOK, "NPC and Mission Status", "Show loaded NPC counts and active contracts.")); menu.inventory.setItem(16, icon(Material.CLOCK, "Quest Camp Guide", "Green: free to roam. Purple: active mission.", "Active contacts are stationary and lit.", "Missions expire after 30 real minutes.")); diff --git a/DuneRealms-minecraft-only/ARRAKIS_WATER.md b/DuneRealms-minecraft-only/ARRAKIS_WATER.md index 077ca2c9..3994f24f 100644 --- a/DuneRealms-minecraft-only/ARRAKIS_WATER.md +++ b/DuneRealms-minecraft-only/ARRAKIS_WATER.md @@ -2,11 +2,11 @@ New Arrakis chunks generate underground cave **sietches** at roughly 2,000-block spacing. Each has connected chambers for sleeping and cooking, a concealed surface entry, a descending waterfall, and a bottom water reservoir. A chest opens a personal cache for each player with at least 250 tagged spice, enchanted gold armor, planks, and bread. Existing chunks will not be retroactively populated. See `plugins/DuneTerrain/config.yml` (`sietches.spacing`) to change the interval. -- `/dune water guild` - become an official Spacing Guild water seller. +- `/dune water guild` - become an official Vaerkring Welvaarder. - `/dune water smuggler` - become a smuggler. - `/dune water status` - show career and rates. - `/dune water sell` - sell tagged Arrakis water buckets at half the configured spice unit price. Smugglers receive 45% more gross pay, but have a configurable 30% chance of angering locals and spawning hostile Husks if on Arrakis. -- All water sales contribute the same 1.21% Spacing Trust levy as spice sales. +- All water sales contribute the same 1.21% Vaerkring Trust levy as spice sales. - On Arrakis, water flow is canceled, bucket placement is blocked, and ice/cauldron water formation is limited. Collected water is tagged and source blocks are consumed. ## Limitations / unfinished diff --git a/DuneRealms-minecraft-only/MINECRAFT_ONLY_SCOPE.md b/DuneRealms-minecraft-only/MINECRAFT_ONLY_SCOPE.md index 13f91acb..633ec3d1 100644 --- a/DuneRealms-minecraft-only/MINECRAFT_ONLY_SCOPE.md +++ b/DuneRealms-minecraft-only/MINECRAFT_ONLY_SCOPE.md @@ -3,6 +3,6 @@ This edition deliberately excludes fictional vehicle items, custom consumables, Retained actual Minecraft materials with plugin metadata: dyed leather faction stillsuits, merged Elytra, netherite shovel (Efficiency V, Unbreaking III) for spice harvesting, orange dye for spice, nether star for the Dune Navigator menu, ender pearls used as travel GUI buttons, water buckets, and ordinary vanilla materials used by the existing gameplay. -The game does not include ornithopters, sandcrawlers, sand bikes, faction banners, shield cores, spice analyzers, water vials, fictional consumables, or fictional decoration blocks. The Spacing Guild remains a travel service, not a vehicle item. +The game does not include ornithopters, sandcrawlers, sand bikes, faction banners, shield cores, spice analyzers, water vials, fictional consumables, or fictional decoration blocks. The Vaerkring remains a travel service, not a vehicle item. Important: source is uncompiled and untested; earlier multiplayer race conditions and other prototype limitations remain. diff --git a/DuneRealms-minecraft-only/NETWORK_SETUP.md b/DuneRealms-minecraft-only/NETWORK_SETUP.md index 9320037c..78cbeda3 100644 --- a/DuneRealms-minecraft-only/NETWORK_SETUP.md +++ b/DuneRealms-minecraft-only/NETWORK_SETUP.md @@ -27,7 +27,7 @@ bungee-plugin-message-channel = true Enable Velocity modern forwarding and configure each Paper backend for Velocity forwarding with the same forwarding secret. Block direct external access to backend ports. Players should connect only through the proxy. Check Velocity's current documentation for the exact forwarding options on your versions. -The Spacing Guild navigator is placed by DuneTerrain; DuneCore handles its click and opens the Guild menu. The menu uses the `BungeeCord` `Connect` plugin message to ask Velocity to switch servers. This is an asynchronous request **without delivery acknowledgment**. DuneCore deducts travel fare when requesting a transfer, even if the destination is offline. +The Vaerkring navigator is placed by DuneTerrain; DuneCore handles its click and opens the Guild menu. The menu uses the `BungeeCord` `Connect` plugin message to ask Velocity to switch servers. This is an asynchronous request **without delivery acknowledgment**. DuneCore deducts travel fare when requesting a transfer, even if the destination is offline. **Critical limitation — not production ready:** `players.yml`, hourly jobs, exchange listings, balances, and inventory are currently local to each backend. They do **not** synchronize across servers. A production network needs a shared authoritative database (e.g., MariaDB/PostgreSQL), transactional fare charges and payouts, cross-server inventory/player-data synchronization, and a proxy-side first-join/homeworld router. Without these, Solaris and contracts will differ between planets, and faction homeworld routing is not reliable. Do not deploy with a live economy until shared state and transfer confirmation are implemented. diff --git a/DuneRealms-minecraft-only/POLITICS_SETUP.md b/DuneRealms-minecraft-only/POLITICS_SETUP.md index d7671066..593cb91a 100644 --- a/DuneRealms-minecraft-only/POLITICS_SETUP.md +++ b/DuneRealms-minecraft-only/POLITICS_SETUP.md @@ -1,8 +1,8 @@ -# Spacing Trust and Politics (prototype) +# Vaerkring Trust and Politics (prototype) This release adds actual Paper plugin code (`Politics.java`) and `/dune politics` commands. -- Spice sales contribute 1.21% of gross Solaris earnings to the Spacing Trust (rounded up). +- Spice sales contribute 1.21% of gross Solaris earnings to the Vaerkring Trust (rounded up). - `/dune politics deposit ` deposits extra Solaris. - `/dune politics status` shows treasury, current election winners and invasion. - `/dune politics vote ` elects a faction leader, one vote per voter per UTC-based 7-day epoch window. diff --git a/DuneRealms-minecraft-only/README.md b/DuneRealms-minecraft-only/README.md index 204e73ab..0c230052 100644 --- a/DuneRealms-minecraft-only/README.md +++ b/DuneRealms-minecraft-only/README.md @@ -16,7 +16,7 @@ Admins with `dune.admin` can force teleport to Arrakis or generated landmarks wi ## Sandworms (Shai-Hulud) -Visible oversized Sniffers with invisible Husk controllers supplying native zombie AI spawn on sandy surfaces near players **only on Arrakis**, at most once per hour serverwide by default. The successful spawn time is saved in the plugin config, so a restart does not reset the cooldown. They have 500 health, 8 melee damage, a controller movement attribute of 0.33, and visible scale 3.5, and play a Warden roar when emerging. Settings are under `sandworms` in `config.yml`. Admins can use `/dune summon sandworm [x y z]` to summon one explicitly. Arrakis sightings include coordinates and a fifteen-minute warning before the Spacing Guild informs the network. See [Session 2](../SESSION-2.md) for timer persistence, proxy delivery, and plateau settings. +Visible oversized Sniffers with invisible Husk controllers supplying native zombie AI spawn on sandy surfaces near players **only on Arrakis**, at most once per hour serverwide by default. The successful spawn time is saved in the plugin config, so a restart does not reset the cooldown. They have 500 health, 8 melee damage, a controller movement attribute of 0.33, and visible scale 3.5, and play a Warden roar when emerging. Settings are under `sandworms` in `config.yml`. Admins can use `/dune summon sandworm [x y z]` to summon one explicitly. Arrakis sightings include coordinates and a fifteen-minute warning before the Vaerkring informs the network. See [Session 2](../SESSION-2.md) for timer persistence, proxy delivery, and plateau settings. ## Spice contracts and sandworm blooms - On Arrakis, defeating a sandworm generates a broad patch of suspicious-sand spice deposits with a target base harvest value of 100,000 Solaris (actual value depends on available sandy terrain and faction bonuses). @@ -55,7 +55,7 @@ The chest menus use configurable stained glass panes as the backdrop, based on t `/dune kit` now grants four leather armor pieces dyed to match the player's faction GUI background: Harkonnen red, Ordos/Fremen green, Atreides blue, Corrino purple. The items keep their `stillsuit` persistent-data identifier, so full-set spice harvesting continues to work. Existing already-issued armor is not recolored automatically; use `/dune kit` to obtain a newly dyed set. ## Expanded faction palette -Fremen now have orange armor and orange glass; Ordos is a distinct green faction with green armor and green glass. Harkonnen remains red, Atreides blue, Corrino purple. Spacing Guild is reserved as a black visual/armor color (`spacing_guild`) but is not a selectable player faction, so no Guild armor is issued through `/dune kit` yet. Ordos currently shares Arrakis as a starting planet. Color values are hardcoded for dyed armor; GUI glass materials are configured in `gui.yml`. +Fremen now have orange armor and orange glass; Ordos is a distinct green faction with green armor and green glass. Harkonnen remains red, Atreides blue, Corrino purple. Vaerkring is reserved as a black visual/armor color (`spacing_guild`) but is not a selectable player faction, so no Guild armor is issued through `/dune kit` yet. Ordos currently shares Arrakis as a starting planet. Color values are hardcoded for dyed armor; GUI glass materials are configured in `gui.yml`. ## Netherite-strength armor and winged stillsuit Each stillsuit armor piece has the same armor points (3/8/6/3), armor toughness (+3 per piece), and knockback resistance (+0.1 per piece) as vanilla netherite armor. Leather stillsuit pieces retain their faction dyes; vanilla leather durability is unchanged. @@ -77,9 +77,9 @@ Each newly issued leather stillsuit piece receives a distinctive vanilla smithin | Atreides | Blue | Coast | Copper / orange | | Corrino | Purple | Spire | Gold / yellow | | Fremen | Orange | Dune | Lapis / blue | -| Spacing Guild (reserved) | Black | Eye | Quartz / white | +| Vaerkring (reserved) | Black | Eye | Quartz / white | -Ordos starts and respawns on its own generated planet `sigma_draconis_iv` (Sigma Draconis IV). Its dark, snowy terrain profile is configured by DuneTerrain. The Spacing Guild remains a non-playable faction and does not receive its own kit through normal gameplay. Existing armor is not automatically upgraded; issue a fresh kit. +Ordos starts and respawns on its own generated planet `sigma_draconis_iv` (Sigma Draconis IV). Its dark, snowy terrain profile is configured by DuneTerrain. The Vaerkring remains a non-playable faction and does not receive its own kit through normal gameplay. Existing armor is not automatically upgraded; issue a fresh kit. Wearing a complete Ordos stillsuit and using an ender pearl activates Shadow Step: the player and armor are invisible for five seconds. The armor is returned after the effect, on logout, or when the plugin shuts down. The Ordos kit also includes a reusable Implosion Charge: its Wind Charge projectile primes TNT immediately on impact and replaces the charge in your inventory after launch. diff --git a/DuneRealms-minecraft-only/SHARED_DATABASE_SETUP.md b/DuneRealms-minecraft-only/SHARED_DATABASE_SETUP.md index 4213e5a3..8e1dab07 100644 --- a/DuneRealms-minecraft-only/SHARED_DATABASE_SETUP.md +++ b/DuneRealms-minecraft-only/SHARED_DATABASE_SETUP.md @@ -1,16 +1,9 @@ -# Shared PostgreSQL network prototype +# Shared PostgreSQL network -Set `database.enabled: true` and identical JDBC settings on every Paper backend. Create a PostgreSQL database and user with schema privileges. The plugin creates `dune_players`, `dune_politics`, and `dune_bounties`. +Current setup, migration, capacity and recovery instructions are maintained in [network/database/README.md](../network/database/README.md). -`SharedDatabase` stores faction, Solaris and serialized full player inventory (including armor/offhand) across planetary servers. `Politics` loads and writes the common political YAML state. Bounties are issued on smuggler water COLLECTION, not sale, on any planet; online players in that planet receive the alert. Player kills claim the bounty once through an atomic SQL UPDATE. +DuneCore 1.0.12 shares planetary inventories (armor/offhand included), faction and XP. Lobby inventory stays separate; ender chests remain local and are never synchronized or exposed in account snapshots. The same PostgreSQL database serves the existing DuneEss wallets and exchange. Direct session locks prevent concurrent backend ownership, durable unclean-session markers require explicit recovery, and exchange operations commit their inventory checkpoint together with wallets, listings and sales history. -**CRITICAL LIMITATIONS / NOT PRODUCTION READY** -- The politics YAML snapshot is NOT transactionally locked. Simultaneous votes/invasions from different servers can overwrite each other. Replace with normalized SQL tables and atomic transactions before public deployment. -- Player inventories are saved on quit and on `savePlayers()`. Concurrent sessions or a crashed backend can cause duplication or stale state. Implement proxy transfer handshakes, single-session leases, and atomic write/version checks. -- Database operations are synchronous on the Paper main thread. Move to async workers with safe main-thread inventory application. -- Smuggler career remains local-memory only; it must be persisted to shared storage. -- A water bucket on non-Arrakis worlds does not automatically become a tagged Arrakis water bucket and cannot be sold through the existing water seller mechanic. -- Bounty reward is based on ONE water bucket's smuggler gross proceeds, not total inventory; adjust for bulk smuggling contracts. -- Local NPC retaliation is immediate on collection; spawned Husks may be affected by local biome/daylight rules. -- The existing lobby routing and travel refund limitations remain. -- This source was not compiled or tested. Test against Paper 1.21.4 and PostgreSQL before deployment. +The new inventory/exchange changes have automated validation. Live PostgreSQL, Paper, Velocity, Geyser and ViaVersion staging validation remains necessary. SQL still runs synchronously. Existing political YAML snapshots, smuggler persistence and travel/bounty limitations are outside this change; this does not claim completion of those systems. + +Known pre-existing limits: political YAML writes can race; smuggler career persistence, cross-world water tagging, bulk bounty calculation and travel/refund behavior need separate review. SQL is synchronous on the game thread. Run real PostgreSQL and multi-backend client acceptance before enabling shared inventory in production. diff --git a/DuneRealms-minecraft-only/build.gradle.kts b/DuneRealms-minecraft-only/build.gradle.kts index aeb54918..b0adde6f 100644 --- a/DuneRealms-minecraft-only/build.gradle.kts +++ b/DuneRealms-minecraft-only/build.gradle.kts @@ -1,6 +1,6 @@ plugins { java } group = "com.example" -version = "1.0.11" +version = "1.0.12" repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/"); maven("https://jitpack.io") } dependencies { compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT") diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/AdminGui.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/AdminGui.java index 848f42d2..382b997c 100644 --- a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/AdminGui.java +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/AdminGui.java @@ -64,7 +64,7 @@ final class AdminGui implements Listener { holder.inventory = Bukkit.createInventory(holder, 36, ChatColor.GOLD + "Dune | Imperial Administration"); for (int slot = 0; slot < 36; slot++) holder.inventory.setItem(slot, icon(Material.BLACK_STAINED_GLASS_PANE, " ")); holder.inventory.setItem(10, icon(Material.SNIFFER_SPAWN_EGG, "Summon Shai-Hulud", "Spawn a sandworm at your position on Arrakis.")); - holder.inventory.setItem(12, icon(Material.VILLAGER_SPAWN_EGG, "Place Guild Navigator", "Spawn a Guild NPC at your position.")); + holder.inventory.setItem(12, icon(Material.VILLAGER_SPAWN_EGG, "Place Vaerkring Routekeeper", "Spawn a Guild NPC at your position.")); holder.inventory.setItem(14, icon(Material.ORANGE_DYE, "Give Test Spice", "Receive one tagged spice item.")); holder.inventory.setItem(16, icon(Material.COMPARATOR, "Reload Menus", "Reload gui.yml from disk.")); holder.inventory.setItem(20, icon(Material.NETHERITE_CHESTPLATE, "Receive Faction Kit", "Receive your selected faction's kit.")); diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ArrakisAnnouncements.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ArrakisAnnouncements.java index 2b1f1e3e..521b1f54 100644 --- a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ArrakisAnnouncements.java +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ArrakisAnnouncements.java @@ -29,11 +29,11 @@ final class ArrakisAnnouncements { String coordinates = "Arrakis [X " + location.getBlockX() + ", Y " + location.getBlockY() + ", Z " + location.getBlockZ() + "]"; String sighting = kind.equals("sandworm") ? "Shai-Hulud stirs beneath the sands at " : "The desert reveals a melange spice bloom at "; String message = sighting + coordinates + "."; - state.set(key + ".message", ChatColor.GOLD + "[Spacing Guild] Our Navigators have detected: " + message + " The Guild now informs all worlds. The spice must flow!"); + state.set(key + ".message", ChatColor.GOLD + "[Vaerkring] Our Navigators have detected: " + message + " The Guild now informs all worlds. The spice must flow!"); state.set(key + ".due", System.currentTimeMillis() + 15L * 60L * 1000L); pending.add(key); save(); - Bukkit.broadcastMessage(ChatColor.GOLD + "[Arrakis] " + message + " You have 15 minutes before the Spacing Guild notices and informs all other servers."); + Bukkit.broadcastMessage(ChatColor.GOLD + "[Arrakis] " + message + " You have 15 minutes before the Vaerkring notices and informs all other servers."); } private void deliver() { diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java index 754c6054..c6ae13de 100644 --- a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ConfigurableGui.java @@ -35,23 +35,25 @@ final class ConfigurableGui { void reload() { config=YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(),"gui.yml")); } private String color(String input) { return ChatColor.translateAlternateColorCodes('&',input); } private String replace(String text, Player p) { - return color(text.replace("%player%",p.getName()) + return color(com.example.dunegui.PublicNames.text(text.replace("Solaris","Dunemarks").replace("%player%",p.getName()) .replace("%balance%",String.valueOf((int)economy.getBalance(p))) .replace("%travel_cost%",String.valueOf(plugin.travelPrice())) - .replace("%active_job%",serverJobs.activeDescription(p))); + .replace("%active_job%",serverJobs.activeDescription(p)))); } private ItemStack item(Player p, String icon, String title, List lore) { + if(icon.equalsIgnoreCase("DUNEMARK")) return com.example.dunegui.DunemarkItems.icon(com.example.dunegui.DunemarkItems.denomination(economy.getBalance(p)),replace(title,p),lore.stream().map(line->replace(line,p)).toList()); Material material=Material.matchMaterial(icon.toUpperCase(Locale.ROOT)); if(material==null || !material.isItem()) material=Material.PAPER; ItemStack stack=new ItemStack(material); ItemMeta meta=stack.getItemMeta(); - meta.setDisplayName(replace(title,p)); + meta.setDisplayName(com.example.dunegui.PublicNames.text(replace(title,p))); meta.setLore(lore.stream().map(line->replace(line,p)).toList()); stack.setItemMeta(meta); return stack; } void open(Player p,String page) { + if(page.equals("appointments")){openAppointments(p);return;} ConfigurationSection section=config.getConfigurationSection("menus."+page); - if(section==null) { p.sendMessage(ChatColor.RED+"Unknown GUI page: "+page); return; } + if(section==null) { p.sendMessage(com.example.dunegui.PublicNames.text(ChatColor.RED+"Unknown GUI page: "+page)); return; } int size=section.getInt("size",54); if(size<9 || size>54 || size%9!=0) { plugin.getLogger().warning("Invalid GUI size for "+page); return; } String title=replace(section.getString("title","Dune | "+page),p); @@ -70,7 +72,10 @@ final class ConfigurableGui { String path=id+"."; int slot=items.getInt(path+"slot",-1); if(slot<0 || slot>=size) continue; - inv.setItem(slot,item(p,items.getString(path+"icon","PAPER"),items.getString(path+"name",id),items.getStringList(path+"lore"))); + String icon=items.getString(path+"icon","PAPER"); + // Recognise the existing wallet entry without replacing the operator's gui.yml. + if(id.equals("wallet")&&icon.equalsIgnoreCase("GOLD_INGOT"))icon="DUNEMARK"; + inv.setItem(slot,item(p,icon,items.getString(path+"name",id),items.getStringList(path+"lore"))); slots.put(slot,items.getString(path+"action","none")); } ConfigurationSection dynamic=section.getConfigurationSection("dynamic"); @@ -86,7 +91,8 @@ final class ConfigurableGui { if(slot<0 || slot>=size || slots.containsKey(slot)) continue; String id=ids.get(i); String label=type.equals("server_jobs")?serverJobs.describe(id):id; - String name=dynamic.getString("name","&e%id%").replace("%id%",id); + String displayId=type.equals("planets")?com.example.dunegui.PlanetSigils.label(id):publicFaction(id); + String name=dynamic.getString("name","&e%id%").replace("%id%",displayId); List lore=dynamic.getStringList("lore").stream().map(line->line.replace("%description%",label).replace("%id%",id)).toList(); String icon=dynamic.getString("icon","PAPER"); if(type.equals("factions")) { @@ -94,21 +100,25 @@ final class ConfigurableGui { icon=config.getString("backgrounds."+key,icon); } - inv.setItem(slot,item(p,icon,name,lore)); + ItemStack displayed=item(p,icon,name,lore); + if(type.equals("planets"))com.example.dunegui.PlanetSigils.apply(displayed,id); + inv.setItem(slot,displayed); slots.put(slot,dynamic.getString("action","none").replace("%id%",id).replace("%index%",String.valueOf(i))); } } + if(page.equals("main")&&size>=54&&!slots.containsKey(46)){ + inv.setItem(46,officeItem("crown","Landsraad appointments",List.of("Emperor-granted spice and water offices","View current appointments"))); + slots.put(46,"open:appointments"); + } opened.put(p.getUniqueId(),page); actions.put(p.getUniqueId(),slots); - Map nativeActions=new HashMap<>(); - slots.forEach((slot,action)->nativeActions.put(slot,()->execute(p,action))); - com.example.dunegui.NativeMenus.inventory(plugin,p,title,inv,nativeActions); + Map nativeActions=new HashMap<>(); slots.forEach((slot,action)->nativeActions.put(slot,()->execute(p,action))); com.example.dunegui.NativeMenus.inventory(plugin,p,title,inv,nativeActions); } void click(InventoryClickEvent e) { if(!(e.getWhoClicked() instanceof Player p)) return; String page=opened.get(p.getUniqueId()); if(page==null) return; - String title=config.getString("menus."+page+".title","Dune | "+page); + String title=page.equals("appointments")?"&6Landsraad appointments":config.getString("menus."+page+".title","Dune | "+page); if(!e.getView().getTitle().equals(replace(title,p))) return; e.setCancelled(true); if(e.getClickedInventory()!=e.getView().getTopInventory()) return; @@ -117,11 +127,23 @@ final class ConfigurableGui { // Defer inventory changes until after InventoryClickEvent. Bukkit.getScheduler().runTask(plugin,()-> execute(p,action)); } + private String publicFaction(String id){return switch(id.toLowerCase(Locale.ROOT)){case "atreides"->"House Aerdrecht";case "harkonnen"->"House Harkveen";case "corrino"->"House Korenholt";case "ordos"->"House Oordwijk";case "fremen"->"Vrijduin";case "spacing_guild","guild"->"Vaerkring";default->id;};} + private ItemStack officeItem(String model,String name,List lore){ItemStack item=new ItemStack(Material.PAPER);ItemMeta meta=item.getItemMeta();meta.setDisplayName(com.example.dunegui.PublicNames.text(ChatColor.GOLD+name));meta.setLore(lore.stream().map(line->ChatColor.GRAY+line).toList());meta.setItemModel(new NamespacedKey("dunerealms","office_"+model));item.setItemMeta(meta);return item;} + private void openAppointments(Player player){ + Inventory inventory=Bukkit.createInventory(null,27,color("&6Landsraad appointments")); + Map offices=plugin.politics().websiteSnapshot(); + inventory.setItem(11,officeItem("spice","Specerhuis",List.of("Landsraad appointment · spice rights",officeHolder(offices,"spiceSteward","Not appointed")))); + inventory.setItem(15,officeItem("water","Welvaart House",List.of("Landsraad appointment · water rights",officeHolder(offices,"houseOfWater","Not appointed")))); + inventory.setItem(13,officeItem("crown","By appointment of the Emperor",List.of(officeHolder(offices,"emperor","Not elected"),"Appointments retain their existing election rules"))); + inventory.setItem(22,item(player,"ARROW","&eBack",List.of())); + opened.put(player.getUniqueId(),"appointments");actions.put(player.getUniqueId(),Map.of(22,"open:main"));com.example.dunegui.NativeMenus.inventory(plugin,player,color("&6Landsraad appointments"),inventory,Map.of(22,()->open(player,"main"))); + } + private String officeHolder(Map offices,String key,String empty){Object value=offices.get(key);return value==null?empty:com.example.dunegui.PublicNames.text(String.valueOf(value));} void drag(InventoryDragEvent e) { if(!(e.getWhoClicked() instanceof Player p)) return; String page=opened.get(p.getUniqueId()); if(page==null) return; - if(!e.getView().getTitle().equals(replace(config.getString("menus."+page+".title","Dune | "+page),p))) return; + if(!e.getView().getTitle().equals(replace(page.equals("appointments")?"&6Landsraad appointments":config.getString("menus."+page+".title","Dune | "+page),p))) return; if(e.getRawSlots().stream().anyMatch(slot->slot operation) throws Exception { + if (!sharesPlayerInventory()) throw new java.sql.SQLException("Shared planetary profiles are required to trade"); + restoreOrdosArmor(player.getUniqueId()); + sharedDatabase.transaction(player, selected, operation); + } + public Politics politics(){return politics;} public String factionOf(Player player){return selected.getOrDefault(player.getUniqueId(),"");} public void persistPlayers(){savePlayers();} @@ -116,8 +126,18 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu if (economyRegistration == null) { getLogger().severe("Install Vault and DuneEss before DuneCore."); getServer().getPluginManager().disablePlugin(this); return; } economy = economyRegistration.getProvider(); if(getConfig().getBoolean("database.enabled",false)) { + for (Player online : new ArrayList<>(Bukkit.getOnlinePlayers())) + online.kickPlayer("Network profiles are starting. Please reconnect."); try { sharedDatabase=new SharedDatabase(this); } - catch(Exception ex){getLogger().severe("Shared database required but unavailable: "+ex.getMessage());getServer().getPluginManager().disablePlugin(this);return;} + catch(Exception ex){getLogger().severe("Shared database required but unavailable: "+ex.getMessage());getServer().getPluginManager().registerEvents(new org.bukkit.event.Listener() { + @org.bukkit.event.EventHandler public void reject(org.bukkit.event.player.PlayerLoginEvent event) { + event.disallow(org.bukkit.event.player.PlayerLoginEvent.Result.KICK_OTHER, "Network database is unavailable."); + } + }, this); return;} + } + if (sharedDatabase != null) { + long interval = Math.max(10, getConfig().getLong("database.autosave-seconds", 60)) * 20L; + Bukkit.getScheduler().runTaskTimer(this, this::savePlayers, interval, interval); } politics = new Politics(this, selected, economy, sharedDatabase); discordWebFeed = new DiscordWebFeed(this); @@ -147,12 +167,24 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu @Override public void onDisable() { for (UUID playerId : new ArrayList<>(ordosCloakedArmor.keySet())) restoreOrdosArmor(playerId); - if(serverJobs!=null)serverJobs.save(); savePlayers(); + if(serverJobs!=null)serverJobs.save(); + if (sharedDatabase != null) { + for (Player p : Bukkit.getOnlinePlayers()) try { sharedDatabase.releasePlayer(p, selected); } + catch (Exception ex) { getLogger().severe("Shared shutdown save failed for " + p.getName() + ": " + ex.getMessage()); } + sharedDatabase.close(); + } else if (data != null && dataFile != null) savePlayers(); } private void savePlayers() { if (sharedDatabase != null) { - for (Player player : Bukkit.getOnlinePlayers()) try { sharedDatabase.savePlayer(player, selected); } - catch (Exception ex) { getLogger().severe("Shared save failed for " + player.getName() + ": " + ex.getMessage()); } + for (Player player : Bukkit.getOnlinePlayers()) try { + // Temporarily hidden Ordos equipment must be present in durable snapshots. + restoreOrdosArmor(player.getUniqueId()); + sharedDatabase.savePlayer(player, selected); + } + catch (Exception ex) { + getLogger().severe("Shared save failed for " + player.getName() + ": " + ex.getMessage()); + player.kickPlayer("Network storage is unavailable. Your profile requires recovery if saving fails."); + } return; } for (UUID id : selected.keySet()) data.set(id + ".faction", selected.getOrDefault(id, "")); @@ -318,7 +350,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu shovel.addUnsafeEnchantment(Enchantment.UNBREAKING,3); items.add(shovel); if (faction.equalsIgnoreCase("Ordos")) - items.add(custom(Material.WIND_CHARGE,"Ordos Implosion Charge","ordos_wind_charge")); + items.add(custom(Material.WIND_CHARGE,"Oordwijk Implosion Charge","ordos_wind_charge")); for (Material m : new Material[]{Material.LEATHER_HELMET, Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS}) { ItemStack armor = custom(m, "Stillsuit " + m.name().toLowerCase(Locale.ROOT), "stillsuit"); org.bukkit.inventory.meta.LeatherArmorMeta meta = (org.bukkit.inventory.meta.LeatherArmorMeta) armor.getItemMeta(); @@ -401,7 +433,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu Bukkit.getScheduler().runTaskLater(this,()->{ Player owner=Bukkit.getPlayer(playerId); if(owner==null)return; - Map leftovers=owner.getInventory().addItem(custom(Material.WIND_CHARGE,"Ordos Implosion Charge","ordos_wind_charge")); + Map leftovers=owner.getInventory().addItem(custom(Material.WIND_CHARGE,"Oordwijk Implosion Charge","ordos_wind_charge")); for(ItemStack leftover:leftovers.values())owner.getWorld().dropItemNaturally(owner.getLocation(),leftover); },1L); } @@ -508,7 +540,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu return true; } if (args.length > 0 && List.of("balance","sell","travel").contains(args[0].toLowerCase(Locale.ROOT))) { - sender.sendMessage(ChatColor.YELLOW + "Solaris, Guild travel, and admin teleports are now in DuneEss. Use /duneess help."); return true; + sender.sendMessage(ChatColor.YELLOW + "Solaris, Vaerkring travel, and admin teleports are now in DuneEss. Use /duneess help."); return true; } if (!(sender instanceof Player p)) { sender.sendMessage("Run this command in-game."); return true; } if (args.length == 0) { gui.open(p, "main"); return true; } @@ -528,7 +560,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu case "kit" -> { if (!selected.containsKey(p.getUniqueId())) { p.sendMessage("Choose a faction first."); break; } kit(p); } case "politics", "trust" -> politics.command(p, args); case "water" -> arrakisWater.command(p,args); - case "balance", "sell", "travel" -> p.sendMessage(ChatColor.YELLOW + "Solaris and Guild travel moved to /duneess."); + case "balance", "sell", "travel" -> p.sendMessage(ChatColor.YELLOW + "Solaris and Vaerkring travel moved to /duneess."); case "menu", "gui" -> gui.open(p, "main"); case "guireload" -> { if (p.hasPermission("dune.admin")) { gui.reload(); p.sendMessage("GUI configuration reloaded."); } else p.sendMessage("Admin only."); } case "menuitem" -> { giveMenuItem(p); p.sendMessage(ChatColor.GREEN + "Dune Navigator ready."); } @@ -552,14 +584,14 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu helpSection(sender, "General"); helpLine(sender, "/dune", "Open the Dune Navigator menu."); helpLine(sender, "/dune help", "Show this command guide."); - helpLine(sender, "/dune choose ", "Join Fremen, Harkonnen, Corrino, Atreides, or Ordos and receive its kit."); + helpLine(sender, "/dune choose ", "Join Vrijduin, Harkveen, Korenholt, Aerdrecht, or Oordwijk and receive its kit."); helpLine(sender, "/dune kit", "Receive your selected faction's kit."); helpLine(sender, "/dune elytra", "Merge or repair elytra equipment in your inventory."); helpLine(sender, "/dune menu | /dune gui", "Open the Dune Navigator menu."); helpLine(sender, "/dune menuitem", "Give yourself a portable Dune Navigator item."); helpSection(sender, "Travel"); - helpLine(sender, "/duneess travel [planet]", "Open Guild travel or travel to a planet."); + helpLine(sender, "/duneess travel [planet]", "Open Vaerkring travel or travel to a planet."); helpSection(sender, "Solaris and spice"); helpLine(sender, "/duneess balance", "Check your Solaris balance."); @@ -568,8 +600,8 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu helpLine(sender, "/dune exchange", "Open the player-posted spice job exchange."); helpSection(sender, "Politics"); - helpLine(sender, "/dune politics status", "Show Trust funds, election leaders, imperial appointments, and any invasion."); - helpLine(sender, "/dune politics deposit ", "Contribute your Solaris to the Spacing Trust."); + helpLine(sender, "/dune politics status", "Show Trust funds, election leaders, Landsraad appointments, and any invasion."); + helpLine(sender, "/dune politics deposit ", "Contribute your Solaris to the Vaerkring Trust."); helpLine(sender, "/dune politics vote ", "Vote for a leader of your faction."); helpLine(sender, "/dune politics emperorvote ", "Vote for the Emperor."); helpLine(sender, "/dune politics leader", "Show the elected leader of your faction."); @@ -580,13 +612,13 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu helpLine(sender, "/dune trust ", "Alias for /dune politics."); helpSection(sender, "Contracts and water"); - helpLine(sender, "/dune serverjobs [accept ]", "View hourly CHOAM spice contracts or accept an available contract."); + helpLine(sender, "/dune serverjobs [accept ]", "View hourly Koopkring spice contracts or accept an available contract."); helpLine(sender, "/dune job", "View player-posted spice exchange jobs."); helpLine(sender, "/dune job post ", "List a spice gathering job for another player."); helpLine(sender, "/dune job accept ", "Accept another player's spice gathering job."); helpLine(sender, "/dune job finish", "Leave your active player-posted job."); helpLine(sender, "/dune job cancel", "Cancel your unclaimed job listing."); - helpLine(sender, "/dune water guild", "Register as a Guild water trader for the standard legal rate."); + helpLine(sender, "/dune water guild", "Register as a Vaerkring Welvaarder for the standard legal rate."); helpLine(sender, "/dune water smuggler", "Choose the higher-paying but riskier water smuggling career."); helpLine(sender, "/dune water sell", "Sell finite water buckets collected on Arrakis."); helpLine(sender, "/dune water status", "Show your water career and how water trading works."); @@ -594,7 +626,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu if (sender.hasPermission("dune.admin")) { helpSection(sender, "Admin (dune.admin)"); helpLine(sender, "/dune guireload", "Reload the configurable Navigator menu."); - helpLine(sender, "/dune guildnpc", "Spawn a Spacing Guild Navigator at your location."); + helpLine(sender, "/dune guildnpc", "Spawn a Vaerkring Navigator at your location."); helpLine(sender, "/dune givespice", "Give yourself one spice item."); helpLine(sender, "/dune admin | /dune adminitem", "Operators: open admin controls or recover the custom blaze rod."); helpLine(sender, "/dune summon sandworm [x y z]", "Summon Shai-Hulud on Arrakis at your position or explicit coordinates."); @@ -712,7 +744,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu } } @EventHandler(priority=org.bukkit.event.EventPriority.LOWEST) public void loadNetworkPlayer(PlayerJoinEvent e) { - if(sharedDatabase==null)return; + if(!sharesPlayerInventory())return; try{sharedDatabase.loadPlayer(e.getPlayer(),selected); if(getConfig().getString("network.local-planet","arrakis").equalsIgnoreCase("arrakis")) Bukkit.getScheduler().runTaskLater(this,()->{if(e.getPlayer().isOnline())checkArrakisArrival(e.getPlayer());},5L); @@ -721,7 +753,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu } @EventHandler public void onNetworkQuit(org.bukkit.event.player.PlayerQuitEvent e) { restoreOrdosArmor(e.getPlayer().getUniqueId()); - if(sharedDatabase!=null)try{sharedDatabase.savePlayer(e.getPlayer(),selected);} + if(sharedDatabase!=null)try{sharedDatabase.releasePlayer(e.getPlayer(),selected);} catch(Exception ex){getLogger().severe("Shared player save failed: "+ex.getMessage());} } @EventHandler public void onBountyKill(org.bukkit.event.entity.PlayerDeathEvent e) { @@ -735,7 +767,8 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu } @EventHandler public void onJoin(PlayerJoinEvent e) { Player p = e.getPlayer(); - Bukkit.getScheduler().runTask(this, () -> giveMenuItem(p)); + if (sharesPlayerInventory() && !sharedDatabase.isLoaded(p.getUniqueId())) return; + Bukkit.getScheduler().runTask(this, () -> { if (p.isOnline()) giveMenuItem(p); }); if (!selected.containsKey(p.getUniqueId()) || selected.get(p.getUniqueId()).isEmpty()) { p.sendMessage(ChatColor.GOLD + "Choose your faction with /dune choose ."); } @@ -889,7 +922,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu Location spawn = new Location(world, x + 0.5, y + 1, z + 0.5); return world.spawn(spawn, Zombie.class, raider -> { raider.getPersistentDataContainer().set(raiderKey, PersistentDataType.BYTE, (byte)1); - raider.setCustomName(ChatColor.DARK_RED + "Haunted Fremen"); + raider.setCustomName(ChatColor.DARK_RED + "Haunted Vrijduin"); raider.setCustomNameVisible(true); raider.setRemoveWhenFarAway(true); raider.setCanPickupItems(false); diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/InventoryWebSnapshot.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/InventoryWebSnapshot.java new file mode 100644 index 00000000..5f27fbd9 --- /dev/null +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/InventoryWebSnapshot.java @@ -0,0 +1,62 @@ +package com.example.dunerealms; + +import com.google.gson.Gson; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import java.time.Instant; +import java.util.*; + +/** Safe display projection only. The web server must never deserialize Bukkit inventory blobs. */ +final class InventoryWebSnapshot { + private static final Gson JSON = new Gson(); + + static String capture(Player player) { + ItemStack[] all = player.getInventory().getContents(); + Map result = new LinkedHashMap<>(); + result.put("version", 1); + result.put("capturedAt", Instant.now().toString()); + result.put("playerName", player.getName()); + result.put("level", player.getLevel()); + result.put("experienceProgress", player.getExp()); + result.put("selectedSlot", player.getInventory().getHeldItemSlot()); + result.put("hotbar", slots(Arrays.copyOfRange(all, 0, 9))); + result.put("inventory", slots(Arrays.copyOfRange(all, 9, 36))); + Map armor = new LinkedHashMap<>(); + armor.put("helmet", item(all[39])); + armor.put("chestplate", item(all[38])); + armor.put("leggings", item(all[37])); + armor.put("boots", item(all[36])); + result.put("armor", armor); + result.put("offhand", item(all[40])); + return JSON.toJson(result); + } + + private static List slots(ItemStack[] items) { + List result = new ArrayList<>(items.length); + for (ItemStack stack : items) result.add(item(stack)); + return result; + } + + static Map item(ItemStack stack) { + if (stack == null || stack.getType().isAir()) return null; + Map result = new LinkedHashMap<>(); + result.put("material", stack.getType().name()); + result.put("amount", stack.getAmount()); + ItemMeta meta = stack.hasItemMeta() ? stack.getItemMeta() : null; + String name = meta != null && meta.hasDisplayName() ? ChatColor.stripColor(meta.getDisplayName()) + : stack.getType().name().toLowerCase(Locale.ROOT).replace('_', ' '); + result.put("name", name == null ? "Item" : com.example.dunegui.PublicNames.text(name.substring(0, Math.min(name.length(), 160)))); + result.put("enchanted", meta != null && !meta.getEnchants().isEmpty()); + if (meta instanceof Damageable damage && stack.getType().getMaxDurability() > 0) { + result.put("durability", Math.max(0, stack.getType().getMaxDurability() - damage.getDamage())); + result.put("maxDurability", (int) stack.getType().getMaxDurability()); + } + if (meta instanceof LeatherArmorMeta leather) + result.put("color", String.format("#%06x", leather.getColor().asRGB())); + return result; + } +} diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/Politics.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/Politics.java index 3997107b..92e3fe44 100644 --- a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/Politics.java +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/Politics.java @@ -85,9 +85,9 @@ public final class Politics { if(args.length<2) { msg(p,"/dune politics status|deposit |vote |emperorvote |leader|invasion |defend|steward |houseofwater "); return true; } String house=faction(p), op=args[1].toLowerCase(Locale.ROOT); if(op.equals("status")) { - msg(p,"Spacing Trust: "+state.getLong("trust")+" Solaris | Election week: "+week()); + msg(p,"Vaerkring Trust: "+state.getLong("trust")+" Solaris | Election week: "+week()); msg(p,"Your faction: "+house+" | Leader: "+leader(house)+" | Emperor: "+emperor()); - msg(p,"Steward of Dune: "+state.getString("appointments.steward.house","none")+" | House of Water: "+state.getString("appointments.water.house","none")); + msg(p,"Specerhuis: "+state.getString("appointments.steward.house","none")+" | Welvaart House: "+state.getString("appointments.water.house","none")); msg(p,"Active invasion: "+state.getString("invasion.attacker","none")+" -> "+state.getString("invasion.defender","none")); return true; } @@ -99,7 +99,7 @@ public final class Politics { if(amount<=0 || !economy.has(p,amount)){msg(p,"Insufficient Solaris.");return true;} economy.withdrawPlayer(p,amount); state.set("trust",state.getLong("trust")+amount); save(); - msg(p,"Deposited "+amount+" Solaris into the Spacing Trust.");return true; + msg(p,"Deposited "+amount+" Solaris into the Vaerkring Trust.");return true; } if(op.equals("leader")) {msg(p,"Elected "+house+" leader: "+leader(house));return true;} if(op.equals("vote") || op.equals("emperorvote")) { @@ -120,7 +120,7 @@ public final class Politics { if(!p.getUniqueId().toString().equals(winnerId("votes.house."+week()+"."+house))) {msg(p,"Only this week's elected leader may invade.");return true;} if(args.length<3 || canon(args[2])==null || house.equalsIgnoreCase(args[2])) {msg(p,"Specify another playable faction.");return true;} int cost=plugin.getConfig().getInt("politics.invasion-cost",50000); - if(state.getLong("trust")System.currentTimeMillis()){msg(p,"An invasion is already active.");return true;} state.set("trust",state.getLong("trust")-cost); state.set("invasion.attacker",house);state.set("invasion.defender",canon(args[2])); @@ -159,7 +159,7 @@ public final class Politics { state.set(root+".emperor",emperorId); save(); plugin.getServer().broadcastMessage(ChatColor.LIGHT_PURPLE+"IMPERIAL APPOINTMENT: "+canon(args[2])+ - (key.equals("steward")?" is now Steward of Dune (legal spice rights).":" is now House of Water (legal water rights).")); + (key.equals("steward")?" is now Specerhuis (legal spice rights).":" is now Welvaart House (legal water rights).")); return true; } msg(p,"Unknown politics command.");return true; diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ServerJobs.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ServerJobs.java index 27dbe473..7205b1a2 100644 --- a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ServerJobs.java +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/ServerJobs.java @@ -72,7 +72,7 @@ final class ServerJobs { Collections.shuffle(all); int count=Math.max(1,YamlConfiguration.loadConfiguration(jobsFile).getInt("offers-per-hour",3)); offers=new ArrayList<>(all.subList(0,Math.min(count,all.size()))); - Bukkit.broadcastMessage(ChatColor.GOLD+"[CHOAM] New server spice contracts are available! /dune serverjobs"); + Bukkit.broadcastMessage(ChatColor.GOLD+"[Koopkring] New server spice contracts are available! /dune serverjobs"); } for(var entry:new ArrayList<>(active.entrySet())) { Active job=entry.getValue(); @@ -89,7 +89,7 @@ final class ServerJobs { int fine=(int)Math.ceil(t.pay()*0.05); economy.withdrawPlayer(Bukkit.getOfflinePlayer(player),fine); // DuneEss permits contract debt. Player online=Bukkit.getPlayer(player); - if(online!=null) online.sendMessage(ChatColor.RED+"CHOAM contract failed: "+t.title()+". Fine: "+fine+" Solaris (5% of pay)."); + if(online!=null) online.sendMessage(ChatColor.RED+"Koopkring contract failed: "+t.title()+". Fine: "+fine+" Solaris (5% of pay)."); } void harvest(Player p,int amount) { Active a=active.get(p.getUniqueId()); @@ -102,7 +102,7 @@ final class ServerJobs { if(progress>=t.spiceRequired()) { active.remove(p.getUniqueId()); economy.depositPlayer(p,t.pay()); - p.sendMessage(ChatColor.GREEN+"CHOAM contract complete: "+t.title()+"! Paid "+t.pay()+" Solaris."); + p.sendMessage(ChatColor.GREEN+"Koopkring contract complete: "+t.title()+"! Paid "+t.pay()+" Solaris."); } else active.put(p.getUniqueId(),new Active(a.id(),a.acceptedAt(),progress)); save(); } @@ -119,7 +119,7 @@ final class ServerJobs { return t.title()+" | "+a.harvested()+"/"+t.spiceRequired()+" spice | "+Math.max(0,(a.acceptedAt()+t.limitSeconds()-Instant.now().getEpochSecond())/60)+" min left"; } void list(Player p) { - p.sendMessage(ChatColor.GOLD+"=== CHOAM Hourly Contracts ==="); + p.sendMessage(ChatColor.GOLD+"=== Koopkring Hourly Contracts ==="); for(String id:offers) { Template t=templates.get(id); if(t==null) continue; p.sendMessage(ChatColor.YELLOW+id+" | "+t.title()+" | "+t.spiceRequired()+" spice | "+t.pay()+" Solaris | "+(t.limitSeconds()/60)+" min | failure fine "+(int)Math.ceil(t.pay()*0.05)+" Solaris"); @@ -138,7 +138,7 @@ final class ServerJobs { p.sendMessage("Server job definitions reloaded; next rotation occurs at the next hour."); return; } if(!args[1].equalsIgnoreCase("accept") || args.length<3) { list(p); return; } - if(active.containsKey(p.getUniqueId())) { p.sendMessage("Finish your existing CHOAM contract first."); return; } + if(active.containsKey(p.getUniqueId())) { p.sendMessage("Finish your existing Koopkring contract first."); return; } Template t=templates.get(args[2]); if(t==null || !offers.contains(t.id())) { p.sendMessage("Job not available in the current rotation."); return; } active.put(p.getUniqueId(),new Active(t.id(),Instant.now().getEpochSecond(),0)); @@ -154,6 +154,6 @@ final class ServerJobs { y.set(path+"accepted-at",e.getValue().acceptedAt()); y.set(path+"harvested",e.getValue().harvested()); } - try { y.save(stateFile); } catch(IOException ex) { plugin.getLogger().warning("Cannot save CHOAM jobs: "+ex.getMessage()); } + try { y.save(stateFile); } catch(IOException ex) { plugin.getLogger().warning("Cannot save Koopkring jobs: "+ex.getMessage()); } } } diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java index 301b9f47..95d4313e 100644 --- a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java @@ -13,9 +13,11 @@ import java.util.*; import java.util.Base64; /** PostgreSQL-backed network player state and shared politics state. */ -public final class SharedDatabase { +public final class SharedDatabase implements AutoCloseable { private final JavaPlugin plugin; private final String url, user, password; + // Main-thread only. A dedicated connection owns the advisory lock until quit. + private final Map sessions = new HashMap<>(); public SharedDatabase(JavaPlugin plugin) throws SQLException { this.plugin = plugin; @@ -28,64 +30,191 @@ public final class SharedDatabase { } try (Connection c = connect(); Statement s = c.createStatement()) { + c.setAutoCommit(false); + s.execute("SELECT pg_advisory_xact_lock(1146441285)"); s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_players (uuid UUID PRIMARY KEY, faction TEXT NOT NULL DEFAULT '', solaris INTEGER NOT NULL DEFAULT 0, inventory TEXT)"); + s.executeUpdate("ALTER TABLE dune_players ADD COLUMN IF NOT EXISTS inventory_view JSONB"); + s.executeUpdate("ALTER TABLE dune_players ADD COLUMN IF NOT EXISTS inventory_updated_at TIMESTAMPTZ"); + s.executeUpdate("ALTER TABLE dune_players ADD COLUMN IF NOT EXISTS experience_level INTEGER"); + s.executeUpdate("ALTER TABLE dune_players ADD COLUMN IF NOT EXISTS experience_progress REAL"); + s.executeUpdate("ALTER TABLE dune_players ADD COLUMN IF NOT EXISTS total_experience INTEGER"); + s.executeUpdate("ALTER TABLE dune_players ADD COLUMN IF NOT EXISTS held_slot INTEGER"); + s.executeUpdate("ALTER TABLE dune_players ADD COLUMN IF NOT EXISTS session_open BOOLEAN NOT NULL DEFAULT FALSE"); s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_politics (id INTEGER PRIMARY KEY, yaml TEXT NOT NULL)"); s.executeUpdate("INSERT INTO dune_politics (id,yaml) VALUES (1,'') ON CONFLICT (id) DO NOTHING"); s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_arrakis_permits (player UUID PRIMARY KEY, expires_at BIGINT NOT NULL)"); s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_bounties (target UUID PRIMARY KEY, world TEXT NOT NULL, reward INTEGER NOT NULL, claimed BOOLEAN NOT NULL DEFAULT FALSE, hunter UUID)"); + c.commit(); } } public Connection connect() throws SQLException { - return DriverManager.getConnection(url, user, password); + Properties properties = new Properties(); + properties.setProperty("user", user); + properties.setProperty("password", password); + properties.setProperty("connectTimeout", "5"); + properties.setProperty("socketTimeout", "10"); + properties.setProperty("tcpKeepAlive", "true"); + properties.setProperty("ApplicationName", "DuneRealms-Core"); + return DriverManager.getConnection(url, properties); } - public void loadPlayer( - Player p, - Map factions - ) throws Exception { - try (Connection c = connect()) { - try (PreparedStatement ins = c.prepareStatement( - "INSERT INTO dune_players(uuid) VALUES (?) ON CONFLICT DO NOTHING")) { - ins.setObject(1, p.getUniqueId()); - ins.executeUpdate(); - } + public boolean isLoaded(UUID id) { return sessions.containsKey(id); } - try (PreparedStatement q = c.prepareStatement( - "SELECT faction,inventory FROM dune_players WHERE uuid=?")) { - q.setObject(1, p.getUniqueId()); - - try (ResultSet r = q.executeQuery()) { - if (r.next()) { - factions.put(p.getUniqueId(), r.getString(1)); - String blob = r.getString(2); - if (blob != null && !blob.isBlank()) { - ItemStack[] contents = decode(blob); - p.getInventory().setContents(contents); - } - } + public void loadPlayer(Player p, Map factions) throws Exception { + UUID id = p.getUniqueId(); + if (sessions.containsKey(id)) throw new SQLException("Profile already loaded on this backend"); + Connection c = connect(); + boolean retained = false; + try { + try (PreparedStatement lock = c.prepareStatement("SELECT pg_try_advisory_lock(?)")) { + lock.setLong(1, id.getMostSignificantBits() ^ id.getLeastSignificantBits()); + try (ResultSet r = lock.executeQuery()) { + if (!r.next() || !r.getBoolean(1)) + throw new SQLException("Profile is still active on another backend; reconnect shortly"); } } + try (PreparedStatement ins = c.prepareStatement( + "INSERT INTO dune_players(uuid,faction) VALUES (?,?) ON CONFLICT DO NOTHING")) { + ins.setObject(1, id); + ins.setString(2, factions.getOrDefault(id, "")); + ins.executeUpdate(); + } + ItemStack[] inventory = null; + String faction; + Integer level, total, slot; + Float progress; + try (PreparedStatement q = c.prepareStatement( + "SELECT faction,inventory,experience_level,experience_progress,total_experience,held_slot,session_open FROM dune_players WHERE uuid=?")) { + q.setObject(1, id); + try (ResultSet r = q.executeQuery()) { + if (!r.next()) throw new SQLException("Missing network profile"); + if (r.getBoolean("session_open")) + throw new SQLException("Unclean previous session; administrator recovery required"); + faction = r.getString("faction"); + String blob = r.getString("inventory"); + if (blob != null && !blob.isBlank()) inventory = decode(blob); + level = (Integer) r.getObject("experience_level"); + progress = (Float) r.getObject("experience_progress"); + total = (Integer) r.getObject("total_experience"); + slot = (Integer) r.getObject("held_slot"); + } + } + // Decode and validate everything before changing the player or marking a session open. + if (inventory != null && inventory.length != p.getInventory().getContents().length) + throw new IOException("Network inventory has an unexpected slot count"); + if ((level != null && level < 0) || (total != null && total < 0) + || (progress != null && (!Float.isFinite(progress) || progress < 0 || progress >= 1)) + || (slot != null && (slot < 0 || slot > 8))) + throw new IOException("Network experience or selected slot is invalid"); + try (PreparedStatement q = c.prepareStatement("UPDATE dune_players SET session_open=TRUE WHERE uuid=?")) { + q.setObject(1, id); + q.executeUpdate(); + } + // Keep the durable marker if any application step fails: do not overwrite the profile. + if (inventory != null) p.getInventory().setContents(inventory); + if (level != null) p.setLevel(level); + if (progress != null) p.setExp(progress); + if (total != null) p.setTotalExperience(total); + if (slot != null) p.getInventory().setHeldItemSlot(slot); + factions.put(id, faction); + sessions.put(id, c); + retained = true; + } finally { + if (!retained) c.close(); } } - public void savePlayer( - Player p, - Map factions - ) throws Exception { - try (Connection c = connect(); PreparedStatement q = c.prepareStatement( - "INSERT INTO dune_players(uuid,faction,inventory) VALUES(?,?,?) " - + "ON CONFLICT(uuid) DO UPDATE SET " - + "faction=EXCLUDED.faction," - + "inventory=EXCLUDED.inventory")) { + public void savePlayer(Player p, Map factions) throws Exception { + writePlayer(p, factions, false); + } - q.setObject(1, p.getUniqueId()); - q.setString(2, factions.getOrDefault(p.getUniqueId(), "")); - q.setString(3, encode(p.getInventory().getContents())); - q.executeUpdate(); + /** Write and clear the durable marker before releasing the lock for the next backend. */ + public void releasePlayer(Player p, Map factions) throws Exception { + if (!isLoaded(p.getUniqueId())) return; // A failed load must never save stale local items. + try { + p.closeInventory(); // Return cursor and crafting items before the final snapshot. + writePlayer(p, factions, true); + } finally { + Connection c = sessions.remove(p.getUniqueId()); + if (c != null) c.close(); } } + private void writePlayer(Player p, Map factions, boolean release) throws Exception { + Connection c = sessions.get(p.getUniqueId()); + if (c == null) return; + // Never reconnect here: a replacement connection would not own the session lock. + String inventory = encode(p.getInventory().getContents()); + try (PreparedStatement q = c.prepareStatement( + "UPDATE dune_players SET faction=?,inventory=?,experience_level=?,experience_progress=?,total_experience=?,held_slot=?,session_open=?,inventory_view=?::jsonb,inventory_updated_at=CURRENT_TIMESTAMP WHERE uuid=?")) { + q.setString(1, factions.getOrDefault(p.getUniqueId(), "")); + q.setString(2, inventory); + q.setInt(3, p.getLevel()); + q.setFloat(4, p.getExp()); + q.setInt(5, p.getTotalExperience()); + q.setInt(6, p.getInventory().getHeldItemSlot()); + q.setBoolean(7, !release); + q.setString(8, InventoryWebSnapshot.capture(p)); + q.setObject(9, p.getUniqueId()); + if (q.executeUpdate() != 1) throw new SQLException("Network profile disappeared during save"); + } catch (SQLException ex) { + try { + org.bukkit.configuration.file.YamlConfiguration recovery = new org.bukkit.configuration.file.YamlConfiguration(); + recovery.set("uuid", p.getUniqueId().toString()); + recovery.set("captured-at", java.time.Instant.now().toString()); + recovery.set("faction", factions.getOrDefault(p.getUniqueId(), "")); + recovery.set("inventory", inventory); + recovery.set("experience-level", p.getLevel()); + recovery.set("experience-progress", p.getExp()); + recovery.set("total-experience", p.getTotalExperience()); + recovery.set("held-slot", p.getInventory().getHeldItemSlot()); + File folder = new File(plugin.getDataFolder(), "inventory-recovery"); + if (!folder.isDirectory() && !folder.mkdirs()) throw new IOException("Cannot create recovery directory"); + recovery.save(new File(folder, p.getUniqueId() + "-" + System.nanoTime() + ".yml")); + } catch (IOException recoveryError) { ex.addSuppressed(recoveryError); } + throw ex; + } + } + + /** Exchange SQL and the resulting authoritative inventory checkpoint commit together. */ + public void transaction(Player p, Map factions, java.util.function.Consumer operation) throws Exception { + Connection c = sessions.get(p.getUniqueId()); + if (c == null) throw new SQLException("A loaded shared network profile is required to trade"); + ItemStack[] before = Arrays.stream(p.getInventory().getContents()) + .map(item -> item == null ? null : item.clone()).toArray(ItemStack[]::new); + boolean committing = false; + c.setAutoCommit(false); + try { + operation.accept(c); + writePlayer(p, factions, false); + committing = true; + c.commit(); + } catch (Exception ex) { + boolean recovered = false; + if (!committing) try { + c.rollback(); + p.getInventory().setContents(before); + recovered = true; + } catch (Exception rollback) { ex.addSuppressed(rollback); } + if (!recovered) { + // Unknown commit result: never perform an ordinary quit save over the evidence. + sessions.remove(p.getUniqueId()); + try { c.close(); } catch (SQLException close) { ex.addSuppressed(close); } + p.kickPlayer("Exchange storage interrupted. An administrator must review your network profile."); + } + throw ex; + } finally { + if (sessions.containsKey(p.getUniqueId())) c.setAutoCommit(true); + } + } + + @Override public void close() { + for (Connection c : sessions.values()) try { c.close(); } + catch (SQLException ex) { plugin.getLogger().warning("Profile connection close failed: " + ex.getMessage()); } + sessions.clear(); + } + public String loadPolitics() throws SQLException { try (Connection c = connect(); PreparedStatement q = c.prepareStatement( diff --git a/DuneRealms-minecraft-only/src/main/resources/config.yml b/DuneRealms-minecraft-only/src/main/resources/config.yml index b3420190..9e6fdb63 100644 --- a/DuneRealms-minecraft-only/src/main/resources/config.yml +++ b/DuneRealms-minecraft-only/src/main/resources/config.yml @@ -57,6 +57,7 @@ arrakis-water: database: enabled: false + autosave-seconds: 60 jdbc-url: "jdbc:postgresql://127.0.0.1:5432/dunerealms" username: "dune" password: "CHANGE_ME" diff --git a/DuneRealms-minecraft-only/src/main/resources/gui.yml b/DuneRealms-minecraft-only/src/main/resources/gui.yml index 51fca7c0..5db49462 100644 --- a/DuneRealms-minecraft-only/src/main/resources/gui.yml +++ b/DuneRealms-minecraft-only/src/main/resources/gui.yml @@ -19,8 +19,8 @@ menus: guild: slot: 10 icon: COMPASS - name: "&eSpacing Guild" - lore: ["&7Travel to another planet", "&7Fare: %travel_cost% Solaris"] + name: "&eVaerkring" + lore: ["&7Travel to another planet", "&7Fare: %travel_cost% Dunemarks"] action: "open:travel" choam: slot: 12 @@ -36,8 +36,8 @@ menus: action: "open:exchange" wallet: slot: 16 - icon: GOLD_INGOT - name: "&6Wallet: %balance% Solaris" + icon: DUNEMARK + name: "&6Wallet: %balance% Dunemarks" lore: ["&7Click to view balance"] action: "dune:balance" sell: @@ -58,7 +58,7 @@ menus: name: "&dWinged Stillsuit Upgrade" lore: - "&7Merge worn chestplate with an Elytra" - - "&6Cost: 1,000,000 Solaris" + - "&6Cost: 1,000,000 Dunemarks" - "&7Wear stillsuit chestplate and carry Elytra" action: "dune:elytra" faction: @@ -146,7 +146,7 @@ menus: max-items: 4 icon: ENDER_PEARL name: "&eTravel to %id%" - lore: ["&7Fare: %travel_cost% Solaris"] + lore: ["&7Fare: %travel_cost% Dunemarks"] action: "dune:travel %id%" factions: title: "&6Dune | Factions" diff --git a/DuneRealms-minecraft-only/src/main/resources/plugin.yml b/DuneRealms-minecraft-only/src/main/resources/plugin.yml index 597aa05b..3aea696e 100644 --- a/DuneRealms-minecraft-only/src/main/resources/plugin.yml +++ b/DuneRealms-minecraft-only/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: DuneCore -version: 1.0.11 +version: 1.0.12 main: com.example.dunerealms.DuneCore api-version: '1.21.8' depend: [Vault, DuneEss] diff --git a/DuneRealms-minecraft-only/src/main/resources/server-jobs.yml b/DuneRealms-minecraft-only/src/main/resources/server-jobs.yml index 0538c6a0..54ff8604 100644 --- a/DuneRealms-minecraft-only/src/main/resources/server-jobs.yml +++ b/DuneRealms-minecraft-only/src/main/resources/server-jobs.yml @@ -7,7 +7,7 @@ jobs: pay: 3000 time-limit-minutes: 30 guild-supply: - title: "Spacing Guild Supply Order" + title: "Vaerkring Supply Order" spice-required: 250 pay: 8500 time-limit-minutes: 45 diff --git a/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/ArrakisAnnouncementsTest.java b/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/ArrakisAnnouncementsTest.java index 32e7fa33..abe72f22 100644 --- a/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/ArrakisAnnouncementsTest.java +++ b/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/ArrakisAnnouncementsTest.java @@ -60,7 +60,7 @@ class ArrakisAnnouncementsTest { verify(carrier, times(1)).sendPluginMessage(eq(plugin), eq("BungeeCord"), packet.capture()); DataInputStream input = new DataInputStream(new ByteArrayInputStream(packet.getValue())); assertEquals("Message", input.readUTF()); assertEquals("ALL", input.readUTF()); - assertTrue(input.readUTF().contains("Spacing Guild")); + assertTrue(input.readUTF().contains("Vaerkring")); assertTrue(YamlConfiguration.loadConfiguration(file).getBoolean(key + ".sent")); } } diff --git a/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/DiplomacySnapshotTest.java b/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/DiplomacySnapshotTest.java index d5886f25..9d3ead26 100644 --- a/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/DiplomacySnapshotTest.java +++ b/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/DiplomacySnapshotTest.java @@ -8,8 +8,8 @@ class DiplomacySnapshotTest { var record=new YamlConfiguration(); String id=UUID.randomUUID().toString(); long week=42; record.set("votes.emperor.42.tally."+id,2); record.set("votes.emperor.42.names."+id,"MuadDib"); - record.set("votes.house.42.Fremen.tally."+id,1); - record.set("votes.house.42.Fremen.names."+id,"MuadDib"); + record.set("votes.house.42.Vrijduin.tally."+id,1); + record.set("votes.house.42.Vrijduin.names."+id,"MuadDib"); record.set("appointments.steward.week",42); record.set("appointments.steward.emperor",id); record.set("appointments.steward.house","Atreides"); diff --git a/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SharedDatabaseTest.java b/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SharedDatabaseTest.java new file mode 100644 index 00000000..65ba8af7 --- /dev/null +++ b/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SharedDatabaseTest.java @@ -0,0 +1,189 @@ +package com.example.dunerealms; + +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.plugin.java.JavaPlugin; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.Path; +import java.sql.*; +import java.util.*; +import java.util.logging.Logger; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class SharedDatabaseTest { + @TempDir Path temp; + private Driver driver; + private Connection owner; + private PreparedStatement lock, row, update; + private ResultSet lockResult, profile; + private SharedDatabase db; + private Player player; + private PlayerInventory inventory; + private Inventory ender; + private final UUID id = UUID.randomUUID(); + private final Map factions = new HashMap<>(); + + @BeforeEach void prepare() throws Exception { + Connection schema = mock(Connection.class); + when(schema.createStatement()).thenReturn(mock(Statement.class)); + owner = mock(Connection.class); + lock = mock(PreparedStatement.class); + row = mock(PreparedStatement.class); + update = mock(PreparedStatement.class); + lockResult = mock(ResultSet.class); + profile = mock(ResultSet.class); + when(owner.prepareStatement(anyString())).thenAnswer(call -> { + String sql = call.getArgument(0); + if (sql.contains("pg_try_advisory_lock")) return lock; + if (sql.startsWith("SELECT faction")) return row; + return update; + }); + when(lock.executeQuery()).thenReturn(lockResult); + when(lockResult.next()).thenReturn(true); + when(lockResult.getBoolean(1)).thenReturn(true); + when(row.executeQuery()).thenReturn(profile); + when(profile.next()).thenReturn(true); + when(profile.getString("faction")).thenReturn("fremen"); + when(update.executeUpdate()).thenReturn(1); + driver = mock(Driver.class); + when(driver.acceptsURL("jdbc:dune-test:profiles")).thenReturn(true); + when(driver.connect(eq("jdbc:dune-test:profiles"), any())).thenReturn(schema, owner); + DriverManager.registerDriver(driver); + JavaPlugin plugin = mock(JavaPlugin.class); + YamlConfiguration config = new YamlConfiguration(); + config.set("database.jdbc-url", "jdbc:dune-test:profiles"); + config.set("database.username", "dune"); + config.set("database.password", "test-only"); + when(plugin.getConfig()).thenReturn(config); + when(plugin.getDataFolder()).thenReturn(temp.toFile()); + when(plugin.getLogger()).thenReturn(Logger.getAnonymousLogger()); + db = new SharedDatabase(plugin); + player = mock(Player.class); + inventory = mock(PlayerInventory.class); + ender = mock(Inventory.class); + when(player.getUniqueId()).thenReturn(id); + when(player.getInventory()).thenReturn(inventory); + when(player.getEnderChest()).thenReturn(ender); + when(inventory.getContents()).thenReturn(new ItemStack[41]); + when(ender.getContents()).thenReturn(new ItemStack[27]); + when(ender.getSize()).thenReturn(27); + } + + @AfterEach void cleanup() throws Exception { + db.close(); + DriverManager.deregisterDriver(driver); + } + + @Test void failedLockNeverLoadsOrSavesLocalItems() throws Exception { + when(lockResult.getBoolean(1)).thenReturn(false); + assertThrows(SQLException.class, () -> db.loadPlayer(player, factions)); + db.releasePlayer(player, factions); + assertFalse(db.isLoaded(id)); + verify(owner).close(); + verify(row, never()).executeQuery(); + verify(update, never()).executeUpdate(); + verifyNoInteractions(inventory, ender); + } + + @Test void dirtySessionRequiresRecoveryAndDoesNotOverwriteDatabase() throws Exception { + when(profile.getBoolean("session_open")).thenReturn(true); + assertThrows(SQLException.class, () -> db.loadPlayer(player, factions)); + clearInvocations(update); + db.savePlayer(player, factions); + db.releasePlayer(player, factions); + verifyNoInteractions(update); + verify(inventory, never()).setContents(any()); + } + + @Test void malformedInventoryFailsBeforeOpeningSessionOrApplyingItems() throws Exception { + when(profile.getString("inventory")).thenReturn("not base64!"); + assertThrows(Exception.class, () -> db.loadPlayer(player, factions)); + verify(owner, never()).prepareStatement("UPDATE dune_players SET session_open=TRUE WHERE uuid=?"); + verify(inventory, never()).setContents(any()); + assertFalse(db.isLoaded(id)); + } + + @Test void autosaveUsesOwnedConnectionAndKeepsSessionOpenThenQuitReleases() throws Exception { + db.loadPlayer(player, factions); + assertEquals("fremen", factions.get(id)); + assertTrue(db.isLoaded(id)); + db.savePlayer(player, factions); + verify(update).setBoolean(7, true); + verify(owner, never()).close(); + db.releasePlayer(player, factions); + verify(update).setBoolean(7, false); + verify(owner).close(); + assertFalse(db.isLoaded(id)); + verify(driver, times(2)).connect(anyString(), any()); // Schema + one owned connection only. + } + + @Test void duplicateLoadOnSameBackendCannotOverwriteSession() throws Exception { + db.loadPlayer(player, factions); + assertThrows(SQLException.class, () -> db.loadPlayer(player, factions)); + verify(driver, times(2)).connect(anyString(), any()); + verify(owner, never()).close(); + } + + @Test void savedInventoryAndExperienceReloadTogether() throws Exception { + db.loadPlayer(player, factions); + clearInvocations(update); + when(player.getLevel()).thenReturn(23); + when(player.getExp()).thenReturn(0.5f); + when(player.getTotalExperience()).thenReturn(900); + when(inventory.getHeldItemSlot()).thenReturn(7); + db.savePlayer(player, factions); + var inv = org.mockito.ArgumentCaptor.forClass(String.class); + verify(update).setString(eq(2), inv.capture()); + db.releasePlayer(player, factions); + when(profile.getString("inventory")).thenReturn(inv.getValue()); + when(profile.getObject("experience_level")).thenReturn(23); + when(profile.getObject("experience_progress")).thenReturn(0.5f); + when(profile.getObject("total_experience")).thenReturn(900); + when(profile.getObject("held_slot")).thenReturn(7); + db.loadPlayer(player, factions); + verify(inventory).setContents(new ItemStack[41]); + verifyNoInteractions(ender); + verify(player).setLevel(23); + verify(player).setExp(0.5f); + verify(player).setTotalExperience(900); + verify(inventory).setHeldItemSlot(7); + } + + @Test void failedQuitSaveWritesRecoverySnapshotAndClosesOwnership() throws Exception { + db.loadPlayer(player, factions); + when(update.executeUpdate()).thenThrow(new SQLException("simulated outage")); + assertThrows(SQLException.class, () -> db.releasePlayer(player, factions)); + assertFalse(db.isLoaded(id)); + verify(owner).close(); + try (var files = java.nio.file.Files.list(temp.resolve("inventory-recovery"))) { + Path recovery = files.findFirst().orElseThrow(); + YamlConfiguration saved = YamlConfiguration.loadConfiguration(recovery.toFile()); + assertEquals(id.toString(), saved.getString("uuid")); + assertNotNull(saved.getString("inventory")); + assertNull(saved.getString("ender-chest")); + } + } + @Test void tradeAndInventoryCheckpointCommitOnTheOwnedConnection() throws Exception { + db.loadPlayer(player,factions);clearInvocations(update); + db.transaction(player,factions,c->assertSame(owner,c)); + verify(update).executeUpdate();verify(owner).commit();verify(owner).setAutoCommit(true); + assertTrue(db.isLoaded(id));verify(owner,never()).close(); + } + @Test void failedTradeRollsBackAndRestoresInventoryWithoutReleasingOwnership() throws Exception { + db.loadPlayer(player,factions); + assertThrows(IllegalArgumentException.class,()->db.transaction(player,factions,c->{throw new IllegalArgumentException("sold out");})); + verify(owner).rollback();verify(owner,never()).commit(); + verify(inventory).setContents(new ItemStack[41]);assertTrue(db.isLoaded(id)); + } + @Test void uncertainCommitQuarantinesPlayerAndCannotPerformAQuitSave() throws Exception { + db.loadPlayer(player,factions);doThrow(new SQLException("connection lost at commit")).when(owner).commit(); + assertThrows(SQLException.class,()->db.transaction(player,factions,c->{})); + assertFalse(db.isLoaded(id));verify(owner).close();verify(player).kickPlayer(anyString()); + clearInvocations(update);db.releasePlayer(player,factions);verifyNoInteractions(update); + } +} diff --git a/DuneResourcePack.zip b/DuneResourcePack.zip index b2b84715..c652ac79 100644 Binary files a/DuneResourcePack.zip and b/DuneResourcePack.zip differ diff --git a/DuneResourcePack/README.md b/DuneResourcePack/README.md index 1bc7de4b..49c752b1 100644 --- a/DuneResourcePack/README.md +++ b/DuneResourcePack/README.md @@ -11,3 +11,11 @@ On a Fabric client, copy `DuneResourcePack.zip` into `.minecraft/resourcepacks`, DuneCore 1.0.7 adds an Arrakis smuggler texture for the vanilla wandering trader model. Enable the updated pack to see sand-tan robes, a face covering, amber trim and leather gear. This texture applies to all wandering traders client-side; smuggling missions only apply to Arrakis traders. + +## Vaerkring Reserve GUI series (2026-10-27) + +Item-model keys: dunerealms:dunemark_1, dunemark_5, dunemark_100, dunemark_1000 and dunemark_5000. Each has its own transparent 128px texture and item/model definition. The legacy dunerealms:dunemark_note remains a 100-note visual alias. These are presentation-only; currency stays in the server ledger, and GUI clicks do not issue bearer notes. Wallet art selects the largest supported denomination not exceeding the balance (minimum visual fallback 1). + +The 0-Dunemark Leto II search tribute is deliberately absent from this pack and the game denomination list. It is website/design artwork only. The five planet textures now use letter rings for Arrakduin, Kaladam, Giedermark, Kaiterhof and Sigmadraken IV; existing internal model IDs remain stable. + +Published pack SHA1: f9470108e9cff93231968e6b8b2d99293e62fce2. Java 1.21.4 item-model format; in-client appearance and Bedrock conversion still require a client check. Character fan art is not represented as licensed merchandise. diff --git a/DuneResourcePack/assets/dunerealms/items/dunemark_1.json b/DuneResourcePack/assets/dunerealms/items/dunemark_1.json new file mode 100644 index 00000000..01e7152f --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/dunemark_1.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/dunemark_1"}} diff --git a/DuneResourcePack/assets/dunerealms/items/dunemark_100.json b/DuneResourcePack/assets/dunerealms/items/dunemark_100.json new file mode 100644 index 00000000..19c14da4 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/dunemark_100.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/dunemark_100"}} diff --git a/DuneResourcePack/assets/dunerealms/items/dunemark_1000.json b/DuneResourcePack/assets/dunerealms/items/dunemark_1000.json new file mode 100644 index 00000000..a80c2655 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/dunemark_1000.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/dunemark_1000"}} diff --git a/DuneResourcePack/assets/dunerealms/items/dunemark_5.json b/DuneResourcePack/assets/dunerealms/items/dunemark_5.json new file mode 100644 index 00000000..80a246a0 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/dunemark_5.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/dunemark_5"}} diff --git a/DuneResourcePack/assets/dunerealms/items/dunemark_5000.json b/DuneResourcePack/assets/dunerealms/items/dunemark_5000.json new file mode 100644 index 00000000..3eed422a --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/dunemark_5000.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/dunemark_5000"}} diff --git a/DuneResourcePack/assets/dunerealms/items/dunemark_note.json b/DuneResourcePack/assets/dunerealms/items/dunemark_note.json new file mode 100644 index 00000000..98ca8e6a --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/dunemark_note.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/dunemark_note"}} diff --git a/DuneResourcePack/assets/dunerealms/items/office_crown.json b/DuneResourcePack/assets/dunerealms/items/office_crown.json new file mode 100644 index 00000000..ff43247c --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/office_crown.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/office_crown"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/items/office_spice.json b/DuneResourcePack/assets/dunerealms/items/office_spice.json new file mode 100644 index 00000000..4ccea1b5 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/office_spice.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/office_spice"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/items/office_water.json b/DuneResourcePack/assets/dunerealms/items/office_water.json new file mode 100644 index 00000000..1ed81227 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/office_water.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/office_water"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/items/planet_nivareth.json b/DuneResourcePack/assets/dunerealms/items/planet_nivareth.json new file mode 100644 index 00000000..aaf4ff02 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/planet_nivareth.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/planet_nivareth"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/items/planet_orivane.json b/DuneResourcePack/assets/dunerealms/items/planet_orivane.json new file mode 100644 index 00000000..e2ea0093 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/planet_orivane.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/planet_orivane"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/items/planet_pelareth.json b/DuneResourcePack/assets/dunerealms/items/planet_pelareth.json new file mode 100644 index 00000000..371ff72d --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/planet_pelareth.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/planet_pelareth"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/items/planet_serevan.json b/DuneResourcePack/assets/dunerealms/items/planet_serevan.json new file mode 100644 index 00000000..a794b48f --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/planet_serevan.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/planet_serevan"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/items/planet_varkesh.json b/DuneResourcePack/assets/dunerealms/items/planet_varkesh.json new file mode 100644 index 00000000..7683cf15 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/items/planet_varkesh.json @@ -0,0 +1 @@ +{"model":{"type":"minecraft:model","model":"dunerealms:item/planet_varkesh"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/models/item/dunemark_1.json b/DuneResourcePack/assets/dunerealms/models/item/dunemark_1.json new file mode 100644 index 00000000..f23638b1 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/dunemark_1.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/dunemark_1"}} diff --git a/DuneResourcePack/assets/dunerealms/models/item/dunemark_100.json b/DuneResourcePack/assets/dunerealms/models/item/dunemark_100.json new file mode 100644 index 00000000..e4751d12 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/dunemark_100.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/dunemark_100"}} diff --git a/DuneResourcePack/assets/dunerealms/models/item/dunemark_1000.json b/DuneResourcePack/assets/dunerealms/models/item/dunemark_1000.json new file mode 100644 index 00000000..9348c549 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/dunemark_1000.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/dunemark_1000"}} diff --git a/DuneResourcePack/assets/dunerealms/models/item/dunemark_5.json b/DuneResourcePack/assets/dunerealms/models/item/dunemark_5.json new file mode 100644 index 00000000..66148f8e --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/dunemark_5.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/dunemark_5"}} diff --git a/DuneResourcePack/assets/dunerealms/models/item/dunemark_5000.json b/DuneResourcePack/assets/dunerealms/models/item/dunemark_5000.json new file mode 100644 index 00000000..e25a75dd --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/dunemark_5000.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/dunemark_5000"}} diff --git a/DuneResourcePack/assets/dunerealms/models/item/dunemark_note.json b/DuneResourcePack/assets/dunerealms/models/item/dunemark_note.json new file mode 100644 index 00000000..3dba0b17 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/dunemark_note.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/dunemark_note"}} diff --git a/DuneResourcePack/assets/dunerealms/models/item/office_crown.json b/DuneResourcePack/assets/dunerealms/models/item/office_crown.json new file mode 100644 index 00000000..9dfd5859 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/office_crown.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/office_crown"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/models/item/office_spice.json b/DuneResourcePack/assets/dunerealms/models/item/office_spice.json new file mode 100644 index 00000000..151bb493 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/office_spice.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/office_spice"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/models/item/office_water.json b/DuneResourcePack/assets/dunerealms/models/item/office_water.json new file mode 100644 index 00000000..86e458a8 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/office_water.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/office_water"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/models/item/planet_nivareth.json b/DuneResourcePack/assets/dunerealms/models/item/planet_nivareth.json new file mode 100644 index 00000000..abda16e9 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/planet_nivareth.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/planet_nivareth"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/models/item/planet_orivane.json b/DuneResourcePack/assets/dunerealms/models/item/planet_orivane.json new file mode 100644 index 00000000..6e363751 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/planet_orivane.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/planet_orivane"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/models/item/planet_pelareth.json b/DuneResourcePack/assets/dunerealms/models/item/planet_pelareth.json new file mode 100644 index 00000000..3a575339 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/planet_pelareth.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/planet_pelareth"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/models/item/planet_serevan.json b/DuneResourcePack/assets/dunerealms/models/item/planet_serevan.json new file mode 100644 index 00000000..ba4abd52 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/planet_serevan.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/planet_serevan"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/models/item/planet_varkesh.json b/DuneResourcePack/assets/dunerealms/models/item/planet_varkesh.json new file mode 100644 index 00000000..c7991b19 --- /dev/null +++ b/DuneResourcePack/assets/dunerealms/models/item/planet_varkesh.json @@ -0,0 +1 @@ +{"parent":"minecraft:item/generated","textures":{"layer0":"dunerealms:item/planet_varkesh"}} \ No newline at end of file diff --git a/DuneResourcePack/assets/dunerealms/textures/item/dunemark_1.png b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_1.png new file mode 100644 index 00000000..bc23a96a Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_1.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/dunemark_100.png b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_100.png new file mode 100644 index 00000000..d861fab2 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_100.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/dunemark_1000.png b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_1000.png new file mode 100644 index 00000000..02c40f53 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_1000.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/dunemark_5.png b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_5.png new file mode 100644 index 00000000..9edcf2a5 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_5.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/dunemark_5000.png b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_5000.png new file mode 100644 index 00000000..9dbc6c94 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_5000.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/dunemark_note.png b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_note.png new file mode 100644 index 00000000..d861fab2 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/dunemark_note.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/office_crown.png b/DuneResourcePack/assets/dunerealms/textures/item/office_crown.png new file mode 100644 index 00000000..c1957455 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/office_crown.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/office_spice.png b/DuneResourcePack/assets/dunerealms/textures/item/office_spice.png new file mode 100644 index 00000000..71d99ce5 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/office_spice.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/office_water.png b/DuneResourcePack/assets/dunerealms/textures/item/office_water.png new file mode 100644 index 00000000..d311a189 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/office_water.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/planet_nivareth.png b/DuneResourcePack/assets/dunerealms/textures/item/planet_nivareth.png new file mode 100644 index 00000000..f18516a0 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/planet_nivareth.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/planet_orivane.png b/DuneResourcePack/assets/dunerealms/textures/item/planet_orivane.png new file mode 100644 index 00000000..a5878d26 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/planet_orivane.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/planet_pelareth.png b/DuneResourcePack/assets/dunerealms/textures/item/planet_pelareth.png new file mode 100644 index 00000000..d27b46db Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/planet_pelareth.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/planet_serevan.png b/DuneResourcePack/assets/dunerealms/textures/item/planet_serevan.png new file mode 100644 index 00000000..fc96d751 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/planet_serevan.png differ diff --git a/DuneResourcePack/assets/dunerealms/textures/item/planet_varkesh.png b/DuneResourcePack/assets/dunerealms/textures/item/planet_varkesh.png new file mode 100644 index 00000000..f1526e68 Binary files /dev/null and b/DuneResourcePack/assets/dunerealms/textures/item/planet_varkesh.png differ diff --git a/DuneResourcePack/pack.mcmeta b/DuneResourcePack/pack.mcmeta index 5947fbae..c1acf245 100644 --- a/DuneResourcePack/pack.mcmeta +++ b/DuneResourcePack/pack.mcmeta @@ -3,8 +3,8 @@ "pack_format": 46, "supported_formats": { "min_inclusive": 46, - "max_inclusive": 46 + "max_inclusive": 64 }, - "description": "Dune — Shai-Hulud, Arrakis Smugglers, Haunted Fremen, and spice-rich sand (Java 1.21.4)" + "description": "dunerealms.com — desert creatures and Dunemark GUI notes (Java 1.21.4–1.21.8)" } } diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/HarkonnenFortress.java b/DuneTerrain/src/main/java/com/example/duneterrain/HarkonnenFortress.java index 4e5a663f..ac43cd8a 100644 --- a/DuneTerrain/src/main/java/com/example/duneterrain/HarkonnenFortress.java +++ b/DuneTerrain/src/main/java/com/example/duneterrain/HarkonnenFortress.java @@ -39,7 +39,7 @@ final class HarkonnenFortress extends BlockPopulator implements Listener { } r.setType(x+3,y-5,z+3,Material.CHEST); if(r.getBlockState(x+3,y-5,z+3) instanceof Chest chest) { - chest.setCustomName("Old Harkonnen Fortress"); + chest.setCustomName("Old Harkveen Fortress"); var table=Bukkit.getLootTable(LOOT); if(table!=null){chest.setLootTable(table);chest.setSeed(DenseSpice.mix(world.getSeed()^cx^((long)cz<<32)));} else for(ItemStack item:kit())chest.getSnapshotInventory().addItem(item); @@ -56,7 +56,7 @@ final class HarkonnenFortress extends BlockPopulator implements Listener { var core=Bukkit.getPluginManager().getPlugin("DuneCore"); if(core!=null && core.isEnabled())try { return (List)core.getClass().getMethod("createFactionKit",String.class).invoke(core,"Harkonnen"); - }catch(ReflectiveOperationException ex){plugin.getLogger().warning("Harkonnen kit requires updated DuneCore: "+ex.getMessage());} + }catch(ReflectiveOperationException ex){plugin.getLogger().warning("Harkveen kit requires updated DuneCore: "+ex.getMessage());} return List.of(new ItemStack(Material.IRON_SWORD),new ItemStack(Material.BREAD,8)); } @EventHandler(ignoreCancelled=true) public void loot(LootGenerateEvent e) { diff --git a/README.md b/README.md index c5662389..c8f200aa 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Illustrated Arrakis dunes and Shai-Hulud -A Dune-themed Minecraft Java plugin suite for **Paper 1.21.8 and Java 21**. Explore Arrakis, harvest melange, join a faction, trade through the Spacing Guild, and encounter Shai-Hulud. +A Dune-themed Minecraft Java plugin suite for **Paper 1.21.8 and Java 21**. Explore Arrakis, harvest melange, join a faction, trade through the Vaerkring, and encounter Shai-Hulud. **[Project Dune website](https://project-dune.bonnystoat9.chatgpt.site)** — illustrated landing page, searchable online manual, Races & Houses, Exchange and News. The website is public; profiles and private support tickets require sign-in. Live feeds show “server not connected” until configured; see [DiscordSRV integration](website/DISCORD-FEEDS.md). @@ -39,7 +39,7 @@ For a planet used as Paper's primary world, configure its generator and biome pr - Arrakis sun exposure, finite-water trading, imperial appointments, prototype politics and invasions, and optional PostgreSQL-backed permits and bounties. - **Visible Sniffer sandworms with native zombie AI**, provided by invisible Husk controllers. The Sniffer body can be fought and killed; its death produces a rich spice field and removes its controller. - Haunted Fremen zombie raiders, with an increased spawn chance near rich spice fields. -- Lore sightings with coordinates on Arrakis, followed by a **fifteen-minute Spacing Guild announcement** to online players across the proxy. Timers persist through restart and avoid repeating a sighting on ordinary chunk reload. +- Lore sightings with coordinates on Arrakis, followed by a **fifteen-minute Vaerkring announcement** to online players across the proxy. Timers persist through restart and avoid repeating a sighting on ordinary chunk reload. - Configurable Navigator menus, a Guild travel menu, and a paged in-game help guide. - Operator-only Imperial Admin Scepters, automatically supplied to ops, with linked DuneNPC management controls. - Roaming Arrakis smugglers with lore-based spice and water missions, a 30-minute real-time deadline, stationary illuminated quest camps and green/purple status particles. @@ -52,7 +52,7 @@ The other planet terrain profiles already exist: Giedi Prime, Kaitain, Caladan, Use `/dune help` or `/duneess help menu`, choose a faction with `/dune choose `, and equip all four stillsuit pieces from the kit. Use the tagged Spice Harvest Shovel on Arrakis suspicious sand, then `/duneess sell` to sell the collected spice. `/dune` opens the Navigator; `/duneess balance` checks Solaris and `/duneess travel [planet]` opens or requests Guild travel. -The default spice price is 15 Solaris, normal Guild fare is 100, and starting balance is zero. Direct sales can incur the Spacing Trust levy and smuggling consequences. Server operators may change these values. +The default spice price is 15 Solaris, normal Guild fare is 100, and starting balance is zero. Direct sales can incur the Vaerkring Trust levy and smuggling consequences. Server operators may change these values. ## Admin sandworm summon @@ -75,7 +75,7 @@ The intended network uses one Paper backend per planet behind Velocity. Match pl Guild travel is an asynchronous transfer request without an arrival acknowledgment. The global Guild notice needs an online player connection on Arrakis; a due notice waits if that backend is empty. Use `network.enabled: false` for local delivery. -PostgreSQL optionally shares player faction/inventory, Solaris, politics, permits, and bounties. CHOAM state and Guild deadlines remain local files. Player exchange worker assignments are in memory, and shared-mode listing persistence is incomplete. Shared profiles do not synchronize every vanilla player property or plugin tag. This is a gameplay prototype; test multi-backend economics and transfer behavior before a public deployment. +PostgreSQL optionally shares player faction/inventory (including armor/offhand), XP, selected hotbar slot, Solaris, politics, permits, and bounties. See [shared database setup and recovery](network/database/README.md) for deployment, single-backend profile ownership, and unclean-session recovery. CHOAM state and Guild deadlines remain local files. Player exchange worker assignments are in memory, and shared-mode listing persistence is incomplete. Shared profiles do not synchronize every vanilla player property or plugin tag. This is a gameplay prototype; test multi-backend economics and transfer behavior before a public deployment. ## Build and verification diff --git a/SESSION-2.md b/SESSION-2.md index cc395cbd..e18740cf 100644 --- a/SESSION-2.md +++ b/SESSION-2.md @@ -10,7 +10,7 @@ New Arrakis darkstone formations have one to three concentric, sand-topped flat ## Arrakis sightings -Generated spice bloom markers announce when their chunk loads. Admin-placed markers, erupted blooms, sandworm spawns/loads, and worm-death spice fields use the same announcement service. Arrakis receives a lore message with X/Y/Z and a fifteen-minute warning. After fifteen real minutes, the Spacing Guild informs all online players across the proxy. A bloom already announced at those coordinates or a worm with the same UUID does not restart the countdown on chunk reload. +Generated spice bloom markers announce when their chunk loads. Admin-placed markers, erupted blooms, sandworm spawns/loads, and worm-death spice fields use the same announcement service. Arrakis receives a lore message with X/Y/Z and a fifteen-minute warning. After fifteen real minutes, the Vaerkring informs all online players across the proxy. A bloom already announced at those coordinates or a worm with the same UUID does not restart the countdown on chunk reload. Timers and sighting identities persist in `plugins/DuneCore/arrakis-announcements.yml`. Restarting the server preserves deadlines. If no player is connected to the Arrakis backend when a Guild message is due, delivery waits for a player connection. This is required by plugin messaging. Delivery uses the standard BungeeCord `Message` subchannel with recipient `ALL`; Velocity must have `bungee-plugin-message-channel = true`. With DuneCore `network.enabled: false`, the Guild message is delivered locally instead. Install DuneCore alongside DuneTerrain and DuneEss for coordinated announcements. No proxy-side custom plugin is required. diff --git a/control-panel-inventory/README.md b/control-panel-inventory/README.md new file mode 100644 index 00000000..c5661a4d --- /dev/null +++ b/control-panel-inventory/README.md @@ -0,0 +1,59 @@ +# Account inventory and History of sales + +Integrated into the existing account control panel source at website/control-panel/. The server now uses its real session validator and verified site_game_links association. Runtime activation still needs the private PostgreSQL reader configuration and a reviewed deployment. This folder retains the original package's adapter tests, installer and standalone design preview; the final section describes the completed source integration. + +## Layout + +Open `inventory-preview.html` for a self-contained layout preview. It contains explicitly labelled fictional data. Production assets never load demo fixtures. + +The component shows a blocky dummy Minecraft skin wearing the saved helmet, chestplate, leggings and boots; leather armor uses its actual saved dye color. Armor, offhand, backpack, hotbar and XP are readable, and clicking an item shows its name, quantity, enchantment flag and durability. Item glyphs are local stylized drawings, with material names for identification; they are not exact Mojang item textures. No player skin service or external CDN is used. Custom armor trims/elytra geometry are not rendered by the simplified mannequin. + +The second tab is exactly **History of sales**. It shows completed exchange sales with item, quantity, buyer, planet, payment and date. It reads an immutable SQL sales ledger and supports older-page cursors. No pre-update sales can be reconstructed if the old exchange never recorded them. Failed, cancelled and unsold listings are not completed sales. + +Lobby inventories stay separate. Ender chests are world/backend local and are neither synchronized nor displayed. Account inventory is read only and shows the last saved checkpoint, not a live item-transfer interface. + +## Integrate with the real CP server + +1. Obtain the existing CP source checkout. Keep its current HTTPS/session/CSRF/account-link implementation. Install this package's `pg` dependency into that server (`pg` 8.16.3 is declared in package.json). +2. Create a small PostgreSQL pool on the CP server, with a private `DUNE_INVENTORY_DATABASE_URL`, max 3 connections, `connectionTimeoutMillis: 5000` and `idleTimeoutMillis: 30000`. Do not expose the connection string in HTML or JavaScript sent to browsers. It must connect to the same network database as Core and Essentials. +3. Import `createInventoryHandler` and `createSalesHistoryHandler` from `inventory-api.mjs`. Construct both with `{authenticate, verifiedMinecraftUuid, pool}`. `authenticate(request)` must validate the CP's existing server-side session and return its account object with `id`, or null. `verifiedMinecraftUuid(accountId)` must query that account's current, verified `/api/game-link` association on the server, or return null. Use the exact existing CP link schema. Never use a submitted username, UUID, editable profile field or public Mojang lookup as proof of ownership. +4. Mount the two handlers on GET `/api/inventory` and GET `/api/exchange/sales-history` in the existing request router. They consume Web `Request` objects and return Web `Response` objects, or null for unrelated paths. Preserve cookies and return their status and headers. They reject writes, foreign-UUID parameters and unsupported snapshot versions, bind SQL parameters, and return private `no-store` results. Do not add public CORS or caching. +5. Run `python3 install-assets.py /absolute/path/to/cp/public`. It copies the component and adds its stylesheet/module references to the existing account HTML, preserving a source backup. The mounting module observes the current dashboard sign-in visibility and verified identity display, clears private data on sign-out/link changes and leaves rewards/security/staff features intact. No edits to panel.js are required. +6. Deploy that reviewed CP checkout through its existing hosting workflow. Verify sign-in, link/unlink, inventory, sales, logout, and account A/B isolation in the browser. The prepared assets do not go live by simply adding this folder to MC. + +## Minimum database grants + +After Core and Essentials have created their tables, create a separate non-superuser reader role in an administrator psql session. Generate the password privately, then run: + +```sql +\prompt -s 'New control-panel reader password: ' cp_password +CREATE ROLE dune_cp LOGIN PASSWORD :'cp_password'; +GRANT CONNECT ON DATABASE dunerealms TO dune_cp; +GRANT USAGE ON SCHEMA public TO dune_cp; +GRANT SELECT(uuid,inventory_view,inventory_updated_at,session_open) ON dune_players TO dune_cp; +GRANT SELECT(id,listing_id,seller,material,display_name,quantity,unit_price,total_price,origin,buyer_name,sold_at) ON dune_exchange_sales TO dune_cp; +``` + +This reader cannot read raw Bukkit inventory blobs, wallet tables, modify inventories or perform purchases. The authenticated application still has to scope each query to the verified account UUID; grants alone do not enforce per-account visibility. + +## Checks + +`node --test tests/*.test.mjs` exercises authentication, verified-link ownership, private caching, input rejection, SQL outages, empty snapshots and sales pagination. Live CP integration is pending access to its source and deployment environment. + +## Existing public website market feed + +`market-bridge.mjs` completes the missing read-only server-to-server listings bridge for `website/worker/exchange-api.mjs`. Mount its `createMarketBridge({pool,readToken})` result at `/internal/exchange/listings` on the CP server. Generate a separate private token (at least 32 characters), set that same secret as the website's `EXCHANGE_READ_TOKEN`, and set its `EXCHANGE_LISTINGS_URL` to `https://cp.dunerealms.com/internal/exchange/listings`. Keep the token out of browser code. The bridge exposes only the latest 500 public offer fields, never serialized item payloads, UUIDs, wallets or account inventories. Purchases remain in-game with confirmation. + +Add the following grant for the CP reader if using this bridge: + +```sql +GRANT SELECT(id,material,category,origin,seller_name,quantity,price) ON dune_exchange_listings TO dune_cp; +``` + +## Integrated account inventory (27 October 2026) + +The supplied Inventory-Exchange-Account ZIP is merged into the current source, including verified account inventory and History of sales routes in website/control-panel/server.mjs. Runtime adapters are in website/control-panel/inventory/, and themed assets are in website/control-panel/public/inventory/. This package's API entry files re-export those canonical runtime adapters; its tests exercise the same implementation. install-assets.py now reads the canonical production asset directory. + +The existing site_sessions and site_game_links tables provide authentication and verified ownership. DUNE_INVENTORY_DATABASE_URL is optional and must be a private PostgreSQL reader connection with the column grants above. Without it, linked players receive an honest unavailable state; no demo inventory is returned. EXCHANGE_READ_TOKEN optionally enables the private listings bridge. Neither database credentials nor a live market feed are activated by committing this source. Existing rewards, security and staff controls are preserved. + +The original standalone preview is an explicitly fictional layout reference. Production currency and planet labels use the current Dutch-inspired names and Dunemarks. In-game code targets Paper 1.21.8; the currently deployed 1.21.4 binaries are not replaced by this integration. diff --git a/control-panel-inventory/install-assets.py b/control-panel-inventory/install-assets.py new file mode 100644 index 00000000..5bce74cf --- /dev/null +++ b/control-panel-inventory/install-assets.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +"""Install account-page assets into an existing CP source checkout; does not deploy or change auth.""" +import argparse, shutil +from pathlib import Path +parser=argparse.ArgumentParser() +parser.add_argument('public_directory',type=Path) +a=parser.parse_args();target=a.public_directory.resolve();index=target/'index.html' +if not index.is_file():parser.error('The supplied directory must contain the existing control panel index.html') +html=index.read_text() +if 'id="dashboard"' not in html or 'id="game"' not in html:parser.error('Expected existing account dashboard and game-link sections were not found') +if not index.with_suffix('.html.before-inventory').exists():shutil.copy2(index,index.with_suffix('.html.before-inventory')) +shutil.copytree(Path(__file__).resolve().parents[1]/'website'/'control-panel'/'public'/'inventory',target/'inventory',dirs_exist_ok=True) +css='' +js='' +if css not in html:html=html.replace('',css+'',1) +if js not in html:html=html.replace('',js+'',1) +index.write_text(html) +print('Account assets installed. Wire the authenticated server routes before deploying this checkout.') diff --git a/control-panel-inventory/inventory-api.mjs b/control-panel-inventory/inventory-api.mjs new file mode 100644 index 00000000..f6577aec --- /dev/null +++ b/control-panel-inventory/inventory-api.mjs @@ -0,0 +1 @@ +export * from '../website/control-panel/inventory/inventory-api.mjs'; diff --git a/control-panel-inventory/inventory-preview.html b/control-panel-inventory/inventory-preview.html new file mode 100644 index 00000000..7639bce7 --- /dev/null +++ b/control-panel-inventory/inventory-preview.html @@ -0,0 +1,46 @@ +DuneRealms account inventory — layout preview

DUNEREALMS.COM / YOUR ACCOUNT

Layout preview with fictional inventory and sales. No account or server connection.

\ No newline at end of file diff --git a/control-panel-inventory/market-bridge.mjs b/control-panel-inventory/market-bridge.mjs new file mode 100644 index 00000000..d08e82e9 --- /dev/null +++ b/control-panel-inventory/market-bridge.mjs @@ -0,0 +1 @@ +export * from '../website/control-panel/inventory/market-bridge.mjs'; diff --git a/control-panel-inventory/package.json b/control-panel-inventory/package.json new file mode 100644 index 00000000..27384a94 --- /dev/null +++ b/control-panel-inventory/package.json @@ -0,0 +1 @@ +{"name":"dunerealms-control-panel-inventory","private":true,"type":"module","scripts":{"test":"node --test tests/*.test.mjs"},"dependencies":{"pg":"8.16.3"}} diff --git a/control-panel-inventory/tests/inventory-api.test.mjs b/control-panel-inventory/tests/inventory-api.test.mjs new file mode 100644 index 00000000..53abcdd3 --- /dev/null +++ b/control-panel-inventory/tests/inventory-api.test.mjs @@ -0,0 +1,50 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {createInventoryHandler} from '../inventory-api.mjs'; +const uuid='00000000-0000-4000-8000-000000000001'; +function setup({user={id:'account-a'},link=uuid,rows=[],fail=false}={}){ + const queries=[],links=[]; + return {queries,links,handler:createInventoryHandler({authenticate:async()=>user, + verifiedMinecraftUuid:async id=>{links.push(id);return link;}, + pool:{query:async q=>{queries.push(q);if(fail)throw Error('password=SECRET');return {rows};}},logger:{error(){}}})}; +} +const req=(suffix='',method='GET')=>new Request('https://cp.dunerealms.com/api/inventory'+suffix,{method}); +test('requires authentication before resolving a link or querying SQL',async()=>{ + const s=setup({user:null}),r=await s.handler(req());assert.equal(r.status,401);assert.equal(s.links.length,0);assert.equal(s.queries.length,0); +}); +test('unlinked accounts do not query game state',async()=>{ + const s=setup({link:null}),r=await s.handler(req());assert.equal((await r.json()).status,'unlinked');assert.equal(s.queries.length,0); +}); +test('only the authenticated verified UUID is queried, with private no-store response',async()=>{ + const snapshot={version:1,hotbar:[],inventory:[]};const s=setup({rows:[{inventory_view:snapshot,session_open:true,inventory_updated_at:'2026-10-27T10:00:00Z'}]}); + const r=await s.handler(req());assert.equal(r.status,200);assert.deepEqual(s.links,['account-a']);assert.deepEqual(s.queries[0].values,[uuid]);assert.match(r.headers.get('Cache-Control'),/no-store/);assert.equal(r.headers.get('Vary'),'Cookie');assert.deepEqual((await r.json()).snapshot,snapshot); +}); +test('cannot request another player by UUID or arbitrary parameters',async()=>{ + const s=setup();assert.equal((await s.handler(req('?uuid='+uuid))).status,400);assert.equal(s.queries.length,0); +}); +test('rejects writes and ignores unrelated endpoints',async()=>{ + const s=setup();assert.equal((await s.handler(req('','POST'))).status,405);assert.equal(await s.handler(new Request('https://cp.dunerealms.com/api/other')),null);assert.equal(s.queries.length,0); +}); +test('missing snapshots have an honest empty state',async()=>{ + const s=setup();assert.equal((await (await s.handler(req())).json()).status,'empty'); +}); +test('outage errors do not disclose SQL credentials',async()=>{ + const s=setup({fail:true}),r=await s.handler(req());assert.equal(r.status,503);assert.doesNotMatch(await r.text(),/SECRET|password/); +}); +test('invalid verified link and unsupported version fail closed',async()=>{ + const s=setup({link:'not-uuid'});assert.equal((await s.handler(req())).status,503);assert.equal(s.queries.length,0); + const t=setup({rows:[{inventory_view:{version:2}}]});assert.equal((await t.handler(req())).status,503); +}); + +import {createSalesHistoryHandler} from '../inventory-api.mjs'; +test('sales history is paginated and belongs only to the verified seller',async()=>{ + const queries=[];const rows=Array.from({length:21},(_,i)=>({id:String(100-i),display_name:'Spice',quantity:1})); + const handler=createSalesHistoryHandler({authenticate:async()=>({id:'owner'}),verifiedMinecraftUuid:async id=>{assert.equal(id,'owner');return uuid;},pool:{query:async q=>{queries.push(q);return{rows};}}}); + const r=await handler(new Request('https://cp.dunerealms.com/api/exchange/sales-history?before=200')); + const data=await r.json();assert.equal(data.sales.length,20);assert.equal(data.nextCursor,'81');assert.deepEqual(queries[0].values,[uuid,'200']);assert.match(queries[0].text,/WHERE seller=\$1/);assert.match(r.headers.get('Cache-Control'),/no-store/); + for(const suffix of ['?uuid='+uuid,'?before=-1','?before=1&before=2','?before=9999999999999999999'])assert.equal((await handler(new Request('https://cp.dunerealms.com/api/exchange/sales-history'+suffix))).status,400); +}); +test('sales history refuses unauthenticated and unlinked account SQL reads',async()=>{ + for(const user of [null,{id:'owner'}]){let calls=0;const handler=createSalesHistoryHandler({authenticate:async()=>user,verifiedMinecraftUuid:async()=>null,pool:{query:async()=>{calls++;}}}); + const r=await handler(new Request('https://cp.dunerealms.com/api/exchange/sales-history'));assert.equal(r.status,user?200:401);assert.equal(calls,0);} +}); diff --git a/control-panel-inventory/tests/market-bridge.test.mjs b/control-panel-inventory/tests/market-bridge.test.mjs new file mode 100644 index 00000000..d7f0fde5 --- /dev/null +++ b/control-panel-inventory/tests/market-bridge.test.mjs @@ -0,0 +1,6 @@ +import {test} from 'node:test';import assert from 'node:assert/strict';import {createMarketBridge} from '../market-bridge.mjs'; +test('market bridge requires a private bearer before reading listings',async()=>{let calls=0;const h=createMarketBridge({readToken:'x'.repeat(40),pool:{query:async()=>{calls++;return{rows:[{id:'1',seller:'Trader',quantity:2,price:'25.00'}]};}}}); + const url='https://cp.dunerealms.com/internal/exchange/listings';assert.equal((await h(new Request(url))).status,401);assert.equal(calls,0); + const r=await h(new Request(url,{headers:{Authorization:'Bearer '+'x'.repeat(40)}}));assert.equal((await r.json()).listings.length,1);assert.equal(calls,1);assert.match(r.headers.get('Cache-Control'),/no-store/); +}); +test('market bridge refuses weak configuration',()=>assert.throws(()=>createMarketBridge({readToken:'short'}))); diff --git a/docs/ACCOUNT-CONTROL-PANEL-HANDOFF.md b/docs/ACCOUNT-CONTROL-PANEL-HANDOFF.md new file mode 100644 index 00000000..97c90ee9 --- /dev/null +++ b/docs/ACCOUNT-CONTROL-PANEL-HANDOFF.md @@ -0,0 +1,69 @@ +# Account control panel — 27 October 2026 + +## Published sites + +- Standalone account site: https://cp.dunerealms.com/ +- Embedded login, registration and account panel: https://www.dunerealms.com/account.html +- Monthly community support: https://www.dunerealms.com/donate.html +- Dutch naming explanation: https://www.dunerealms.com/wiki.html and the first manual chapter. +- Planet sigils: https://www.dunerealms.com/arrakis.html#route-sigils and the currency/travel manual chapter. +- Imperial artwork and Landsraad appointments: https://www.dunerealms.com/diplomacy.html + +The panel is a separate Node application and HTTPS host, sharing the existing website account database. Sessions are host-specific; accounts and passwords are shared. This is not a hosting control panel. + +## Accounts and rewards + +- Registration cannot grant staff access. Passwords use salted scrypt; session cookies are Secure, HttpOnly and host-only. +- The owner staff account was provisioned separately. Its random credentials are in the private local `output/DuneRealms-admin-login.txt`; no password is included in this repository or public site. Change it after signing in. +- Account linking uses a private, single-use 128-bit code, expires after ten minutes, and must be entered with `/linkwebsite CODE` by the actual game player. The game bridge authenticates independently over HTTPS. +- Minecraft UUID is the permanent eligibility and claim key. The first verified link time survives unlinking, website account changes and player renames. +- Personal codes are generated only for goals reached after that first verified link. There is no personal-code backfill. Linking alone does not release currency. +- Staff create a monthly target and fixed equal reward. Verified totals can unlock it during that month, in Europe/Brussels time. Staff changes are audited. Targets and reward amounts cannot be casually edited after creation. +- Public codes remain equally available to all players, including players without a website link. Personal and public codes use one UUID/month claim record. +- `/communitycode CODE` prepares a receipt, then the game durably credits the balance and claim together. Only a game acknowledgement marks the website code used. Unacknowledged receipts retry after restart; used codes leave Available and appear in History. +- Codes have no expiry or shared redemption cap. Currency cannot be cashed out or redeemed for real-world value. +- No payment provider, live funding target or currency reward has been activated. Verified totals are manually recorded, not automatically inferred from a payment provider. + +## Deployment + +Website release: `/home/dunerealms/apps/dunerealms/releases/20261027-leto-zero`; `current` points there. Main application: `dunerealms-web`; account application: `dunerealms-account-panel`, localhost port 3003. Forgejo uses port 3001 and was left running. + +The `cp` CNAME resolves to the existing host. Its certificate covers `cp.dunerealms.com`, `dunerealms.com` and `www.dunerealms.com`; public HTTPS and HTTP-to-HTTPS redirects were checked without disabling certificate verification. The cp vhost shares the CloudPanel-managed certificate. Its ACME location uses the main site's document root. The panel permits framing only by the two main-site origins; the main site explicitly permits the cp frame. + +The owner login, staff authorization, forged-header rejection, empty reward state, logout, embedded rendering and registration-mode UI were verified live. No fake campaign, test donation or live currency credit was created. + +The gameplay backend remains Paper 1.21.4. Compatible DuneEss, DuneCore and DuneNPC binaries come from the separate `dunemarks-live-1.21.4` checkout. It was backed up and restarted with zero players. The proxy and lobby stayed running. The account bridge secret is kept in operator-only configuration, never source or public assets. + +Resource pack: `/downloads/Dunemarks-ResourcePack-1.21.4.zip`, SHA1 `f9470108e9cff93231968e6b8b2d99293e62fce2`. Pack acceptance is optional; Java clients declining it see material fallbacks. Bedrock texture rendering and in-client menu appearance have not been verified. + +The active account/reward bridge is installed on the gameplay backend. Do not deploy independent local currency ledgers on multiple redemption backends: concurrent cross-backend redemption requires the shared PostgreSQL ledger. Its existing economy/market connection warning is separate from the website account database. + +The main checkout also contains the 1.21.8 source implementation, retaining native menu support. Do not deploy its binaries onto Paper 1.21.4. The source is included in the DuneGit inventory/account integration. Server publication still uses the saved deployment packages; new inventory runtime activation is documented separately in INVENTORY-EXCHANGE-INTEGRATION.md. + +## Artwork and wording + +Public houses: Aerdrecht, Harkveen, Korenholt, Oordwijk, Vrijduin. Travel: Vaerkring; exchange: Koopkring; water sellers: Welvaarders. The Emperor's spice and water offices are presented as **Landsraad appointments**, with Specerhuis and Welvaart House office labels. Existing faction/world IDs, command arguments, ballots and balances remain compatible. Old binaries, imported lobby/world text and technical identifiers may still contain earlier names; this is not a claim of a full saved-world migration. + +The five route sigils were authored as SVGs, with angular letter rings encoding the Dutch-inspired destination names, retaining their original-name roots. GUI textures are derived from those same SVGs. The imperial banner was generated with the built-in image tool; its exact prompt is saved beside the artwork documentation. The rights disclaimer does not claim that renaming or attribution clears underlying IP. + +## Tomorrow's checks + +1. Open the private login file, sign in on cp, and change the password in Account security. +2. Generate a private link command, enter it on the gameplay backend, and refresh the panel. Check the exact Minecraft UUID. +3. Confirm no old personal rewards appear. No rewards should exist before an actual funded goal is configured and reached. +4. Accept the Java resource pack; open travel and Landsraad menus. Check the sigils, office seals, back button and unchanged travel/appointment rules. +5. Once a real goal is met, claim its reward, confirm the balance and History entry, then retry both its personal and public codes. Neither may issue a second credit. + +Automated checks: 54 website tests; 27 compatible DuneEss/DuneCore checks; both target-version game builds; local ledger restart, duplicate-receipt, failed-write and acknowledgement tests. Client interaction remains a manual check, not a completed test. + +## Vaerkring note series and theme update + +Five full front/reverse designs and transparent GUI icons: 1 (Stilgar), 5 (Aliah), 100 (Mira Vesk), 1,000 (Ghanima), 5,000 (Leto and an imagined victory over House Harkonnen). Every note reads Vaerkring Reserve and uses the newly designed crown/sun/dunes imperial seal. The 0-Dunemark Leto II search tribute is website/design-only: no game item model, GUI denomination, balance value or resource-pack entry. It is explicitly commemorative and has no cash value. + +The character editions are an explicit operator-requested exception to the earlier original-character-only artwork policy. The wiki and IP risk review disclose this; they are not cleared merchandise. Exact built-in imagegen prompts and PNG masters are in docs/artwork/dunemarks/; production WebP and 64px/128px transparent icons are in website/web/assets/. + +Main account page, standalone control panel, login/register, dashboard and staff forms share the site artwork, fonts, parchment and gold/teal theme. Full-note artwork uses natural image proportions; the preview icon selector is scoped separately at 64px to prevent accidental full-column enlargement. Browser measurements confirmed all five previews are 64 by 64. + +The Dutch explanation appears both on wiki.html#dutch-inspired-names and the first manual chapter. It describes Landsraad's Dutch-language connection and broader Germanic parallels, rather than claiming an exclusively Dutch origin. It cites a linguistic study and retains the no-licence/no-endorsement wording. + +Latest gameplay binaries: DuneEss SHA256 bec211ed8807d841cc997e1fce264af497ceea6718fda563b62bf612de9f0dad; DuneCore SHA256 8df87b13122a28a932913cc6e11b1fb5a1ce74efbf180f1bc54dcd04d613701b. Startup completed in 35.524 seconds without ERROR/Exception entries. Proxy, lobby and gameplay services were active after deployment. The public resource-pack download SHA1 matches the configured hash above. No zero-note game changes were deployed. diff --git a/docs/INVENTORY-EXCHANGE-IMPORT-NOTES.md b/docs/INVENTORY-EXCHANGE-IMPORT-NOTES.md new file mode 100644 index 00000000..b6ae5250 --- /dev/null +++ b/docs/INVENTORY-EXCHANGE-IMPORT-NOTES.md @@ -0,0 +1,90 @@ +Imported handoff from the supplied ZIP. This records the package's original state; current integration and deployment status is in INVENTORY-EXCHANGE-INTEGRATION.md. The CP source is now available and wired locally; the package's statement that CP integration is missing is historical. + +# DuneRealms — shared planetary inventory, exchange and account UI handoff + +Prepared 27 October 2026. This package contains implemented source plus compiled Core/Essentials JARs. It does not deploy a running database, Minecraft server or cp.dunerealms.com. + +## Repository and source state + +- Repository read: https://www.dunerealms.com/git/unimatrix/MC +- Base main commit: `73e1bc8b75608b77280c6d957bf590be3f3ed8b6`. +- Local checkout: `/workspace/scratch/54b8ff792ef6/MC`. +- Changes are local, packaged in this ZIP, and have not been pushed to DuneGit. +- The separate MC-inventory-sharing repository was inspected; its main branch is an older copy of this project. This package implements inventory ownership inside DuneCore; do not install a competing inventory sync plugin. +- Source package includes plugin modules, shared GUI code, website source/assets, scripts/configurations and text documentation. Existing large generated manual/artwork exports and pre-generated world archives are omitted. Keep the current worlds and resource/data files on production; this is not a replacement server directory. + +## Requirements described by the supplied package + +1. Shared inventory is for the five planetary servers only: Arrakis, Giedi Prime, Kaitain, Caladan and Sigma Draconis IV. +2. Lobby inventory is separate and must never be loaded from or saved to the planetary shared inventory. +3. Ender chests are local to each world/backend. Do not synchronize, copy into shared SQL or expose them in the account inventory display. +4. Account page on cp.dunerealms.com should display saved planetary inventory using a nice Minecraft-style layout and a dummy skin wearing the saved armor. +5. Show completed exchange items under the exact label **History of sales**. +6. Finish exchange coding, package the code/JARs and provide a handoff. No production deployment or DuneGit push was performed in this session. + +## Implemented + +### Core 1.0.12 + +SharedDatabase loads inventory/hotbar/armor/offhand, faction, XP level/progress/total and selected hotbar slot. Existing serialized inventories remain readable. It never calls ender-chest accessors. Existing unused legacy SQL ender-chest columns, if any, are left untouched. + +Only known planetary network.local-planet identifiers enable profile loading. Lobby and spacing_guild are excluded. Keep this setting correct on each backend; planet identifiers with hyphens are normalized to underscores. + +Each online planetary player owns a dedicated PostgreSQL connection and session advisory lock. Concurrent/early transfer loads are rejected. Failed loads cannot write a stale local inventory on quit. Durable session_open markers block automatic login after a process/connection loss until an administrator reconciles the checkpoint. Controlled quit closes the open inventory, writes the full checkpoint, clears the marker, then releases the connection. Autosave defaults to 60 seconds (minimum 10). Failed SQL saves attempt a timestamped local recovery YAML snapshot. + +InventoryWebSnapshot writes a safe JSONB display projection and timestamp in the same SQL checkpoint, with material/name/quantity, enchantment flag, durability and leather dye color. It contains no ender chest data or Bukkit serialization for the browser to decode. + +transactNetworkInventory coordinates exchange SQL and the resulting authoritative inventory checkpoint on the same owned connection. Ordinary transaction failures restore the prior in-memory inventory. Unknown commit outcomes quarantine and disconnect the profile without an ordinary quit save over the evidence. + +### Essentials 1.0.4 / exchange + +Existing native Java/Bedrock menus, held-item listing, purchase confirmation, owner cancellation/reclaim, filters, pagination, inventory capacity checks and admin inspection are retained. + +Actual trades require a loaded planetary Core profile. Listing escrow, buyer debit, seller credit, stock changes and the inventory checkpoint commit together. The bound ExchangeStore cannot independently commit or close Core's transaction. Delivery overflow aborts the transaction; it does not drop items into the world. + +Every completed unit purchase also records dune_exchange_sales: listing ID, seller/buyer identities and names, material/display name, quantity, exact unit/total price, planet and timestamp. Failures and cancellations create no sale. Existing historic sales were not previously recorded and cannot be backfilled from missing data. + +Shared economy deposits/withdrawals now use SQL arithmetic, avoiding stale read/overwrite races with exchange payments. Configured shared mode does not fall back to local cached wallets during SQL failures. This does not make all other Core/gameplay actions atomic with the economy; review those separately before public launch. + +### Database deployment + +network/database provides a PostgreSQL 17 Compose template, non-superuser application role and setup.sh with generated private credentials, persistent volume, localhost-default listener and health check. The guide explains private networking, backend configuration, migration, capacity, backups and manual recovery. The scripts have not been run against the user's server. Migrations are additive and preserve existing records. + +### Account inventory and sales UI + +control-panel-inventory contains the account UI, self-contained inventory-preview.html, safe authenticated API adapters, read-only market bridge, public asset installer and tests. The dark teal/gold layout has a local block-style dummy mannequin wearing saved armor, equipment/offhand slots, backpack/hotbar grid, item inspection, XP and a **History of sales** tab. No lobby or ender chest items appear. Item icons are stylized local vector glyphs, not exact Minecraft textures; the mannequin supports base armor shapes/colors but not exact trims, resource-pack models or elytra geometry. + +Account APIs resolve the signed-in CP account's verified Minecraft UUID server-side. Visitors cannot supply another UUID. Responses are private/no-store. Queries are parameterized, bounded and read only. Sales use seller-only keyset pagination. The optional private market bridge supplies sanitized live listings to the existing website gateway with a separate server-to-server bearer token; purchases remain in-game. + +## Critical remaining CP integration work + +The public cp.dunerealms.com page and panel.js were inspected. They already implement verified /api/game-link associations, account sessions and rewards. The real CP server source, verified-link schema and deployment environment are NOT present in MC main, the public beta/cloudpanel branches or the older MC-inventory-sharing main copy. Personal Context did not provide another source location. + +Do not claim this feature is live. Obtain the current CP source from its actual owner/workspace. Follow control-panel-inventory/README.md to wire the provided handlers into the existing server's session validator and verified-link resolver. Preserve existing account/reward/security/staff features. Install public assets using install-assets.py, grant a separate CP reader only the documented columns, deploy through the existing CP workflow, and test two-account isolation and link/unlink/logout behavior. Never replace verified linking with an editable profile name or guess a link table. + +For the existing public website live exchange, mount the supplied private bridge, then configure its EXCHANGE_LISTINGS_URL and EXCHANGE_READ_TOKEN secrets. Without that runtime configuration the existing website intentionally keeps labelled demo listings. This session did not change live settings. + +## Build and validation completed + +Target: Java 21 / Paper 1.21.8 as pinned by the repository. No unverified change to a newer Paper API was made. + +- Core: `gradle build` successful, **21 tests passed** (mocked JDBC/Paper), including failed/dirty loads, ownership, snapshots, transaction rollback and unknown commit quarantine. +- Essentials: `gradle build` successful, **21 tests passed**. Exchange SQL tests use H2 in PostgreSQL compatibility mode and cover last-item concurrency, wallet/stock rollback, ownership, sales history and rollback of externally owned transactions. This is not a live PostgreSQL test. +- Account integration: `node --test tests/*.test.mjs`, **12 tests passed**, including verified ownership, no-store, parameter rejection, outage handling, sales pagination and the private market bridge. +- Layout: JSDOM checked 41 equipment/inventory buttons, the armor mannequin, item selection, History of sales navigation and zero runtime errors with the demo fixture. A real-browser visual review was not available in this environment. +- Asset installer: tested idempotence and preservation of the original HTML backup against the observed CP page. +- Shell syntax, YAML parsing, Python compilation, JavaScript syntax and `git diff --check` passed. + +## Files and installation + +The `plugins/` directory in this ZIP contains the built `DuneRealms-Core.jar` and `DuneRealms-Essentials.jar`. Replace both together with all planetary servers stopped. Preserve existing worlds, player data, config files, Vault, terrain/NPC/lobby plugins and proxy settings. Do not install the planetary Core/profile stack in place of the selection lobby plugin. + +Before enabling shared mode, select one authoritative first-login backend for existing inventories. A player with no SQL snapshot adopts that backend's inventory; inventories from other backend player files are not merged automatically. Back up/archive alternatives. Configure the same database on all planets before DuneEss starts; it reads Core's config from disk. + +Run fresh database setup only on the intended database host. For an existing database keep its data/credentials and use the plugin's additive migrations. Configure private routing/firewall to allow only backend/CP hosts. Never expose PostgreSQL publicly, overwrite configs with defaults or clear all unclean-session markers. + +## Staging acceptance before public use + +Test two real planetary backends with PostgreSQL, Velocity and the same player UUIDs. Verify exact custom item metadata/quantities, armor/offhand, XP, listing escrow, purchase/reclaim, wallets, sales history, transfers and process/SQL failure paths. Verify the lobby inventory is different and unchanged; verify each planet keeps different local ender contents. Check Java, Bedrock/Floodgate and ViaVersion clients. Review synchronous SQL tick time and PostgreSQL connection capacity under expected concurrency. SQL profile locks require direct/session-compatible connections; do not use transaction-pooled PgBouncer. + +Known scope limits: general non-exchange item/container mutations still depend on checkpoints and manual crash reconciliation; politics still uses its existing shared YAML snapshot and is not normalized by this change. Health/hunger/position/advancements/other plugin data are not synchronized. Fast transfers may need a reconnect while the source backend finishes its final save. Autosaving restores temporarily hidden Ordos armor, which can shorten the hidden-armor portion of Shadow Step. Per-world ender isolation assumes the intended one-planet-per-backend network; vanilla worlds within a single backend still follow that backend's existing ender-chest behavior. diff --git a/docs/INVENTORY-EXCHANGE-INTEGRATION.md b/docs/INVENTORY-EXCHANGE-INTEGRATION.md new file mode 100644 index 00000000..d42f786b --- /dev/null +++ b/docs/INVENTORY-EXCHANGE-INTEGRATION.md @@ -0,0 +1,22 @@ +# Inventory, exchange and account integration + +Prepared 27 October 2026. Imported DuneRealms-Inventory-Exchange-Account.zip (SHA256 666db85847308b5f24fb461d466df86de6d2a38b0df6d59d163573bae70b7b99), based on DuneGit main 73e1bc8b75608b77280c6d957bf590be3f3ed8b6. + +## Merged behavior + +- Planetary inventory ownership, dedicated PostgreSQL session locks, durable unclean-session markers, armor/offhand and XP checkpoints, safe browser projections. Lobby and ender chests remain separate. +- Core-owned exchange transactions commit inventory, escrow, wallet changes and completed sales together. SQL arithmetic preserves concurrent wallet updates. Existing durable monthly community rewards and UUID/month receipts are retained. +- CP inventory and exact History of sales UI are wired into the real account server. It validates the existing host session and resolves the current verified UUID from site_game_links. The client cannot choose a UUID. Unlink/logout and two-account isolation are covered by integration tests. +- Canonical runtime modules: website/control-panel/inventory/. Canonical UI: website/control-panel/public/inventory/. The original package API entry points re-export the canonical modules so its tests exercise production code. The asset installer reads those canonical assets. +- Current Vaerkring/Dunemarks names, planet labels, site/account theme, notes/seal, disclaimer, CAPTCHA contact, rewards and staff controls are preserved. Existing internal world/faction/model identifiers remain compatible. +- An explicitly configured but incomplete shared database cannot silently use a second local wallet. + +## Validation and publication scope + +Core 1.0.12 and Essentials 1.0.4 target Java 21 / Paper 1.21.8. Rebuilt JARs come from reviewed merged source, not the ZIP's precompiled plugins. The live server remains on its existing 1.21.4 compatibility binaries. No database setup, migration, inventory import or new game deployment is performed by this source integration. + +Website build/tests, package API tests, merged Core/Essentials tests and a local browser review cover the integration. The browser uses clearly fictional local fixture data; it is not evidence of live inventory availability. PostgreSQL, multi-backend transfer/crash behavior and real Java/Bedrock clients still need staging acceptance. + +For activation, configure DUNE_INVENTORY_DATABASE_URL with the separate column-limited reader described in control-panel-inventory/README.md. It is optional: a linked account receives an honest unavailable response while unconfigured. EXCHANGE_READ_TOKEN optionally protects the private server-to-server market bridge; the main website requires its existing EXCHANGE_LISTINGS_URL setting. No production secret is committed. + +The original supplied handoff is preserved as INVENTORY-EXCHANGE-IMPORT-NOTES.md. Its missing-CP-source statements describe the original package, before this integration. Source publication is a normal DuneGit push, not a force push or an automatic live rollout. diff --git a/docs/IP-RISK-REVIEW.md b/docs/IP-RISK-REVIEW.md new file mode 100644 index 00000000..2858a625 --- /dev/null +++ b/docs/IP-RISK-REVIEW.md @@ -0,0 +1,58 @@ +# Website naming and IP exposure review + +Review date: 26 October 2026; publication status updated 27 October 2026. This is an evidence-based editorial assessment, not legal clearance or an estimate of litigation probability. Applicable jurisdictions, licences, commercial activity and rights-holder enforcement intentions have not been established. + +## Source and publication + +Source: https://www.dunerealms.com/git/unimatrix/MC, main at 73e1bc8b75608b77280c6d957bf590be3f3ed8b6. + +Changes are in the separate local checkout `dunerealms-story-update`. No synced `sources/` files or other existing project checkouts were edited. The website was deployed and verified on 27 October 2026 as release 20261027-manual-disclaimer. No source push to DuneGit has been performed. + +## Changes assessed + +- Removed the six-essay journal, index, data, graphics metadata, browser code, styles and generator, together with navigation and public contribution-record references. The build no longer regenerates these routes. +- The three requested novel characters appeared only in that removed journal. They were not globally relabelled inside a retained retelling. A separate original supporting outline now features Tavren Sile, Mira Vesk and Archivist Elian Voss investigating conflicting cargo records. +- Public website labels now use the original proposals recorded in `PUBLIC-NAMES.json`. This covers static pages, the searchable manual, accessible image labels, SVG text, faction panels, market labels, world-status names and dynamic feed presentation. +- The visible site brand is `dunerealms.com`; spice is retained at the owner's explicit request. +- Added an unofficial-project notice and the operator contact `unimatrix@dunerealms.com` to every generated public page and the custom-host login page. +- Added the requested comparison wiki. Legacy terminology remains intentionally in its clearly labelled comparison column, also included as the first manual chapter, not as current public faction or planet labels. +- Replaced direct legacy manual PDF download links with the current web manual. Historical PDFs and prior plugin releases still exist in the repository and external distribution history. + +## Remaining concerns + +| Area | Assessment after the local changes | Reason | +| --- | --- | --- | +| Website retelling of the novels | Reduced substantially within the edited site | The journal and its build inputs are removed; the new outline is about unrelated adults and a cargo-record dispute. | +| Current faction and planet labels | Reduced direct naming overlap | Public labels are replaced. The new proposals have not received a comprehensive trademark clearance search. | +| Brand and overall association | Material residual concern | The owner retained the Dune-containing domain, spice and a recognisable desert-resource/faction/creature theme. Renaming does not establish that the overall expression is independent or licensed. | +| Artwork, heraldry and textures | Unresolved | Existing illustrations and raster assets were not replaced or given a provenance/licensing audit. Updated captions do not change ownership of an image. | +| Game plugins, saved worlds and old releases | Material residual concern outside the website rename | Persistent IDs, command arguments, plugin artifact filenames, binaries, source histories, old documentation and previously distributed PDFs retain earlier names. They need a separately planned game-side migration and distribution audit if the intention is to rebrand the actual server too. | +| Comparison wiki | Limited contextual use, not a clearance | Short source names identify the comparison; no novel passages are reproduced. Whether a particular use is lawful depends on context and jurisdiction. | +| Disclaimer | Helps explain independence; no licence | It addresses apparent affiliation and identifies a contact. It does not remove copyright or trademark rights or guarantee Minecraft policy compliance. | +| Monetary exposure | Not quantified | There is no evidential basis here for a percentage, damages amount or enforcement prediction. Revenue, permissions, distribution and jurisdiction would matter. | + +Overall: these edits reduce direct copying and naming overlap in the website, but do **not** justify describing the project as legally cleared or low risk. The most substantial unresolved areas are the retained brand/overall presentation, asset provenance, and the unchanged game/distribution materials. No conclusion about a particular live trademark registration was reached. + +## Scan scope and exceptions + +Checked tracked text sources in the current repository before editing, then checked public HTML, JSON, browser scripts, SVG text, the built Worker and custom-host labels. Runtime checks cover retired routes and current pages. The original character names and retired journal terminology no longer occur in public content. Old setting names remain deliberately in the comparison wiki, compatibility label maps, filenames/anchors, API identifiers and accurate command examples. Historical repository documentation and game sources remain reference/compatibility material; binaries, raster image text and all third-party sites were not exhaustively audited. + +## Legal sources + +- [U.S. Copyright Office Circular 33](https://www.copyright.gov/circs/circ33.pdf): individual names and short phrases are generally not copyrightable; trademark protection is a separate issue. +- [U.S. Copyright Office Circular 14](https://www.copyright.gov/circs/circ14.pdf): original additions do not acquire rights in underlying protected material; unauthorised adaptations may infringe. +- [USPTO: likelihood of confusion](https://www.uspto.gov/trademarks/search/likelihood-confusion): similarity and related goods/services matter to source confusion. +- [Minecraft Usage Guidelines](https://www.minecraft.net/en-us/usage-guidelines): require a prominent independence notice and identifiable responsibility/contact; they do not license someone else's fictional universe. +- [Official Dune overview](https://dunenovels.com/dune/): source context for the wiki's desert-setting and spice comparison. + +These are background sources, primarily U.S. copyright/trademark summaries, not a jurisdiction-specific legal opinion. + +Publication follow-up: the operator contact is now revealed only after self-hosted ALTCHA verification. Public HTML and static browser code do not contain the plain address. This protects against basic harvesting, not all automated solving or spam. Contact access controls do not affect the IP assessment above. + +## 2026-10-27 commemorative note series update + +At the operator's request the 1, 5, 1,000 and 5,000 Dunemark designs now explicitly portray Stilgar, Aliah, Ghanima and Leto as Minecraft-style fan characters. The 5,000 reverse imagines a victory over House Harkonnen. The 100 retains original character Mira Vesk. All notes use Vaerkring Reserve and a newly designed crown/sun/dunes imperial seal. + +Assessment: the character editions reintroduce Dune adaptation references and therefore undermine any claim that all published artwork is independent of the source works. Their Minecraft styling and unofficial label do not supply adaptation rights. They are decorative game artwork, no cash value, not licensed merchandise. No percentage probability of a claim can be supported from the available evidence. This is not a jurisdiction-specific legal clearance. + +The U.S. Copyright Office describes adaptations and the rights-holder's derivative-work right: https://www.copyright.gov/circs/circ14.pdf (checked 2026-10-27). Trademark confusion is a separate inquiry: https://www.uspto.gov/trademarks/search/likelihood-confusion . The new seal and invented reserve label have not undergone a trademark clearance search. A lower-risk merchandise edition would use wholly original characters and stories or obtain appropriate licences. diff --git a/docs/Native-GUI.md b/docs/Native-GUI.md index b64afad2..9656acf7 100644 --- a/docs/Native-GUI.md +++ b/docs/Native-GUI.md @@ -66,7 +66,7 @@ ports protected. Do not regenerate keys, forwarding secrets or player UUID setti GitHub build.yml publishes **DuneRealms-All-Server-Jars.zip**, containing every Dune plugin, Vault and the platform-specific crossplay plugins together, plus the lock manifest and instructions. The network workflow puts the appropriate JARs into each server directory and includes the lobby -plugin only on the Spacing Guild backend. Paper/Velocity engine executables are obtained separately; +plugin only on the Vaerkring backend. Paper/Velocity engine executables are obtained separately; this package contains server **plugin** JARs. ## Minimal essentials diff --git a/docs/PUBLIC-NAMES.json b/docs/PUBLIC-NAMES.json new file mode 100644 index 00000000..80f6f218 --- /dev/null +++ b/docs/PUBLIC-NAMES.json @@ -0,0 +1,27 @@ +{ + "brand": "dunerealms.com", + "planets": { + "arrakis": "Arrakduin", + "caladan": "Kaladam", + "giedi_prime": "Giedermark", + "kaitain": "Kaiterhof", + "sigma_draconis_iv": "Sigmadraken IV" + }, + "factions": { + "Fremen": "Vrijduin", + "Atreides": "Aerdrecht", + "Harkonnen": "Harkveen", + "Corrino": "Korenholt", + "Ordos": "Oordwijk" + }, + "terms": { + "Shai-Hulud": "Dune Maw", + "Spacing Guild": "Vaerkring", + "CHOAM": "Koopkring", + "Solaris": "dunemarks", + "spice": "spice", + "stillsuit": "reclaimer suit", + "sietch": "rockhaven" + }, + "note": "Public website names only. Existing game identifiers, plugin artifact names, URLs, commands, saves and feed contracts retain compatibility. New names are proposals, not trademark-cleared." +} diff --git a/docs/STORYLINE.md b/docs/STORYLINE.md new file mode 100644 index 00000000..5c0744ab --- /dev/null +++ b/docs/STORYLINE.md @@ -0,0 +1,23 @@ +# The Missing Cargo Ledger + +Original supporting story outline for dunerealms.com. This is a narrative reference, not an announcement of implemented quests or new mechanics. Existing houses, planets, offices, items and commands retain their names and behavior. + +## Characters + +- **Tavren Sile**, an independent freight surveyor, checks cargo measurements against arrival receipts. His reputation rests on a shipment he once certified incorrectly; he wants to correct the record without concealing his own mistake. +- **Mira Vesk**, a water-route coordinator, protects the crews who depend on reliable deliveries. She distrusts Tavren's paperwork until his measurements explain shortages her crews have been blamed for. +- **Archivist Elian Voss**, a civilian records custodian on Kaiterhof, preserves conflicting shipment reports. Elian must decide whether to release evidence that also exposes negligence in the archive. + +The three are unrelated adults. Their authority comes from their work and the evidence they can defend. + +## Story sequence + +A routine Arrakduin delivery arrives short of its recorded water allocation. Tavren finds that the seal numbers agree while the recorded container capacities do not. Mira traces the discrepancy through the delivery schedule and establishes which crews actually handled each shipment. Their initial disagreement becomes a partnership when both sets of records point to the same altered entry. + +Elian locates two independently filed copies on Kaiterhof. One records an ordinary cargo transfer; the other silently redirects part of the allocation. Neither copy establishes guilt on its own. The group follows the chain of signatures rather than treating a house affiliation as proof. + +At the confrontation, Tavren admits his earlier certification error, Mira presents the crew receipts, and Elian supplies the archive's dated copies. Publishing the evidence costs each of them professional protection. Their success restores a disputed allocation and opens a public accounting of the route; it does not settle the wider rivalry between the Great Houses. + +## Continuity + +Keep the conflict about logistics, evidence and responsibility. No character inherits supernatural authority, takes a dynastic spouse, undergoes a transformation into a ruler, or resolves the conflict through a predetermined future. Planet and faction references establish the existing setting without changing gameplay. Any playable implementation needs its own specification; this document grants no new rewards, ranks or abilities. diff --git a/docs/WEBSITE-UPDATE-HANDOFF.md b/docs/WEBSITE-UPDATE-HANDOFF.md new file mode 100644 index 00000000..1566d65b --- /dev/null +++ b/docs/WEBSITE-UPDATE-HANDOFF.md @@ -0,0 +1,37 @@ +# Website update handoff + +Prepared 26 October 2026 from self-hosted DuneGit `unimatrix/MC`, revision `73e1bc8b75608b77280c6d957bf590be3f3ed8b6`. + +Status updated 27 October 2026: deployed and verified on https://www.dunerealms.com. Active release: /home/dunerealms/apps/dunerealms/releases/20261027-manual-disclaimer. The existing PM2 website process was restarted after an atomic release switch. The preceding releases remain available for rollback. The source changes have not been pushed to DuneGit. + +The owner requested `dunerealms.com` as the visible brand and retained `spice`. The public setting labels and supporting story are original proposals; see `PUBLIC-NAMES.json`, `STORYLINE.md` and `IP-RISK-REVIEW.md` for mappings and limits. The old journal is removed, including its build inputs. The comparison wiki intentionally identifies older names for context. The notice includes `unimatrix@dunerealms.com`; no email was sent. + +## Validation + +- Website build succeeds: 146 embedded assets. +- All 47 website tests pass, including the new removal, notice, compatibility-label and command-copy checks. +- Twenty web HTML pages have no broken local file/asset links. The sign-in route is an application route, not a static file. +- Twenty web pages plus the separately served login page each receive one visible independence notice. +- Retired index, essay, script, stylesheet and data URLs return 404 in the rebuilt Worker for GET and HEAD. +- New public planet names work in market search; legacy live feed values remain accepted and display the new labels. +- Local browser checks covered the wiki layout, renamed branding and factions. Saved wiki preview: `output/dunerealms-wiki-preview.png` in the parent workspace. +- Repeated build was checked for stable tracked output. +- Plugin binaries were not changed or built; this is a website and supporting-story update. + +## Applying the prepared source + +Review the patch against the stated base revision. If the server repository has advanced, merge the patch and resolve any overlap before deployment. The patch records deleted files; copying only changed files over an old checkout is insufficient. + +Use a fresh release directory for the website. Install the existing exact locked dependencies and build with the existing website scripts. The source supports both a Worker bundle and the repository's custom Node/MySQL host. Preserve the current private environment, database, login configuration, monitor configuration and Forgejo reverse proxy; no credentials are included in this handoff. + +Use the operator's existing release-switch procedure for the actual host. No deployment target or credentials have been inferred. Recheck health, sign-in, forums, tickets, exchange, world status and `/git/` after the release. Confirm that old journal routes are absent and purge any cached copies at the serving layer. A successful local build is not deployment confirmation. + +The existing game commands, plugin filenames, world IDs, feed contracts and saved data retain their old identifiers. Renaming those requires a separate game-side compatibility migration, not a website-only release. Historical PDFs and releases remain in repository history and external distribution; direct legacy PDF links have been replaced with the current web manual in this website. + +## Published follow-up + +The comparison/disclaimer is the first manual chapter, `world-and-disclaimer`, with 58 chapters total. Its standalone page remains at `/wiki.html`, linked from the site-wide disclaimer notice; the former World wiki main-menu entry is removed. + +Operator email is absent from public HTML and static browser assets. The contact button uses self-hosted ALTCHA proof-of-work verification and a Node endpoint. Only a valid, unexpired, single-use proof returns the address. Origin checks, bounded challenge storage and bounded payloads are enforced. This raises scraping effort; it does not guarantee freedom from spam. The contact endpoint is part of the custom Node host, not the standalone Worker deployment. + +Verified live: homepage, wiki, manual, manual data, login, forums, tickets, exchange, world status, diplomacy, database health and Git API; old journal route returns 404. Valid CAPTCHA reveal returns 200 and replay returns 403. No production test accounts, messages, tickets or market orders were created. Existing schema, authentication code and Git proxy matched the deployed baseline. The temporary loopback preflight process was stopped. diff --git a/docs/artwork/dunemarks/README.md b/docs/artwork/dunemarks/README.md new file mode 100644 index 00000000..e83852ae --- /dev/null +++ b/docs/artwork/dunemarks/README.md @@ -0,0 +1,18 @@ +# Vaerkring Reserve artwork deliverables + +Created with the built-in imagegen tool. Original PNG masters are kept alongside this file; web production assets are optimized WebP, and game icons are transparent PNG at 64px and 128px. All characters use Minecraft-style cubic heads and pixel features. The original imperial seal is shared across the series. + +| Value | Subject | Full-note master | Icon master | +|---|---|---|---| +| 1 | Stilgar | dunemark-1-front-and-back.png | dunemark-1-icon-master.png | +| 5 | Aliah | dunemark-5-front-and-back.png | dunemark-5-icon-master.png | +| 100 | Mira Vesk | dunemark-100-vaerkring-front-and-back.png | dunemark-100-icon-master.png | +| 1000 | Ghanima | dunemark-1000-front-and-back.png | dunemark-1000-icon-master.png | +| 5000 | Leto, imagined victory over House Harkonnen | dunemark-5000-front-and-back.png | dunemark-5000-icon-master.png | +| 0 | In the search for Leto II | dunemark-0-leto-ii-commemorative.png | None: not an in-game item | + +Seal master: imperial-seal.png. Exact series prompts: vaerkring-complete-prompts.json. Exact zero-note prompt: dunemark-0.prompt.txt. Earlier masters are retained as design history. + +Production note files: website/web/assets/dunemark-{1,5,100,1000,5000}.webp. Production GUI files: website/web/assets/dunemark-{value}-icon-{64,128}.png. Zero design: website/web/assets/dunemark-0-commemorative.webp. Seal files: website/web/assets/imperial-seal.png and imperial-seal-128.png. Paths are relative to the repository root except the masters/prompts, which are alongside this README. + +Published in the exchange gallery and currency manual chapter. Full-note images retain natural aspect ratio; GUI previews are limited to 64px. The zero note is commemorative artwork only and is excluded from resource-pack items, currency denominations and redemptions. Canon character editions remain unofficial fan artwork, not licensed merchandise. diff --git a/docs/artwork/dunemarks/dunemark-0-leto-ii-commemorative.png b/docs/artwork/dunemarks/dunemark-0-leto-ii-commemorative.png new file mode 100644 index 00000000..74cc6560 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-0-leto-ii-commemorative.png differ diff --git a/docs/artwork/dunemarks/dunemark-0.prompt.txt b/docs/artwork/dunemarks/dunemark-0.prompt.txt new file mode 100644 index 00000000..2b1fa07f --- /dev/null +++ b/docs/artwork/dunemarks/dunemark-0.prompt.txt @@ -0,0 +1,2 @@ +Tool: Built-in imagegen +Use case: stylized-concept. Create an original commemorative ZERO Dunemarks banknote design, front and reverse pair stacked vertically, full flat notes with every border visible, matching reference 1's luxurious engraved late Deutsche Mark inspired Minecraft desert-space style. Reference 1 is series style only; reference 2 is the imperial seal, use that original stepped crown/sun/dunes gold seal on both sides. New distinctive design: ivory parchment, moonlit silver-blue, dark teal and antique gold with restrained amber highlights. Front portrait: LETO II, a Minecraft skin character with a truly cubic block head, square blue pixel eyes, dark hair under a desert hood, small gold circlet, contemplative expression; no realistic face, no actor likeness. Surrounding scene: a fading trail of blocky footprints leading into distant dunes under twin moons, cartographic search bearings. Reverse: Minecraft desert search party with lanterns on a ridge, a map table and an empty ceremonial chair far away, hopeful missing-person search mood, not mourning. Large numeral "0" in both corners on BOTH notes. Exact prominent text front: "0", "DUNEMARKS", "VAERKRING RESERVE", "LETO II". Exact prominent reverse headline: "IN THE SEARCH FOR LETO II". Exact footer both sides: "COMMEMORATIVE DESIGN · NO CASH VALUE". Include "dunerealms.com" and small "UNOFFICIAL FAN DESIGN". This is a decorative zero-value search-themed tribute, NOT usable in-game currency. No reward promise, no invented redemption code, no real currency logo, no corpse, no gore, no official franchise crest. Extremely refined guilloche and original angular imperial ornaments, distinct composition from other series notes. diff --git a/docs/artwork/dunemarks/dunemark-1-front-and-back.png b/docs/artwork/dunemarks/dunemark-1-front-and-back.png new file mode 100644 index 00000000..8c162b50 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-1-front-and-back.png differ diff --git a/docs/artwork/dunemarks/dunemark-1-icon-master.png b/docs/artwork/dunemarks/dunemark-1-icon-master.png new file mode 100644 index 00000000..28892d75 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-1-icon-master.png differ diff --git a/docs/artwork/dunemarks/dunemark-100-front-and-back-arrakduin.png b/docs/artwork/dunemarks/dunemark-100-front-and-back-arrakduin.png new file mode 100644 index 00000000..341512ee Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-100-front-and-back-arrakduin.png differ diff --git a/docs/artwork/dunemarks/dunemark-100-front-and-back.png b/docs/artwork/dunemarks/dunemark-100-front-and-back.png new file mode 100644 index 00000000..e86fccf2 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-100-front-and-back.png differ diff --git a/docs/artwork/dunemarks/dunemark-100-icon-master.png b/docs/artwork/dunemarks/dunemark-100-icon-master.png new file mode 100644 index 00000000..d9928b30 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-100-icon-master.png differ diff --git a/docs/artwork/dunemarks/dunemark-100-vaerkring-front-and-back.png b/docs/artwork/dunemarks/dunemark-100-vaerkring-front-and-back.png new file mode 100644 index 00000000..ce5ddf47 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-100-vaerkring-front-and-back.png differ diff --git a/docs/artwork/dunemarks/dunemark-1000-front-and-back.png b/docs/artwork/dunemarks/dunemark-1000-front-and-back.png new file mode 100644 index 00000000..346ad783 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-1000-front-and-back.png differ diff --git a/docs/artwork/dunemarks/dunemark-1000-icon-master.png b/docs/artwork/dunemarks/dunemark-1000-icon-master.png new file mode 100644 index 00000000..62e0f0b7 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-1000-icon-master.png differ diff --git a/docs/artwork/dunemarks/dunemark-5-front-and-back.png b/docs/artwork/dunemarks/dunemark-5-front-and-back.png new file mode 100644 index 00000000..d174d436 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-5-front-and-back.png differ diff --git a/docs/artwork/dunemarks/dunemark-5-icon-master.png b/docs/artwork/dunemarks/dunemark-5-icon-master.png new file mode 100644 index 00000000..8ea3f11b Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-5-icon-master.png differ diff --git a/docs/artwork/dunemarks/dunemark-5000-front-and-back.png b/docs/artwork/dunemarks/dunemark-5000-front-and-back.png new file mode 100644 index 00000000..940ba568 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-5000-front-and-back.png differ diff --git a/docs/artwork/dunemarks/dunemark-5000-icon-master.png b/docs/artwork/dunemarks/dunemark-5000-icon-master.png new file mode 100644 index 00000000..def75fbc Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-5000-icon-master.png differ diff --git a/docs/artwork/dunemarks/dunemark-icon-master.png b/docs/artwork/dunemarks/dunemark-icon-master.png new file mode 100644 index 00000000..2bc02df3 Binary files /dev/null and b/docs/artwork/dunemarks/dunemark-icon-master.png differ diff --git a/docs/artwork/dunemarks/imperial-seal.png b/docs/artwork/dunemarks/imperial-seal.png new file mode 100644 index 00000000..81c520d9 Binary files /dev/null and b/docs/artwork/dunemarks/imperial-seal.png differ diff --git a/docs/artwork/dunemarks/vaerkring-complete-prompts.json b/docs/artwork/dunemarks/vaerkring-complete-prompts.json new file mode 100644 index 00000000..9ce9ea65 --- /dev/null +++ b/docs/artwork/dunemarks/vaerkring-complete-prompts.json @@ -0,0 +1,48 @@ +{ + "tool": "Built-in imagegen", + "seal": "Use case: logo-brand. Create an original imperial seal for fictional dunerealms.com banknotes. Single isolated circular embossed gold seal, transparent background. Splendour of a desert space empire, Minecraft/block-built geometry, refined numismatic engraving. Central stepped imperial crown above an eight-point desert sun and three geometric dune bands, circular double gold border, symmetric palm-like geometric branches. Deep teal enamel recesses, antique gold highlights. No franchise crest, no eagle, no letters, no text, no mockup, no background, no cast shadow outside seal. Crisp readable silhouette at 64 pixels, luxurious engraved details at full size.", + "notes": [ + { + "value": 1, + "prompt": "Use case: stylized-concept. Create a finished front-and-back pair of a fictional 1 DUNEMARKS banknote for dunerealms.com, two very wide rectangular notes stacked vertically with narrow dark teal spacing, exactly as the format of reference 1. Reference 1 is style/layout guidance only; create a unique new composition for this denomination. Reference 2 is the original imperial seal: reproduce this crown, sun and dune seal prominently in gold on BOTH sides. Subject: Stilgar as a Minecraft desert leader in a sand-coloured hood and stillsuit, blue square eyes, cubic head, broad square shoulders. Reverse: a desert rockhaven and water cisterns, desert travellers. All people must be unmistakably Minecraft skin characters with cubic heads and pixel facial features, no realistic human faces or actor likenesses. Palette: copper, sand, olive and deep teal. Luxurious late Deutsche Mark inspired engraved guilloche, intricate original desert science fiction ornament, voxel architecture, refined security-pattern lines, crisp denomination typography. Each note shows 1 large in corners. Exact text front: \"1\", \"DUNEMARKS\", \"VAERKRING RESERVE\", \"STILGAR\", \"dunerealms.com\". Small footer both sides \"GAME CURRENCY · NO CASH VALUE\". Small caption \"UNOFFICIAL FAN DESIGN\". Reverse shows \"1\" and \"DUNEMARKS\" and the distinctive scene described. No ARRAKDUIN RESERVE, no SEREVAN, no real bank logos, no real currency, no photoreal people, no perspective mockup. Complete flat full notes with all borders visible." + }, + { + "value": 5, + "prompt": "Use case: stylized-concept. Create a finished front-and-back pair of a fictional 5 DUNEMARKS banknote for dunerealms.com, two very wide rectangular notes stacked vertically with narrow dark teal spacing, exactly as the format of reference 1. Reference 1 is style/layout guidance only; create a unique new composition for this denomination. Reference 2 is the original imperial seal: reproduce this crown, sun and dune seal prominently in gold on BOTH sides. Subject: Aliah as a Minecraft ceremonial young woman in a violet and teal desert robe, cubic head, pixel square eyes. Reverse: a stepped desert archive and celestial instruments. All people must be unmistakably Minecraft skin characters with cubic heads and pixel facial features, no realistic human faces or actor likenesses. Palette: violet, gold, parchment and deep teal. Luxurious late Deutsche Mark inspired engraved guilloche, intricate original desert science fiction ornament, voxel architecture, refined security-pattern lines, crisp denomination typography. Each note shows 5 large in corners. Exact text front: \"5\", \"DUNEMARKS\", \"VAERKRING RESERVE\", \"ALIAH\", \"dunerealms.com\". Small footer both sides \"GAME CURRENCY · NO CASH VALUE\". Small caption \"UNOFFICIAL FAN DESIGN\". Reverse shows \"5\" and \"DUNEMARKS\" and the distinctive scene described. No ARRAKDUIN RESERVE, no SEREVAN, no real bank logos, no real currency, no photoreal people, no perspective mockup. Complete flat full notes with all borders visible." + }, + { + "value": 100, + "prompt": "Use case: stylized-concept. Create a finished front-and-back pair of a fictional 100 DUNEMARKS banknote for dunerealms.com, two very wide rectangular notes stacked vertically with narrow dark teal spacing, exactly as the format of reference 1. Reference 1 is style/layout guidance only; create a unique new composition for this denomination. Reference 2 is the original imperial seal: reproduce this crown, sun and dune seal prominently in gold on BOTH sides. Subject: Mira Vesk as the existing Minecraft woman cartographer, teal hood and gold headband, cubic head, pixel square eyes. Reverse: a rockhaven reservoir, block-built caravan vehicles and water engineering. All people must be unmistakably Minecraft skin characters with cubic heads and pixel facial features, no realistic human faces or actor likenesses. Palette: deep teal, turquoise, antique gold and parchment. Luxurious late Deutsche Mark inspired engraved guilloche, intricate original desert science fiction ornament, voxel architecture, refined security-pattern lines, crisp denomination typography. Each note shows 100 large in corners. Exact text front: \"100\", \"DUNEMARKS\", \"VAERKRING RESERVE\", \"MIRA VESK\", \"dunerealms.com\". Small footer both sides \"GAME CURRENCY · NO CASH VALUE\". Reverse shows \"100\" and \"DUNEMARKS\" and the distinctive scene described. No ARRAKDUIN RESERVE, no SEREVAN, no real bank logos, no real currency, no photoreal people, no perspective mockup. Complete flat full notes with all borders visible." + }, + { + "value": 1000, + "prompt": "Use case: stylized-concept. Create a finished front-and-back pair of a fictional 1000 DUNEMARKS banknote for dunerealms.com, two very wide rectangular notes stacked vertically with narrow dark teal spacing, exactly as the format of reference 1. Reference 1 is style/layout guidance only; create a unique new composition for this denomination. Reference 2 is the original imperial seal: reproduce this crown, sun and dune seal prominently in gold on BOTH sides. Subject: Ghanima as a Minecraft imperial woman in sapphire robes and a restrained golden circlet, cubic head, square pixel eyes. Reverse: a grand desert observatory with star charts and imperial gardens. All people must be unmistakably Minecraft skin characters with cubic heads and pixel facial features, no realistic human faces or actor likenesses. Palette: sapphire blue, ivory, antique gold and deep teal. Luxurious late Deutsche Mark inspired engraved guilloche, intricate original desert science fiction ornament, voxel architecture, refined security-pattern lines, crisp denomination typography. Each note shows 1000 large in corners. Exact text front: \"1000\", \"DUNEMARKS\", \"VAERKRING RESERVE\", \"GHANIMA\", \"dunerealms.com\". Small footer both sides \"GAME CURRENCY · NO CASH VALUE\". Small caption \"UNOFFICIAL FAN DESIGN\". Reverse shows \"1000\" and \"DUNEMARKS\" and the distinctive scene described. No ARRAKDUIN RESERVE, no SEREVAN, no real bank logos, no real currency, no photoreal people, no perspective mockup. Complete flat full notes with all borders visible." + }, + { + "value": 5000, + "prompt": "Use case: stylized-concept. Create a finished front-and-back pair of a fictional 5000 DUNEMARKS banknote for dunerealms.com, two very wide rectangular notes stacked vertically with narrow dark teal spacing, exactly as the format of reference 1. Reference 1 is style/layout guidance only; create a unique new composition for this denomination. Reference 2 is the original imperial seal: reproduce this crown, sun and dune seal prominently in gold on BOTH sides. Subject: Leto as a Minecraft imperial leader on the front, cubic head, square pixel eyes, richly detailed desert imperial costume. Reverse: an alternate-game symbolic scene of Leto overthrowing House Harkonnen: Leto standing triumphant above a fallen red-and-black Harkonnen standard at a conquered block-built fortress, soldiers with lowered weapons, no gore. This is an imagined game scene, not a book-accurate history. All people must be unmistakably Minecraft skin characters with cubic heads and pixel facial features, no realistic human faces or actor likenesses. Palette: imperial burgundy, blackened teal, ivory and abundant gold. Luxurious late Deutsche Mark inspired engraved guilloche, intricate original desert science fiction ornament, voxel architecture, refined security-pattern lines, crisp denomination typography. Each note shows 5000 large in corners. Exact text front: \"5000\", \"DUNEMARKS\", \"VAERKRING RESERVE\", \"LETO\", \"dunerealms.com\". Small footer both sides \"GAME CURRENCY · NO CASH VALUE\". Small caption \"UNOFFICIAL FAN DESIGN\". Reverse shows \"5000\" and \"DUNEMARKS\" and the distinctive scene described. No ARRAKDUIN RESERVE, no SEREVAN, no real bank logos, no real currency, no photoreal people, no perspective mockup. Complete flat full notes with all borders visible." + } + ], + "icons": [ + { + "value": 1, + "prompt": "Use case: stylized-concept. A single isolated cartoon inventory icon of the 1 Dunemark note in reference 1, front face only, wide rectangular note centred on a square transparent canvas. Simplify the ornate engraved note into a bold Minecraft GUI item, with thick dark teal outline, warm parchment, copper-gold border and a clearly cubic Minecraft Stilgar portrait wearing sand hood, square blue eyes. Large extremely legible \"1\" on left, small imperial crown/sun/dunes seal at lower left using reference 2. Keep all details inside note silhouette, no cast shadow. Must remain clear at 64x64 pixels. No stacked notes, no coins, no background, no tiny text except the large number. Genuine transparent alpha." + }, + { + "value": 5, + "prompt": "Use case: stylized-concept. A single isolated cartoon Minecraft inventory icon of the 5 Dunemarks note in reference 1, front face only, wide rectangular note centred on square transparent canvas. Simplify engraving into bold GUI art with thick dark teal outline, parchment, violet and gold border, cubic Minecraft Aliah portrait with purple hood, square pixel eyes. Large extremely legible \"5\" on left. Small imperial crown/sun/dunes seal from reference 2 at lower left. Readable at 64x64 pixels. All details within note silhouette, no shadow outside. No tiny text except the number, no coins or stack. Genuine transparent alpha." + }, + { + "value": 100, + "prompt": "Use case: stylized-concept. Single isolated cartoon Minecraft inventory icon of the 100 Dunemarks note in reference 1, front face only, wide rectangular banknote centred on a square transparent canvas. Simplify into bold readable GUI art: thick dark teal outline, parchment and teal/gold border, cubic Minecraft woman Mira Vesk in teal hood with gold headband, square pixel eyes. Very large legible \"100\" on left, small gold imperial crown/sun/dunes seal from reference 2 lower left. Must read at 64x64 pixels. No tiny text except number, no shadow outside note, no coins, no stack. Genuine transparent alpha." + }, + { + "value": 1000, + "prompt": "Use case: stylized-concept. Single isolated cartoon Minecraft inventory icon of the 1000 Dunemarks note in reference 1, front face only, wide rectangular note centred on a square transparent canvas. Simplify into bold readable GUI art with thick dark teal outline, parchment and sapphire/gold border. Cubic Minecraft Ghanima portrait with sapphire blue hood and gold circlet, square pixel blue eyes. Very large clear \"1000\" on left, small imperial crown/sun/dunes gold seal from reference 2 below it. Readable at 64x64 pixels. No tiny text except number, no coins or stack, all detail within note silhouette, no external shadow. Genuine transparent alpha." + }, + { + "value": 5000, + "prompt": "Use case: stylized-concept. Single isolated cartoon Minecraft inventory icon of the 5000 Dunemarks note in reference 1, front face only, wide rectangular note centred on square transparent canvas. Simplify ornate engraving into bold readable GUI art: thick dark teal outline, parchment and imperial burgundy/gold border. Cubic Minecraft Leto portrait with dark hair, square pixel eyes, gold stepped crown and burgundy cape. Very large clear \"5000\" on left, small imperial gold crown/sun/dunes seal from reference 2 below it. Readable at 64x64 pixels. No tiny text except number, no coins or stack, no shadows beyond note silhouette. Genuine transparent alpha." + } + ] +} diff --git a/docs/artwork/dunemarks/vaerkring-series-prompts.json b/docs/artwork/dunemarks/vaerkring-series-prompts.json new file mode 100644 index 00000000..70961608 --- /dev/null +++ b/docs/artwork/dunemarks/vaerkring-series-prompts.json @@ -0,0 +1,10 @@ +{ + "tool": "Built-in imagegen", + "seal": "Use case: logo-brand. Create an original imperial seal for fictional dunerealms.com banknotes. Single isolated circular embossed gold seal, transparent background. Splendour of a desert space empire, Minecraft/block-built geometry, refined numismatic engraving. Central stepped imperial crown above an eight-point desert sun and three geometric dune bands, circular double gold border, symmetric palm-like geometric branches. Deep teal enamel recesses, antique gold highlights. No franchise crest, no eagle, no letters, no text, no mockup, no background, no cast shadow outside seal. Crisp readable silhouette at 64 pixels, luxurious engraved details at full size.", + "icons": [ + { + "value": 1, + "prompt": "Use case: stylized-concept. A single isolated cartoon inventory icon of the 1 Dunemark note in reference 1, front face only, wide rectangular note centred on a square transparent canvas. Simplify the ornate engraved note into a bold Minecraft GUI item, with thick dark teal outline, warm parchment, copper-gold border and a clearly cubic Minecraft Stilgar portrait wearing sand hood, square blue eyes. Large extremely legible \"1\" on left, small imperial crown/sun/dunes seal at lower left using reference 2. Keep all details inside note silhouette, no cast shadow. Must remain clear at 64x64 pixels. No stacked notes, no coins, no background, no tiny text except the large number. Genuine transparent alpha." + } + ] +} diff --git a/docs/artwork/landsraad-appointments.prompt.txt b/docs/artwork/landsraad-appointments.prompt.txt new file mode 100644 index 00000000..8457d2ec --- /dev/null +++ b/docs/artwork/landsraad-appointments.prompt.txt @@ -0,0 +1,3 @@ +Create an original wide landscape ceremonial website banner for dunerealms.com, a Minecraft desert science fiction community, matching deep ink teal (#102321), antique gold (#d4b476), aged ivory parchment. Imperial splendour, ornate Dutch Golden Age inspired civic heraldry blended with original desert-space architecture, dignified rich engraved workmanship, symmetrical composition with a central grand gold coronet above two hanging wax-sealed appointment parchments. Left parchment has an ORIGINAL geometric sun-and-crystal emblem for spice-trading office; right parchment has an ORIGINAL geometric droplet-and-vessel emblem for water-selling office. Small block-built minecraft-like palace architectural silhouettes in background, but no game screenshots, no recognizable Minecraft character or official texture. Dramatic warm gold light, dark teal shadows, prestigious ceremonial documents. Landscape 3:1 composition suitable as a shallow header; no text whatsoever because accessible text will be overlaid in HTML. Do not depict any existing Dune house crest, film design or Stargate symbol. Illustration, not UI screenshot. + +Generated with the built-in image-generation tool. Website asset: website/web/assets/landsraad-appointments.webp diff --git a/docs/manual-authoring/build_current_manual.py b/docs/manual-authoring/build_current_manual.py index f878406a..b394b5fb 100644 --- a/docs/manual-authoring/build_current_manual.py +++ b/docs/manual-authoring/build_current_manual.py @@ -73,7 +73,7 @@ def footer(c,doc): c.setFillColor(PALE);c.setFont('ArialBold',10);c.drawString(48,H-56,'PROJECT DUNE / PLAYER + ADMIN EDITION') c.setFont('GeorgiaBold',68);c.drawString(48,H-140,'DUNE') c.setFont('Arial',25);c.drawString(48,H-178,'The illustrated field manual') - c.setFont('Arial',11);c.drawString(48,H-213,'ARRAKIS / FACTIONS / SPICE / THE SPACING GUILD') + c.setFont('Arial',11);c.drawString(48,H-213,'ARRAKIS / FACTIONS / SPICE / THE VAERKRING') c.setStrokeColor(PALE);c.line(48,H-233,W-48,H-233) c.setFont('Arial',9);c.drawString(48,H-251,'DuneCore 1.0.8 | DuneNPC 1.0.0 | DuneTerrain 1.0.7 | DuneEss 1.0.1') c.setFillColor(colors.HexColor('#102322'));c.setFillAlpha(.80);c.rect(0,0,W,59,fill=1,stroke=0);c.setFillAlpha(1) @@ -150,7 +150,7 @@ HEROES = { 'Meeting the roaming smugglers': ('A contact beyond the ledgers','smuggler-spice-mission.png','Sand-tan robes and green dust identify a roaming contact. Approach on Arrakis and right-click to see the smuggling offers available to your house.'), 'Water for the Hidden Sietch': ('A light in the desert','smuggler-water-camp.png','Purple dust marks an active quest contact. Invisible light blocks brighten its camp while the player carries water toward a different smuggler.'), 'The Imperial Admin Scepter': ('The keeper of the routes','imperial-npc-administration.png','The glowing blaze rod opens operator controls. DuneNPC manages Guild Navigators, smugglers and their missions through its own linked administration page.'), - 'The Arrakis landscape': ('Arrakis / the desert world','world-0.png','Arrakis receives the full gameplay treatment in this edition: terrain, spice, sietches, survival, worms, rights and smuggling. This is the active field guide.'), + 'The Arrakduin landscape': ('Arrakduin / the desert world','world-0.png','Arrakis receives the full gameplay treatment in this edition: terrain, spice, sietches, survival, worms, rights and smuggling. This is the active field guide.'), 'Giedi Prime': ('Giedi Prime / industrial shadows','world-1.png','A lore-inspired view of the Harkonnen world. The following reserved chapter records the released swamp and blackstone profile; the depicted industry is concept scenery.'), 'Kaitain': ('Kaitain / the Imperial horizon','world-2.png','A lore-inspired Imperial vista. The following reserved chapter records the released plains, flowers and ores; palace architecture is concept scenery.'), 'Caladan': ('Caladan / water and green lands','world-3.png','A lore-inspired Atreides vista. The following reserved chapter records the current jungle and water profile; additional local missions remain future documentation.'), @@ -162,7 +162,7 @@ toc=TableOfContents();toc.levelStyles=[ParagraphStyle('toc',fontName='Arial',fon toc.tableStyle=TableStyle([('VALIGN',(0,0),(-1,-1),'TOP'),('LEFTPADDING',(0,0),(-1,-1),0),('RIGHTPADDING',(0,0),(-1,-1),0),('TOPPADDING',(0,0),(-1,-1),1),('BOTTOMPADDING',(0,0),(-1,-1),1)]) story += [Paragraph('HOW TO USE THIS BOOK',STYLE['label']),Paragraph('Contents',STYLE['title']),Paragraph('Player guidance comes first, followed by command references and server administration. Each of the four reserved planet chapters contains its currently implemented profile and space for future additions. Configuration values shown here are shipped defaults; your administrator may change them.',STYLE['body']),toc,PageBreak()] raw=Path(__file__).with_name('manual-current-content.txt').read_text(encoding='utf-8') -artwork_intro('Beneath the sands of Arrakis','A field guide to the desert: reach a sietch, prepare your stillsuit, follow the spice and watch for Shai-Hulud. The gameplay chapters that follow explain exactly what the release implements.',ART/'sietch-panorama.png') +artwork_intro('Beneath the sands of Arrakduin','A field guide to the desert: reach a sietch, prepare your stillsuit, follow the spice and watch for Shai-Hulud. The gameplay chapters that follow explain exactly what the release implements.',ART/'sietch-panorama.png') for block in raw.split('\n===PAGE===\n'): lines=block.strip().splitlines() if not lines:continue @@ -171,12 +171,12 @@ for block in raw.split('\n===PAGE===\n'): scenes={ 'Harvesting melange': ('Melange among the terraces','spice-expedition.png','Wear your stillsuit, recognize the tagged netherite shovel and harvest the desert. Fremen receive two spice units per deposit. The plateau formations can have up to three levels, with at most five blocks between their heights.'), 'Shai-Hulud: model, AI and combat': ('When Shai-Hulud rises','shai-hulud-encounter.png','A visible Sniffer body carries the sandworm skin while an invisible Husk supplies native zombie AI. Fight the visible body. Its default 500 health makes it a serious encounter; its death creates a rich spice field rather than a direct cash payout.'), - 'The five-backend network': ('The Guild connects the worlds','guild-navigator.png','The Spacing Guild navigator opens planet travel. Arrakis sighting coordinates remain local for fifteen real minutes before the Guild informs the proxy network. The heighliner in this illustration is lore scenery, not a flyable feature in the plugin.') + 'The five-backend network': ('The Guild connects the worlds','guild-navigator.png','The Vaerkring navigator opens planet travel. Arrakis sighting coordinates remain local for fifteen real minutes before the Guild informs the proxy network. The heighliner in this illustration is lore scenery, not a flyable feature in the plugin.') } if title in scenes: scene_title,filename,caption=scenes[title] sh=Paragraph(scene_title,STYLE['title']);sh.toc_title=scene_title - story.extend([Paragraph('ARRAKIS / ILLUSTRATED FIELD NOTES',STYLE['label']),sh,Image(str(ROOT/'docs/artwork'/filename),width=W-96,height=(W-96)*2/3),Spacer(1,20),Paragraph(caption,STYLE['body']),Spacer(1,12),Paragraph('The spice must flow.',STYLE['sub']),Paragraph('Concept artwork illustrates the game\'s themes. Creature scale and architecture are artistic interpretations, not screenshots. The following chapter describes the actual release behavior.',STYLE['small']),PageBreak()]) + story.extend([Paragraph('ARRAKDUIN / ILLUSTRATED FIELD NOTES',STYLE['label']),sh,Image(str(ROOT/'docs/artwork'/filename),width=W-96,height=(W-96)*2/3),Spacer(1,20),Paragraph(caption,STYLE['body']),Spacer(1,12),Paragraph('The spice must flow.',STYLE['sub']),Paragraph('Concept artwork illustrates the game\'s themes. Creature scale and architecture are artistic interpretations, not screenshots. The following chapter describes the actual release behavior.',STYLE['small']),PageBreak()]) heading=Paragraph(markup(title),STYLE['title']);heading.toc_title=title story += [Paragraph(markup(label.upper()),STYLE['label']),heading] if title=='The fifteen-minute Guild notice':story.append(GuildTimeline()) diff --git a/docs/manual-authoring/build_decorated_manual.py b/docs/manual-authoring/build_decorated_manual.py index bad68d76..890c9e2b 100644 --- a/docs/manual-authoring/build_decorated_manual.py +++ b/docs/manual-authoring/build_decorated_manual.py @@ -73,7 +73,7 @@ def footer(c,doc): c.setFillColor(PALE);c.setFont('ArialBold',10);c.drawString(48,H-56,'PROJECT DUNE / PLAYER + ADMIN EDITION') c.setFont('GeorgiaBold',68);c.drawString(48,H-140,'DUNE') c.setFont('Arial',25);c.drawString(48,H-178,'The illustrated field manual') - c.setFont('Arial',11);c.drawString(48,H-213,'ARRAKIS / FACTIONS / SPICE / THE SPACING GUILD') + c.setFont('Arial',11);c.drawString(48,H-213,'ARRAKIS / FACTIONS / SPICE / THE VAERKRING') c.setStrokeColor(PALE);c.line(48,H-233,W-48,H-233) c.setFont('Arial',9);c.drawString(48,H-251,'DuneCore 1.0.8 | DuneNPC 1.0.0 | DuneTerrain 1.0.7 | DuneEss 1.0.1') c.setFillColor(colors.HexColor('#102322'));c.setFillAlpha(.80);c.rect(0,0,W,59,fill=1,stroke=0);c.setFillAlpha(1) @@ -165,7 +165,7 @@ HEROES = { 'Meeting the roaming smugglers': ('A contact beyond the ledgers','smuggler-spice-mission.png','Sand-tan robes and green dust identify a roaming contact. Approach on Arrakis and right-click to see the smuggling offers available to your house.'), 'Water for the Hidden Sietch': ('A light in the desert','smuggler-water-camp.png','Purple dust marks an active quest contact. Invisible light blocks brighten its camp while the player carries water toward a different smuggler.'), 'The Imperial Admin Scepter': ('The keeper of the routes','imperial-npc-administration.png','The glowing blaze rod opens operator controls. DuneNPC manages Guild Navigators, smugglers and their missions through its own linked administration page.'), - 'The Arrakis landscape': ('Arrakis / the desert world','world-0.png','Arrakis receives the full gameplay treatment in this edition: terrain, spice, sietches, survival, worms, rights and smuggling. This is the active field guide.'), + 'The Arrakduin landscape': ('Arrakduin / the desert world','world-0.png','Arrakis receives the full gameplay treatment in this edition: terrain, spice, sietches, survival, worms, rights and smuggling. This is the active field guide.'), 'Giedi Prime': ('Giedi Prime / industrial shadows','world-1.png','A lore-inspired view of the Harkonnen world. The following reserved chapter records the released swamp and blackstone profile; the depicted industry is concept scenery.'), 'Kaitain': ('Kaitain / the Imperial horizon','world-2.png','A lore-inspired Imperial vista. The following reserved chapter records the released plains, flowers and ores; palace architecture is concept scenery.'), 'Caladan': ('Caladan / water and green lands','world-3.png','A lore-inspired Atreides vista. The following reserved chapter records the current jungle and water profile; additional local missions remain future documentation.'), @@ -177,7 +177,7 @@ toc=TableOfContents();toc.levelStyles=[ParagraphStyle('toc',fontName='Arial',fon toc.tableStyle=TableStyle([('VALIGN',(0,0),(-1,-1),'TOP'),('LEFTPADDING',(0,0),(-1,-1),0),('RIGHTPADDING',(0,0),(-1,-1),0),('TOPPADDING',(0,0),(-1,-1),1),('BOTTOMPADDING',(0,0),(-1,-1),1)]) story += [Paragraph('HOW TO USE THIS BOOK',STYLE['label']),Paragraph('Contents',STYLE['title']),Paragraph('Player guidance comes first, followed by command references and server administration. Each of the four reserved planet chapters contains its currently implemented profile and space for future additions. Configuration values shown here are shipped defaults; your administrator may change them.',STYLE['body']),toc,PageBreak()] raw=Path(__file__).with_name('manual-current-content.txt').read_text(encoding='utf-8') -artwork_intro('Beneath the sands of Arrakis','A field guide to the desert: reach a sietch, prepare your stillsuit, follow the spice and watch for Shai-Hulud. The gameplay chapters that follow explain exactly what the release implements.',ART/'sietch-panorama.png') +artwork_intro('Beneath the sands of Arrakduin','A field guide to the desert: reach a sietch, prepare your stillsuit, follow the spice and watch for Shai-Hulud. The gameplay chapters that follow explain exactly what the release implements.',ART/'sietch-panorama.png') for block in raw.split('\n===PAGE===\n'): lines=block.strip().splitlines() if not lines:continue @@ -186,12 +186,12 @@ for block in raw.split('\n===PAGE===\n'): scenes={ 'Harvesting melange': ('Melange among the terraces','spice-expedition.png','Wear your stillsuit, recognize the tagged netherite shovel and harvest the desert. Fremen receive two spice units per deposit. The plateau formations can have up to three levels, with at most five blocks between their heights.'), 'Shai-Hulud: model, AI and combat': ('When Shai-Hulud rises','shai-hulud-encounter.png','A visible Sniffer body carries the sandworm skin while an invisible Husk supplies native zombie AI. Fight the visible body. Its default 500 health makes it a serious encounter; its death creates a rich spice field rather than a direct cash payout.'), - 'The five-backend network': ('The Guild connects the worlds','guild-navigator.png','The Spacing Guild navigator opens planet travel. Arrakis sighting coordinates remain local for fifteen real minutes before the Guild informs the proxy network. The heighliner in this illustration is lore scenery, not a flyable feature in the plugin.') + 'The five-backend network': ('The Guild connects the worlds','guild-navigator.png','The Vaerkring navigator opens planet travel. Arrakis sighting coordinates remain local for fifteen real minutes before the Guild informs the proxy network. The heighliner in this illustration is lore scenery, not a flyable feature in the plugin.') } if title in scenes: scene_title,filename,caption=scenes[title] sh=Paragraph(scene_title,STYLE['title']);sh.toc_title=scene_title - story.extend([Paragraph('ARRAKIS / ILLUSTRATED FIELD NOTES',STYLE['label']),sh,Image(str(ROOT/'docs/artwork'/filename),width=W-96,height=(W-96)*2/3),Spacer(1,20),Paragraph(caption,STYLE['body']),Spacer(1,12),Paragraph('The spice must flow.',STYLE['sub']),Paragraph('Concept artwork illustrates the game\'s themes. Creature scale and architecture are artistic interpretations, not screenshots. The following chapter describes the actual release behavior.',STYLE['small']),PageBreak()]) + story.extend([Paragraph('ARRAKDUIN / ILLUSTRATED FIELD NOTES',STYLE['label']),sh,Image(str(ROOT/'docs/artwork'/filename),width=W-96,height=(W-96)*2/3),Spacer(1,20),Paragraph(caption,STYLE['body']),Spacer(1,12),Paragraph('The spice must flow.',STYLE['sub']),Paragraph('Concept artwork illustrates the game\'s themes. Creature scale and architecture are artistic interpretations, not screenshots. The following chapter describes the actual release behavior.',STYLE['small']),PageBreak()]) heading=Paragraph(markup(title),STYLE['title']);heading.toc_title=title story += [Paragraph(markup(label.upper()),STYLE['label']),heading] if title=='The fifteen-minute Guild notice':story.append(GuildTimeline()) diff --git a/docs/manual-authoring/manual-current-content.txt b/docs/manual-authoring/manual-current-content.txt index 728fd539..f2b7c65c 100644 --- a/docs/manual-authoring/manual-current-content.txt +++ b/docs/manual-authoring/manual-current-content.txt @@ -26,7 +26,7 @@ Bring the shovel, a complete suit, food and a weapon. Locate shelter before taki PLAYER GUIDE | Menus and help The Navigator is a configurable chest-style interface. Background colors reflect your faction. Buttons are actions, not free inventory items: clicking them opens a page or runs a player command. Menus expose the same systems available through chat. |Navigator button|Action| -|Spacing Guild|Open the destination menu.| +|Vaerkring|Open the destination menu.| |CHOAM Contracts|Browse the current hourly contracts and accept one.| |Player Spice Exchange|Open shortcuts to post or cancel a listing, or leave a job.| |Wallet / Sell Spice|Read the balance or sell tagged spice through DuneEss.| @@ -34,7 +34,7 @@ The Navigator is a configurable chest-style interface. Background colors reflect |Winged Stillsuit Upgrade|Run the paid Elytra merge.| |Choose Faction|Open the five playable faction selections.| ## Other ways to navigate -`/dune menu` and `/dune gui` also open the Navigator. `/dune exchange` opens the exchange menu; `/dune job` prints the actual listings and remaining quotas. Interacting with a tagged Spacing Guild Navigator opens DuneEss's travel menu. The automatically generated navigator is an invulnerable, stationary villager at planet spawn. +`/dune menu` and `/dune gui` also open the Navigator. `/dune exchange` opens the exchange menu; `/dune job` prints the actual listings and remaining quotas. Interacting with a tagged Vaerkring Navigator opens DuneEss's travel menu. The automatically generated navigator is an invulnerable, stationary villager at planet spawn. ## Current menu details The default DuneCore travel page displays only four destinations because its dynamic list is capped at four. Sigma Draconis IV is still available through `/duneess travel sigma_draconis_iv` or the DuneEss travel menu, which lists all five worlds. The exchange page has listing-management shortcuts but no dynamic listing browser; use `/dune job` to find a sponsor. Help supports `/duneess help `, `next`, `previous` and `menu`. The chat guide includes clickable navigation. Some introductory messages and older files omit Ordos, but it is a distinct playable faction in the current code. @@ -50,7 +50,7 @@ Faction passives use the recorded faction. Full-set effects additionally check t ## Arrival and respawning Faction selection requests travel to the corresponding homeworld without a normal paid fare. On a proxy network, this is a server-transfer request. On a single backend, the homeworld must already be loaded for a local arrival. Respawn is redirected to the homeworld only when that world is loaded on the current backend; there is no general cross-server respawn router. ## Choosing carefully -Fremen suits favor harvesting and sneaking; Harkonnen and Corrino favor combat; Atreides favor speed and extra full-set health; Ordos favor short concealment and explosives. Spacing Guild has appearance-related support but is not one of the five player-selectable factions. +Fremen suits favor harvesting and sneaking; Harkonnen and Corrino favor combat; Atreides favor speed and extra full-set health; Ordos favor short concealment and explosives. Vaerkring has appearance-related support but is not one of the five player-selectable factions. ===PAGE=== PLAYER GUIDE | Stillsuits, flight and Ordos equipment ## Armor that looks like leather but protects like netherite @@ -65,14 +65,14 @@ The tagged Ordos Implosion Charge launches a wind charge and supplies a replacem PLAYER GUIDE | Solaris, spice sales and Guild travel Solaris is the currency supplied by DuneEss through Vault. The default spice price is 15 Solaris per unit, normal Guild fare is 100 and starting balance is zero. Balances can be negative by default, allowing contract fines to create debt. There are no player-to-player pay or general bank commands in this plugin's command set. ## Selling spice -`/duneess sell` sells all correctly tagged spice in storage inventory. It does not sell ordinary orange dye or an item renamed Melange Spice. With DuneCore enabled, a Spacing Trust levy is taken and unauthorized spice sales can create smuggling bounties. A sale of 100 spice has a gross value of 1,500 Solaris; the default 1.21% levy rounds up to 19, leaving 1,481 Solaris for a player without an appointment. Members of the current Spice Steward or House of Water instead receive +33% gross: 1,995 gross, levy 25, net 1,970. See Imperial spice profit and mission eligibility for the complete rules. +`/duneess sell` sells all correctly tagged spice in storage inventory. It does not sell ordinary orange dye or an item renamed Melange Spice. With DuneCore enabled, a Vaerkring Trust levy is taken and unauthorized spice sales can create smuggling bounties. A sale of 100 spice has a gross value of 1,500 Solaris; the default 1.21% levy rounds up to 19, leaving 1,481 Solaris for a player without an appointment. Members of the current Spice Steward or House of Water instead receive +33% gross: 1,995 gross, levy 25, net 1,970. See Imperial spice profit and mission eligibility for the complete rules. ## Travelling `/duneess travel` opens the five-world menu. `/duneess travel arrakis` requests a specific destination; use the internal world IDs listed in this book. If the destination is the local loaded world, you teleport to its spawn. If networking is enabled and the destination is remote, DuneEss asks the proxy to switch servers. The appointed Spice Steward faction has free Arrakis travel. Other travelers normally pay the fare. A local failed teleport refunds the fare; a proxy request refunds only when sending the request itself fails. The proxy does not confirm destination arrival to this plugin, so an offline destination can still leave a fare charged. ## Arrival rights are a separate system Paying the fare does not grant legal spice rights or necessarily prevent an arrival bounty. The current arrival rule treats the Spice Steward faction as sanctioned and uses shared PostgreSQL permits. Ordinary arrivals without a valid permit can be marked wanted when the database-backed arrival check is active. See the legal-rights chapter before organizing a multiplayer expedition. ===PAGE=== -ARRAKIS FIELD GUIDE | The Arrakis landscape +ARRAKDUIN FIELD GUIDE | The Arrakduin landscape Arrakis is fully implemented in this manual. Its world ID is `arrakis`. The terrain profile uses Desert biome, sand at the surface and red sand filler. Default base height is 70, height variation 11 and noise scale 0.02. It contains sparse ores, procedural dunes and Dune-specific landmarks, rather than a custom city map. |Landmark or resource|Shipped generation setting| |Cave sietches|About one anchor per 2,000-block spacing cell.| @@ -87,7 +87,7 @@ Trees have persistent leaves, and vanilla vegetation is disabled for Arrakis. Th ## Existing terrain is preserved Generation changes apply to newly generated chunks. Old chunks do not grow additional plateaus after an upgrade. Administrators must plan exploration into new terrain or a backed-up world regeneration if they want the new formations everywhere. ===PAGE=== -ARRAKIS FIELD GUIDE | Harvesting melange +ARRAKDUIN FIELD GUIDE | Harvesting melange Suspicious sand on Arrakis is treated as a spice deposit. With the resource pack it appears bright spice-gold. Harvest it by breaking the block with the tagged Spice Harvest Shovel from your faction kit. A regular netherite shovel is rejected even if it has the same enchantments or name. Other worlds' suspicious sand does not use this Arrakis harvesting rule. ## Yield and provenance Fremen harvest two tagged spice units per deposit; other factions normally get one. Outside an active player-sponsored job, the block drops Melange Spice, represented by tagged orange dye. Its lore records the miner, faction and the current unit price. Collect the drop before using `/duneess sell`. @@ -97,7 +97,7 @@ The default regeneration delay is 120 seconds. At the end of that scheduled dela ## Estimating value Values advertised for a field are based on ordinary one-unit harvest at the configured spice price. Actual returns depend on how much sand was converted, how many deposits remain, faction yield, contract assignment and levies. A target field worth 15,000 Solaris at a 15-Solaris unit price seeks 1,000 deposits; it is not a guaranteed cash reward on discovery. ===PAGE=== -ARRAKIS FIELD GUIDE | Spice blooms and spice blows +ARRAKDUIN FIELD GUIDE | Spice blooms and spice blows An untriggered generated spice bloom is marked by a 3-by-3 magma patch with a raised central magma block. The server announces its coordinates when the marker's chunk loads. Finding the marker is separate from activating its rich field. ## Triggering a blow A player or other moving living entity touching the marker can trigger it. An arrow or trident impact at the marker also works. The trigger removes the lower magma patch, turns the raised center to glowstone and produces an explosion sound and particle. The source does not use a destructive world explosion for this bloom effect. @@ -107,7 +107,7 @@ Nearby sandy surface blocks within the default 24-block radius become suspicious ## Two other types of rich field Random suspicious-sand patches have their own procedural setting and a 5,000-Solaris default target. Defeating a sandworm creates a much larger field targeting 100,000 Solaris. The loaded-marker announcement is specifically for spice blooms, not an alert for every ordinary suspicious-sand deposit or random patch in the world. ===PAGE=== -ARRAKIS FIELD GUIDE | Sietches and personal caches +ARRAKDUIN FIELD GUIDE | Sietches and personal caches Procedural cave sietches have a broad stone-arched entrance, sleeping and kitchen spaces, a winding descent, and a lower reservoir with a waterfall. Their default anchor spacing is 2,000 blocks. Landmarks are generated only where the terrain and region permit placement. ## What is in a cache |Supply|Amount and properties| @@ -121,7 +121,7 @@ Closing the cache automatically transfers its remaining contents to your invento The cache's gold armor is useful loot, but it is not tagged as a stillsuit. Wearing it does not satisfy the Arrakis heat-protection or faction full-set requirements. Its spice is correctly tagged and can be sold, but claiming a chest is not harvesting deposits and does not advance CHOAM's harvested-spice counter. At the default sale price, 250 cache spice has 3,750 Solaris gross value. With the normal Trust levy, the direct sale leaves 3,704 Solaris, before any separate consequences of unauthorized trade. ===PAGE=== -ARRAKIS FIELD GUIDE | Sun exposure and shelter +ARRAKDUIN FIELD GUIDE | Sun exposure and shelter Arrakis has a dedicated heatstroke timer. Default lethal exposure is 300 seconds: five minutes of uninterrupted qualifying sunlight. The plugin checks once each second and warns on the first exposed second and at thirty-second intervals. ## When the timer runs All of these conditions must apply: you are alive on Arrakis, outside Creative and Spectator modes, not wearing a full tagged stillsuit, in clear weather, during daytime before world time 12300, and exposed at the top of the surface rather than beneath shelter. @@ -133,7 +133,7 @@ DuneTerrain disables the daylight cycle on Arrakis and sets world time to 6000 d ## Equipment edge cases A winged stillsuit counts as the chest piece. A mixed-faction set can still satisfy heat protection if every equipped slot has the stillsuit tag, but faction set bonuses require matching tags. Ordos Shadow Step temporarily removes armor, so its five-second concealment also temporarily breaks the full stillsuit condition. ===PAGE=== -ARRAKIS FIELD GUIDE | Shai-Hulud: model, AI and combat +ARRAKDUIN FIELD GUIDE | Shai-Hulud: model, AI and combat The current sandworm uses a real Sniffer as the visible, damageable body. An invisible Husk supplies native zombie-family targeting, pursuit and melee attacks. The body follows its controller each server tick. It is a composite gameplay creature: a vanilla Sniffer silhouette with a desert worm skin, not a custom elongated sandworm mesh. |Sandworm property|Default| |Visible body|Adult Sniffer; scale 3.5; 500 health points.| @@ -148,7 +148,7 @@ The visible Sniffer can be attacked and killed. Damage to the hidden controller ## Persistence and conversion Both parts carry saved partner UUIDs. Existing loaded Husk-based worms from 1.0.4 are converted to the visible Sniffer implementation without resetting their remaining health. The plugin repairs links after load and removes the counterpart when a linked entity dies. Live-server movement and collision behavior still need testing on the deployed Paper build. ===PAGE=== -ARRAKIS FIELD GUIDE | Defeating and summoning a sandworm +ARRAKDUIN FIELD GUIDE | Defeating and summoning a sandworm ## Death rewards Killing the tagged visible body removes the invisible controller. The worm has no normal item drops or experience reward. Instead, it strikes a visual lightning effect and converts available sandy terrain around the death location into suspicious-sand deposits. The field targets 100,000 Solaris at ordinary base yield. At 15 Solaris per unit this means a target of 6,667 deposits. Its radius is derived from the target, and each eligible position also has an 85% placement chance. Unsuitable terrain can reduce actual deposit count. The death message reports how much was actually placed; it does not deposit 100,000 Solaris into the killer's account. @@ -158,7 +158,7 @@ If at least one deposit is placed, this new spice field receives an Arrakis coor Both forms require `dune.admin`, granted to operators by default. Coordinates must be finite numbers within the world border and build height, with open feet and head space. The coordinate-free form fails outside Arrakis. A server without a loaded Arrakis world cannot summon there. Admin summons bypass the automatic population cap and do not alter the saved automatic cooldown. They use the same Sniffer body, zombie AI, configured attributes, sighting messages and death-field behavior as natural worms. Summoning can therefore deliberately create more than the default three-worm population. ===PAGE=== -ARRAKIS FIELD GUIDE | Haunted Fremen and rich-field danger +ARRAKDUIN FIELD GUIDE | Haunted Fremen and rich-field danger Haunted Fremen are hostile zombie raiders, distinct from sandworms and from water-retaliation Angry Locals. They spawn on Arrakis near players and are more likely near high-value suspicious-sand fields. The resource pack gives zombies their haunted Fremen appearance. |Raider property|Default| |Population cap|12 tagged raiders on Arrakis.| @@ -174,8 +174,8 @@ Raider sunlight combustion is cancelled by the plugin. Their equipment is for be ## Value is based on the field still present The rich-field scan counts nearby surface suspicious sand and multiplies by the spice price. At the default price, more than 5,000 Solaris requires at least 334 counted deposits. It does not inspect the total value of your inventory, sale proceeds or a hidden field ownership record. A shrinking harvested field can consequently stop qualifying for the increased chance. ===PAGE=== -ARRAKIS FIELD GUIDE | The fifteen-minute Guild notice -Session 2 introduces a discovery window for sandworms and spice blooms. The first message is local to the Arrakis server, includes X/Y/Z and warns that the Spacing Guild will notify other worlds in fifteen minutes. +ARRAKDUIN FIELD GUIDE | The fifteen-minute Guild notice +Session 2 introduces a discovery window for sandworms and spice blooms. The first message is local to the Arrakis server, includes X/Y/Z and warns that the Vaerkring will notify other worlds in fifteen minutes. ## Which events create sightings - A generated, untriggered bloom marker is found when its chunk loads, including loaded chunks checked at server startup. - An admin places a bloom marker; a previously unannounced marker erupts. @@ -188,7 +188,7 @@ Plugin messaging requires an online player connection on the sending backend. If ## Interpreting coordinates Coordinates are the initial sighting, not a live moving-worm tracker. A worm may move, despawn or die before the Guild message arrives. The notice also does not reserve the field for the discoverer, lock harvesting, or establish political ownership. The fifteen-minute window is an information embargo. ===PAGE=== -ARRAKIS FIELD GUIDE | Finite water and selling buckets +ARRAKDUIN FIELD GUIDE | Finite water and selling buckets Arrakis water is deliberately constrained. Natural source buckets collected through the water listener receive the Arrakis Water - Finite Source tag. `/dune water sell` sells these tagged buckets. Ordinary water buckets bought or collected elsewhere are not automatically accepted as Arrakis trade goods. Water flow is cancelled on Arrakis. Emptying water buckets there is blocked, and the listener prevents new ice or snow formation and water-cauldron filling. The intended loop is to locate existing natural sources, collect finite buckets, and trade them rather than build a renewable placed-water farm. The source-tag check applies to natural water generally; it is not tied to ownership of one specific sietch. ## Price and legal status @@ -283,7 +283,7 @@ Harvested job spice is not also dropped for a second sale. CHOAM progress is cre ## Leaving, cancellation and saving `/dune job finish` leaves your worker assignment; it does not force-complete the quota. `/dune job cancel` cancels your own unclaimed listing, but refuses while a worker is assigned. Listings are local to a backend. Worker assignments are in memory and need reacceptance after restart. In shared-database mode, the current save path returns after saving player profiles and does not persist new exchange-listing changes, so do not rely on listing restart durability in that mode. ===PAGE=== -PLAYER SYSTEMS | Politics, elections and the Spacing Trust +PLAYER SYSTEMS | Politics, elections and the Vaerkring Trust `/dune politics` and `/dune trust` access the same prototype political system. `/dune politics status` shows the Trust balance, election bucket, faction, leader, Emperor, stored appointments and invasion state. You need a selected faction for actions other than status. ## The treasury and elections The default Trust levy is 1.21% of applicable gross direct sales, rounded up. `/dune politics deposit 500` voluntarily withdraws 500 from your wallet and adds it to the Trust if you have sufficient funds. The Trust is not a personal withdrawable bank account. diff --git a/gui-common/src/main/java/com/example/dunegui/DunemarkItems.java b/gui-common/src/main/java/com/example/dunegui/DunemarkItems.java new file mode 100644 index 00000000..a0b1f36a --- /dev/null +++ b/gui-common/src/main/java/com/example/dunegui/DunemarkItems.java @@ -0,0 +1,38 @@ +package com.example.dunegui; + +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import java.util.List; + +/** Presentation-only note: never a bearer token or a source of wallet credit. */ +public final class DunemarkItems { + public static final NamespacedKey MODEL = new NamespacedKey("dunerealms", "dunemark_note"); + public static final String ICON_URL = "https://www.dunerealms.com/assets/dunemark-icon-128.png"; + private DunemarkItems() {} + public static int denomination(double balance) { + for (int value : new int[]{5000,1000,100,5,1}) if (balance >= value) return value; + return 1; + } + @SuppressWarnings("deprecation") + public static ItemStack icon(String name, List lore) { + return icon(100,name,lore); + } + @SuppressWarnings("deprecation") + public static ItemStack icon(int value, String name, List lore) { + if (value!=1 && value!=5 && value!=100 && value!=1000 && value!=5000) throw new IllegalArgumentException("Unsupported Dunemark denomination"); + ItemStack item = new ItemStack(Material.PAPER); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(PublicNames.text(name)); + meta.setLore(lore); + meta.setItemModel(new NamespacedKey("dunerealms", "dunemark_"+value)); + item.setItemMeta(meta); + return item; + } + public static boolean isNote(ItemStack item) { + if(item==null || !item.hasItemMeta()) return false; + NamespacedKey key=item.getItemMeta().getItemModel(); + return key!=null && key.getNamespace().equals("dunerealms") && (key.equals(MODEL) || java.util.Set.of("dunemark_1","dunemark_5","dunemark_100","dunemark_1000","dunemark_5000").contains(key.getKey())); + } +} diff --git a/gui-common/src/main/java/com/example/dunegui/NativeMenus.java b/gui-common/src/main/java/com/example/dunegui/NativeMenus.java index 75a8e0fe..17a5ee57 100644 --- a/gui-common/src/main/java/com/example/dunegui/NativeMenus.java +++ b/gui-common/src/main/java/com/example/dunegui/NativeMenus.java @@ -12,6 +12,7 @@ import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; import java.time.Duration; import java.util.*; @@ -20,10 +21,13 @@ import java.util.*; /** Shared presentation layer. All gameplay callbacks run once on the server thread. */ public final class NativeMenus { private NativeMenus() {} - public record Choice(String label, String description, Runnable action) {} + public record Choice(String label, String description, Runnable action, String imageUrl) { + public Choice(String label,String description,Runnable action) { this(label,description,action,null); } + } public static void inventory(JavaPlugin plugin, Player player, String title, Inventory model, Map actions) { List choices = new ArrayList<>(); List information = new ArrayList<>(); + List illustrations = new ArrayList<>(); for(int slot=0;slot choices) { show(plugin,player,title,"",choices); } public static void show(JavaPlugin plugin, Player player, String title, String content, List choices) { + show(plugin,player,title,content,choices,List.of()); + } + private static void show(JavaPlugin plugin, Player player, String title, String content, List choices,List illustrations) { MenuSession session=new MenuSession(player.getUniqueId()); Bukkit.getScheduler().runTaskLater(plugin,session::expire,2400L); List guarded=choices.stream().map(c->new Choice(c.label(),c.description(),()-> { if(!session.claim(player.getUniqueId())) return; Bukkit.getScheduler().runTask(plugin,()-> { if(player.isOnline()) c.action().run(); }); - })).toList(); + },c.imageUrl())).toList(); if(Bukkit.getPluginManager().isPluginEnabled("floodgate") && Bedrock.isPlayer(player)) { Bedrock.show(player,title,content,guarded); return; } @@ -57,8 +67,11 @@ public final class NativeMenus { .action(DialogAction.customClick((view,audience)-> { if(audience instanceof Player actor && actor.getUniqueId().equals(player.getUniqueId())) c.action().run(); },ClickCallback.Options.builder().uses(1).lifetime(Duration.ofMinutes(2)).build())).build()).toList(); + List body=new ArrayList<>(); + if(!content.isBlank())body.add(DialogBody.plainMessage(Component.text(content))); + for(ItemStack illustration:illustrations)body.add(DialogBody.item(illustration,null,false,true,48,48)); player.showDialog(Dialog.create(builder->builder.empty() - .base(DialogBase.builder(Component.text(title)).body(content.isBlank()?List.of():List.of(DialogBody.plainMessage(Component.text(content)))).build()) + .base(DialogBase.builder(Component.text(title)).body(body).build()) .type(DialogType.multiAction(buttons).build()))); return; } @@ -85,7 +98,11 @@ public final class NativeMenus { static boolean isPlayer(Player player) { return org.geysermc.floodgate.api.FloodgateApi.getInstance().isFloodgatePlayer(player.getUniqueId()); } static void show(Player player,String title,String content,List choices) { var form=org.geysermc.cumulus.form.SimpleForm.builder().title(title).content(content); - for(Choice choice:choices) form.button(choice.label()+ (choice.description().isBlank()?"":"\n"+choice.description())); + for(Choice choice:choices) { + String label=choice.label()+ (choice.description().isBlank()?"":"\n"+choice.description()); + if(choice.imageUrl()==null)form.button(label); + else form.button(label,org.geysermc.cumulus.util.FormImage.Type.URL,choice.imageUrl()); + } form.validResultHandler(response->{ int index=response.clickedButtonId(); if(index>=0 && index IDS=Map.of("arrakis","serevan","caladan","pelareth","giedi_prime","varkesh","kaitain","orivane","sigma_draconis_iv","nivareth"); + private static final Map LABELS=Map.of("arrakis","Arrakduin","caladan","Kaladam","giedi_prime","Giedermark","kaitain","Kaiterhof","sigma_draconis_iv","Sigmadraken IV"); + public static String label(String id){String name=LABELS.getOrDefault(id,id);return name.isEmpty()?name:Character.toUpperCase(name.charAt(0))+name.substring(1);} + public static ItemStack apply(ItemStack item,String id){String name=IDS.get(id);if(name!=null){var meta=item.getItemMeta();meta.setItemModel(new NamespacedKey("dunerealms","planet_"+name));item.setItemMeta(meta);}return item;} + private PlanetSigils(){} +} diff --git a/gui-common/src/main/java/com/example/dunegui/PublicNames.java b/gui-common/src/main/java/com/example/dunegui/PublicNames.java new file mode 100644 index 00000000..3c86e223 --- /dev/null +++ b/gui-common/src/main/java/com/example/dunegui/PublicNames.java @@ -0,0 +1,11 @@ +package com.example.dunegui; +import java.util.Map; +/** Presentation only; callers retain canonical faction/world keys for persistence and commands. */ +public final class PublicNames { + private static final Map LABELS=Map.ofEntries(Map.entry("Atreides","Aerdrecht"),Map.entry("Harkonnen","Harkveen"),Map.entry("Corrino","Korenholt"),Map.entry("Ordos","Oordwijk"),Map.entry("Fremen","Vrijduin"),Map.entry("Spacing Guild","Vaerkring"),Map.entry("Guild Navigators","Vaerkring Routekeepers"),Map.entry("Guild Navigator","Vaerkring Routekeeper"),Map.entry("CHOAM","Koopkring"),Map.entry("Solaris","Dunemarks"),Map.entry("Steward of Dune","Specerhuis"),Map.entry("House of Water","Welvaart House")); + private static final Map WORLDS=Map.of("Arrakis","Arrakduin","Caladan","Kaladam","Giedi Prime","Giedermark","Kaitain","Kaiterhof","Sigma Draconis IV","Sigmadraken IV","Stillsuit","Reclaimer suit","Sietch","Rockhaven"); + private static final Map LEGACY=Map.of("Serevan","Arrakduin","Pelareth","Kaladam","Varkesh","Giedermark","Orivane","Kaiterhof","Nivareth","Sigmadraken IV"); + public static String text(String text){if(text==null)return null;for(var pair:LABELS.entrySet())text=text.replaceAll("\\b"+java.util.regex.Pattern.quote(pair.getKey())+"\\b",java.util.regex.Matcher.quoteReplacement(pair.getValue()));for(var pair:WORLDS.entrySet())text=text.replaceAll("\\b"+java.util.regex.Pattern.quote(pair.getKey())+"\\b",java.util.regex.Matcher.quoteReplacement(pair.getValue()));for(var pair:LEGACY.entrySet())text=text.replaceAll("\\b"+java.util.regex.Pattern.quote(pair.getKey())+"\\b",java.util.regex.Matcher.quoteReplacement(pair.getValue()));return text;} + @SuppressWarnings("unchecked") public static T text(T value){return value instanceof String string?(T)text(string):value;} + private PublicNames(){} +} diff --git a/network/CLOUDPANEL.md b/network/CLOUDPANEL.md index c7079323..cfabadfa 100644 --- a/network/CLOUDPANEL.md +++ b/network/CLOUDPANEL.md @@ -1,11 +1,11 @@ -# Hetzner DuneRealms: CloudPanel on the Spacing Guild lobby host +# Hetzner DuneRealms: CloudPanel on the Vaerkring lobby host -The **Spacing Guild lobby server is also the web hosting server**. -Run CloudPanel and the Spacing Guild Paper backend on the same Debian VM. +The **Vaerkring lobby server is also the web hosting server**. +Run CloudPanel and the Vaerkring Paper backend on the same Debian VM. Velocity and the other five planets may run on this VM or another VM. ## Recommended hostname -- `dune-lobby-01`: CloudPanel, Nginx, website, and Spacing Guild Paper (port 25571) +- `dune-lobby-01`: CloudPanel, Nginx, website, and Vaerkring Paper (port 25571) - `dune-mc-01`: Velocity and five planet backends (optional second VM) ## Install order on a fresh Debian 12/13 VM @@ -13,7 +13,7 @@ Velocity and the other five planets may run on this VM or another VM. 2. Complete CloudPanel initial setup on `https://LOBBY_IP:8443`. 3. Run `network/hetzner-debian-setup.sh` to install Java 21 and Minecraft dependencies. 4. Deploy the GitHub Actions network ZIP with `network/deploy-network.sh` if running the full network locally. - If using separate VMs, copy only the Spacing Guild backend to the lobby VM and + If using separate VMs, copy only the Vaerkring backend to the lobby VM and adjust Velocity's `spacing-guild` address to its private Hetzner network IP. The existing deployment script assumes all six backends and proxy are local: multi-VM installation is not automated yet. @@ -23,7 +23,7 @@ Velocity and the other five planets may run on this VM or another VM. - TCP 8443: CloudPanel admin, restricted to your administrator IP. - TCP 22: SSH, restricted to your administrator IP. - Public TCP 25565: Velocity proxy **only on the VM hosting Velocity**. -- TCP 25571: Spacing Guild backend; only accessible from Velocity over private network. +- TCP 25571: Vaerkring backend; only accessible from Velocity over private network. - TCP 25566–25570: Planet backends; private access only. - Never expose MariaDB or Paper backends to the public internet. - If Velocity and lobby are on different hosts, change `server-ip=127.0.0.1` @@ -32,7 +32,7 @@ Velocity and the other five planets may run on this VM or another VM. - Reserve sufficient RAM for CloudPanel services and Minecraft; do not allocate all RAM to Java. Monitor CPU, disk, and memory during testing. -The network packaging and lobby generation are prototypes: custom Spacing Guild +The network packaging and lobby generation are prototypes: custom Vaerkring terrain, NPC navigation, and economy synchronization are not yet verified. CloudPanel official documentation: diff --git a/network/DEPLOYMENT-TOPOLOGIES.md b/network/DEPLOYMENT-TOPOLOGIES.md index 63e7c664..d13e7cfc 100644 --- a/network/DEPLOYMENT-TOPOLOGIES.md +++ b/network/DEPLOYMENT-TOPOLOGIES.md @@ -4,7 +4,7 @@ ## Current layout: seven virtual machines - `dune-proxy-01`: Velocity, public Minecraft TCP 25565. -- `dune-lobby-01`: Spacing Guild Paper (25571) **plus CloudPanel website** (80, 443, 8443). +- `dune-lobby-01`: Vaerkring Paper (25571) **plus CloudPanel website** (80, 443, 8443). - `dune-arrakis-01`: Arrakis Paper, private TCP 25566. - `dune-giedi-01`: Giedi Prime Paper, private TCP 25567. - `dune-kaitain-01`: Kaitain Paper, private TCP 25568. @@ -36,5 +36,5 @@ Velocity; if CloudPanel is on that VM install CloudPanel before Minecraft. 6. Review/accept Minecraft EULA on each backend, then enable/start services using `sudo systemctl enable --now dune-NODE`. -The generated ZIP includes a *prototype* Spacing Guild terrain profile; the +The generated ZIP includes a *prototype* Vaerkring terrain profile; the custom lobby generation and navigator behavior are not yet implemented. diff --git a/network/PTERODACTYL.md b/network/PTERODACTYL.md index 928896a3..7b6eb5a4 100644 --- a/network/PTERODACTYL.md +++ b/network/PTERODACTYL.md @@ -1,7 +1,7 @@ # DuneRealms Pterodactyl deployment ## Topology -- dune-lobby-01: CloudPanel, public website, Pterodactyl **panel**, Wings node for Spacing Guild. +- dune-lobby-01: CloudPanel, public website, Pterodactyl **panel**, Wings node for Vaerkring. - dune-proxy-01: Wings node for Velocity. - dune-arrakis-01, dune-giedi-01, dune-kaitain-01, dune-caladan-01, dune-sigma-01: one Wings node each for its Paper backend. diff --git a/network/TONIGHT-DEPLOYMENT.md b/network/TONIGHT-DEPLOYMENT.md index 429ecd75..8bcf64e1 100644 --- a/network/TONIGHT-DEPLOYMENT.md +++ b/network/TONIGHT-DEPLOYMENT.md @@ -6,7 +6,7 @@ | VM | Role | Port | |---|---|---| | dune-proxy-01 | Velocity | 25565 public | -| dune-lobby-01 | Spacing Guild Paper + CloudPanel website + Pterodactyl panel/Wings | 25571 private | +| dune-lobby-01 | Vaerkring Paper + CloudPanel website + Pterodactyl panel/Wings | 25571 private | | dune-arrakis-01 | Arrakis Paper + Wings | 25566 private | | dune-giedi-01 | Giedi Prime Paper + Wings | 25567 private | | dune-kaitain-01 | Kaitain Paper + Wings | 25568 private | @@ -32,7 +32,7 @@ installed services; test on staging before using it. and zip for each world, based on the DuneTerrain source configuration. These are **world-generation configuration files**, not pre-generated Minecraft region (.mca) files. Actual playable worlds must be generated by starting each -Paper backend with the correct compatible generator installed. Spacing Guild +Paper backend with the correct compatible generator installed. Vaerkring custom lobby generator is not implemented; do not advertise it as ready. World generation should be tested with a fresh world directory first. @@ -50,4 +50,4 @@ World generation should be tested with a fresh world directory first. ## Known gaps No Hetzner VM has been created by these scripts. No pre-generated Minecraft world data exists. Pterodactyl is not installed remotely. The generator's support for -Spacing Guild and the full network package still require verification. +Vaerkring and the full network package still require verification. diff --git a/network/apply-network.py b/network/apply-network.py index 082a7565..9953ba8c 100644 --- a/network/apply-network.py +++ b/network/apply-network.py @@ -44,7 +44,7 @@ def main(): out.mkdir(parents=True,exist_ok=True) (out/"proxy").mkdir(exist_ok=True) lines=['config-version = "2.7"','bind = "0.0.0.0:'+str(nodes["proxy"]["port"])+'"', - 'motd = "DuneRealms | Spacing Guild"','show-max-players = 100', + 'motd = "DuneRealms | Vaerkring"','show-max-players = 100', 'online-mode = true','player-info-forwarding-mode = "modern"', 'forwarding-secret-file = "forwarding.secret"','[servers]'] for name in BACKENDS: diff --git a/network/database/README.md b/network/database/README.md new file mode 100644 index 00000000..58eaf0ae --- /dev/null +++ b/network/database/README.md @@ -0,0 +1,89 @@ +# DuneRealms shared PostgreSQL setup + +This is a fresh database deployment template. It does not modify a running host until you run it. Existing PostgreSQL installations should keep their current database and credentials; only install the updated plugin and additive migrations. Back up SQL and backend player data before upgrading, and stop all backends during the change. + +## Fresh install + +Install Docker Engine and the Compose plugin on the database host. Run: + +```bash +cd network/database +./setup.sh +``` + +The script creates a private `.env` with two independently generated passwords and starts PostgreSQL 17. The `dune_admin` account is the container administrator. The `dune` application account can create its tables in the public schema but is not a superuser. The database volume persists across restarts. Never use `docker compose down -v` on an installation with player data. Changing `.env` passwords after initialization does not rotate existing PostgreSQL role passwords. + +The listener binds to localhost by default. If Paper backends run on different machines, set `DB_BIND_IP` in `.env` to the database host's private network IP, then rerun `./setup.sh`. Permit TCP 5432 from backend private IPs only in the host/Hetzner firewall. Use the database host's private IP in each JDBC URL. Do not use a public listener. For traffic outside a trusted private network, configure PostgreSQL TLS and a trusted certificate before using `sslmode=verify-full`. + +## Configure every backend before starting it + +Use the same existing configuration keys in `plugins/DuneCore/config.yml` on every planetary backend. Copy the `DUNE_PASSWORD` value from the database host's `.env`; do not use the administrator password. + +```yaml +database: + enabled: true + autosave-seconds: 60 + jdbc-url: "jdbc:postgresql://DATABASE_PRIVATE_IP:5432/dunerealms" + username: "dune" + password: "YOUR_GENERATED_DUNE_PASSWORD" +``` + +In `plugins/DuneEss/config.yml`, keep: + +```yaml +database: + use-core-database: true +``` + +DuneEss starts before Core and reads Core's file directly. Create/configure that file before the first network startup. Check that Essentials reports a working shared economy; configured shared mode now refuses network payments during an outage instead of falling back to a local wallet. Wallet deposits and withdrawals use atomic SQL arithmetic so they cannot overwrite concurrent exchange payments. The older `dune_players.solaris` column is legacy data; current wallets live in `dune_economy_balances`. Inventory saves do not overwrite wallets. + +Core creates missing tables and adds missing player columns automatically, under a transaction-scoped schema lock. It preserves existing profile rows, inventory blobs, economy tables, and politics. No manual inventory schema import is required. Use one dedicated database for this network. + +## Shared inventory behavior + +- Shares main inventory, hotbar, armor, offhand, selected hotbar slot, faction, XP level/progress/total. +- Uses the existing Bukkit item serialization and retains compatibility with stored inventory blobs. Verify custom item metadata on staging with your actual plugins. +- First shared login adopts that backend's local inventory when no shared inventory exists. It does not merge items from other backend player files. Choose the authoritative first-login backend and archive other backend inventories before migration. Null legacy XP columns adopt the first upgraded backend's values. +- Saves every configured interval (minimum 10 seconds), on quit/server switch, and on orderly shutdown. Final saves close open inventories to return cursor/crafting items. +- A dedicated PostgreSQL session lock admits one backend per UUID. A fast transfer arriving before the source finishes saving is rejected; reconnect after the source quits. There is no automatic proxy retry in this change. +- A failed load cannot save local stale inventory back into SQL. An unclean session remains marked open in SQL even after its connection dies; login is blocked until an administrator reconciles it. +- SQL save failures attempt a timestamped local `plugins/DuneCore/inventory-recovery/UUID-*.yml` snapshot. These files are evidence for manual recovery, never automatically replayed. A hard process/machine crash may leave no such file. +- Autosaving restores temporarily hidden Ordos armor before capturing it; a save can shorten Shadow Step's hidden-armor period. The invisibility effect retains its existing timer. +- Ender chests, positions, beds, health, hunger, effects, advancements, statistics and arbitrary plugin player tags are not synchronized. All backends must use compatible Paper/plugin/item versions and identical authenticated player UUIDs through Velocity/Floodgate. + +Do not run another inventory synchronization plugin on these same backends. This code is part of DuneCore. Only the five configured planetary identifiers opt into shared profiles; lobby and spacing_guild are excluded even if Core is installed. Keep network.local-planet correct on every backend. The lobby keeps its own inventory. Ender chests are never read, written, synchronized or exposed in account snapshots by this code; each planetary backend retains its local ender chest. Do not add an external ender chest sync plugin. + +## Recovery after an unclean session + +Never clear `session_open` as a routine login fix. A crash can leave the last SQL checkpoint older than item trades, drops or container changes. Automatically restoring that checkpoint would risk duplicating or losing items. + +1. Keep the affected player disconnected everywhere. Stop the affected backends; for recovery during an outage, stop all planetary backends. +2. Back up SQL, backend player data and all `inventory-recovery` files. +3. Inspect the affected `dune_players` row and compare checkpoint data with local recovery/player data and any trades/container changes. Reconcile items explicitly. Recovery snapshots contain Base64 Bukkit item arrays; interpret them with this plugin on the same compatible Paper version. Do not concatenate blobs or merge inventories blindly. +4. Only after reconciling and choosing the authoritative checkpoint, use an administrator SQL session to clear the marker for that single UUID: + +```sql +BEGIN; +SELECT uuid,faction,session_open FROM dune_players +WHERE uuid='REPLACE-WITH-PLAYER-UUID' FOR UPDATE; +UPDATE dune_players SET session_open=FALSE +WHERE uuid='REPLACE-WITH-PLAYER-UUID'; +COMMIT; +``` + +5. Start the backends, reconnect the player and verify all slots, XP and wallet. Archive the incident and recovery files. Never clear markers for all players at once. + +## Capacity, backups and verification + +Inventory I/O follows this plugin's existing synchronous server-thread model with connection/socket timeouts. Each active planetary player holds one direct PostgreSQL connection plus short-lived economy/politics connections. Size `max_connections`, memory and backend player caps together; do not use PgBouncer transaction pooling for these session locks. Measure login and autosave tick times before increasing player limits. Java 21 and Paper 1.21.8 are the repository's pinned target, not an unverified newer release. + +Example backup from this directory (shell creates the backup on the host): + +```bash +umask 077 +docker compose exec -T postgres pg_dump -U dune_admin -d dunerealms -Fc > dunerealms-backup.dump +``` + +Test restores on a separate database. Keep backups outside the Docker volume and off the host. + +Staging acceptance: transfer between two distinct planetary backends with tagged spice, named/enchanted/PDC items, armor, offhand and XP; confirm different local ender contents remain different; verify exact quantities and metadata. Try duplicate connections, fast transfer, database loss during login and quit, and a forced backend crash. Confirm rejected/unclean sessions cannot overwrite SQL. Verify Java, Bedrock/Floodgate and ViaVersion clients. Production deployment is pending this live validation. diff --git a/network/database/compose.yml b/network/database/compose.yml new file mode 100644 index 00000000..ba057294 --- /dev/null +++ b/network/database/compose.yml @@ -0,0 +1,21 @@ +services: + postgres: + image: postgres:17 + restart: unless-stopped + environment: + POSTGRES_DB: dunerealms + POSTGRES_USER: dune_admin + POSTGRES_PASSWORD: ${POSTGRES_ADMIN_PASSWORD:?Run setup.sh first} + DUNE_PASSWORD: ${DUNE_PASSWORD:?Run setup.sh first} + ports: + - "${DB_BIND_IP:-127.0.0.1}:5432:5432" + volumes: + - dune_postgres:/var/lib/postgresql/data + - ./init-app-user.sh:/docker-entrypoint-initdb.d/10-app-user.sh:ro + healthcheck: + test: ["CMD-SHELL", "pg_isready -U dune_admin -d dunerealms"] + interval: 10s + timeout: 5s + retries: 6 +volumes: + dune_postgres: diff --git a/network/database/init-app-user.sh b/network/database/init-app-user.sh new file mode 100644 index 00000000..f861df37 --- /dev/null +++ b/network/database/init-app-user.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<'SQL' +\getenv app_password DUNE_PASSWORD +CREATE ROLE dune LOGIN PASSWORD :'app_password'; +GRANT CONNECT ON DATABASE dunerealms TO dune; +GRANT USAGE, CREATE ON SCHEMA public TO dune; +SQL diff --git a/network/database/setup.sh b/network/database/setup.sh new file mode 100644 index 00000000..79442afa --- /dev/null +++ b/network/database/setup.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")" +command -v docker >/dev/null || { echo 'Install Docker Engine with the Compose plugin first.' >&2; exit 1; } +docker compose version >/dev/null +umask 077 +if [[ ! -e .env ]]; then + command -v openssl >/dev/null + { + printf 'POSTGRES_ADMIN_PASSWORD=%s\n' "$(openssl rand -hex 32)" + printf 'DUNE_PASSWORD=%s\n' "$(openssl rand -hex 32)" + printf 'DB_BIND_IP=127.0.0.1\n' + } > .env +fi +docker compose up -d --wait +printf '\nDatabase ready. Configure every backend using the dune password in this directory/.env.\nSee README.md for network binding, migration, backups and recovery.\n' diff --git a/network/generate-world-files.py b/network/generate-world-files.py index d1f76cd1..74440da5 100644 --- a/network/generate-world-files.py +++ b/network/generate-world-files.py @@ -35,7 +35,7 @@ def main(): lobby = output / "spacing-guild" lobby.mkdir(exist_ok=True) (lobby / "README.txt").write_text( - "Spacing Guild custom world generator is not implemented.\n" + "Vaerkring custom world generator is not implemented.\n" "Use vanilla Paper world generation temporarily; do NOT set DuneTerrain server.planet to spacing_guild.\n", encoding="utf-8") with ZipFile(output / "spacing-guild-world-config.zip", "w", ZIP_DEFLATED) as z: diff --git a/network/package.py b/network/package.py index 36457d07..0f51924a 100644 --- a/network/package.py +++ b/network/package.py @@ -27,7 +27,7 @@ if len(list((ROOT/"proxy"/"plugins").glob("*.jar"))) != 2: servers="\n".join(f' {name} = "127.0.0.1:{port}"' for name,port in PLANETS.items()) (ROOT/"proxy"/"velocity.toml").write_text(f'''config-version = "2.7" bind = "0.0.0.0:25565" -motd = "DuneRealms | Spacing Guild" +motd = "DuneRealms | Vaerkring" show-max-players = 100 online-mode = true player-info-forwarding-mode = "modern" @@ -86,8 +86,8 @@ See docs/Native-GUI.md in the source for Floodgate forwarding and shared key set Run the Velocity proxy and six Paper backends separately. Download the matching server and proxy binaries from their official distribution sites. Do not expose backend ports. Set eula=true only after reviewing the Minecraft EULA. -Spacing Guild is the first-join lobby (port 25571); connect players to Velocity port 25565. -IMPORTANT: Spacing Guild world generation is NOT yet implemented by DuneTerrain; its +Vaerkring is the first-join lobby (port 25571); connect players to Velocity port 25565. +IMPORTANT: Vaerkring world generation is NOT yet implemented by DuneTerrain; its configuration is a proposed profile and will not generate a custom lobby until code is added. generation.yml is a staging copy; DuneTerrain currently reads config.yml. Guild NPC/return command and cross-server economy synchronization are not verified. diff --git a/website/.env.example b/website/.env.example index bac3890f..ba192071 100644 --- a/website/.env.example +++ b/website/.env.example @@ -14,3 +14,7 @@ DISCORD_DIPLOMACY_CHANNEL_ID= # Read-only HTTPS endpoint for sanitized PostgreSQL exchange listings (server-side only) EXCHANGE_LISTINGS_URL= EXCHANGE_READ_TOKEN= + +# Optional private read-only PostgreSQL role for CP inventory/sales. +# Never use the game writer role or publish this URL to browser code. +DUNE_INVENTORY_DATABASE_URL= diff --git a/website/ALTCHA-LICENSE.txt b/website/ALTCHA-LICENSE.txt new file mode 100644 index 00000000..9bcb4714 --- /dev/null +++ b/website/ALTCHA-LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023-2026 Daniel Regeci, BAU Software s.r.o. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/website/README.md b/website/README.md index d890a514..2efbf6f2 100644 --- a/website/README.md +++ b/website/README.md @@ -17,10 +17,4 @@ See [Forums and player support](FORUMS-PORTAL.md) for independent forums, the Yo The standalone [Sietch Armoury](https://project-dune.bonnystoat9.chatgpt.site/armoury.html) contains all 68 illustrated item entries and full suit abilities. [Diplomacy](https://project-dune.bonnystoat9.chatgpt.site/diplomacy.html) reads the DuneCore 1.0.10 current-office snapshot via a dedicated DiscordSRV channel. -## The Prophecy blog - -The top menu links to `prophecy.html`, a book-focused Paul Atreides journal with six illustrated posts covering Dune, Dune Messiah and Children of Dune. Each article has a spoiler gate, source notes and previous/next links. The index supports book filters and search. Original commentary is separated from plot context. Posts live in `web/prophecy-data.json`; the build regenerates their static pages with `scripts/build-prophecy.mjs`. - -The Prophecy articles are extended essays of at least 3,000 body words each. Reading estimates use 200 words per minute and exclude graphic text. Each essay includes a timeline, relationship map, comparison board and linked contents. Long-form source lives in `content/prophecy/*.md`; `web/prophecy-graphics.json` holds visual-aid labels. The build fails if an essay falls below the minimum length. - See [Patchnote workflow](PATCHNOTES.md) for the 5–10 product-task bundle policy, permanent DUNE request IDs, pending queue, urgent bugfix reports and source-driven public archive. Staff and contributor records are on `staff.html`; Patch Notes is on `patch-notes.html`. diff --git a/website/content/prophecy/prescience-and-the-desert.md b/website/content/prophecy/prescience-and-the-desert.md deleted file mode 100644 index 661e22d3..00000000 --- a/website/content/prophecy/prescience-and-the-desert.md +++ /dev/null @@ -1,93 +0,0 @@ -# Seeing ahead changes the present - -Prescience is easiest to imagine as a window into a later time. But for the person who believes he can look through that window, its first effect is on the present. An anticipated loss can change how an ordinary conversation is heard. A possible danger can shape a decision long before the danger becomes visible to anyone else. The future becomes an active pressure within a moment that other people experience as open. - -This means that Paul's relation to possibility cannot be described only by asking whether a vision proves accurate. Accuracy matters, but it does not exhaust the question. We also need to ask how the vision organises his attention. Which outcomes become emotionally dominant? Which alternatives acquire an unbearable cost? Which immediate experiences are treated as steps along an anticipated sequence? The gift changes the way a person inhabits time, not merely the quantity of information he possesses. - -Our interpretation focuses on that changed relation. A person who anticipates disaster may find it difficult to remain available to the uncertainty of the people around him. He can be present in a room while already responding to a future no one else can inspect. That makes his apparent confidence ambiguous. It may express mastery, fear, resignation or dependence on an expected pattern. Reading for those different possibilities prevents the word prescience from becoming a simple explanation that makes further attention unnecessary. - -# A map is not the ground beneath a foot - -A useful distinction is the difference between a representation of a route and the experience of travelling it. A map can make choices easier, but it cannot remove the body's exposure to the route. Likewise, anticipating an event does not eliminate the experience of living through it. Knowledge and experience remain related without becoming interchangeable. Paul can know something about a possible future and still be vulnerable to what that future demands of him. - -The distinction also guards against a misleading idea of emotional preparation. We sometimes assume that knowing a loss is coming must make the loss less shocking or less difficult. It might allow preparation, but it can also extend fear across a much longer period. The person is not simply waiting for an event. He is already living with an interpretation of it, making decisions under its influence and measuring other possibilities against it. Anticipation can deepen a burden rather than lighten it. - -We read Paul's prescience through this tension between guidance and exposure. The graphic route in this article is deliberately an analytical aid, not a claim that his visions form one neat diagram. Its purpose is to keep distinct three things: what is anticipated, what is chosen and what is experienced. When reading a passage about a vision, ask which of those levels is being described. Confusing them can turn a character's suffering into proof of inevitability, or turn anticipated information into the false impression that he has already lived every relevant consequence. - -# Physical blindness and another form of dependence - -The stone-burner attack makes Paul's physical vulnerability unmistakable. A capacity that has marked him as extraordinary now becomes involved in how he negotiates ordinary movement. The relation between seeing and vision changes. This is not simply a dramatic demonstration that supernatural ability can replace a damaged sense. It creates a new dependence on an anticipated pattern and makes the distinction between bodily capacity and prescient guidance harder to ignore. - -Readers should take care not to treat physical blindness merely as a convenient metaphor. Within the story it concerns a person whose body has been injured and whose practical relation to his surroundings has changed. The thematic questions arise from that situation; they should not erase it. The contrast between ordinary sight and another form of perception is politically and philosophically suggestive, but the injury also belongs to the continuing vulnerability of a human being. - -Our interpretation asks what happens when navigation depends on correspondence between expectation and experience. An ordinary map can be revised after a mistaken turn. A route treated as foreknown may be harder to approach with that same flexibility. If confidence in the route becomes the condition of movement, uncertainty acquires a different cost. Paul dramatizes this problem at an unusual scale. The broader question is whether a person can become so invested in the predictive structure that supports him that any divergence feels like the collapse of the ground under his feet. - -# Knowing danger does not remove choice - -Prescient narratives encourage difficult arguments about freedom. If a person sees an outcome and acts with that outcome in mind, how much of the resulting action belongs to choice? The question cannot be answered simply by calling the future fixed or calling the person free. Those descriptions may conceal the process through which anticipated outcomes become reasons for action. A decision can be shaped by pressure without becoming meaningless as a decision. - -For reading Paul, it helps to distinguish external constraint from an interpretation of constraint. A threat can be real, while the belief that one response is the only acceptable response remains something to examine. At the same time, examining the belief should not become an easy claim that every alternative was harmless and available. The reader occupies a different position from the person confronting the dilemma. We can ask about possibilities without pretending that uncertainty has no practical or emotional force. - -Our interpretation preserves responsibility and difficulty together. Paul's anticipation of worse outcomes does not automatically excuse every action he chooses. Nor does his responsibility make every choice simple. The critical question is how the narrative presents the field of alternatives. Does it allow us to inspect them, or do we largely receive them through Paul's fear? How does a feared possibility acquire the status of necessity? These questions help turn a debate about destiny into a close reading of the language through which a particular character understands his options. - -# Chani and the future that becomes intimate - -The threat of personal loss changes the scale of Paul's concern. Imperial futures can be described through institutions, factions and broad consequences. Chani's place in his life makes anticipation intimate. A possible future is no longer only a political arrangement to be managed. It involves someone he loves. The emotional significance of that person can give one outcome a weight that an abstract map of alternatives cannot adequately express. - -This should not reduce Chani to an instrument for explaining Paul's feelings. Her life is not merely the material through which the reader discovers his vulnerability. A careful reading asks how the narrative's concentration on his foreknowledge affects the visibility of her own experience. The person whose future becomes an object of another's fear is still a person living in a present, with knowledge and concerns that are not identical to the oracle's account. - -We interpret the intimate future as a point where protective intention becomes especially difficult to analyse. Wanting to prevent suffering can encourage care, but it can also encourage decisions made on another person's behalf. Unequal knowledge complicates that relation. If one person believes he sees what the other cannot, the wish to protect may make ordinary conversation seem insufficient. Ask how much remains shared, how much is withheld and who bears the consequences of the difference. The novel does not need to eliminate the sincerity of love in order to make those questions troubling. - -# The twins and the failure of complete anticipation - -The birth of Leto II and Ghanima places the question of an inherited future beside the limits of Paul's expectation. Whatever the scale of his ability, the future cannot comfortably be reduced to his mastery of it. The children are not simply a continuation of a plan. They are people whose presence changes the terms under which a plan could be understood. This is part of why the ending carries both continuity and rupture. - -A dynasty encourages the description of children as heirs, solutions or risks. Those descriptions reflect adult concerns. They are not complete accounts of the people who will grow into the positions being imagined. Reading the twins through this distinction keeps the future from becoming merely an object already possessed by their father. His knowledge and authority affect their world, but they do not exhaust the meaning of their lives. The next generation enters a history without being identical to its expectations. - -Our interpretation treats this as a challenge to the emotional appeal of total prediction. Complete anticipation might promise safety, yet a world entirely contained within one person's vision would leave little room for other people to become genuinely new to him. The narrative's pressure on Paul's expectations can therefore be read as more than an unfortunate gap in a useful ability. It exposes the difference between knowing a future and having a rightful claim to contain it. A parent can care deeply about what comes next without becoming the final author of everyone who will live there. - -# Grief and the limits of public explanation - -When a public figure experiences private grief, observers often translate the grief into the language of the public role. A loss becomes a succession problem, a political weakness, a symbolic event or a sign of destiny. Those descriptions can identify real consequences. They can also make it difficult to see the loss as a person's experience rather than an element in a larger explanation. Paul's position makes this translation especially intense. - -For the reader, there is a corresponding temptation to use grief as a final key to the character. If we can explain why he suffers, we may feel that we have explained why he acts. But grief does not produce a single predictable response. It can coexist with calculation, obligation, fear and exhaustion. A person can continue to make consequential choices while also being overwhelmed by loss. The emotional and political dimensions remain connected without collapsing into one another. - -We read the ending of Dune Messiah as preserving this complexity. Paul's humanity matters, but it does not erase the history of his authority. His public significance matters, but it does not make his intimate attachments unreal. The difficult task is to allow both scales into the same judgment. Ask whether a particular passage invites the reader to understand suffering, to excuse an action, or to reconsider the adequacy of a public identity. Those invitations are different. A careful reading can accept the first without automatically accepting every implication of the others. - -# Walking away and what remains behind - -Paul's departure into the desert changes his relation to his public identity, but it does not dissolve the order built around that identity. This distinction is central to understanding the ending. A person can leave a position while institutions continue using his name. He can reject an arrangement while people who depended on it continue inhabiting its consequences. Withdrawal is an action within a history, not an erasure of the history. - -That does not make departure insignificant. Refusing to remain at the centre can change how authority is experienced and remembered. It can remove an immediate source of command or create a new symbolic meaning. But the action must be evaluated through what it changes and what it leaves unresolved. Otherwise, walking away can be imagined either as complete redemption or as complete abandonment. Both descriptions are too quick to capture the different relationships involved. - -Our interpretation asks readers to follow the remainder. Who continues governing? Who continues believing? Who must explain the absence? What responsibilities were attached to the person, and which have become attached to an institution? These questions lead toward Children of Dune, but they are already available at the end of the earlier book. A narrative departure can feel final because it gives the central character a decisive movement. The social world has no obligation to share that sense of finality. Its continuing life is part of the meaning of the movement. - -# Fremen custom and the meaning of an ending - -The Fremen expectation associated with blindness gives Paul's departure a communal frame. He does not simply choose an isolated gesture with no cultural meaning. His action is legible through a practice that exists beyond his individual life. That connection matters because the ending places an extraordinary person within a shared rule, while the public history of that person makes the shared rule difficult to treat as an ordinary event. - -Readers can interpret this movement in several ways without claiming that one exhausted explanation has been supplied. It can suggest a return to a community's terms after a period of exceptional authority. It can mark an attempt to stop organising life around prescient control. It can also remain connected to loss, exhaustion and the desire to leave an unbearable position. The presence of a communal meaning does not cancel these personal dimensions. It gives them another context in which to be considered. - -Our reading stresses that a symbolic action is not necessarily a simple action. The more meanings gather around it, the less useful a single label becomes. Does Paul act as a Fremen, a grieving partner, a father, a ruler withdrawing from his office, or a figure trying to change his legend? The question may require several answers. Keeping them together allows the ending to remain unresolved in a productive way. It closes one stage of his life while leaving the reader with a problem that cannot be solved merely by identifying the direction in which he walks. - -# Why uncertainty can be a condition of freedom - -Much of the appeal of prescience comes from the hope that uncertainty can be removed. If danger could be anticipated and loss prevented, knowing the future might appear to be the highest form of protection. Yet uncertainty is also part of encountering other people as beings whose lives are not fully contained in one's own plans. Removing every surprise would change the relationship between protection and control. - -This is not a romantic defence of preventable suffering. Uncertainty can be frightening and costly. Knowledge can be valuable. The question is whether every increase in predictive power automatically improves the conditions of a shared life. If anticipation makes one person indispensable, if alternatives must be justified to the person who claims to see all their consequences, or if other people's futures become elements in a private calculation, more knowledge can also produce a more concentrated form of authority. - -We interpret Paul's experience as an invitation to examine this trade-off without pretending that it has an easy solution. Freedom may require ways of living with what cannot be entirely known. That requirement does not eliminate responsibility for foreseeable harm. It changes the standard from total control to accountable action under incomplete conditions. When reading, notice whether the desire to prevent one feared outcome has become a desire to prevent every departure from the expected pattern. The difference can reveal the point at which foresight stops functioning mainly as guidance and begins functioning as a claim over the future. - -# A guided exercise in possible futures - -Draw three columns labelled anticipated, chosen and experienced. Select one moment in the novel in which Paul's understanding of a future affects his immediate conduct. In the first column, describe what he believes may happen. In the second, describe what he actually does. In the third, describe what the narrative lets him or another person undergo. Keep the columns separate even when they seem closely connected. - -Now identify what is missing from each account. A vision may leave emotional experience unexplained. A decision may leave its alternatives uncertain. An experienced consequence may not tell us what would have happened otherwise. These absences are not failures of the exercise. They show why an ethical judgment cannot always be reduced to a single piece of information. The relationship between the columns is the subject of analysis, rather than a mechanical proof that one column completely determines the others. - -Finally, ask what a person without Paul's knowledge could reasonably say about the action. Would an explanation be possible? Would disagreement have any place? Would the affected person be asked to trust, to consent or simply to accept? The questions bring prescience back into the realm of relationships. They also provide a bridge to the next chronicle, where the man who carried an enormous public identity returns to a world that has continued interpreting him. The limits of seeing ahead become inseparable from the limits of controlling what other people will make of a life. - -# Hold the ending open - -Before moving to the next book, write two accounts of Paul's departure. In one, concentrate on what he refuses to continue doing. In the other, concentrate on what remains active without him. The first description may make departure feel like an ending; the second may make it feel like a change within an ongoing situation. Keeping both accounts lets you distinguish the end of a person's role from the end of the consequences associated with that role. - -This distinction is especially useful when a story presents a strong final image. A memorable image can make an interpretation feel complete before the social questions have been answered. Do not discard the image's emotional force. Instead, ask what it cannot show: institutions continuing to operate, people explaining an absence, and children inheriting a world they did not choose. These are the unfinished conditions into which the next novel opens. Paul's movement matters precisely because it changes a life while leaving so much of its surrounding world available for further conflict. diff --git a/website/content/prophecy/the-heir-of-caladan.md b/website/content/prophecy/the-heir-of-caladan.md deleted file mode 100644 index 64ec6641..00000000 --- a/website/content/prophecy/the-heir-of-caladan.md +++ /dev/null @@ -1,85 +0,0 @@ -# An education is also a political arrangement - -Paul's education is easiest to admire when we treat its different parts as a list of advantages. He learns to observe, to reason, to fight, to regulate himself, and to recognise danger. Yet an education never consists only of techniques. It also teaches a student what deserves attention, whom to trust, what to fear, and what kind of future to regard as normal. A noble heir is being prepared for a world in which some people command and others depend on their command. That expectation is part of his inheritance before any supernatural possibility enters the story. - -This makes the early Paul interesting in a way that a catalogue of exceptional powers cannot capture. Different adults have different investments in what he becomes. The family needs continuity. Teachers want competence. The Bene Gesserit view individual development through a much longer institutional perspective. Jessica is both a mother and someone formed by that institution. Paul receives skills from people whose purposes do not completely coincide. His apparent coherence as a young person rests on relationships that are more complicated than a single heroic training programme. - -For a close reading, distinguish the question of what Paul can do from the question of what his training encourages him to value. Self-command can help him survive; it can also become a measure by which he judges himself and others. Political awareness can make him considerate; it can also teach him to translate people into strategic possibilities. The novel invites admiration for discipline while leaving room to ask how discipline serves power. Our interpretation is that Paul's education provides both resources and habits he will later have to reconsider. A trained response can be useful without being the final answer to an unfamiliar world. - -# The body before the prophecy - -Stories of extraordinary destiny often move quickly past the ordinary body. The gifted child becomes an idea: a future ruler, a promised saviour, a name waiting for history. Dune keeps bringing attention back to bodily vulnerability. Fear, pain, fatigue, breath and exposure matter. This attention prevents Paul's importance from becoming a complete exemption from being human. The larger the story makes his potential, the more useful it is to notice moments when that potential still belongs to a body that can be hurt. - -Consider what self-control means when its immediate purpose is survival. There is a difference between having no fear and deciding what to do while afraid. The first is an absence; the second is an achievement under pressure. A reader who confuses the two can turn Paul's preparation into a fantasy of emotional invulnerability. A more careful interpretation sees control as work. It requires attention, effort and the ability to remain present when instinct urges a simpler reaction. That work is especially significant for someone repeatedly assessed by powerful adults. - -This distinction also complicates the relation between feeling and leadership. If a leader is praised only for controlling visible emotion, observers may mistake a calm surface for a complete moral understanding. But emotional restraint cannot by itself establish that an action is wise or fair. It only tells us something about how the action is performed. In reading Paul's early story, ask what his discipline makes possible, and what it cannot decide for him. The body's survival and the community's good are connected, but they are not identical. A person can learn to master a reaction long before learning how to bear the consequences of authority. - -# Caladan as a remembered measure - -Caladan functions as more than an attractive starting location. A home gives a person an implicit measure of normality. The familiar environment tells you what you can assume about water, shelter, movement and the behaviour of other people. Those assumptions are usually invisible while the environment continues to support them. Leaving home makes them available for examination. Paul's transition matters because he is not simply exchanging scenery; he is moving between different conditions of life and different systems of expectation. - -The remembered security of Caladan can therefore be read as a privilege that does not initially announce itself as privilege. Abundance is most easily taken for granted by someone whose life has been organised around it. Arrakis makes that ease impossible. Water becomes a consideration that cannot be left in the background. The contrast asks the reader to reconsider the habits of a ruling family as environmental habits as well as political ones. Authority does not make the body independent of the world that sustains it. - -There is also an emotional cost to this contrast. A remembered home can guide a person, but it can become a misleading standard if every unfamiliar practice is measured against it. Reading Paul carefully means noticing the difference between retaining affection for Caladan and assuming that Caladan explains everything. We interpret the movement between worlds as a challenge to inherited certainty. A person who wants to act responsibly in a new environment must become capable of learning from people whose experience was not part of his education. The past remains valuable, but it cannot serve as an instruction manual for every possible future. - -# The family as shelter and obligation - -House Atreides provides Paul with identity, affection, resources and a public position. It is important not to reduce these connections to manipulation. Family relationships can be sincere even when they also serve political purposes. The difficulty is that Paul cannot cleanly separate the private and public meanings of his family. Loving his father and inheriting his father's name place him within a structure of duty. The same connection that gives him belonging also makes him legible to allies and enemies. - -This is why inheritance is a richer subject than ownership. Paul inherits a place in other people's stories about the Atreides. Some people attach hope to that name, some attach resentment, and some calculate its usefulness. He does not control the whole meaning of his own identity. A title can be handed down, but reputation travels through a community and changes as it travels. The heir receives not only something to preserve, but something already interpreted by people outside the family. - -Our reading places particular weight on the tension between fidelity and adaptation. To remain loyal to a family's memory does not necessarily mean repeating every family assumption. A new situation may require a different way of acting. Conversely, change can become an excuse to abandon obligations without acknowledging the abandonment. Paul must carry a name into circumstances that make its old supports unreliable. The question is not simply whether he will recover what was lost. It is what preservation means when preserving a family can involve transforming the very form of its power. That tension is worth following before treating his later success as a straightforward restoration. - -# Arrakis and the geography of dependence - -Arrakis forces a political story to reveal its material foundations. The struggle for spice is a struggle over something needed beyond the place where it is found. That creates an unequal relation between a local environment and a much larger system of demand. Powerful institutions can regard the planet as a resource while people who live there experience it as a world. Those descriptions overlap, but neither can simply replace the other. A world is not exhausted by the price assigned to what can be taken from it. - -Paul enters this situation with a family's political responsibilities, but the reader should resist treating that perspective as the planet's only perspective. A ruler's problem may be how to govern effectively. A worker's problem may be how to survive a dangerous day. A community's problem may be how to protect practices that outsiders do not understand. The point is not that one perspective makes all the others meaningless. It is that a single privileged viewpoint can hide the conditions on which its own plans depend. - -We interpret the geography of the early novel as a lesson in dependence. The distant consumer depends on a substance. The governing institution depends on production. Production depends on local knowledge, labour and environmental conditions. A young heir depends on people who can interpret dangers he has only recently encountered. Mapping these relations changes the meaning of power. Power may appear at the top of an organisation, but its ability to act rests on connections running far below that visible position. Ask what happens when a character mistakes the height of his rank for freedom from those connections. - -# Betrayal and the failure of a protected future - -The fall of House Atreides breaks the assumption that Paul's future can be managed by the people who have prepared him. An education aimed at continuity meets a situation defined by rupture. The family's resources no longer function as a reliable protective structure. That does not make Paul's training useless, but it changes the problems the training must address. Competence is now needed in circumstances its teachers could not simply keep under control. - -It is tempting to describe such a rupture only as the necessary beginning of an adventure. That reading can make loss look like a convenient device for releasing the hero's potential. A more attentive reading allows both meanings to remain visible: the event changes the direction of the story, and it represents the destruction of relationships and expectations. Narrative usefulness is not the same thing as personal benefit. Paul's possibilities may widen in one sense while his life becomes narrower and more dangerous in another. - -Our interpretation is that this rupture also exposes the limits of political foresight. Knowing that a system is dangerous does not guarantee protection from it. People can understand risk and still be overcome by combinations of force, deception and circumstance. For a reader, this is a useful guard against hindsight. Once an outcome is known, every earlier sign can seem like an obvious warning that should have determined every decision. The people inside the story do not stand in that comfortable retrospective position. Read their uncertainty as part of the event, rather than treating later knowledge as something they simply failed to possess. - -# Jessica and the problem of shared survival - -Paul's movement into the desert is not the solitary journey of a completely self-sufficient prodigy. Jessica's presence matters. Their survival involves a relationship between two people with overlapping but different kinds of experience. She is not merely an explanation for abilities he already possesses. She remains a person whose knowledge, concern and choices affect the conditions in which he acts. That makes the early transition a story of shared adaptation as well as individual development. - -Reading their relationship only through the language of destiny can obscure ordinary forms of responsibility. A mother protecting a child and a trained person interpreting danger are not interchangeable roles, even when one person occupies both. Jessica must respond to immediate circumstances while carrying the consequences of an institutional past. Paul must learn from her while also changing the balance of their relationship. The pressure of survival can bring people together without making their purposes completely identical. - -We read this relationship as a challenge to the myth that exceptional achievement must be exclusively personal. Paul's later symbolic prominence can make the contributions of other people seem like preliminary steps toward his greatness. Yet the story can also be read in the opposite direction: his prominence rests on networks of teaching, protection and cooperation that a heroic label compresses. A useful question is who becomes less visible as a central figure becomes more visible. Following Jessica's role helps preserve that question. It also keeps the reader aware that the private costs of a public destiny are often carried by more than the person who receives the famous name. - -# Learning from an unfamiliar community - -The transition toward Fremen life changes what counts as expertise. Paul's inherited education remains important, but it cannot replace the knowledge of people who have learned to live on Arrakis. Techniques developed for the desert emerge from repeated contact with its demands. They are practical, social and environmental at once. A visitor who sees only their unfamiliar appearance misses the intelligence contained in them. The need to learn can therefore become an ethical test, not just a technical one. - -There is a difference between respecting a community's knowledge and treating that knowledge as another resource to acquire. The first acknowledges that practices belong to relationships and a history. The second regards them mainly as tools that improve an individual's prospects. Paul can be read through this distinction without assuming that every interaction belongs wholly to one category. People can learn sincerely while also recognising strategic advantages. The discomfort of that combination is part of what gives the story its political complexity. - -Our interpretation asks readers to watch how quickly admiration can become a claim to leadership. Being unusually capable in a community does not automatically answer the question of what authority a person should have over it. Ability, belonging and political legitimacy are different matters. The early story prepares the ground for those differences before Paul's later rise makes them urgent. While reading, ask whether a scene shows him listening, adapting, persuading, commanding or being interpreted by others. Those verbs describe distinct relationships. Keeping them separate prevents the convenient assumption that every form of successful participation already contains a rightful claim to rule. - -# Why the shape of a hero is so persuasive - -The early Paul gathers features that readers readily associate with a hero: youth, discipline, family loyalty, endangered inheritance and the capacity to meet difficulty. These features make it easy to invest in his survival. That investment is not a mistake. A story needs the reader to care about people. The problem begins when care for a person becomes automatic approval of every form of power that later attaches to him. - -This is where reading habits deserve attention. We often want the abilities established early in a narrative to be rewarded with recognition. We want injustice to be answered and losses to acquire a meaningful place in a larger design. Those desires can make a rising central figure feel like a solution before we have examined the terms of the solution. The narrative does not need to force us to surrender judgment; sympathy can encourage us to do some of that work ourselves. - -We interpret the first stage of Paul's story as a training ground for the reader as well as for Paul. The reader learns to recognise the signs of exceptional potential, then must remain alert to what that recognition leaves out. A heroic structure can carry genuine courage and troubling assumptions at the same time. A character can deserve sympathy without deserving unlimited authority. Keeping those propositions together is more demanding than deciding once that Paul is either admirable or dangerous. It lets the early novel retain its emotional force while preparing a more careful response to what follows. - -# A reading route through the early story - -For a deliberate rereading, follow three threads rather than attempting to memorise every political name. First, track the sources of Paul's knowledge. When does he draw on training, when does he learn from another person, and when does experience force him to revise an assumption? This thread keeps ability attached to a process of formation. It prevents the vague label of genius from swallowing the specific work through which a character becomes capable. - -Second, track the changing scale of his obligations. In one moment he is a son, in another an heir, in another a person facing immediate danger. Those roles can make different demands. Ask when the narrative makes their conflict visible and when the desire to move forward encourages you to smooth the conflict away. A character's priorities may be understandable without being easy to reconcile. That is often the point at which an apparently simple adventure becomes an ethical story. - -Third, track the relationship between place and expectation. Notice what Caladan allows characters to take for granted, what Arrakis makes unavoidable, and what the desert asks them to learn. These observations do not require a verdict on Paul's entire life. They provide a foundation for the next chronicle. Before a community names a saviour, there is a vulnerable person, a damaged family, an unfamiliar environment and a network of people whose knowledge matters. Holding that fuller picture in mind makes the arrival of prophecy more interesting. It also makes it harder to mistake the recognition of a destined hero for the end of every political question. - -# Questions to take back to the novel - -Choose an early exchange between Paul and one of the adults who teaches him. Read it twice, once for what the adult explicitly wants and once for what Paul has reason to infer. Do the two readings produce the same picture of their relationship? The exercise matters because instruction can be both generous and interested. A teacher can care about a student while also caring about the future that student represents. You do not need to reduce the relationship to one motive in order to analyse it carefully. - -Then choose a moment after the family's protection has failed. Identify what Paul retains from his education and what the immediate situation supplies that education could not. Compare the kinds of knowledge rather than ranking their owners. Finally, write a short response to this question: what would a responsible heir need to learn that a successful survivor might not yet know? The difference helps explain why survival is the beginning of Paul's political story, rather than proof that all its difficult questions have already been answered. diff --git a/website/content/prophecy/the-making-of-muad-dib.md b/website/content/prophecy/the-making-of-muad-dib.md deleted file mode 100644 index 978aee8e..00000000 --- a/website/content/prophecy/the-making-of-muad-dib.md +++ /dev/null @@ -1,89 +0,0 @@ -# Three stories meet in one name - -The name Muad'Dib can be approached through three overlapping stories. One is the story of a displaced heir seeking survival and a future after the loss of his family's position. Another is the story of a community whose knowledge and aspirations long precede the visitor who enters its world. A third is the story of religious expectations shaped partly by an institution with purposes beyond that community. Treating any one of these as the complete explanation makes Paul's rise easier to describe and harder to understand. - -These stories do not meet as equal abstractions. They meet through relationships, danger and decisions made under pressure. A person needs shelter; another person interprets a sign; a political possibility becomes available. Meaning grows through encounters rather than arriving as a finished label. When Paul acquires a new identity among the Fremen, that identity belongs simultaneously to his choices and to the expectations of people who interpret him. The name is neither completely private nor completely outside his control. - -Our reading is that the force of this convergence lies in its unevenness. Survival can encourage adaptation that later becomes politically significant. Genuine belonging can exist alongside strategic calculation. A religious expectation can be inherited without every believer understanding its institutional history. The reader should therefore resist a clean division between authentic experience and manufactured symbolism. The rise of Muad'Dib involves both. Keeping the three stories visible lets us ask how they reinforce one another, where they conflict, and whose purposes become less visible when their convergence is celebrated as a single destiny. - -# A community is more than an audience - -A central-character narrative encourages us to see other people through their relation to its protagonist. Teachers prepare him, allies help him, enemies obstruct him, and communities recognise him. That grammar is convenient, but it can reduce a living community to an audience waiting for the right person to arrive. Reading the Fremen more carefully means asking what their lives, knowledge and hopes look like before those things become elements of Paul's ascent. - -The desert does not begin to demand intelligence when Paul encounters it. Its inhabitants have already developed practices that make life possible. Their knowledge is not merely an unusual collection of skills available to enhance a newcomer. It belongs to social arrangements, environmental experience and shared meanings. This is why descriptions of water, shelter and discipline should not be read only as picturesque details. They reveal a community's relations with a world that outsiders can misunderstand while still wanting to control its resources. - -We interpret Paul's relationship with that community through the difference between participation and possession. Learning a practice can establish respect, but possessing the ability to perform it does not mean possessing the people who taught it. Admiration for exceptional competence can create trust, yet trust is not the same thing as consent to every future political action. As the story gathers momentum, notice when these distinctions are made visible and when a heroic expectation encourages you to glide past them. A community can recognise an extraordinary figure without becoming only the background against which that figure proves extraordinary. - -# Religious preparation and the uses of belief - -The Missionaria Protectiva makes the history of belief important to the interpretation of Paul's arrival. Religious expectations can provide protection and a language through which unfamiliar people recognise one another. They can also serve institutional interests. Knowing that a tradition has been shaped by political intervention changes how a reader understands its use, but it does not automatically describe the whole experience of everyone who inherits it. A belief can have a strategic origin and acquire meanings that exceed the strategy. - -This distinction is essential if we want to avoid treating believers as people who simply failed to notice a trick. Communities interpret beliefs through needs, memories and hopes. A tradition may help them make sense of suffering or imagine a different future. An institution that exploits such a tradition is acting on something meaningful, not on an empty mechanism. The political power of religion partly depends on this depth. Manipulation can be effective precisely because it uses a language that already carries emotional and social weight. - -Our interpretation asks two questions at once. What has been arranged before Paul arrives, and what do people actually experience when they encounter him? The first question makes institutional planning visible. The second preserves the reality of relationships and events. Paul's abilities cannot be dismissed simply because some expectations were prepared. Conversely, unusual abilities do not turn every inherited expectation into a politically innocent one. The tension between these questions is more revealing than a verdict that the prophecy is either wholly true or wholly false. - -# Extraordinary ability does not settle legitimacy - -Paul's capacities matter. A reading that treats him merely as a skilled actor taking advantage of belief loses a central difficulty of the novel: there really is something extraordinary about him. But the existence of an extraordinary capacity does not determine the correct political arrangement around its possessor. Being able to anticipate, persuade or survive in remarkable ways answers a question about ability. It does not by itself answer questions about the limits of authority, accountability or the rights of other people. - -This distinction becomes especially difficult when competence appears to promise protection. If one person can respond to dangers that others cannot foresee, trusting that person may seem practical as well as reverent. The problem is not that trust has no reasons. It is that reasons for trust can become reasons against ever questioning the trusted figure. An advantage in judgment may gradually be treated as a complete exemption from scrutiny. The difference between listening carefully and obeying without limit can become harder to identify. - -We read Muad'Dib's emergence as a challenge to the habit of turning excellence into entitlement. The community's response may be understandable, and Paul's role may be effective, while the resulting concentration of power remains troubling. These propositions do not cancel one another. They describe the difficulty. To analyse a scene, separate the evidence for Paul's ability from the language used to justify his position. Does the justification remain specific to a problem, or does it expand into a claim about who he must be in every possible circumstance? - -# Names as bridges between selves - -A chosen name can make a new form of life imaginable. It can connect a person to a community and mark a change in the way he understands himself. Yet names also circulate independently of their bearer. Other people repeat them, attach stories to them and use them to explain events the bearer did not directly control. The name Muad'Dib is therefore a bridge, but bridges allow movement in more than one direction. Paul enters a new identity while public meaning enters his life. - -That reciprocal movement complicates the idea that self-definition is entirely free. Paul can participate in choosing a name without controlling everything that follows from it. A private intention may become a public assertion. A useful identity may become an expectation that limits the person's available actions. What begins as a way to inhabit a community can become a position from which retreat appears impossible. The more people invest in the identity, the more expensive any departure from it may become. - -Our reading treats naming as an early version of a problem that later expands to imperial scale. The person and the symbol remain related, but they cease to be identical. When reading, ask who is using the name in a particular scene and what the use accomplishes. Is it affectionate, practical, reverent, persuasive or commanding? A single word can do different kinds of work. Keeping those uses distinct helps explain how a leader's identity can become a shared political resource without ever becoming completely detached from the person whose life it transforms. - -# Chani and the scale of personal attachment - -The political and religious importance of Paul's rise does not eliminate the significance of personal relationships. His connection with Chani gives the story a scale on which attachment is not simply an office, a programme or a prophecy. That does not place intimacy outside politics. It does provide a way to see how public identities enter private lives. A person who becomes an emblem is still someone who must relate to another person without the protection of an abstract title. - -Readers should be careful not to treat a relationship only as evidence that the central character remains human. Chani has a place in the world Paul enters; her meaning is not exhausted by what she reveals about him. The same caution applies to every relationship organised around an exceptional protagonist. Another person's presence can make his story emotionally convincing while that person's independent perspective becomes harder to notice. Reading for that perspective changes the questions we ask about attachment and obligation. - -We interpret intimacy as a counterweight to the scale of destiny, though not a guaranteed escape from it. Public authority can make personal choices carry consequences beyond the relationship itself. The reader can understand the desire to preserve an intimate bond while also recognising that exceptional power changes the conditions under which the bond exists. Keep track of moments when Paul is addressed as a person rather than as a promised figure. What possibilities become available in that form of address? What pressures return when the public identity reasserts itself? - -# Prescience as a changed relation to possibility - -Prescience is often discussed as if it were simply better information about tomorrow. That approach misses its effect on the present. Once a person anticipates several possible outcomes, immediate choices can become organised around those outcomes. Possibility becomes something to compare, avoid or pursue. The future begins to influence action before it arrives. This makes the gift politically important and psychologically difficult even before we decide how reliable any particular vision is. - -The distinction between seeing a possibility and choosing it should remain visible. A vision does not make every step toward its outcome involuntary. At the same time, believing that certain outcomes are more dangerous can place pressure on every alternative. The person making a decision may experience the available options as a narrowing corridor. Outsiders may see only confidence. Readers may be tempted to accept the corridor as the whole moral world because the narrative gives them access to the leader's fear of what lies beyond it. - -Our interpretation does not require a theory that resolves every mechanism of prescience. It requires attention to the uses of anticipated futures. When an action is justified by what might otherwise happen, what can anyone else examine? Who has access to the relevant knowledge? What remains uncertain? Such questions connect the apparently supernatural theme to ordinary problems of authority. A person claiming privileged knowledge of consequences can become indispensable and difficult to challenge. Paul's gift makes that situation dramatic without making its political implications disappear. - -# Liberation and the danger of a single solution - -The appeal of liberation is central to why Paul's rise can feel compelling. A community's desire for a different future is not a trivial illusion that a cautious reader should dismiss. Oppression, vulnerability and exclusion make hope politically important. The difficulty arises when hope becomes inseparable from a single person. An effective leader may help organise a movement, while the movement gradually loses the ability to imagine its purposes apart from that leader's identity. - -This is not an argument that collective action can succeed without relationships of trust. It is an argument for distinguishing trust from the complete concentration of meaning. A movement needs ways to act, remember and disagree. If its identity becomes entirely dependent on the exceptional figure, disagreement can begin to look like betrayal of the movement itself. The political problem changes from deciding what should be done to deciding who is allowed to interpret the leader's mission. - -We read the end of Dune with this tension in mind. A victory can answer immediate questions about an enemy or a throne while opening more difficult questions about the future of the victorious movement. The reader's relief is understandable. It should not become a reason to stop looking. Ask which institutions have changed, which dependencies remain, and how public belief has acquired a new centre. The heroic outcome is an event within a continuing social world. That world does not lose its capacity for conflict simply because the central character has achieved a decisive success. - -# The reader's participation in prophecy - -Readers bring expectations to a story before any character utters a prophecy. We recognise patterns of endangered heirs, unusual gifts, demanding teachers and meaningful names. Those patterns encourage us to connect early signs with later fulfilment. The pleasure of recognition can make the movement toward an extraordinary destiny feel natural. In that sense, the reader has a small part in making the heroic structure persuasive. - -This participation does not mean that reading with sympathy is foolish. It means that sympathy can coexist with habits worth examining. When a feared outcome appears in a vision, do we regard it as an obstacle the hero will overcome, or as a warning about the form his success may take? When a community expresses reverence, do we hear only confirmation of a character's worth, or do we also hear the risks of placing collective hope in one identity? The answers can change during a rereading. - -Our interpretation encourages a double attention. Follow Paul's immediate difficulties closely enough to understand why his choices appeal to him. At the same time, follow the broader language that makes those choices meaningful to other people. The novel can be emotionally persuasive precisely where it is politically unsettling. That combination is more demanding than standing outside the story and congratulating ourselves for refusing its appeal. A careful reader can feel the pull of prophecy and still ask what it does to the people who accept it, the person who embodies it, and the possibilities it pushes out of view. - -# Looking beyond the triumph - -The conclusion of a heroic narrative often promises that the central question has been settled. Dune gives the reader reasons to question that expectation. Paul's victory changes his position, but the forces that enabled the rise do not simply vanish. Religious hope, imperial demand, family continuity and prescient anxiety remain connected to what he has become. The end of the novel can therefore be read as both an accomplishment and the beginning of a more difficult arrangement. - -To follow this difficulty, distinguish an immediate outcome from a lasting condition. Defeating an adversary is an outcome. Governing a movement whose members invest their faith in a leader is a condition. Taking a throne is an outcome. Sustaining legitimacy, managing institutions and remaining accountable are continuing problems. Readers sometimes use the clarity of the outcome to cover the ambiguity of the condition. Herbert's sequel will make that habit increasingly uncomfortable. - -We interpret Muad'Dib's emergence as a question about how a person becomes larger than himself in public life. The process involves real ability and real need. It also involves inherited expectations and choices whose consequences expand beyond their original purposes. Return to the name at the end of this chronicle. What does it now contain that it did not contain at the beginning? The answer should include the experiences of people other than Paul. That wider answer prepares us to read his imperial life without assuming that power, fulfilment and freedom have become the same thing. - -# A guided rereading of belief - -Select a scene in which someone interprets Paul through an expectation that existed before his arrival. Write down the observable event first, using only what a person in the scene could witness. Then write down the meaning attached to that event. Comparing the two descriptions is not a way to prove that one is empty. It is a way to see how an occurrence becomes evidence within a tradition. What prior knowledge makes the interpretation possible? What uncertainty does the interpretation leave open? - -Next, choose a scene in which Paul learns from Fremen experience. Identify the practical knowledge being shared and the relationship through which it is shared. Ask whether the scene changes his understanding or merely improves his capacity to carry out a purpose he already had. Both kinds of change can occur, but they should not be confused. Finally, compare a private use of his new name with a public one. This small exercise helps make the movement from person to symbol visible. It also gives the next chronicle a precise question: what happens when the public symbol becomes powerful enough to govern the conditions of the private life? - -One last comparison concerns the reader's own language. Describe the same scene once using the vocabulary of destiny and once using the vocabulary of relationships. In the first version, a sign may be fulfilled and a saviour recognised. In the second, someone observes an action, connects it with an inherited expectation, and makes a choice about trust. Neither description necessarily cancels the other. They bring different features into focus. The exercise is valuable because the language of destiny can make actions seem inevitable, while the language of relationships returns attention to the people who interpret, choose and bear consequences. When both versions remain visible, prophecy becomes something to analyse rather than a shortcut that ends analysis. - -Carry this distinction into the next book. If the title Muad'Dib now explains a command before anyone considers its consequences, the meaning of recognition has changed. A name that helped establish a relationship may now be used to close a discussion. Watch that change in function, rather than assuming that every repetition of a familiar name performs the same social act. diff --git a/website/content/prophecy/the-path-paul-refused.md b/website/content/prophecy/the-path-paul-refused.md deleted file mode 100644 index 214823d3..00000000 --- a/website/content/prophecy/the-path-paul-refused.md +++ /dev/null @@ -1,93 +0,0 @@ -# Inheritance is a condition, not a complete instruction - -Leto II inherits a world shaped by his father's authority, but inheritance does not provide a complete set of instructions for living in that world. The family name carries legitimacy, danger and expectations. It also carries unresolved problems. To inherit such a position is not simply to receive power. It is to become the object of other people's purposes before choosing a purpose of one's own. - -This makes the relation between Paul and Leto more complicated than a comparison between two degrees of determination. The son does not begin where the father began. He encounters institutions and beliefs already transformed by Paul's life. A decision that resembles an earlier decision can therefore have a different meaning. Historical position matters. The question is not only whether Leto is willing to do something Paul refused, but what kind of world now makes that willingness significant. - -Our interpretation treats inheritance as both a resource and a burden. It gives the children access to capacities and public positions that other people do not possess. It also narrows the ways in which others are prepared to recognise them. The next generation may seek an unfamiliar future, yet its claims will be heard through the history of the old one. Reading for that double condition makes Leto's choices more interesting than a simple completion of his father's unfinished task. It also keeps the reader aware that an inherited problem can change while still carrying a familiar name. - -# The difference between comparison and competition - -Readers naturally compare father and son. Comparison can reveal differences in judgment, willingness and relation to power. It becomes less useful when it turns into a competition in which one character must be declared stronger, braver or more farsighted in every respect. Such a ranking can hide the specific demands of the situations being compared. A willingness to accept a burden does not by itself explain the burden's moral character. - -To compare carefully, specify the dimension of comparison. Are we discussing endurance, political judgment, tolerance for coercion, attachment to ordinary human life or confidence in an anticipated future? These qualities do not form one simple scale. A person might possess more of one and less of another. The language of strength can obscure the difference by making every refusal sound like a deficiency and every acceptance sound like an achievement. - -We interpret the contrast between Paul and Leto as a way to hold competing standards in view. The father's limit may be understandable at the scale of a human life. The son's claim may be intelligible at the scale of a very long future. Neither scale automatically invalidates the other. The difficulty is that actions taken in the name of the larger scale still affect people living at the smaller one. A useful reading asks how the novel makes both scales available, and where a character's commitment to one encourages him to treat the other as a cost that must simply be paid. - -# What a claimed necessity asks us to accept - -The Golden Path raises a problem larger than the question of whether a particular leader has good intentions. A future presented as necessary can reorganise the evaluation of every present action. Harm may be described as the price of survival. Objection may be answered by reference to consequences that ordinary people cannot inspect. The language of necessity can make an enormous concentration of authority appear like a burden reluctantly carried for everyone else. - -This is why the distinction between a claim and its justification matters. A character can sincerely believe that a path is needed without sincerity making the claim publicly accountable. The reader may receive privileged access to the character's reasoning, but that access does not automatically explain what the people affected by the decision are able to know or contest. The story's presentation of knowledge and the political distribution of knowledge are separate subjects. - -Our interpretation does not settle the Golden Path with a simple approval or rejection. It asks what accepting the claim would require. Must we accept not only an end, but the right of one person to define its means? Must present people regard their interests as subordinate to a future they cannot verify? Can disagreement exist without being represented as a threat to humanity? These questions are part of the meaning of the path. They keep the reader from treating a grand scale as a reason to stop examining the smaller relations through which grand purposes become action. - -# Refusal can be both a limit and a judgment - -Paul's refusal should not be reduced to a single label. It can be approached as a human limit: there are forms of sacrifice or transformation a person cannot bring himself to accept. It can also be approached as a judgment about what accepting them would mean. These possibilities can coexist. A limit is not necessarily devoid of thought, and a judgment is not necessarily independent of emotion. - -The temptation to call the refusal weakness often depends on reading history backward from a later commitment. Once another character accepts the path, the earlier refusal can seem like nothing more than failure to perform an assigned task. That interpretation makes the later acceptance the standard by which everything is measured. A more careful reading asks why the refusal remains meaningful even after the son chooses differently. What does it preserve, and what does it leave unresolved? - -We interpret Paul's limit as part of the series' resistance to uncomplicated exceptionalism. Extraordinary capacity does not make a person endlessly available to every role that capacity could support. Yet declining such a role does not necessarily free other people from its consequences. The tension is difficult because neither side supplies a painless answer. A refusal can protect something human while leaving a frightening problem with the next generation. An acceptance can address the problem while imposing a new cost. The reader's task is to examine these relations rather than turn either character into a simple illustration of courage or cowardice. - -# The body becomes part of the political argument - -Leto's union with sandtrout makes bodily transformation central to the future he chooses. The political question is no longer expressed only through offices, commands or inherited titles. It also concerns what a person is willing to become. The body is not merely a vehicle through which an idea acts. Its transformation changes the conditions of the actor's life and the relationship between that actor and ordinary human experience. - -This creates a powerful contrast with Paul's continuing vulnerability. In the earlier chronicles, breath, pain, blindness and grief keep exceptional authority attached to a recognisably exposed human life. Leto's chosen direction puts that attachment under pressure. Readers should not treat the change only as an increase in capability. Ask what is gained, what is surrendered and which kinds of relationship become more difficult when a person adopts a form designed for an extraordinary historical task. - -Our interpretation reads transformation as an ethical question embodied in an image. The image can be spectacular, but spectacle should not replace analysis. A body altered in the service of a future expresses the seriousness of a commitment; it does not automatically settle the legitimacy of every action the commitment may require. The same caution applies to the cost borne by the person undertaking it. Personal sacrifice can be genuine while other people also bear costs they did not choose. Keeping both kinds of cost visible prevents the transformed leader from becoming morally unquestionable simply because he has given up something enormous. - -# Ghanima and the limits of a single-line inheritance - -A story focused on the relation between Paul and Leto can encourage a simple line: father, son, future. Ghanima's presence makes that line inadequate. The family contains more than one child, more than one perspective and more than one relation to inherited expectation. A diagram that erases that plurality can make the dynasty appear to carry a single purpose naturally forward, when purpose is actually negotiated through several lives. - -Readers should notice whose experience becomes central when a future is described as the continuation of a male line of extraordinary power. Other family relationships can be made to look supporting or secondary because the central story has already assigned them a place. That assignment is itself worth examining. It does not mean that every character has the same narrative function. It means that unequal narrative attention should not automatically become a verdict on the importance of the people receiving it. - -We interpret the twins as a reminder that inheritance is shared without being experienced identically. They occupy related positions but are not interchangeable solutions to a dynastic problem. Following that difference helps preserve the human complexity of a narrative that repeatedly operates at an enormous historical scale. Ask when family members are treated as people, when they are treated as carriers of a name, and when they are treated as instruments of a plan. These descriptions can overlap, but their overlap should be made visible. The future of House Atreides is not simply another name for the future imagined by one of its members. - -# Ecology as more than a background - -The setting's ecological dimensions complicate any attempt to separate the political future from the material world. A planet is not a neutral stage on which rulers compete. Water, desert conditions, spice and the forms of life connected with them shape what institutions can do. Changes in the environment alter dependencies, practices and possibilities. A political project that reaches across generations must therefore involve the world people inhabit, not only the offices they hold. - -This relationship also makes the language of improvement difficult. A change that appears desirable from one perspective can undermine something necessary from another. The value of water, the demands of survival and the role of spice do not form a simple list of benefits that can all be maximised independently. The setting asks readers to think in relations. Altering one condition can transform the meaning of another because communities and institutions have organised their lives around the connection. - -We interpret ecology here as a check on the fantasy of unlimited political choice. Even an extraordinary leader acts within material relationships. He may transform them, but transformation has consequences that must be understood across different scales. Ask what a plan treats as a resource, what it treats as a limit and what it treats as expendable. These categories are political judgments as well as descriptions of a world. Their distribution reveals whose experience counts in the imagined future. The importance of ecological relations is one reason a purely dynastic reading of Paul's legacy cannot explain everything the next generation confronts. - -# Long horizons and the people alive now - -A very long historical horizon can make present suffering look small. That change of scale is analytically useful in some contexts and morally dangerous in others. It can reveal consequences an immediate perspective misses. It can also make existing people appear mainly as temporary carriers of a future objective. The difficulty is not resolved by declaring either short-term experience or long-term survival the only legitimate concern. - -The contrast between scales should instead become explicit. What matters to someone living through a decision may differ from what matters in a projection across generations. The person proposing the decision may claim to reconcile the scales, but reconciliation requires more than the announcement that the larger future is important. Ask who decides which present costs are acceptable, what evidence supports that decision and whether people who bear the costs have any capacity to question it. - -Our interpretation reads Leto's commitment through these questions. The seriousness of a long-term purpose does not make its political form irrelevant. A future imagined as survival can still involve a present organised through coercion. Conversely, concern for present people does not automatically answer every danger reaching beyond their lifetimes. The novel's force comes partly from refusing to make either truth disappear. A reader can understand the attraction of a path while remaining unsettled by the authority needed to impose it. That unsettled response is not necessarily a failure to understand the plot; it may be a careful response to the ethical problem the plot creates. - -# Why the father's story does not receive a final grade - -The presence of a son who acts differently can make Paul's life seem like a preliminary version of a more successful design. That is one possible way to organise the narrative, but it risks treating the father only through what comes after him. His attachments, fears, refusals and interventions become relevant mainly as steps toward a later outcome. A character's life then receives a grade from history rather than being understood in its own changing conditions. - -This is especially tempting in a story about foresight. If a later figure presents a far-reaching purpose, earlier lives can be described as successful or unsuccessful according to their contribution to it. But that method can reproduce the very political logic we are trying to analyse: people become means through which an exceptional plan arrives. The reader should notice when an interpretation adopts a character's scale of judgment so completely that alternatives cease to be visible. - -We interpret Paul's legacy as an unresolved relation rather than a final score. He has helped create conditions that others must inherit. He has also experienced limits that the larger historical language cannot simply dismiss. Leto's different choice changes the meaning of the inheritance without turning every earlier uncertainty into an error. This is why the story remains richer than a contest between two exceptional rulers. It gives the reader a continuing problem: how to judge actions whose scale exceeds ordinary experience without allowing that scale to cancel the lives through which the actions take effect. - -# Reading beyond a chosen destiny - -The phrase chosen destiny contains a tension. Destiny suggests an outcome that has already acquired necessity; choice suggests the involvement of a person who could act differently. The series repeatedly brings these ideas together without making their relation entirely comfortable. A character may understand his action as both a personal commitment and acceptance of something demanded by a future. The reader must decide how to examine that claim. - -One useful method is to separate explanation from endorsement. Understanding why a character accepts a path does not require accepting every justification he gives. Rejecting an action does not require pretending that the problem motivating it was trivial. These distinctions keep analysis from turning into a competition in loyalty. We can examine the force of a claimed necessity, the seriousness of a sacrifice and the distribution of authority without treating them as interchangeable proofs of moral legitimacy. - -Our reading encourages readers to carry this method into the later series without prematurely resolving it here. The first three novels already provide enough material to question the relation between exceptional people and the communities organised around them. Paul's story begins with inherited responsibility and ends with an inheritance that includes the consequences of his public legend. Leto moves toward another form of exceptional power. The movement does not close the argument. It makes the argument continue at a different scale, with a different body and with a future whose meaning the reader must still examine rather than merely admire. - -# A diagram of costs rather than a verdict - -Draw a triangle with three corners: the individual who acts, the people affected now and the people imagined in the future. Place a proposed action in the centre. Connect it to each corner, and write down what is claimed as a benefit and what is acknowledged as a cost. If a corner has no entry, ask whether the omission reflects the story, the character's reasoning or your own attention. Empty space in a moral diagram can be as revealing as a crowded one. - -Next, mark which claims can be publicly examined and which depend on privileged knowledge. The purpose is not to pretend that every future consequence can be proved in advance. It is to identify the political relation created when some claims are treated as decisive despite being inaccessible to the people whose lives they organise. A plan may be sincerely held and still depend on an unequal distribution of authority. The diagram should make that dependence visible rather than settling the plan with a single colour. - -Finally, compare Paul's refusal with Leto's acceptance using the same triangle. Do not change the standards between the two cases. Note how their different positions alter the meaning of a cost. A personal limit may preserve something at one corner while leaving a danger at another. An extraordinary commitment may address one danger while intensifying the need for accountability elsewhere. The resulting comparison should be more demanding than a label of weakness or strength. It should show why the legacy of Paul Atreides remains a question about power and human limits, even when another character claims a path beyond those limits. - -# A final question for the trilogy - -At the end of this reading route, return to the vulnerable heir introduced in the first chronicle. The movement from that person to an Emperor, an absent legend and a dissenting voice can be understood as a series of changes in the relationship between private life and public meaning. His son inherits both the possibilities and the unresolved consequences of those changes. The continuity is not simply a line of names; it is a history of relationships between exceptional capacity, institutional purpose and the people affected by them. - -The final question is therefore not only whether Paul fulfilled a prophecy. It is what the effort to make a life fulfil a public destiny does to the freedom of everyone involved. Who gains a voice, who becomes difficult to hear, and whose future is treated as something another person is entitled to decide? These questions do not remove the wonder, courage or tragedy from the novels. They give those qualities a political and ethical setting. That setting is what makes Paul's story worth rereading after the initial fascination with his rise has become a more complicated interest in what his life leaves behind. diff --git a/website/content/prophecy/the-preacher-returns.md b/website/content/prophecy/the-preacher-returns.md deleted file mode 100644 index 3c9e25f0..00000000 --- a/website/content/prophecy/the-preacher-returns.md +++ /dev/null @@ -1,95 +0,0 @@ -# A return that refuses restoration - -A returning central character often promises restoration. Readers expect the person they recognise to reclaim a position, correct an injustice or provide the missing explanation that makes a damaged world whole. Paul's return as the Preacher unsettles that expectation. The figure who once stood at the centre of imperial authority now intervenes from another position. Recognition does not simply restore the earlier arrangement. It makes the relation between the person and his legacy newly difficult. - -This matters because the world has continued in his absence. Other people have governed, interpreted and acted. A public identity has acquired uses that do not depend on its bearer being present to approve them. When Paul returns, he does not encounter a blank space awaiting his command. He encounters an order with its own interests and a history in which his earlier life has become material. His absence has not made him meaningless; it has made the meaning more available to other interpreters. - -Our reading treats the return as a change in the terms of intervention. The question is no longer simply what Paul can command. It is what his speech can challenge and what authority listeners will grant it. A voice outside an institution can disclose something the institution's own language makes difficult to say. Yet that voice also carries the burden of its past. The Preacher is not a completely independent critic who arrives without responsibility for the world he confronts. His return holds criticism and implication together. - -# The political life of an absent name - -Names continue working when their bearers are absent. They can authenticate decisions, gather loyalty, justify practices and provide a shared vocabulary for remembering events. This continuing life can be comforting, because it gives a community a way to preserve significance. It can also become politically useful to people who control the authorised interpretation. The memory of a leader is not merely a memory when it helps organise present obedience. - -Paul's absence makes this problem visible at an unusual scale. Muad'Dib is not only a person someone misses. The name belongs to a religious and political order. Its public force creates a separation between lived experience and institutional meaning. A person who knew Paul privately and a person whose authority depends on his legend may use the same name for different purposes. Neither use has to be emotionally empty in order for the difference to matter. - -We interpret the absent name as a form of contested inheritance. Ask who is permitted to explain what it requires. Ask what practices appear natural because they are attached to the memory. Ask how disagreement is described when it challenges something presented as the leader's legacy. These questions bring attention to the work of interpretation. The name does not issue every instruction by itself. People use it, defend uses of it and dispute alternatives. Making that activity visible prevents a public legend from appearing as an independent force whose human operators no longer need examination. - -# Alia and the pressures of continuity - -Alia's governing position connects personal, dynastic and religious pressures. Readers can recognise the role she occupies without reducing her to a simple substitute for the absent Paul. A regency involves the management of continuity, but continuity is not a neutral condition. It requires decisions about which practices must be maintained, who can speak for the dynasty and how threats to the existing arrangement should be understood. - -The challenge of preserving a powerful identity can encourage defensiveness. If a governing figure's authority is tied to a inherited legend, criticism may appear to threaten more than an individual policy. It may challenge the foundation that makes the governing position intelligible. This does not justify every response to criticism. It helps explain why a regime can invest so much effort in controlling meaning. The issue is not merely whether people remember a leader, but whether they remember him in a way compatible with present authority. - -Our interpretation reads Alia's situation alongside, rather than entirely beneath, the Preacher's intervention. The public system has several participants with different vulnerabilities and interests. Paul can challenge its meaning, but the people who inhabit it must respond from the positions it has given them. A careful reader asks how those positions shape perception. What appears threatening to an institution may appear liberating to an outsider. What appears necessary to a governing figure may appear oppressive to someone whose voice the arrangement excludes. The difference is a subject for analysis, not proof that one perspective automatically contains the whole story. - -# Why a preacher's authority differs from an Emperor's - -The word preacher directs attention to speech, audience and interpretation. An Emperor can draw on offices, commands and organised force. A preacher must also contend with the response of listeners. This difference does not mean that speech is politically weak or that imperial authority never depends on persuasion. It means that the Preacher's intervention asks us to notice another relationship between a person and the people he addresses. - -A voice can disrupt an order by making familiar practices sound strange. It can question the language that turns obedience into virtue or exposes a gap between a sacred claim and its institutional use. But disruption is not identical with replacement. A criticism can be powerful without supplying a complete new arrangement. The reader should distinguish the ability to reveal a problem from the capacity to govern everything that follows from the revelation. - -We read the Preacher's role through that distinction. His position gives him a different freedom to speak, yet it does not remove every form of power from the encounter. His identity and history influence how a voice is received. The reader may also grant him authority because of recognition. Ask whether a passage persuades through what is said, through who is believed to be speaking, or through the contrast with an established order. Those are related but different sources of force. Following them makes the return more than a dramatic unveiling of a familiar character. - -# The person who cannot own his legend - -It seems reasonable that a person should possess special authority over the meaning of his own life. Yet public legends do not operate like private property. Once a life becomes part of institutions, rituals and collective memory, its meaning is carried by people whose interests extend beyond the bearer. Paul can confront interpretations of Muad'Dib without being able to withdraw the name from every use or make his own account final. - -This creates an uncomfortable possibility: the person may challenge what the symbol is used to support and still be treated as a problem for the symbol rather than its rightful interpreter. Institutions can preserve an authorised image by distancing themselves from inconvenient aspects of a living life. They may need the leader's name more than they need his changing judgment. Public devotion can therefore coexist with resistance to the actual person's intervention. - -Our reading treats this separation as one of the strongest challenges to a simple account of charismatic power. A famous individual may initially gather authority around himself, but the authority can outlive his control. The process does not make him unrelated to the resulting order. It changes the form of the relation. He becomes both a source of legitimacy and a potential disturbance to the system that uses that legitimacy. Look for moments when respect for the symbol and responsiveness to the person diverge. The divergence helps explain why returning does not necessarily recover the freedom that departing failed to secure. - -# Criticism from inside a compromised history - -The Preacher's challenge carries force partly because it is connected to the history he criticises. That connection also raises a question of responsibility. Can someone speak against an order formed around his earlier authority without explaining his part in its formation? The question need not silence criticism. It does require us to separate the truth of a criticism from a complete absolution of the critic. - -Readers sometimes treat a character's later rejection of harmful practices as evidence that the character never truly belonged to them. That can be emotionally satisfying, but it makes change difficult to understand. If rejection has no relation to earlier involvement, it ceases to be a response within a life and becomes a claim of permanent innocence. A more demanding reading recognises that insight can develop through consequences for which a person remains responsible. - -We interpret Paul's return as allowing both recognition and discomfort. He can identify something wrong without thereby settling every question about what he previously enabled. The reader can value the intervention while continuing to examine the history. This is particularly important in a story about authority, because an exceptional figure can otherwise receive a second exemption from judgment: first because he appears to fulfil a destiny, later because he appears to reject its abuses. Neither form of significance should make ordinary questions of responsibility disappear. The critic's involvement may make his speech more informed and more difficult at the same time. - -# The children do not inherit a clean beginning - -Leto II and Ghanima enter a world already organised around the significance of their father. Their future is not simply a matter of family affection or biological continuity. It is bound to institutions that need heirs, memories that need interpretation and powers that regard unusual abilities as opportunities or threats. The inheritance includes expectations the children did not create. - -This is why a family diagram should distinguish relationships from political demands. A line connecting parent and child can show descent, but it cannot by itself show the pressures attached to that descent. Another kind of line is needed to represent the dynasty's requirements, the regency's purposes and the public meaning of the family name. Combining the diagrams reveals how the same connection can be intimate and instrumental without making either dimension imaginary. - -Our interpretation reads the children as a challenge to the idea that Paul's departure could close the problems of his authority. A person's action may change his own position while leaving other people to navigate the structure associated with it. The next generation must encounter the world as an inherited condition, not as a neutral field. Ask what choices become difficult because the children are already legible as heirs. Ask whether their unusual capacities broaden their possibilities or intensify the efforts of others to organise those possibilities. The answer is unlikely to fit a simple distinction between freedom and constraint. - -# Arrakis is changing while its symbols endure - -A place can change while the language used to describe it remains familiar. Communities may preserve symbols of a desert identity even as material conditions and political arrangements alter. That gap matters because an institution can appeal to continuity while people experience transformation. Readers should notice whether claims about the meaning of Arrakis describe a present reality, a remembered way of life or an authorised image useful to those who govern. - -This observation does not require us to treat tradition as empty nostalgia. Practices and memories can provide meaningful ways to understand change. The difficulty is that memory can be used either to examine a transition or to conceal it. A symbol that once described a relationship with a demanding environment can become a decorative confirmation of a political identity. The familiar sign remains, while the conditions that gave it practical force are reorganised. - -We read the Preacher's setting through this possibility of uneven continuity. Ask what has remained the same because it still serves life, what has remained because it serves authority, and what has changed without being openly acknowledged. A careful comparison should include people whose experience differs from that of the governing centre. The return of Paul does not restore the Arrakis he remembers simply by bringing a familiar name back into it. The world he encounters has a history of his absence, and that history includes changes in what inherited symbols are allowed to mean. - -# Death does not end interpretation - -The death of the Preacher concludes Paul's living intervention, but it cannot conclusively settle the public meaning of his life. A death is an event that other people interpret. It can be attached to explanations of sacrifice, disorder, justice, betrayal or fulfilment. Those explanations do not emerge from the event without human activity. They are made, repeated and defended within relationships of power and memory. - -This is particularly important for a character already surrounded by a religious legend. Readers may be tempted to treat the final event as the decisive key that tells us what the whole life has meant. Yet the very history of Muad'Dib should make that temptation suspect. A single interpretation can acquire great public force without exhausting the person or resolving the consequences of his authority. An ending can be definite at the level of bodily life while remaining contested at the level of collective meaning. - -Our interpretation keeps these levels separate. Paul's death matters as the end of a person who has lived through enormous changes in identity and responsibility. It also becomes part of a world that continues needing explanations. The reader can acknowledge tragedy without assuming that tragedy supplies a complete political verdict. Ask which questions the death answers and which it leaves with surviving people. That distinction prepares us for Leto II's story. The inheritance is not only the memory of a father; it is also a field of unresolved arguments about power, foresight and the future. - -# Recognition, sympathy and the reader's expectations - -Discovering a familiar person beneath another identity can reorganise a reader's judgment. Earlier scenes acquire new meanings; a voice is heard through a different history. This is one reason the Preacher's identity is more than a plot surprise. Recognition changes what the reader brings to the figure, including sympathy, trust and assumptions about significance. - -The change should itself be examined. Would the criticism matter differently if the speaker were someone without Paul's history? Does recognition make us more willing to listen to the words, or more willing to overlook the limits of the intervention? A reader who has followed a person through several books may invest in that person's meaning in a way similar to the investment of people inside the story. Familiarity creates a relation that can be valuable and can also narrow attention. - -We interpret the return as a test of that relation. The reader does not have to refuse sympathy in order to remain critical. Instead, ask what sympathy makes visible and what it risks hiding. Paul's vulnerability can help us recognise the distance between a person and an authorised image. His recognisability can also make other voices seem less important. Keep both possibilities in mind. The most careful reading follows the return without allowing recognition to become a new proof that one exceptional person must remain the final measure of every political question. - -# A workshop in public memory - -Choose one statement about Muad'Dib made by someone other than Paul. Identify the speaker's position before evaluating the statement. Does the speaker benefit from continuity, seek change, express private attachment or defend a public role? A statement can contain truth while also doing political work. Its purpose is not established solely by deciding whether the speaker is sincere. - -Next, choose an intervention by the Preacher and write two descriptions. One should explain the content of the criticism. The other should explain what the fact of his speaking does to the surrounding arrangement. It may expose a contradiction, disturb an authorised interpretation or invite listeners to reconsider a familiar practice. These effects need not be identical with the proposition expressed in the words. Speech is an event as well as a message. - -Finally, draw two circles, one labelled person and one labelled public symbol. Place between them the groups and relationships that carry Paul's meaning: family, governing institutions, believers and critics. Do not give every connection the same arrow. Some relationships preserve memory; others organise authority; others challenge an explanation. The resulting map should be less tidy than a simple story of a leader and his followers. Its complexity is the point. It helps show why the Preacher's return can confront a legacy without recovering complete ownership of it, and why a character's death does not make all the meanings attached to him cease to act. - -# Listening to an inconvenient voice - -A final exercise concerns the conditions under which criticism becomes audible. Imagine the same objection expressed by three speakers: a person inside a governing institution, an ordinary person affected by it and a figure whose name is central to its legitimacy. The words may be identical while their risks and effects differ. The insider may be heard as disloyal, the ordinary person as insignificant, and the famous figure as either authoritative or dangerous. This comparison makes status part of the analysis without treating status as proof that the objection is true. - -Apply the comparison to the Preacher's interventions. Ask what his particular history allows him to reveal and what it prevents listeners from considering independently. His words can open a question, but the fascination of his identity can also make that question appear to belong only to him. An attentive reader should follow the criticism beyond its extraordinary speaker. Which people have reason to share it? Which people might experience the problem differently? Which voices would remain unheard if the scene were remembered only as another important moment in Paul's life? - -The exercise brings the chronicle back to its central tension. The person and the legend are connected, but public meaning is created through many relationships. A return can expose the difference without eliminating it. When we allow the scene to contain more than the recognition of a famous figure, the Preacher becomes part of a wider struggle over who can describe the world and whose description can change it. diff --git a/website/content/prophecy/the-price-of-an-imperium.md b/website/content/prophecy/the-price-of-an-imperium.md deleted file mode 100644 index d20a0820..00000000 --- a/website/content/prophecy/the-price-of-an-imperium.md +++ /dev/null @@ -1,93 +0,0 @@ -# What a sequel can do to a victory - -A sequel can reward a successful hero by giving him a larger stage. Dune Messiah does something more unsettling: it treats the stage itself as a problem. Paul has acquired the position toward which so much of the earlier narrative moved, but that position does not settle the questions raised by his ascent. It enlarges them. What was once a struggle for survival has become a system of authority, devotion and continuing consequence. - -This change asks the reader to revise the meaning of victory without pretending that the earlier struggle did not matter. The fall of an adversary may have been important. The survival of Paul and his family may still deserve concern. But neither event guarantees that the order built afterward will be just. The sequel separates relief at a particular outcome from approval of everything that outcome makes possible. It preserves emotional investment while refusing to let emotional investment close the political inquiry. - -Our interpretation begins with that separation. A person can win against a cruel opponent and still become responsible for cruelty carried out under his own authority. An institution can speak the language of liberation while creating new forms of obedience. A reader who treats the first novel's ending as a complete moral certificate will have difficulty with the second novel's scale of responsibility. The useful question is not whether the earlier victory should simply be reversed in our judgment. It is what new obligations arise when the winner no longer acts only as a threatened individual, but as the centre of an expanding order. - -# The difference between having power and directing it - -Paul's imperial position appears to place enormous power in one pair of hands. Yet possessing a position and directing every consequence of that position are different things. Institutions, followers, officials and rivals do not become extensions of a ruler's mind merely because they act within his empire. They interpret purposes, pursue interests and respond to incentives. A command can travel through a system and return as an outcome its issuer did not completely intend. - -This observation should not become a convenient excuse for the person at the centre. If a leader benefits from an arrangement, authorises its operation or depends on its continuation, the fact that he cannot control every detail does not make him unrelated to its harm. Responsibility is not limited to actions personally performed. But responsibility is also not best understood by imagining a ruler as the sole mechanical cause of everything done around him. The difficulty lies between those simplifications. - -We read Paul's imperial predicament as a way to examine that middle ground. Where does his authority make action possible? Where do the institutions built around his name develop their own momentum? What could he change, and what would changing it require him to risk? These questions make power less glamorous and more specific. They also protect the analysis from the false comfort of a single explanation. Neither total mastery nor total helplessness gives an adequate account of a ruler whose public identity supports a system larger than his direct control. - -# Devotion as an administrative force - -Religious devotion does not remain confined to private feeling when it surrounds an Emperor. It can shape how commands are received, how dissent is interpreted and how political action acquires moral urgency. A policy attached to a sacred figure may be understood differently from a policy presented as a fallible judgment. The language through which authority operates changes the room available for hesitation and disagreement. - -Readers should distinguish a believer's sincerity from the political use of that sincerity. People can experience genuine devotion while institutions organise their actions toward purposes that deserve scrutiny. A system does not have to manufacture every emotion in order to exploit emotion. Nor does acknowledging exploitation require us to imagine that devotion has no depth. The political effectiveness of a sacred identity often depends on its ability to connect public action with intimate convictions. - -Our interpretation asks what happens when uncertainty becomes difficult to express. If a ruler is more than a ruler in the eyes of his followers, a practical objection can become a challenge to the meaning of the whole order. That raises the cost of ordinary political correction. Mistakes are harder to name when authority is protected by a language of fulfilment. Read scenes of imperial life with attention to the difference between persuasion and reverence. Both can produce compliance, but they create different relationships between the person deciding and the people who might otherwise question the decision. - -# A conspiracy is not the whole political world - -The organised opposition Paul faces gives the novel a recognisable structure of danger. Enemies have plans, alliances and methods. That structure is important, but it can tempt readers to make loyalty the only measure of judgment. If the Emperor is under attack, every criticism of the order around him may begin to look like another weapon in the attackers' hands. A threatened central figure can draw sympathy so strongly that the system he governs becomes difficult to examine on its own terms. - -This is one reason to keep external threat separate from internal accountability. The existence of a conspiracy does not establish that every imperial action is justified. Conversely, recognising harmful consequences of imperial power does not mean that every opponent offers a desirable alternative. Political danger can come from several directions. A narrative can make one set of antagonists vivid while still asking whether the central authority has created problems that cannot be reduced to those antagonists. - -We interpret the conspiracy as a pressure that reveals Paul's situation, not as a complete explanation of it. Ask which problems would remain even if a particular enemy disappeared. Religious momentum, institutional interest and the management of public belief are not simply the products of a hostile plot. Keeping those problems visible allows a more careful reading of Paul's decisions. It also helps separate the understandable desire to protect a person from the much broader claim that protecting his position should automatically take precedence over every other consideration. - -# Public marriage and private attachment - -Imperial politics brings relationships into a field of public consequence. The reader encounters people whose intimate lives are entangled with dynastic expectation, institutional planning and the distribution of influence. Paul, Chani and Irulan cannot be understood only as positions in an abstract diagram. But a diagram can help reveal the pressures acting on them, provided we remember that every line connects people whose experiences are not interchangeable. - -The distinction between a political relationship and an intimate attachment does not create an escape from responsibility. A political arrangement can have private costs, and an intimate decision can have public effects. The people involved may understand those effects differently. A reader who identifies too completely with one participant can turn the others into obstacles or instruments. The novel becomes more interesting when we keep each person's situation visible without assuming that visibility amounts to endorsement. - -Our reading treats these relationships as a test of the Emperor's apparent freedom. A powerful position multiplies the consequences of choice. It does not necessarily make the chooser less constrained. A decision that seems personal may alter expectations about succession or institutional access. A decision that seems purely strategic may shape the lives of people closest to the ruler. Notice how often discussions of dynasty make a future person appear mainly as a solution to a present political problem. That tendency reveals the cost of viewing family continuity only through the needs of an order that wants to preserve itself. - -# The problem of an inherited future - -A dynasty turns the future into a question of continuity. Who will inherit authority? What relationships will sustain the inheritance? Which institutions will gain or lose access? These questions can make the life of an unborn child politically meaningful before the child has any capacity to act. The future becomes organised around expectations that are already being negotiated by other people. - -This is not unique to imperial families in fiction, but the scale of Paul's position makes it especially visible. His public role encourages institutions to regard his family through their own purposes. The person seeking to protect a loved one and the ruler seeking to protect a political arrangement may occupy the same body. Their priorities can overlap and conflict. A choice can be both emotionally understandable and connected to a system that uses people as carriers of continuity. - -We interpret the dynastic problem as an extension of the earlier problem of prophecy. In both cases, a future is imagined before the people who will live it have an ordinary opportunity to shape it. Expectation can become a form of power. To read this carefully, ask what is being preserved and for whom. Is continuity presented as a good in itself, or is its value examined through the lives it affects? The answer can shift from scene to scene. A dynasty's survival is not automatically identical with the well-being of a family, and the survival of a family is not automatically identical with the well-being of an empire. - -# Accountability under unequal knowledge - -Prescience makes political judgment more difficult because Paul does not appear to share the same field of information as everyone around him. If he anticipates outcomes that others cannot evaluate, ordinary disagreement can be displaced by an appeal to knowledge that is inaccessible. The disagreement no longer concerns only what should be done. It concerns who is qualified to understand why an action is necessary. - -That asymmetry creates a danger even when the claim to unusual knowledge is sincere. A person can honestly believe that he is preventing something worse while finding it increasingly difficult to accept correction. Others may trust him because of his demonstrated abilities, but trust provides no simple way to examine a future they cannot see. The very quality that makes him useful can weaken the public conditions under which his use of power might be questioned. - -Our interpretation does not assume that every decision based on specialised knowledge is illegitimate. Communities routinely rely on people whose expertise they cannot immediately reproduce. The important questions concern how the expertise is explained, what remains open to challenge and whether the expert's conclusion is treated as unlimited authority. Paul makes these questions dramatic. Read his judgments not only for the futures he fears, but for the relationship those fears establish with other people. Does the claim of necessity invite understanding, demand trust or make disagreement appear impossible? Those are different political acts, even when they begin from the same anticipated danger. - -# The scale of harm and the scale of a character - -A novel can make one person's grief vivid while describing widespread harm at a distance. This difference is not automatically a failure. Narrative attention has limits, and personal relationships provide a powerful means of understanding a central character. But readers should notice how those limits affect their judgment. The person we know closely can feel more real than the many people whose lives are altered by the system around him. - -That imbalance becomes ethically important when an Emperor is also the protagonist. We may understand the pressures acting on Paul with great intimacy while understanding the consequences of his authority only through broad descriptions. The emotional weight of the narrative can therefore favour him even when the political scale suggests a much wider field of responsibility. Sympathy follows attention. A careful reading asks whether attention has also become an unexamined allocation of moral importance. - -We interpret the novel as inviting this discomfort rather than resolving it. The task is not to stop caring about Paul. It is to prevent caring about him from making everyone else abstract. When a passage moves between private distress and imperial consequence, pause over the change in scale. What does each scale make visible? What does it leave out? A character's suffering may be genuine and still not balance the suffering associated with his position. Acknowledging both keeps the discussion from collapsing into either a defence of the sympathetic person or a refusal to recognise any of his human difficulty. - -# Reform, preservation and the habits of a regime - -A powerful ruler can recognise flaws in an order and still depend on its continuation. This creates a distinction between correcting individual practices and reconsidering the structure that makes those practices useful. Reform may reduce harm. It may also preserve the larger arrangement by making it more tolerable. Neither possibility should be assumed without examining the relationship between the proposed change and the power it leaves intact. - -For readers, the useful question is what a regime must retain in order to remain itself. Does it rely on concentrated legitimacy, dynastic continuity, the organisation of devotion or a resource that others need? A correction that leaves those dependencies untouched may have a different significance from one that changes how authority is distributed. The difference can be easy to miss when reforms are evaluated only through the intentions of the person proposing them. - -We read Paul's imperial life through this tension between preservation and change. A leader's awareness of a problem is not the same thing as an ability or willingness to transform its causes. Yet failure to transform everything does not make every limited correction meaningless. The novel's difficulty lies in the coexistence of these truths. Ask what a particular decision protects, what it changes and what it cannot allow to become uncertain. This approach makes reform a specific political action rather than a flattering description of the ruler's character. It also helps explain why intelligence and good intention do not automatically free a person from the habits of a powerful position. - -# Why a disappointed reader can be a more careful reader - -The movement from Dune to Dune Messiah can feel like a refusal of the reward a reader expected. A figure whose survival mattered has become the centre of troubling consequences. It is possible to experience that change as disappointment without concluding that the sequel has misunderstood the earlier story. The disappointment can reveal how much our approval depended on the expected shape of the hero's success. - -This emotional response is useful evidence about reading habits. Did we expect Paul's exceptional qualities to guarantee an exceptional government? Did we regard the defeat of his enemies as proof that the future would now belong to the morally right people? Did we assume that a leader who feared harm would necessarily remain able to prevent it? Such expectations are understandable, but the sequel subjects them to pressure. It asks us to continue thinking after the moment at which a simpler story might have stopped. - -Our interpretation treats that continued thinking as one of the book's central achievements. A character need not remain an object of uncomplicated admiration for the reader's original concern to have been worthwhile. We can preserve the experience of the earlier story while revising what we believed it promised. This gives Paul a more demanding place in our judgment. He is not merely a hero revealed to have been false from the start. He is a person whose capacities, choices and symbolic position create consequences that the earlier heroic frame could not comfortably contain. - -# A political reading exercise - -Choose one decision in Paul's imperial life and describe it at three levels. At the personal level, identify what he fears losing and what he hopes to preserve. At the institutional level, identify which positions or practices make the decision possible. At the public level, identify who must live with its consequences without possessing the same information or influence. These three descriptions may produce different pictures of the same action. - -Now ask what evidence would be needed to justify the action at each level. Personal sincerity might matter at the first level, but it cannot by itself settle the third. Institutional stability might matter at the second, but stability is not an automatic answer to the distribution of harm. The exercise does not require you to pronounce a final verdict on the entire empire. It requires you to keep the relevant standards from being silently exchanged for one another. A sympathetic motive should not be used as if it were proof of a just outcome. - -Finally, return to the title of this chronicle. The price of an Imperium is not only something paid by its ruler. It is distributed across relationships, institutions and people whom the narrative cannot follow equally closely. Ask who pays visibly, who pays at a distance and who gains the authority to explain the payment as necessary. Those questions connect the political register to the next article's concern with prescience and loss. They also make clear why the story of a victorious Emperor can become a story about the limits of being its central figure. - -# Compare two standards of success - -Make a brief list of what counts as success for a threatened individual and a second list of what counts as success for a government. Survival, protection of loved ones and escape from an enemy might dominate the first. Fair procedures, limits on force, space for disagreement and protection of people outside the ruler's immediate circle might matter in the second. The lists can overlap without becoming identical. A government needs more than an expanded version of its leader's personal survival strategy. - -Now ask whether your judgment of Paul changes when you change lists. This does not require abandoning sympathy. It requires identifying the standard that sympathy may otherwise hide. A ruler who is understandable as a person can still be inadequate by the standards of the office. Conversely, a political criticism that ignores the pressures acting on the person can miss how the office reproduces its own habits. The productive reading keeps both standards explicit instead of allowing one to silently stand in for the other. diff --git a/website/control-panel/inventory/inventory-api.mjs b/website/control-panel/inventory/inventory-api.mjs new file mode 100644 index 00000000..5a6339fb --- /dev/null +++ b/website/control-panel/inventory/inventory-api.mjs @@ -0,0 +1,58 @@ +const uuidPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const reply=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store','Vary':'Cookie','X-Content-Type-Options':'nosniff'}}); + +/** Mount inside cp.dunerealms.com's existing server. Callbacks are server-owned, never client input. */ +export function createInventoryHandler({authenticate,verifiedMinecraftUuid,pool,logger=console}) { + if(typeof authenticate!=='function'||typeof verifiedMinecraftUuid!=='function'||!pool?.query) + throw new TypeError('Authenticated account, verified game-link resolver and PostgreSQL pool are required.'); + return async request=>{ + const url=new URL(request.url); + if(url.pathname!=='/api/inventory')return null; + if(request.method!=='GET')return reply({message:'Method not allowed.'},405); + if(url.search)return reply({message:'This endpoint only accepts the signed-in account.'},400); + try { + const account=await authenticate(request); + if(!account?.id)return reply({message:'Sign in to view your inventory.'},401); + // Resolve the verified link using this account ID. Never trust a submitted UUID or profile name. + const uuid=await verifiedMinecraftUuid(account.id); + if(!uuid)return reply({status:'unlinked',message:'Link your Minecraft account to view your inventory.'}); + if(!uuidPattern.test(uuid))return reply({message:'The verified game link is invalid.'},503); + const result=await pool.query({ + text:'SELECT inventory_view,inventory_updated_at,session_open FROM dune_players WHERE uuid=$1', + values:[uuid],query_timeout:5000 + }); + const row=result.rows[0]; + if(!row?.inventory_view)return reply({status:'empty',message:'No saved inventory yet. Join a planetary server, then wait for a save.'}); + const snapshot=typeof row.inventory_view==='string'?JSON.parse(row.inventory_view):row.inventory_view; + if(snapshot?.version!==1)return reply({message:'This inventory snapshot version is unavailable.'},503); + return reply({status:'ready',snapshot,updatedAt:row.inventory_updated_at,sessionOpen:!!row.session_open}); + } catch(error) { + // No SQL, addresses, credentials or player UUIDs in client errors. + logger.error?.('Account inventory unavailable.'); + return reply({status:'unavailable',message:'Inventory is temporarily unavailable. Please try again later.'},503); + } + }; +} + +export function createSalesHistoryHandler({authenticate,verifiedMinecraftUuid,pool,logger=console}) { + return async request=>{ + const url=new URL(request.url); + if(url.pathname!=='/api/exchange/sales-history')return null; + if(request.method!=='GET')return reply({message:'Method not allowed.'},405); + const keys=[...url.searchParams.keys()],before=url.searchParams.get('before'); + if(keys.some(key=>key!=='before')||keys.length>1||(before!==null&&!/^[1-9][0-9]{0,18}$/.test(before))||(before!==null&&BigInt(before)>9223372036854775807n))return reply({message:'Invalid sales history cursor.'},400); + try { + const account=await authenticate(request); + if(!account?.id)return reply({message:'Sign in to view your sales.'},401); + const uuid=await verifiedMinecraftUuid(account.id); + if(!uuid)return reply({status:'unlinked',sales:[],nextCursor:null}); + if(!uuidPattern.test(uuid))return reply({message:'The verified game link is invalid.'},503); + const result=await pool.query({text:'SELECT id::text,listing_id::text,material,display_name,quantity,unit_price::text,total_price::text,origin,buyer_name,sold_at FROM dune_exchange_sales WHERE seller=$1 AND ($2::bigint IS NULL OR id<$2::bigint) ORDER BY id DESC LIMIT 21',values:[uuid,before],query_timeout:5000}); + const sales=result.rows.slice(0,20); + return reply({status:'ready',sales,nextCursor:result.rows.length>20?sales.at(-1).id:null}); + } catch { + logger.error?.('Account sales history unavailable.'); + return reply({status:'unavailable',message:'Sales history is temporarily unavailable.'},503); + } + }; +} diff --git a/website/control-panel/inventory/market-bridge.mjs b/website/control-panel/inventory/market-bridge.mjs new file mode 100644 index 00000000..4b473033 --- /dev/null +++ b/website/control-panel/inventory/market-bridge.mjs @@ -0,0 +1,18 @@ +import {timingSafeEqual} from 'node:crypto'; +/** Private server-to-server bridge for the existing website exchange gateway. */ +export function createMarketBridge({pool,readToken}){ + if(typeof readToken!=='string'||readToken.length<32)throw new TypeError('A private exchange read token of at least 32 characters is required.'); + return async request=>{ + const url=new URL(request.url); + if(url.pathname!=='/internal/exchange/listings')return null; + const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + if(request.method!=='GET')return reply({error:'method_not_allowed'},405); + const received=Buffer.from(request.headers.get('authorization')||''),expected=Buffer.from('Bearer '+readToken); + if(received.length!==expected.length||!timingSafeEqual(received,expected))return reply({error:'unauthorized'},401); + if(url.search)return reply({error:'invalid_request'},400); + try{ + const result=await pool.query({text:'SELECT id::text,material,category,origin,seller_name AS seller,quantity,price::text FROM dune_exchange_listings ORDER BY id DESC LIMIT 500',query_timeout:5000}); + return reply({listings:result.rows}); + }catch{return reply({error:'market_unavailable'},503);} + }; +} diff --git a/website/control-panel/provision-owner.mjs b/website/control-panel/provision-owner.mjs new file mode 100644 index 00000000..f0f0c29b --- /dev/null +++ b/website/control-panel/provision-owner.mjs @@ -0,0 +1,10 @@ +import {readFile,unlink} from 'node:fs/promises'; +import {randomUUID,randomBytes,scrypt as rawScrypt} from 'node:crypto';import {promisify} from 'node:util'; +import {openDatabase} from '../node/mysql.mjs'; +const file=process.argv[2];if(!file||!file.startsWith('/tmp/'))throw Error('Use a private bootstrap JSON file in /tmp.'); +const input=JSON.parse(await readFile(file,'utf8'));if(!/^[a-z0-9_]{3,32}$/.test(input.username)||typeof input.password!=='string'||input.password.length<24)throw Error('Invalid owner bootstrap.'); +const db=await openDatabase(process.env);try{ + const id=randomUUID(),now=Date.now(),salt=randomBytes(16).toString('hex'),hash=(await promisify(rawScrypt)(input.password,salt,64)).toString('hex'); + await db.batch([db.prepare('INSERT INTO site_accounts(id,username,display_name,password_salt,password_hash,role,created_at) VALUES(?,?,?,?,?,?,?)').bind(id,input.username,'Unimatrix',salt,hash,'staff',now),db.prepare('INSERT INTO player_profiles(user_id,display_name,minecraft_name,discord_name,created_at,updated_at) VALUES(?,?,?,?,?,?)').bind(id,'Unimatrix','','',now,now),db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),id,'owner-provisioned','Explicit owner request; private bootstrap',now)]); + await unlink(file);console.log('Owner staff account provisioned; bootstrap removed.'); +}finally{await db.close();} diff --git a/website/control-panel/public/index.html b/website/control-panel/public/index.html new file mode 100644 index 00000000..9ffb6d68 --- /dev/null +++ b/website/control-panel/public/index.html @@ -0,0 +1 @@ +Account control panel · dunerealms.com

DUNEREALMS.COM / ACCOUNT CONTROL PANEL

Welcome, traveller.

Your identity. Your journeys. Your place in the caravan.

Website accountVerified game identityCommunity rewards

THE CARAVANS MUST ENDURE

One account.
A world of journeys.

Link your Minecraft identity and keep your earned rewards in one place.

Your website password is separate from Minecraft. We never ask for your Microsoft or Minecraft password.

diff --git a/website/control-panel/public/inventory/inventory-mount.mjs b/website/control-panel/public/inventory/inventory-mount.mjs new file mode 100644 index 00000000..3133704f --- /dev/null +++ b/website/control-panel/public/inventory/inventory-mount.mjs @@ -0,0 +1,13 @@ +import {mountInventory} from './inventory-view.mjs'; +const dashboard=document.getElementById('dashboard'); +if(dashboard){ + const root=document.createElement('section');root.id='planetary-inventory'; + const game=document.getElementById('game');if(game)game.after(root);else dashboard.append(root); + let view=null; + const sync=()=>{if(dashboard.hidden){view?.clear();view=null;root.hidden=true;}else{root.hidden=false;if(!view)view=mountInventory(root);}}; + const changed=()=>{view?.clear();view=null;sync();}; + new MutationObserver(sync).observe(dashboard,{attributes:true,attributeFilter:['hidden']}); + for(const id of ['identity','game-status']){const target=document.getElementById(id);if(target)new MutationObserver(changed).observe(target,{childList:true,subtree:true,characterData:true});} + window.addEventListener('dune:game-link-changed',changed); + sync(); +} diff --git a/website/control-panel/public/inventory/inventory-view.mjs b/website/control-panel/public/inventory/inventory-view.mjs new file mode 100644 index 00000000..6f8f1f2f --- /dev/null +++ b/website/control-panel/public/inventory/inventory-view.mjs @@ -0,0 +1,44 @@ +const planetName=id=>({arrakis:'Arrakduin',caladan:'Kaladam',giedi_prime:'Giedermark',kaitain:'Kaiterhof',sigma_draconis_iv:'Sigmadraken IV'}[id]||String(id).replaceAll('_',' ')); +const armorKeys=['helmet','chestplate','leggings','boots']; +const node=(tag,text,cls)=>{const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e;}; +const money=value=>new Intl.NumberFormat(undefined,{maximumFractionDigits:2,minimumFractionDigits:2}).format(Number(value)); +const colors={NETHERITE:'#69616f',DIAMOND:'#62d6cc',IRON:'#d5d6c7',GOLDEN:'#e7bc57',CHAINMAIL:'#9da9a6',LEATHER:'#9b7050'}; +function armorColor(item){if(!item)return null;if(/^#[0-9a-f]{6}$/i.test(item.color||''))return item.color;return Object.entries(colors).find(([key])=>item.material?.startsWith(key))?.[1]||'#a9b4a8';} +function rect(svg,x,y,w,h,fill){const e=document.createElementNS('http://www.w3.org/2000/svg','rect');for(const [k,v]of Object.entries({x,y,width:w,height:h,fill}))e.setAttribute(k,v);svg.append(e);} +function svgBox(box){const s=document.createElementNS('http://www.w3.org/2000/svg','svg');s.setAttribute('viewBox',box);s.setAttribute('aria-hidden','true');s.setAttribute('shape-rendering','crispEdges');return s;} +function mannequin(armor){const s=svgBox('0 0 80 144');s.classList.add('kit-mannequin'); + rect(s,18,136,44,3,'#0a1f1a');rect(s,28,6,24,24,'#bd906d');rect(s,28,6,24,7,'#3c3026');rect(s,28,13,4,8,'#3c3026');rect(s,33,17,4,3,'#cfe6df');rect(s,43,17,4,3,'#cfe6df');rect(s,35,18,2,2,'#396e8b');rect(s,43,18,2,2,'#396e8b');rect(s,37,24,8,2,'#805d48'); + rect(s,16,32,12,38,'#aa8164');rect(s,52,32,12,38,'#aa8164');rect(s,16,32,12,18,'#457d78');rect(s,52,32,12,18,'#376862');rect(s,28,32,24,39,'#457d78');rect(s,28,32,5,39,'#56938a');rect(s,28,71,11,53,'#2e414d');rect(s,41,71,11,53,'#253946');rect(s,28,119,11,9,'#463b33');rect(s,41,119,11,9,'#392f29'); + const color=Object.fromEntries(armorKeys.map(k=>[k,armorColor(armor?.[k])])); + if(color.helmet){rect(s,26,3,28,11,color.helmet);rect(s,26,14,4,15,color.helmet);rect(s,50,14,4,15,color.helmet);rect(s,29,5,22,2,'#ffffff40');} + if(color.chestplate){rect(s,27,32,26,39,color.chestplate);rect(s,14,32,14,15,color.chestplate);rect(s,52,32,14,15,color.chestplate);rect(s,30,35,4,32,'#ffffff25');rect(s,46,35,5,32,'#00000025');rect(s,35,34,10,7,'#142a2855');} + if(color.leggings){rect(s,27,71,26,10,color.leggings);rect(s,27,81,12,30,color.leggings);rect(s,41,81,12,30,color.leggings);rect(s,29,83,3,24,'#ffffff20');rect(s,49,83,3,24,'#00000025');} + if(color.boots){rect(s,26,111,13,18,color.boots);rect(s,41,111,13,18,color.boots);rect(s,26,125,13,4,'#00000035');rect(s,41,125,13,4,'#00000035');}return s;} +function itemIcon(item){const s=svgBox('0 0 24 24'),m=item?.material||'',c=armorColor(item)||'#c7b67f'; + if(/HELMET/.test(m)){rect(s,4,4,16,8,c);rect(s,4,12,4,7,c);rect(s,16,12,4,7,c);rect(s,7,5,10,2,'#ffffff55');} + else if(/CHESTPLATE/.test(m)){rect(s,6,5,12,15,c);rect(s,2,4,5,7,c);rect(s,17,4,5,7,c);rect(s,9,4,6,4,'#263b37');rect(s,8,10,2,8,'#ffffff35');} + else if(/LEGGINGS/.test(m)){rect(s,5,4,14,5,c);rect(s,5,9,5,12,c);rect(s,14,9,5,12,c);} + else if(/BOOTS/.test(m)){rect(s,4,5,6,14,c);rect(s,14,5,6,14,c);rect(s,2,16,8,4,c);rect(s,14,16,8,4,c);} + else if(/SWORD|SHOVEL|PICKAXE|AXE/.test(m)){rect(s,7,14,3,7,'#9b7750');rect(s,10,5,4,11,c);rect(s,6,13,12,3,c);if(/PICKAXE|AXE/.test(m))rect(s,4,4,15,5,c);} + else if(/DYE|SPICE/.test(m)){rect(s,7,5,10,3,'#c97732');rect(s,4,9,16,9,'#df9447');rect(s,7,18,10,3,'#b85c29');rect(s,7,10,6,3,'#ffd18b');} + else if(/SHIELD/.test(m)){rect(s,5,3,14,14,'#a4aaa1');rect(s,8,5,8,13,'#8b7054');rect(s,8,17,8,4,'#a4aaa1');} + else if(/DIAMOND|EMERALD/.test(m)){const f=m.includes('DIAMOND')?'#64d8d0':'#61be87';rect(s,7,4,10,4,f);rect(s,4,8,16,8,f);rect(s,7,16,10,4,f);rect(s,7,7,4,4,'#d3fff2');} + else if(/INGOT/.test(m)){rect(s,4,8,16,9,m.includes('GOLD')?'#e9c367':'#c6cbc3');rect(s,7,5,13,5,m.includes('GOLD')?'#ffe29a':'#eef0e5');rect(s,4,17,16,3,'#7f8371');} + else if(/BREAD|FOOD|CARROT/.test(m)){rect(s,3,9,17,9,'#c5954c');rect(s,6,6,11,4,'#e0b168');rect(s,7,8,2,7,'#f1cf89');rect(s,13,8,2,7,'#f1cf89');} + else{rect(s,4,5,15,14,'#8e9a7b');rect(s,4,5,15,4,'#b4bc92');rect(s,15,9,4,10,'#6e7a60');rect(s,6,11,3,3,'#c4bc8a');}return s;} +export function mountInventory(root,{request=async path=>{const r=await fetch(path,{credentials:'same-origin',cache:'no-store'});const data=await r.json();if(!r.ok)throw Error(data.message||'Please try again later.');return data;},demo=false}={}){ + root.classList.add('dr-inventory');root.replaceChildren();const heading=node('header',undefined,'kit-heading'),titles=node('div');titles.append(node('div',demo?'ACCOUNT / INVENTORY PREVIEW':'ACCOUNT / PLANETARY INVENTORY','kit-eyebrow'),node('h2','Your expedition kit'),node('p','Everything you carry, across the five worlds.','kit-muted'));const refresh=node('button','Refresh');refresh.type='button';heading.append(titles,refresh);root.append(heading); + const status=node('p','Loading your saved inventory…','kit-notice');status.setAttribute('role','status');root.append(status);const layout=node('div',undefined,'kit-layout');layout.hidden=true;root.append(layout); + const equipment=node('section',undefined,'kit-equipment');equipment.append(node('h3','Equipped armor'));const person=node('div',undefined,'kit-person'),armorSlots=node('div',undefined,'kit-armor-slots'),avatar=node('div'),hand=node('div',undefined,'kit-hand');person.append(armorSlots,avatar,hand);equipment.append(person,node('p','Equipment mannequin · dummy skin','kit-avatar-label'));const xp=node('div',undefined,'kit-xp'),track=node('div',undefined,'kit-xp-track'),fill=node('div',undefined,'kit-xp-fill');track.setAttribute('role','progressbar');track.setAttribute('aria-label','Progress to next experience level');track.setAttribute('aria-valuemin','0');track.setAttribute('aria-valuemax','100');track.append(fill);equipment.append(xp,track);layout.append(equipment); + const content=node('section'),tabs=node('div',undefined,'kit-tabs');tabs.setAttribute('role','tablist');tabs.setAttribute('aria-label','Account inventory sections');content.append(tabs);layout.append(content);const panel=node('div');panel.id='kit-panel-'+Math.random().toString(36).slice(2);panel.setAttribute('role','tabpanel');content.append(panel);const detail=node('div',undefined,'kit-detail');detail.setAttribute('aria-live','polite');content.append(detail);const footer=node('p',undefined,'kit-footer');root.append(footer); + let data=null,active='inventory',generation=0,historyGeneration=0,historyRows=[],cursor=null; + function select(item,label){detail.replaceChildren(node('strong',item?.name||label||'Empty slot'));if(item)detail.append(node('p',`${item.amount} × ${item.material.replaceAll('_',' ').toLowerCase()}${item.enchanted?' · Enchanted':''}${item.maxDurability?` · Durability ${item.durability} / ${item.maxDurability}`:''}`));else detail.append(node('p','Select an item to inspect its saved details.'));} + function slot(item,label,equipped=false){const b=node('button',undefined,'kit-slot');b.type='button';b.setAttribute('aria-label',label+': '+(item?`${item.name}, quantity ${item.amount}`:'empty'));b.dataset.equipped=String(equipped);if(item){b.append(itemIcon(item));if(item.amount>1)b.append(node('span',String(item.amount),'kit-count'));}else b.append(node('span','·','kit-empty'));b.onclick=()=>{root.querySelectorAll('.kit-slot[aria-pressed]').forEach(e=>e.removeAttribute('aria-pressed'));b.setAttribute('aria-pressed','true');select(item,label);};return b;} + function grid(items,count,label,hot=false){const wrap=node('div',undefined,hot?'kit-hotbar':''),title=node('div',undefined,'kit-grid-title');title.append(node('span',label),node('span',`${(items||[]).filter(Boolean).length} / ${count} slots`));wrap.append(title);const g=node('div',undefined,'kit-grid');for(let i=0;i{active=key;renderPanel();};tabs.append(b);tabButtons[key]=b;} + function renderPanel(){for(const [k,b]of Object.entries(tabButtons))b.setAttribute('aria-selected',String(k===active));panel.setAttribute('aria-labelledby',tabButtons[active].id);panel.replaceChildren();detail.hidden=active==='history';historyGeneration++; + if(active==='history'){historyRows=[];cursor=null;loadSales(false);return;}const s=data?.snapshot;if(!s){panel.append(node('p','No saved items yet.','kit-muted'));return;}panel.append(grid(s.inventory,27,'Backpack'),grid(s.hotbar,9,'Hotbar',true));} + async function loadSales(older){const token=++historyGeneration;panel.replaceChildren(node('p','Loading sales…','kit-muted'));try{const r=await request('/api/exchange/sales-history'+(older&&cursor?'?before='+encodeURIComponent(cursor):''));if(token!==historyGeneration)return;historyRows=older?[...historyRows,...(r.sales||[])]:r.sales||[];cursor=r.nextCursor;panel.replaceChildren(node('h3','History of sales'));if(!historyRows.length)panel.append(node('p',r.status==='unlinked'?'Link your Minecraft account to view your sales.':'No completed sales yet. Sales made after this update appear here.','kit-muted'));for(const sale of historyRows){const row=node('article',undefined,'kit-sale'),left=node('div');left.append(node('strong',sale.display_name||sale.material.replaceAll('_',' ')),node('small',`${sale.quantity} item${sale.quantity===1?'':'s'} · ${planetName(sale.origin)} · Buyer: ${sale.buyer_name}`),node('small',new Date(sale.sold_at).toLocaleString()));const right=node('div',undefined,'kit-money');right.append(node('div','+'+money(sale.total_price)),node('small','Dunemarks'));row.append(left,right);panel.append(row);}if(cursor){const more=node('button','Load older sales','kit-older');more.type='button';more.onclick=()=>loadSales(true);panel.append(more);}}catch(error){if(token===historyGeneration)panel.replaceChildren(node('p',error.message,'kit-notice'));}} + async function refreshData(){const token=++generation;refresh.disabled=true;status.textContent='Loading your saved inventory…';status.hidden=false;layout.hidden=true;historyGeneration++;try{const r=await request('/api/inventory');if(token!==generation)return;data=r;layout.hidden=false;status.hidden=r.status==='ready';status.textContent=r.message||'';const s=r.snapshot||{};armorSlots.replaceChildren(...armorKeys.map(k=>slot(s.armor?.[k],k)));avatar.replaceChildren(mannequin(s.armor));hand.replaceChildren(slot(s.offhand,'Offhand'),node('span','Offhand'));xp.replaceChildren(node('span','Level '+(s.level||0)),node('span',s.playerName||'Minecraft account'));const progress=Math.max(0,Math.min(100,Number(s.experienceProgress||0)*100));fill.style.width=progress+'%';track.setAttribute('aria-valuenow',String(Math.round(progress)));select(null);footer.textContent=demo?'DEMO DATA · Layout preview only. Lobby and ender chests remain separate.':r.status==='ready'?`Saved ${new Date(r.updatedAt||s.capturedAt).toLocaleString()} · ${r.sessionOpen?'Active or unclean session; showing last saved items.':'Last completed save.'} Read only. Lobby and ender chests remain separate.`:'Planetary servers only. Lobby and ender chests remain separate.';renderPanel();}catch(error){if(token!==generation)return;data=null;layout.hidden=true;status.hidden=false;status.textContent=error.message;footer.textContent='Inventory could not be loaded.';}finally{if(token===generation)refresh.disabled=false;}} + refresh.onclick=refreshData;refreshData();return{refresh:refreshData,clear(){generation++;historyGeneration++;data=null;historyRows=[];root.replaceChildren();}}; +} diff --git a/website/control-panel/public/inventory/inventory.css b/website/control-panel/public/inventory/inventory.css new file mode 100644 index 00000000..e0316f29 --- /dev/null +++ b/website/control-panel/public/inventory/inventory.css @@ -0,0 +1,3 @@ +.dr-inventory{--bg:#101f20;--line:#35514b;--gold:#e4bb72;--muted:#b1c3ba;--text:#f2eee3;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:20px;padding:clamp(16px,3vw,30px);font:15px/1.5 system-ui,sans-serif;margin:24px 0;box-sizing:border-box}.dr-inventory *{box-sizing:border-box}.dr-inventory [hidden]{display:none!important}.dr-inventory h2{font:500 clamp(25px,4vw,36px)/1.15 Georgia,serif;margin:4px 0 10px}.dr-inventory h3{font-size:16px;margin:0 0 12px}.dr-inventory p{margin:0 0 12px}.dr-inventory .kit-eyebrow{color:var(--gold);letter-spacing:.16em;font-size:11px;font-weight:700}.dr-inventory .kit-muted{color:var(--muted);font-size:13px}.dr-inventory .kit-heading{display:flex;justify-content:space-between;align-items:center;gap:16px;flex-wrap:wrap;margin-bottom:22px}.dr-inventory button{font:inherit;color:inherit;background:#233c36;border:1px solid #48665a;border-radius:8px;padding:9px 14px;cursor:pointer}.dr-inventory button:hover{background:#315246}.dr-inventory button:focus-visible{outline:3px solid var(--gold);outline-offset:3px}.dr-inventory button:disabled{opacity:.55;cursor:wait}.dr-inventory .kit-layout{display:grid;grid-template-columns:minmax(240px,.8fr) minmax(0,1.6fr);gap:22px}.dr-inventory .kit-equipment{background:linear-gradient(160deg,#213c36,#142a28 70%);border:1px solid var(--line);border-radius:14px;padding:20px;min-width:0}.dr-inventory .kit-person{display:grid;grid-template-columns:46px minmax(90px,1fr) 46px;gap:8px;align-items:center;min-height:240px}.dr-inventory .kit-armor-slots{display:grid;gap:10px}.dr-inventory .kit-mannequin{display:block;width:100%;max-width:170px;margin:auto;filter:drop-shadow(0 16px 12px #071b1880);image-rendering:pixelated}.dr-inventory .kit-avatar-label{text-align:center;margin:6px 0 18px;color:var(--muted);font-size:12px}.dr-inventory .kit-xp{display:flex;justify-content:space-between;gap:8px;color:#b7d58b;font-size:13px;margin:12px 0 7px}.dr-inventory .kit-xp-track{height:5px;background:#0a1916;border-radius:8px;overflow:hidden}.dr-inventory .kit-xp-fill{height:100%;background:#afd178}.dr-inventory .kit-tabs{display:flex;gap:5px;flex-wrap:wrap;margin-bottom:20px;border-bottom:1px solid var(--line);padding-bottom:12px}.dr-inventory .kit-tabs button{border:0;background:transparent;padding:8px 10px;color:var(--muted);font-size:13px}.dr-inventory .kit-tabs button[aria-selected=true]{background:#364b38;color:#f4d49b}.dr-inventory .kit-grid{display:grid;grid-template-columns:repeat(9,minmax(0,1fr));gap:6px}.dr-inventory button.kit-slot{position:relative;border-radius:6px;aspect-ratio:1;padding:5px;width:100%;min-width:0;background:linear-gradient(135deg,#253b36,#1a302c);border:1px solid #43574b;display:grid;place-items:center;box-shadow:inset 2px 2px #ffffff08,inset -2px -2px #00000025}.dr-inventory button.kit-slot[data-equipped=true]{border-color:#d3af70;background:#3d4735}.dr-inventory button.kit-slot[aria-pressed=true]{outline:2px solid var(--gold);outline-offset:1px}.dr-inventory .kit-slot svg{width:100%;height:100%;max-width:42px;image-rendering:pixelated;filter:drop-shadow(2px 3px 0 #0005)}.dr-inventory .kit-count{position:absolute;right:4px;bottom:0;font-size:12px;color:#fff;text-shadow:1px 1px #000}.dr-inventory .kit-empty{color:#72867a;font-size:19px}.dr-inventory .kit-hotbar{margin-top:10px;border-top:1px solid var(--line);padding-top:10px}.dr-inventory .kit-grid-title{display:flex;justify-content:space-between;margin:0 0 8px;font-size:12px;color:var(--muted)}.dr-inventory .kit-detail{background:#1c302c;border:1px solid var(--line);border-radius:10px;padding:14px 16px;margin-top:18px;min-height:76px}.dr-inventory .kit-detail strong{display:block;color:#f1d19b;margin-bottom:3px}.dr-inventory .kit-detail p{margin:0;color:var(--muted);font-size:13px;overflow-wrap:anywhere}.dr-inventory .kit-notice{color:var(--muted);padding:14px 0}.dr-inventory .kit-footer{font-size:12px;color:var(--muted);margin-top:20px;border-top:1px solid var(--line);padding-top:12px}.dr-inventory .kit-sale{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:8px 16px;padding:13px 0;border-bottom:1px solid var(--line)}.dr-inventory .kit-sale small{display:block;color:var(--muted);font-size:12px}.dr-inventory .kit-sale strong{color:#f1d19b;font-size:14px;overflow-wrap:anywhere}.dr-inventory .kit-money{text-align:right;white-space:nowrap;color:#c6da96;font-size:14px}.dr-inventory .kit-older{margin-top:14px}.dr-inventory .kit-hand span{font-size:10px;color:var(--muted)}@media(max-width:760px){.dr-inventory .kit-layout{grid-template-columns:1fr}.dr-inventory .kit-equipment{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}.dr-inventory .kit-equipment h3{grid-column:1/-1}.dr-inventory .kit-person{grid-row:2/5;min-height:220px}.dr-inventory .kit-avatar-label{align-self:end}.dr-inventory .kit-xp{align-self:end}.dr-inventory .kit-mannequin{max-width:140px}.dr-inventory .kit-grid{gap:5px}}@media(max-width:380px){.dr-inventory .kit-equipment{display:block}.dr-inventory .kit-person{max-width:240px;margin:auto}.dr-inventory .kit-tabs button{padding:7px}.dr-inventory .kit-slot svg{max-width:24px}.dr-inventory .kit-count{font-size:10px}.dr-inventory .kit-grid{gap:3px}} +/* Match the existing account panel's pixel lettering and imperial borders. */ +.dr-inventory{border:3px solid #8e7846;border-radius:0;background:linear-gradient(#19382ff3,#132c25f9),url('/assets/ornament.webp') center/600px;font-family:Manrope,Arial,sans-serif;box-shadow:inset 2px 2px #afbe8b22,5px 6px #07160f99}.dr-inventory h2{font-family:VT323,monospace;font-size:42px;color:#e1bd74}.dr-inventory h3{font-family:VT323,monospace;font-size:28px}.dr-inventory button,.dr-inventory .kit-equipment,.dr-inventory .kit-detail{border-radius:0;border-width:2px}.dr-inventory .kit-heading{position:static;min-height:0;height:auto;padding:0;background:none;border:0;box-shadow:none}.dr-inventory button.kit-slot{border-radius:0;border-width:2px}.dr-inventory .kit-tabs button[aria-selected=true]{border:2px ridge #c3a359;background:#b99443;color:#102c2b}.tabs a[href='#planetary-inventory']:before{background-image:url('/assets/menu-12.webp')} diff --git a/website/control-panel/public/panel.css b/website/control-panel/public/panel.css new file mode 100644 index 00000000..9a07930d --- /dev/null +++ b/website/control-panel/public/panel.css @@ -0,0 +1,2 @@ +@import url('https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=VT323&display=swap'); +:root{color-scheme:dark;--ink:#142a28;--dark:#10201f;--paper:#f3e5c6;--gold:#d5ab63;--muted:#babbb0;--line:#8e753e}*{box-sizing:border-box}[hidden]{display:none!important}html{scroll-behavior:smooth}body{margin:0;background:linear-gradient(#111d1def,#111d1def),url('assets/ornament.webp') center/700px;color:var(--paper);font:14px/1.7 Manrope,Arial,sans-serif}a{color:var(--gold);text-decoration:none}img{max-width:100%;display:block}button,input{font:inherit}button,a{touch-action:manipulation}button{cursor:pointer}button:disabled{opacity:.55;cursor:wait}.skip{position:fixed;top:-100px;z-index:20;background:var(--paper);color:var(--ink);padding:12px}.skip:focus{top:0}:focus-visible{outline:3px solid var(--gold);outline-offset:4px}.site-header{min-height:90px;display:flex;justify-content:space-between;align-items:center;gap:25px;padding:18px 5%;border-bottom:4px solid #ae8847;background:linear-gradient(110deg,#132c2aed,#1f3330f2),url('assets/ornament.webp') center/650px;box-shadow:inset 0 -2px #382b18}.brand{font:29px VT323,monospace;letter-spacing:.055em;color:var(--paper);white-space:nowrap}.brand small{display:block;font:8px Manrope,sans-serif;color:var(--gold);letter-spacing:.28em;margin-left:38px}.sun{display:inline-block;width:28px;height:28px;background:url('assets/item-23.webp') center/contain;vertical-align:middle;margin-right:8px}.site-header nav{display:flex;gap:12px;flex-wrap:wrap}.site-header nav a{display:flex;align-items:center;gap:8px;padding:8px 12px;font-size:11px;color:var(--paper);background:linear-gradient(#3f5145,#243b32);border:2px solid #9b986c;box-shadow:inset 1px 1px #b4bb8d44,3px 3px #050f0b99}.site-header nav img{width:27px;height:27px;object-fit:contain}.site-header nav a:hover{border-color:var(--gold)}.panel-hero{margin:0;padding:62px max(6%,calc((100vw - 1180px)/2));min-height:340px;border-bottom:4px solid #ac8743;background:linear-gradient(90deg,#0b201bf2,#102b26a6 55%,#102b2622),url('assets/minecraft-hero.webp') center 48%/cover}.hero-copy{max-width:900px}.eyebrow{font-size:10px;letter-spacing:.23em;color:var(--gold);font-weight:800;margin:0 0 20px}h1,h2,h3{font-family:VT323,'Courier New',monospace;line-height:1;letter-spacing:.015em;font-weight:400;margin-top:0;text-shadow:2px 3px #0003}h1{font-size:clamp(58px,7vw,100px);margin-bottom:17px}h2{font-size:42px;margin-bottom:18px}h3{font-size:30px;margin-bottom:12px}.hero-description{font-size:15px;color:#e4dfca}.hero-tags{display:flex;gap:12px;flex-wrap:wrap;margin-top:25px}.hero-tags span{font-size:10px;letter-spacing:.1em;text-transform:uppercase;border:1px solid #b59454;padding:7px 12px;background:#13291ec9}.panel-workspace{max-width:1240px;margin:auto;padding:30px 28px 65px}.account-topbar{display:flex;justify-content:space-between;align-items:center;gap:20px;padding-bottom:20px;margin-bottom:10px;border-bottom:1px solid #6c6642}.account-summary{color:var(--gold);font-weight:700;letter-spacing:.04em;font-size:12px}#notice{color:var(--gold);padding:12px 15px;border-left:3px solid var(--gold);background:#233d2f}#notice:empty{display:none}button,.tabs a{display:inline-block;padding:10px 16px;border:2px solid #ad8a43;border-radius:0;color:var(--paper);background:linear-gradient(#34503c,#20372b);box-shadow:inset 2px 2px #c6d99d22,inset -2px -2px #08170c77,3px 4px #06130ca8;font-weight:700;font-size:12px;text-decoration:none}button:hover,.tabs a:hover{border-color:#f1cd83;transform:translateY(-1px)}button[aria-pressed=true],.primary{background:linear-gradient(#f0ce77,#c79845);color:#182218;box-shadow:inset 2px 2px #fff3c577,inset -2px -2px #61451c70,3px 4px #050f0bb8}.tabs{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:24px}.auth-card{display:grid;grid-template-columns:1fr 1.05fr;border:4px solid #a78644;box-shadow:inset 0 0 0 2px #e4ca83,7px 8px #06150fa8;margin-top:26px}.auth-scene{min-height:480px;display:flex;align-items:flex-end;background:linear-gradient(0deg,#0c211df5,#102a2633 80%),url('assets/guild.webp') center/cover;border-right:3px solid #a78644}.scene-caption{padding:35px}.scene-caption h2{font-size:52px;margin-bottom:18px}.scene-caption>p:last-child{color:#d6d8c6;font-size:12px;max-width:330px}.auth-fields{padding:35px;background:linear-gradient(#f4e8cdea,#f4e8cdef),url('assets/ornament.webp') center/480px;color:#263c2b}.auth-fields .tabs{padding-bottom:20px;border-bottom:1px solid #aa915d}.auth-fields .muted{color:#4a5b43}.auth-fields h2{color:#263c2b;text-shadow:none}form{max-width:650px}label{display:grid;gap:8px;margin:16px 0;font-size:12px;font-weight:700}input{width:100%;padding:13px;border:3px solid #7d744e;border-radius:0;background:#163329;color:var(--paper);box-shadow:inset 2px 2px #07170d88;font-size:14px}.muted,.site-footer{font-size:12px;color:#b7c1b0}.tabs a:before{content:'';display:inline-block;width:25px;height:25px;margin-right:8px;vertical-align:middle;background:center/contain no-repeat}.tabs a[href='#game']:before{background-image:url('assets/menu-12.webp')}.tabs a[href='#rewards']:before{background-image:url('assets/dunemark-icon-64.png')}.tabs a[href='#security']:before{background-image:url('assets/menu-9.webp')}.tabs a[href='#staff']:before{background-image:url('assets/menu-0.webp')}#dashboard>section{padding:30px;margin:24px 0;border:3px solid #8e7846;box-shadow:inset 2px 2px #afbe8b22,5px 6px #07160f99;background:linear-gradient(#19382ff3,#132c25f9),url('assets/ornament.webp') center/600px;scroll-margin-top:20px}#dashboard h2{color:#e1bd74;border-bottom:1px solid #6a6943;padding-bottom:15px}#dashboard h2:before{content:'✦';color:#c49d52;font-size:22px;vertical-align:middle;margin-right:12px}#staff form{border:1px solid #6c6c47;padding:20px;margin:22px 0}pre,code{white-space:pre-wrap;overflow-wrap:anywhere;background:#0e241b;padding:8px;color:#f0d99b}pre{border:1px solid #9c854a;padding:18px}pre:empty{display:none}dl{display:grid;grid-template-columns:150px 1fr;gap:10px}dt{color:var(--gold);font-size:12px}dd{margin:0;overflow-wrap:anywhere}.reward{position:relative;border:2px solid #8e7846;background:linear-gradient(115deg,#2d4933,#172e25);box-shadow:inset 1px 1px #b1c18733,3px 4px #05140c66;padding:20px;margin:16px 0}.reward h3{color:#e7c984}.reward p{margin:8px 0}.reward code{display:block;padding:12px;margin:15px 0}.site-footer{text-align:center;border-top:3px solid #9f7b3d;padding:0 24px 30px;background:#102017}.footer-frieze{max-width:1200px;width:100%;height:120px;object-fit:cover;object-position:center;margin:0 auto 24px;opacity:.75}.site-footer p{max-width:850px;margin:0 auto 12px}.embedded .site-header,.embedded .panel-hero,.embedded .site-footer{display:none}.embedded .panel-workspace{padding:20px 22px 35px}.embedded .auth-card{margin-top:18px}.embedded .auth-scene{min-height:450px}@media(max-width:850px){.site-header{flex-direction:column;align-items:flex-start}.panel-hero{padding:42px 6%;min-height:300px}.auth-card{grid-template-columns:.8fr 1fr}.scene-caption{padding:22px}.scene-caption h2{font-size:40px}.auth-fields{padding:25px}.panel-workspace{padding:25px 20px 50px}}@media(max-width:620px){.site-header nav a{font-size:10px;padding:7px}.site-header nav{gap:8px}.site-header nav img{width:20px;height:20px}.auth-card{grid-template-columns:1fr}.auth-scene{min-height:220px;border-right:0;border-bottom:3px solid #a78644}.scene-caption{padding:24px}.scene-caption h2{font-size:37px;margin-bottom:10px}.scene-caption h2 br{display:none}.scene-caption .eyebrow{margin-bottom:10px}.auth-fields{padding:25px 20px}.panel-workspace,.embedded .panel-workspace{padding:20px 14px 40px}.embedded .auth-scene{min-height:210px}.hero-tags{gap:7px}.hero-tags span{font-size:8px;padding:6px 8px}#dashboard>section{padding:23px 17px}dl{grid-template-columns:1fr;gap:5px}dd{margin-bottom:12px}.account-topbar{gap:10px}.tabs{gap:10px}.tabs a{padding:8px 10px}.tabs a:before{width:20px;height:20px;margin-right:5px}h2{font-size:35px}} diff --git a/website/control-panel/public/panel.js b/website/control-panel/public/panel.js new file mode 100644 index 00000000..6c78e0a4 --- /dev/null +++ b/website/control-panel/public/panel.js @@ -0,0 +1,23 @@ +let mode='login',session=null;const $=id=>document.getElementById(id),notice=message=>{$('notice').textContent=message;}; +if(new URLSearchParams(location.search).get('embedded')==='1')document.body.classList.add('embedded'); +async function api(path,body){const response=await fetch('/api/'+path,{method:body===undefined?'GET':'POST',headers:{'Content-Type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)}),cache:'no-store'});const data=await response.json();if(!response.ok)throw Error(data.message||'Please try again later.');return data;} +function el(tag,text){const node=document.createElement(tag);if(text!==undefined)node.textContent=text;return node;} +async function action(button,work){button.disabled=true;notice('');try{await work();}catch(error){notice(error.message);}finally{button.disabled=false;}} +for(const next of ['login','register'])$(next+'-tab').onclick=()=>{mode=next;for(const tab of ['login','register'])$(tab+'-tab').setAttribute('aria-pressed',String(tab===next));$('auth-submit').textContent=next==='login'?'Sign in':'Create account';$('auth-form').elements.password.autocomplete=next==='login'?'current-password':'new-password';notice('');}; +$('auth-form').onsubmit=event=>{event.preventDefault();action($('auth-submit'),async()=>{await api('auth/'+mode,Object.fromEntries(new FormData(event.target)));event.target.reset();await load();});}; +$('logout').onclick=()=>action($('logout'),async()=>{await api('auth/logout',{});location.reload();}); +async function linking(){const data=await api('game-link');$('identity').replaceChildren();$('game-status').textContent=data.linked?'Your Minecraft account is verified.':'No verified Minecraft UUID linked.';$('unlink-game').hidden=!data.linked;$('link-game').hidden=data.linked;if(data.linked){$('link-command').textContent='';for(const [label,value]of [['Player',data.link.minecraft_name],['Minecraft UUID',data.link.minecraft_uuid],['Eligible since',new Date(Number(data.link.first_linked_at)).toLocaleString()]])$('identity').append(el('dt',label),el('dd',value));}} +$('link-game').onclick=()=>action($('link-game'),async()=>{const data=await api('game-link',{});$('link-command').textContent=data.command;notice('Enter this command yourself in game within 10 minutes.');}); +$('check-link').onclick=()=>action($('check-link'),async()=>{await linking();await rewards();}); +$('unlink-game').onclick=()=>{if(confirm('Unlink this website account? UUID eligibility and previous claims will be retained to prevent duplicate rewards.'))action($('unlink-game'),async()=>{await api('game-link/unlink',{});await linking();await rewards();});}; +async function rewards(){const data=await api('community/rewards');for(const [id,rows]of [['available',data.available],['history',data.history]]){const root=$(id);root.replaceChildren();if(!rows.length)root.append(el('p',data.linked?'No '+(id==='available'?'unused earned codes yet.':'claims yet.'):'Link your Minecraft account to see rewards.'));for(const row of rows){const card=el('article');card.className='reward';card.append(el('h3',row.month+' community reward'),el('p',row.reward_amount+' in-game Dunemarks'));if(row.personal_code){const command='/communitycode '+row.personal_code;card.append(el('code',command));const copy=el('button','Copy command');copy.onclick=()=>action(copy,async()=>{await navigator.clipboard.writeText(command);notice('Command copied.');});card.append(el('p'),copy);}else card.append(el('p','Claimed '+new Date(Number(row.delivered_at)).toLocaleString()));root.append(card);}}} +$('refresh-rewards').onclick=()=>action($('refresh-rewards'),rewards); +$('password-form').onsubmit=event=>{event.preventDefault();action(event.target.querySelector('button'),async()=>{await api('auth/password',Object.fromEntries(new FormData(event.target)));event.target.reset();notice('Password changed. Other sessions have been signed out.');});}; +async function campaigns(){const data=await api('community/campaigns');$('campaigns').replaceChildren();for(const row of data.campaigns){const card=el('article');card.className='reward';card.append(el('h3',row.month),el('p',new Intl.NumberFormat(undefined,{style:'currency',currency:'EUR'}).format(row.received_cents/100)+' / '+new Intl.NumberFormat(undefined,{style:'currency',currency:'EUR'}).format(row.target_cents/100)),el('p',row.reward_amount+' Dunemarks per UUID · '+(row.reached_at?'Goal reached':'Not reached')));$('campaigns').append(card);}} +for(const [form,endpoint]of [['campaign-form','community/campaigns'],['total-form','community/verify-total']])$(form).onsubmit=event=>{event.preventDefault();action(event.target.querySelector('button'),async()=>{const data=Object.fromEntries(new FormData(event.target));for(const key of ['targetCents','rewardAmount','receivedCents'])if(key in data)data[key]=Number(data[key]);if(!confirm(endpoint.endsWith('verify-total')?'Confirm that this total is verified against payment records? Reaching the target unlocks rewards.':'Create this goal? The target and reward cannot be edited afterward.'))return;await api(endpoint,data);notice('Saved.');await campaigns();});}; +async function load(){const data=await api('auth/session');session=data.user;document.querySelector('.account-summary').textContent=data.authenticated?'Signed in as '+data.user.username:'Your dunerealms.com account';$('auth').hidden=data.authenticated;$('dashboard').hidden=!data.authenticated;$('logout').hidden=!data.authenticated;$('welcome').textContent=data.authenticated?'Welcome, '+data.user.username+'.':'Welcome, traveller.';if(data.authenticated){$('staff').hidden=!data.user.staff;$('staff-tab').hidden=!data.user.staff;await linking();await rewards();if(data.user.staff){await campaigns();await accounts();}}} +async function accounts(){const data=await api('admin/accounts');$('accounts').replaceChildren();for(const row of data.accounts){const card=el('article');card.className='reward';card.append(el('h3',row.username+' · '+row.role),el('p',row.minecraft_uuid?'Linked UUID: '+row.minecraft_uuid:'No verified game account'));const revoke=el('button','Sign out this account');revoke.onclick=()=>{if(confirm('Revoke current sessions for '+row.username+'?'))action(revoke,async()=>{await api('admin/revoke-sessions',{userId:row.id});notice('Sessions revoked.');});};card.append(revoke);$('accounts').append(card);}} +$('refresh-accounts').onclick=()=>action($('refresh-accounts'),accounts); +load().catch(error=>notice(error.message)); +// Embedded parent receives only layout information, never credentials, UUIDs or reward codes. +new ResizeObserver(()=>{if(parent!==window)for(const origin of ['https://www.dunerealms.com','https://dunerealms.com'])parent.postMessage({type:'dunerealms-account-height',height:document.documentElement.scrollHeight},origin);}).observe(document.body); diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs new file mode 100644 index 00000000..e648a337 --- /dev/null +++ b/website/control-panel/server.mjs @@ -0,0 +1,54 @@ +import {createServer} from 'node:http'; +import {readFile} from 'node:fs/promises'; +import {pathToFileURL} from 'node:url'; +import {openDatabase} from '../node/mysql.mjs'; +import {createAuth} from '../node/auth.mjs'; +import {identity} from '../node/auth.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'; +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(['ornament.webp','guild.webp','minecraft-hero.webp','menu-0.webp','menu-5.webp','menu-6.webp','menu-9.webp','menu-12.webp','item-23.webp','dunemark-icon-64.png','arrakis-lore-frieze.svg']); +export function createPanel(db,settings={},dependencies={}){ + const origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin; + const auth=createAuth(db,origin),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin); + const admin=createAccountAdmin(db,origin); + const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}}; + 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 path=new URL(request.url).pathname; + 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.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(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'}});} + const file=path==='/'?'index.html':path.slice(1); + if(!['index.html','panel.js','panel.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){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 db=await openDatabase(settings),handle=createPanel(db,settings,{inventoryPool}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self'; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors https://www.dunerealms.com https://dunerealms.com"}; + const server=createServer(async(req,res)=>{try{ + req.setTimeout(15000);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>16384){res.writeHead(413,security);res.end();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)}:{})})); + res.writeHead(result.status,{...security,...Object.fromEntries(result.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',()=>server.close(async()=>{await Promise.allSettled([db.close(),inventoryPool?.end()]);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/control-panel/start.mjs b/website/control-panel/start.mjs new file mode 100644 index 00000000..6e966d96 --- /dev/null +++ b/website/control-panel/start.mjs @@ -0,0 +1,2 @@ +import {startPanel} from './server.mjs'; +await startPanel(); diff --git a/website/node/account-admin.mjs b/website/node/account-admin.mjs new file mode 100644 index 00000000..964c90a5 --- /dev/null +++ b/website/node/account-admin.mjs @@ -0,0 +1,18 @@ +import {randomUUID} from 'node:crypto'; +import {identity} from './auth.mjs'; +import {json} from './game-link.mjs'; +export function createAccountAdmin(db,origin){return async request=>{ + const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401);if(user.role!=='staff')return json({message:'Staff access required.'},403); + const path=new URL(request.url).pathname; + if(request.method==='GET'&&path==='/api/admin/accounts'){ + const {results}=await db.prepare('SELECT a.id,a.username,a.role,a.created_at,l.minecraft_uuid,l.minecraft_name FROM site_accounts a LEFT JOIN site_game_links l ON l.user_id=a.id ORDER BY a.created_at DESC LIMIT 200').all();return json({accounts:results}); + } + if(request.method!=='POST'||path!=='/api/admin/revoke-sessions')return json({message:'Not found'},404); + if(request.headers.get('origin')!==origin)return json({message:'Origin rejected'},403); + let data;try{data=await request.json();}catch{return json({message:'Invalid request'},400);} + if(typeof data.userId!=='string'||data.userId.length!==36)return json({message:'Invalid account'},400); + const target=await db.prepare('SELECT id,role FROM site_accounts WHERE id=?').bind(data.userId).first(); + if(!target)return json({message:'Account not found'},404); + if(target.role==='staff'&&target.id!==user.id)return json({message:'Other staff sessions require operator review.'},403); + await db.batch([db.prepare('DELETE FROM site_sessions WHERE user_id=?').bind(target.id),db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'sessions-revoked',target.id,Date.now())]);return json({ok:true}); +};} diff --git a/website/node/auth.mjs b/website/node/auth.mjs index 00fd96a6..9f1d600f 100644 --- a/website/node/auth.mjs +++ b/website/node/auth.mjs @@ -18,6 +18,19 @@ export function createAuth(db,origin){ if(path==='/api/auth/session'&&request.method==='GET'){const user=await identity(request,db);return json({authenticated:!!user,user:user?{username:user.username,staff:user.role==='staff'}:null});} if(request.method!=='POST')return json({message:'Method not allowed.'},405); if(request.headers.get('Origin')!==origin)return json({message:'Request origin rejected.'},403); + if(path==='/api/auth/password'){ + const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401); + if(!allowed('password:'+user.id,5))return json({message:'Too many attempts. Please try later.'},429); + let data;try{data=await request.json();}catch{return json({message:'Invalid request.'},400);} + if(typeof data.currentPassword!=='string'||data.currentPassword.length>256||typeof data.newPassword!=='string'||data.newPassword.length<12||data.newPassword.length>256)return json({message:'Use a new password of 12–256 characters.'},400); + const row=await db.prepare('SELECT * FROM site_accounts WHERE id=?').bind(user.id).first(); + const actual=await scrypt(data.currentPassword,row.password_salt,64); + if(!timingSafeEqual(actual,Buffer.from(row.password_hash,'hex')))return json({message:'Incorrect current password.'},403); + const salt=randomBytes(16).toString('hex'),hash=(await scrypt(data.newPassword,salt,64)).toString('hex'); + const result=await db.batch([db.prepare('UPDATE site_accounts SET password_salt=?,password_hash=? WHERE id=? AND password_hash=?').bind(salt,hash,user.id,row.password_hash),db.prepare('DELETE FROM site_sessions WHERE user_id=?').bind(user.id)]); + if(!result[0].meta.changes)return json({message:'Account changed. Sign in again.'},409); + return issue(row); + } if(path==='/api/auth/logout'){const token=sessionToken(request);if(token)await db.prepare('DELETE FROM site_sessions WHERE token_hash=?').bind(digest(token)).run();return json({ok:true},200,{'Set-Cookie':`${cookieName}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`});} if(!['/api/auth/login','/api/auth/register'].includes(path))return json({message:'Not found.'},404); let data;try{data=await request.json();}catch{return json({message:'Send valid JSON.'},400);} diff --git a/website/node/community-rewards.mjs b/website/node/community-rewards.mjs new file mode 100644 index 00000000..884438ea --- /dev/null +++ b/website/node/community-rewards.mjs @@ -0,0 +1,73 @@ +import {randomBytes,randomUUID} from 'node:crypto'; +import {identity} from './auth.mjs'; +import {json,gameAuthorized,validUuid} from './game-link.mjs'; +const code=()=>randomBytes(16).toString('hex').toUpperCase(); +const monthValid=value=>typeof value==='string'&&/^20\d\d-(0[1-9]|1[0-2])$/.test(value); +export function createCommunityRewards(db,settings,origin){ + return async request=>{ + const path=new URL(request.url).pathname; + if(path.startsWith('/api/community/game/')){ + if(request.method!=='POST')return json({message:'Method not allowed'},405); + if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401); + let data;try{data=await request.json();}catch{return json({message:'Invalid request'},400);} + if(!validUuid(data.uuid))return json({message:'Invalid player UUID'},400); + if(path==='/api/community/game/ack'){ + if(!/^[a-f0-9]{64}$/.test(data.receipt||''))return json({message:'Invalid receipt'},400); + const now=Date.now(); + const result=await db.batch([ + db.prepare('UPDATE community_claims SET delivered_at=COALESCE(delivered_at,?) WHERE minecraft_uuid=? AND receipt=?').bind(now,data.uuid,data.receipt), + db.prepare('UPDATE community_rewards SET used_at=COALESCE(used_at,?) WHERE minecraft_uuid=? AND month IN (SELECT month FROM community_claims WHERE minecraft_uuid=? AND receipt=? AND delivered_at IS NOT NULL)').bind(now,data.uuid,data.uuid,data.receipt) + ]); + // MySQL reports zero changes for a replayed acknowledgement; a delivered receipt remains valid. + const row=await db.prepare('SELECT delivered_at FROM community_claims WHERE minecraft_uuid=? AND receipt=?').bind(data.uuid,data.receipt).first(); + return row?.delivered_at?json({ok:true}):json({message:'Unknown receipt'},404); + } + if(path!=='/api/community/game/prepare')return json({message:'Not found'},404); + if(!/^[A-Z0-9-]{4,48}$/.test(data.code||''))return json({message:'Invalid code'},400); + const campaign=await db.prepare('SELECT c.* FROM community_campaigns c WHERE c.reached_at IS NOT NULL AND (c.public_code=? OR EXISTS (SELECT 1 FROM community_rewards r WHERE r.month=c.month AND r.minecraft_uuid=? AND r.personal_code=?))').bind(data.code,data.uuid,data.code).first(); + if(!campaign)return json({message:'Code unavailable or not earned by this UUID.'},404); + await db.prepare('INSERT INTO community_claims(minecraft_uuid,month,receipt,amount,prepared_at) VALUES(?,?,?,?,?) ON CONFLICT(minecraft_uuid,month) DO UPDATE SET minecraft_uuid=excluded.minecraft_uuid').bind(data.uuid,campaign.month,randomBytes(32).toString('hex'),campaign.reward_amount,Date.now()).run(); + const claim=await db.prepare('SELECT * FROM community_claims WHERE minecraft_uuid=? AND month=?').bind(data.uuid,campaign.month).first(); + return json({month:claim.month,amount:claim.amount,receipt:claim.receipt,delivered:!!claim.delivered_at}); + } + if(path==='/api/community/campaigns'&&request.method==='GET'){ + const {results}=await db.prepare('SELECT month,target_cents,received_cents,reward_amount,reached_at,CASE WHEN reached_at IS NOT NULL THEN public_code ELSE NULL END AS public_code FROM community_campaigns ORDER BY month DESC LIMIT 120').all();return json({campaigns:results,paymentsOpen:false}); + } + const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401); + if(path==='/api/community/rewards'&&request.method==='GET'){ + const link=await db.prepare('SELECT l.minecraft_uuid,i.first_linked_at FROM site_game_links l JOIN site_game_identities i ON i.minecraft_uuid=l.minecraft_uuid WHERE l.user_id=?').bind(user.id).first(); + if(!link)return json({linked:false,available:[],history:[]}); + const {results:earned}=await db.prepare('SELECT month FROM community_campaigns WHERE reached_at>? ORDER BY month').bind(link.first_linked_at).all(); + for(const campaign of earned)await db.prepare('INSERT INTO community_rewards(minecraft_uuid,month,personal_code,issued_at) VALUES(?,?,?,?) ON CONFLICT(minecraft_uuid,month) DO UPDATE SET minecraft_uuid=excluded.minecraft_uuid').bind(link.minecraft_uuid,campaign.month,code(),Date.now()).run(); + // Public-code claims and personal-code claims share exactly one UUID/month ledger. + const {results}=await db.prepare('SELECT r.month,r.personal_code,r.issued_at,c.reward_amount,q.delivered_at FROM community_rewards r JOIN community_campaigns c ON c.month=r.month LEFT JOIN community_claims q ON q.minecraft_uuid=r.minecraft_uuid AND q.month=r.month WHERE r.minecraft_uuid=? ORDER BY r.month DESC').bind(link.minecraft_uuid).all(); + return json({linked:true,eligibleSince:link.first_linked_at,available:results.filter(r=>!r.delivered_at),history:results.filter(r=>r.delivered_at).map(({personal_code,...row})=>row)}); + } + if(user.role!=='staff')return json({message:'Staff access required.'},403); + if(request.method!=='POST')return json({message:'Method not allowed'},405); + if(request.headers.get('origin')!==origin)return json({message:'Origin rejected'},403); + let data;try{data=await request.json();}catch{return json({message:'Invalid request'},400);} + const now=Date.now(); + if(path==='/api/community/campaigns'){ + const today=new Date(now).toLocaleDateString('sv-SE',{timeZone:'Europe/Brussels'}).slice(0,7); + if(!monthValid(data.month)||data.month10000000||!Number.isSafeInteger(data.rewardAmount)||data.rewardAmount<1||data.rewardAmount>10000)return json({message:'Use a current/future month, target €1–€100,000 and reward 1–10,000 Dunemarks.'},400); + try{await db.batch([ + db.prepare('INSERT INTO community_campaigns(month,target_cents,reward_amount,public_code,created_at) VALUES(?,?,?,?,?)').bind(data.month,data.targetCents,data.rewardAmount,'COMMUNITY-'+code(),now), + db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'campaign-created',JSON.stringify(data),now) + ]);}catch(error){if(error.code==='ER_DUP_ENTRY'||String(error.message).includes('UNIQUE'))return json({message:'That month already has a campaign. Targets and rewards are fixed.'},409);throw error;} + return json({ok:true},201); + } + if(path==='/api/community/verify-total'){ + const today=new Date(now).toLocaleDateString('sv-SE',{timeZone:'Europe/Brussels'}).slice(0,7); + if(!monthValid(data.month)||data.month!==today||!Number.isSafeInteger(data.receivedCents)||data.receivedCents<0||data.receivedCents>10000000||typeof data.reference!=='string'||data.reference.trim().length<5||data.reference.length>150)return json({message:'Record the current month, a verified total and an accounting reference.'},400); + const result=await db.batch([ + db.prepare('UPDATE community_campaigns SET received_cents=?,reached_at=CASE WHEN ?>=target_cents THEN COALESCE(reached_at,?) ELSE reached_at END WHERE month=? AND received_cents<=?').bind(data.receivedCents,data.receivedCents,now,data.month,data.receivedCents), + db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'total-verified',JSON.stringify(data),now) + ]); + const row=await db.prepare('SELECT received_cents FROM community_campaigns WHERE month=?').bind(data.month).first(); + if(!row||Number(row.received_cents)!==data.receivedCents)return json({message:'Campaign missing or total would decrease. Use operator accounting review for corrections.'},409); + return json({ok:true}); + } + return json({message:'Not found'},404); + }; +} diff --git a/website/node/contact.mjs b/website/node/contact.mjs new file mode 100644 index 00000000..d175c619 --- /dev/null +++ b/website/node/contact.mjs @@ -0,0 +1,39 @@ +import {randomBytes} from 'node:crypto'; +import {createChallenge,randomInt,verifySolution} from 'altcha-lib'; +import {deriveKey} from 'altcha-lib/algorithms/pbkdf2'; + +export function createContact(settings={},options={}){ + const secret=randomBytes(32).toString('hex'),keySecret=randomBytes(32).toString('hex'); + const issued=new Map(),now=options.now||Date.now; + const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); + return async request=>{ + const url=new URL(request.url); + for(const [signature,item] of issued)if(item.expires<=now())issued.delete(signature); + if(url.pathname==='/api/contact/challenge'){ + if(request.method!=='GET')return reply({error:'method_not_allowed'},405); + if(issued.size>=256)return reply({error:'Please try again shortly.'},429); + const expires=now()+120000; + const challenge=await createChallenge({algorithm:'PBKDF2/SHA-256',cost:options.cost||1000,counter:options.counter??randomInt(1000,2000),deriveKey,expiresAt:new Date(expires),hmacSignatureSecret:secret,hmacKeySignatureSecret:keySecret,data:{purpose:'operator-contact'}}); + issued.set(challenge.signature,{challenge,expires}); + return reply(challenge); + } + if(url.pathname!=='/api/contact/reveal')return reply({error:'not_found'},404); + if(request.method!=='POST')return reply({error:'method_not_allowed'},405); + if(request.headers.get('Origin')!==url.origin)return reply({error:'origin_required'},403); + if(!request.headers.get('Content-Type')?.startsWith('application/json'))return reply({error:'json_required'},415); + try{ + const text=await request.text();if(text.length>8192)return reply({error:'payload_too_large'},413); + const {payload}=JSON.parse(text);if(typeof payload!=='string'||payload.length>7000)return reply({error:'verification_required'},400); + const decoded=JSON.parse(Buffer.from(payload,'base64').toString('utf8')); + const signature=decoded?.challenge?.signature,item=issued.get(signature); + if(!item||item.expires<=now())return reply({error:'Verification expired. Please try again.'},403); + const solution=decoded.solution; + if(!Number.isSafeInteger(solution?.counter)||solution.counter<0||solution.counter>0xffffffff||!/^[a-f0-9]{64}$/i.test(solution?.derivedKey||''))return reply({error:'verification_failed'},403); + // Consume before awaiting verification: the same proof cannot be replayed concurrently. + issued.delete(signature); + const result=await verifySolution({challenge:item.challenge,solution,deriveKey,hmacSignatureSecret:secret,hmacKeySignatureSecret:keySecret}); + if(!result.verified)return reply({error:'Verification failed. Please try again.'},403); + return reply({email:settings.CONTACT_EMAIL||'unimatrix@dunerealms.com'}); + }catch{return reply({error:'verification_required'},400);} + }; +} diff --git a/website/node/game-link.mjs b/website/node/game-link.mjs new file mode 100644 index 00000000..31ef5a86 --- /dev/null +++ b/website/node/game-link.mjs @@ -0,0 +1,46 @@ +import {randomBytes,createHash,timingSafeEqual} from 'node:crypto'; +import {identity} from './auth.mjs'; +export const digest=value=>createHash('sha256').update(value).digest('hex'); +export const json=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}}); +export function gameAuthorized(request,settings){const secret=settings.GAME_LINK_SECRET||'';return secret.length>=32&&timingSafeEqual(Buffer.from(digest(request.headers.get('authorization')||'')),Buffer.from(digest('Bearer '+secret)));} +export const validUuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value); +export function createGameLink(db,settings,origin){ + const attempts=new Map(); + return async request=>{ + const path=new URL(request.url).pathname; + if(path==='/api/game-link/consume'){ + if(request.method!=='POST')return json({message:'Method not allowed'},405); + if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401); + let body;try{body=await request.json();}catch{return json({message:'Invalid request'},400);} + if(!/^[a-f0-9]{32}$/.test(body.code||'')||!validUuid(body.uuid)||!/^[A-Za-z0-9_.-]{1,32}$/.test(body.name||''))return json({message:'Invalid request'},400); + const now=Date.now(),token=digest(body.code); + try{ + const result=await db.batch([ + db.prepare('INSERT INTO site_game_links(user_id,minecraft_uuid,minecraft_name,linked_at) SELECT user_id,?,?,? FROM site_link_challenges WHERE token_hash=? AND expires_at>?').bind(body.uuid,body.name,now,token,now), + db.prepare('INSERT INTO site_game_identities(minecraft_uuid,first_linked_at,last_name) SELECT minecraft_uuid,linked_at,minecraft_name FROM site_game_links WHERE minecraft_uuid=? ON CONFLICT(minecraft_uuid) DO UPDATE SET last_name=excluded.last_name').bind(body.uuid), + db.prepare('DELETE FROM site_link_challenges WHERE token_hash=?').bind(token) + ]); + return result[0].meta.changes?json({ok:true}):json({message:'Code expired, used or invalid.'},409); + }catch(error){if(error.code==='ER_DUP_ENTRY'||String(error.message).includes('UNIQUE'))return json({message:'This website or game account is already linked. Unlink before linking again.'},409);throw error;} + } + const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401); + if(request.method==='GET'&&path==='/api/game-link'){ + const link=await db.prepare('SELECT l.minecraft_uuid,l.minecraft_name,l.linked_at,i.first_linked_at FROM site_game_links l LEFT JOIN site_game_identities i ON i.minecraft_uuid=l.minecraft_uuid WHERE l.user_id=?').bind(user.id).first(); + return json({linked:!!link?.minecraft_uuid,link:link?.minecraft_uuid?link:null}); + } + if(request.method!=='POST')return json({message:'Method not allowed'},405); + if(request.headers.get('origin')!==origin)return json({message:'Origin rejected'},403); + const now=Date.now();for(const [key,time]of attempts)if(now-time>60000)attempts.delete(key); + if(path==='/api/game-link/unlink'){ + await db.batch([db.prepare('DELETE FROM site_game_links WHERE user_id=?').bind(user.id),db.prepare('DELETE FROM site_link_challenges WHERE user_id=?').bind(user.id)]);return json({ok:true}); + } + if(path!=='/api/game-link')return json({message:'Not found'},404); + if(attempts.size>=5000||now-(attempts.get(user.id)||0)<30000)return json({message:'Wait 30 seconds before trying again.'},429); + if((settings.GAME_LINK_SECRET||'').length<32)return json({message:'Game linking is not configured yet.'},503); + if((await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first())?.minecraft_uuid)return json({message:'Unlink your current game account first.'},409); + attempts.set(user.id,now); + const code=randomBytes(16).toString('hex'); + await db.prepare('INSERT INTO site_link_challenges(user_id,token_hash,expires_at) VALUES(?,?,?) ON CONFLICT(user_id) DO UPDATE SET token_hash=excluded.token_hash,expires_at=excluded.expires_at').bind(user.id,digest(code),now+600000).run(); + return json({code,expiresAt:now+600000,command:'/linkwebsite '+code}); + }; +} diff --git a/website/node/mysql.mjs b/website/node/mysql.mjs index f9cdb17a..ef2ec4a4 100644 --- a/website/node/mysql.mjs +++ b/website/node/mysql.mjs @@ -1,7 +1,7 @@ import mysql from 'mysql2/promise'; import {readFile} from 'node:fs/promises'; export function mysqlSql(sql) { - return sql.replace(/ON CONFLICT\(user_id\) DO UPDATE SET /gi,'ON DUPLICATE KEY UPDATE ') + return sql.replace(/ON CONFLICT\([a-z_, ]+\) DO UPDATE SET /gi,'ON DUPLICATE KEY UPDATE ') .replace(/excluded\.([a-z_]+)/gi,'VALUES($1)'); } export async function openDatabase(env) { diff --git a/website/node/public/login.css b/website/node/public/login.css index eb0ea022..9cb364e9 100644 --- a/website/node/public/login.css +++ b/website/node/public/login.css @@ -1 +1,2 @@ .account{max-width:580px;margin:70px auto;padding:0 24px 70px}.account h1{font-size:clamp(60px,10vw,95px)}.account>p{color:var(--muted)}.account-tabs{display:flex;gap:12px;margin:35px 0 24px}.account-tabs button,#account-logout{background:var(--ink);color:var(--paper);border:1px solid var(--line);padding:12px 20px}.account-tabs button[aria-pressed=true]{color:var(--gold);border-color:var(--gold)}.account label{display:grid;gap:8px;margin-bottom:20px;color:var(--gold);font-size:13px}.account input{width:100%;padding:14px;border:1px solid var(--line);background:var(--ink);color:var(--paper);font:inherit}.account-note{font-size:12px;color:var(--muted)}#account-status{color:var(--gold);min-height:25px}.account .button{cursor:pointer}header>a:last-child{font-size:12px;color:var(--gold)}@media(max-width:600px){.account{margin-top:40px}header>a:last-child{max-width:110px;text-align:right}} +body{background:#132d2c url('/assets/ornament.webp') center/640px;color:#f3e8cc}header{border-bottom:4px solid #a88b49;background:#203a37e8}.account{max-width:820px;margin:45px auto;padding:44px;border:4px ridge #bd9a50;background:linear-gradient(90deg,#132d2cec,#132d2c96),url('/assets/guild.webp') center/cover;box-shadow:8px 8px 0 #081c1d}.account h1{font-family:'VT323',monospace;color:#f5e7bf}.account-tabs button,#account-logout,.account .button{border:3px ridge #c3a359;box-shadow:3px 3px 0 #081c1d}.account-tabs button[aria-pressed=true]{background:#b99443;color:#102c2b}#account-form{background:#f1e5c6;color:#183b36;padding:26px;border:3px ridge #b99443}.account label{color:#183b36;font-weight:700}.account input{background:#fff8e6;border:2px solid #8f784a;color:#183b36}.account #account-note,.account #account-status{color:#35524b}.account>.account-note{color:#e5d8b6}@media(max-width:600px){.account{margin:20px 12px;padding:20px}#account-form{padding:18px}} diff --git a/website/node/public/login.html b/website/node/public/login.html index 3cb9ad84..330b95e4 100644 --- a/website/node/public/login.html +++ b/website/node/public/login.html @@ -1 +1 @@ -Sign in — DuneRealms
✦ PROJECT DUNEMINECRAFT REALMSReturn to the realms →

YOUR PLACE IN THE IMPERIUM

Welcome,
traveller.

Sign in to join discussions, save your player profile and contact staff privately.

+Sign in — dunerealms.com
✦ dunerealms.comDESERT WORLDSReturn to the realms →

YOUR PLACE IN THE CONCORD

Welcome,
traveller.

Sign in to join discussions, save your player profile and contact staff privately.

diff --git a/website/node/schema.sql b/website/node/schema.sql index 01e18bb5..4608b106 100644 --- a/website/node/schema.sql +++ b/website/node/schema.sql @@ -42,3 +42,38 @@ CREATE TABLE IF NOT EXISTS support_messages ( INDEX support_messages_ticket(ticket_id,created_at), INDEX support_messages_author(author_id,created_at), FOREIGN KEY(ticket_id) REFERENCES support_tickets(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS site_game_links ( + user_id CHAR(36) PRIMARY KEY, + minecraft_uuid CHAR(36) UNIQUE DEFAULT NULL, + minecraft_name VARCHAR(32) DEFAULT NULL, + token_hash CHAR(64) UNIQUE DEFAULT NULL, + expires_at BIGINT NOT NULL DEFAULT 0, + linked_at BIGINT DEFAULT NULL, + FOREIGN KEY(user_id) REFERENCES site_accounts(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS site_game_identities ( + minecraft_uuid CHAR(36) PRIMARY KEY, first_linked_at BIGINT NOT NULL, last_name VARCHAR(32) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS site_link_challenges ( + user_id CHAR(36) PRIMARY KEY, token_hash CHAR(64) NOT NULL UNIQUE, expires_at BIGINT NOT NULL, + FOREIGN KEY(user_id) REFERENCES site_accounts(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS community_campaigns ( + month CHAR(7) PRIMARY KEY, target_cents BIGINT NOT NULL, received_cents BIGINT NOT NULL DEFAULT 0, + reward_amount INT NOT NULL, public_code VARCHAR(48) NOT NULL UNIQUE, + reached_at BIGINT DEFAULT NULL, created_at BIGINT NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS community_rewards ( + minecraft_uuid CHAR(36) NOT NULL, month CHAR(7) NOT NULL, personal_code VARCHAR(48) NOT NULL UNIQUE, + issued_at BIGINT NOT NULL, used_at BIGINT DEFAULT NULL, + PRIMARY KEY(minecraft_uuid,month), FOREIGN KEY(month) REFERENCES community_campaigns(month) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS community_claims ( + minecraft_uuid CHAR(36) NOT NULL, month CHAR(7) NOT NULL, receipt CHAR(64) NOT NULL UNIQUE, + amount INT NOT NULL, prepared_at BIGINT NOT NULL, delivered_at BIGINT DEFAULT NULL, + PRIMARY KEY(minecraft_uuid,month), FOREIGN KEY(month) REFERENCES community_campaigns(month) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS account_audit ( + id CHAR(36) PRIMARY KEY, actor_id CHAR(36) NOT NULL, action VARCHAR(40) NOT NULL, + details VARCHAR(500) NOT NULL, created_at BIGINT NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/website/node/server.mjs b/website/node/server.mjs index d6cfc16d..5b54b3a6 100644 --- a/website/node/server.mjs +++ b/website/node/server.mjs @@ -6,14 +6,23 @@ import {openDatabase} from './mysql.mjs'; import {createAuth,identity,safeReturn} from './auth.mjs'; import {createWorldStatus} from './world-status.mjs'; import {createForgejoProxy} from './forgejo-proxy.mjs'; +import {createContact} from './contact.mjs'; +import {createGameLink} from './game-link.mjs'; +import {createCommunityRewards} from './community-rewards.mjs'; const root=new URL('./public/',import.meta.url); -const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin','Content-Security-Policy':"default-src 'self'; img-src 'self' data:; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'self'"}; +const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin','Content-Security-Policy':"default-src 'self'; frame-src https://cp.dunerealms.com; img-src 'self' data:; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'self'"}; export function createApplication(db,settings={}) { const origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin; const auth=createAuth(db,origin); const worldStatus=createWorldStatus(settings); + const contact=createContact(settings); + const gameLink=createGameLink(db,settings,origin); + const rewards=createCommunityRewards(db,settings,origin); return async function handle(request) { const url=new URL(request.url); + if(url.pathname.startsWith('/api/community/'))return rewards(request); + if(url.pathname==='/api/game-link'||url.pathname.startsWith('/api/game-link/'))return gameLink(request); + if(url.pathname.startsWith('/api/contact/'))return contact(request); if(url.pathname==='/api/worlds')return request.method==='GET'?worldStatus():new Response('Method not allowed',{status:405}); if(url.pathname==='/signin-with-chatgpt')return Response.redirect(origin+'/login.html?return_to='+encodeURIComponent(safeReturn(url.searchParams.get('return_to'))),302); if(url.pathname==='/healthz'){await db.prepare('SELECT 1 AS ok').first();return Response.json({status:'ok',database:'connected'},{headers:{'Cache-Control':'no-store'}});} @@ -49,7 +58,7 @@ export async function start(settings=process.env) { let bytes=0;const chunks=[];for await(const chunk of req){bytes+=chunk.length;if(bytes>65536){res.writeHead(413);res.end('Request too large');return;}chunks.push(chunk);} const path=req.url||'/';if(!path.startsWith('/')||path.startsWith('//')){res.writeHead(400);res.end('Bad request');return;} const request=new Request(origin+path,{method:req.method,headers:req.headers,body:['GET','HEAD'].includes(req.method)?undefined:Buffer.concat(chunks)}); - const result=await handle(request);res.writeHead(result.status,{...security,...Object.fromEntries(result.headers)});res.end(Buffer.from(await result.arrayBuffer())); + const result=await handle(request),outgoing=new Headers(security);for(const [key,value]of result.headers)outgoing.set(key,value);outgoing.set('Content-Security-Policy',security['Content-Security-Policy']);res.writeHead(result.status,Object.fromEntries(outgoing));res.end(Buffer.from(await result.arrayBuffer())); }catch(error){console.error('Request failed:',error.code||error.name);if(!res.headersSent)res.writeHead(503,{'Content-Type':'application/json','Cache-Control':'no-store'});res.end(JSON.stringify({message:'The website is temporarily unavailable.'}));} }); server.requestTimeout=300000;server.headersTimeout=10000; diff --git a/website/node/world-status.mjs b/website/node/world-status.mjs index acbe10b2..b8bcab9d 100644 --- a/website/node/world-status.mjs +++ b/website/node/world-status.mjs @@ -1,4 +1,4 @@ -const names=[['spacing-guild','Spacing Guild'],['arrakis','Arrakis'],['caladan','Caladan'],['giedi-prime','Giedi Prime'],['kaitain','Kaitain'],['sigma-draconis-iv','Sigma Draconis IV'],['velocity','Velocity']]; +const names=[['spacing-guild','Vaerkring'],['arrakis','Arrakduin'],['caladan','Kaladam'],['giedi-prime','Giedermark'],['kaitain','Kaiterhof'],['sigma-draconis-iv','Sigmadraken IV'],['velocity','Velocity']]; export function createWorldStatus(settings,fetcher=fetch){ let cached,inflight,expires=0; async function check(){ diff --git a/website/package.json b/website/package.json index 2b7feeb3..7154054a 100644 --- a/website/package.json +++ b/website/package.json @@ -8,6 +8,9 @@ "start": "node --env-file-if-exists=.env node/server.mjs" }, "dependencies": { - "mysql2": "3.24.6" + "altcha": "3.5.0", + "altcha-lib": "2.8.0", + "mysql2": "3.24.6", + "pg": "8.16.3" } } diff --git a/website/pnpm-lock.yaml b/website/pnpm-lock.yaml index cc23d3dc..fc6c981b 100644 --- a/website/pnpm-lock.yaml +++ b/website/pnpm-lock.yaml @@ -8,15 +8,75 @@ importers: .: dependencies: + altcha: + specifier: 3.5.0 + version: 3.5.0 + altcha-lib: + specifier: 2.8.0 + version: 2.8.0 mysql2: specifier: 3.24.6 version: 3.24.6(@types/node@26.6.5) + pg: + specifier: 8.16.3 + version: 8.16.3 packages: '@types/node@26.6.5': resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==} + altcha-lib@2.8.0: + resolution: {integrity: sha512-at1DAqS8u6Z+XbPV2xQd/oATDTxYN83gITqIfsCSz7a2ENqUNIvn9h9xPuAbjeQ3JFqrW8KCjinphhm+bUrRzQ==} + hasBin: true + peerDependencies: + '@fastify/cookie': ^11.0.0 + '@fastify/cors': ^11.0.0 + '@fastify/formbody': ^8.0.0 || ^9.0.0 + '@nestjs/common': ^10.0.0 || ^11.0.0 || ^12.0.0 + '@nestjs/core': ^10.0.0 || ^11.0.0 || ^12.0.0 + '@nestjs/platform-express': ^10.0.0 || ^11.0.0 || ^12.0.0 + '@nestjs/platform-fastify': ^10.0.0 || ^11.0.0 || ^12.0.0 + '@sveltejs/kit': ^2.0.0 || ^3.0.0 + cookie-parser: ^1.0.0 + cors: ^2.0.0 + express: ^4.0.0 || ^5.0.0 + fastify: ^5.0.0 + h3: ^1.15.0 || ^2.0.0 + hono: ^4.0.0 + peerDependenciesMeta: + '@fastify/cookie': + optional: true + '@fastify/cors': + optional: true + '@fastify/formbody': + optional: true + '@nestjs/common': + optional: true + '@nestjs/core': + optional: true + '@nestjs/platform-express': + optional: true + '@nestjs/platform-fastify': + optional: true + '@sveltejs/kit': + optional: true + cookie-parser: + optional: true + cors: + optional: true + express: + optional: true + fastify: + optional: true + h3: + optional: true + hono: + optional: true + + altcha@3.5.0: + resolution: {integrity: sha512-wBXNK1bBeWs/XTOZiyE3JQvRNECgFKYEJqcPxFW7tFd7ErG62yQmMlRasygZrza3zyNTTuon3BfMF/PcBcepcw==} + aws-ssl-profiles@1.1.2: resolution: {integrity: sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==} engines: {node: '>= 6.0.0'} @@ -24,6 +84,9 @@ packages: generate-function@2.3.1: resolution: {integrity: sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==} + hash-wasm@4.12.0: + resolution: {integrity: sha512-+/2B2rYLb48I/evdOIhP+K/DD2ca2fgBjp6O+GBEnCDk2e4rpeXIK8GvIyRPjTezgmWn9gmKwkQjjx6BtqDHVQ==} + iconv-lite@0.7.3: resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==} engines: {node: '>=0.10.0'} @@ -48,9 +111,63 @@ packages: resolution: {integrity: sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==} engines: {node: '>=8.0.0'} + pg-cloudflare@1.4.1: + resolution: {integrity: sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==} + + pg-connection-string@2.14.1: + resolution: {integrity: sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==} + + pg-int8@1.0.1: + resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==} + engines: {node: '>=4.0.0'} + + pg-pool@3.14.0: + resolution: {integrity: sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==} + peerDependencies: + pg: '>=8.0' + + pg-protocol@1.16.1: + resolution: {integrity: sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==} + + pg-types@2.2.0: + resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==} + engines: {node: '>=4'} + + pg@8.16.3: + resolution: {integrity: sha512-enxc1h0jA/aq5oSDMvqyW3q89ra6XIIDZgCX9vkMrnz5DFTw/Ny3Li2lFQ+pt3L6MCgm/5o2o8HW9hiJji+xvw==} + engines: {node: '>= 16.0.0'} + peerDependencies: + pg-native: '>=3.0.1' + peerDependenciesMeta: + pg-native: + optional: true + + pgpass@1.0.5: + resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==} + + postgres-array@2.0.0: + resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==} + engines: {node: '>=4'} + + postgres-bytea@1.0.1: + resolution: {integrity: sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==} + engines: {node: '>=0.10.0'} + + postgres-date@1.0.7: + resolution: {integrity: sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==} + engines: {node: '>=0.10.0'} + + postgres-interval@1.2.0: + resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==} + engines: {node: '>=0.10.0'} + safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + split2@4.2.0: + resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} + engines: {node: '>= 10.x'} + sql-escaper@1.5.2: resolution: {integrity: sha512-6CKD38c31SENivxOADeMNLdukOnUxUcflKtzVWzace7Riv1v7cAEym5Cx9Q7gYZ3ezIJI7ZpqecQq8cqNeSSFg==} engines: {bun: '>=1.0.0', deno: '>=2.0.0', node: '>=12.0.0'} @@ -58,18 +175,30 @@ packages: undici-types@8.9.0: resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + xtend@4.0.2: + resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} + engines: {node: '>=0.4'} + snapshots: '@types/node@26.6.5': dependencies: undici-types: 8.9.0 + altcha-lib@2.8.0: {} + + altcha@3.5.0: + dependencies: + hash-wasm: 4.12.0 + aws-ssl-profiles@1.1.2: {} generate-function@2.3.1: dependencies: is-property: 1.0.2 + hash-wasm@4.12.0: {} + iconv-lite@0.7.3: dependencies: safer-buffer: 2.1.2 @@ -95,8 +224,57 @@ snapshots: dependencies: lru.min: 1.1.5 + pg-cloudflare@1.4.1: + optional: true + + pg-connection-string@2.14.1: {} + + pg-int8@1.0.1: {} + + pg-pool@3.14.0(pg@8.16.3): + dependencies: + pg: 8.16.3 + + pg-protocol@1.16.1: {} + + pg-types@2.2.0: + dependencies: + pg-int8: 1.0.1 + postgres-array: 2.0.0 + postgres-bytea: 1.0.1 + postgres-date: 1.0.7 + postgres-interval: 1.2.0 + + pg@8.16.3: + dependencies: + pg-connection-string: 2.14.1 + pg-pool: 3.14.0(pg@8.16.3) + pg-protocol: 1.16.1 + pg-types: 2.2.0 + pgpass: 1.0.5 + optionalDependencies: + pg-cloudflare: 1.4.1 + + pgpass@1.0.5: + dependencies: + split2: 4.2.0 + + postgres-array@2.0.0: {} + + postgres-bytea@1.0.1: {} + + postgres-date@1.0.7: {} + + postgres-interval@1.2.0: + dependencies: + xtend: 4.0.2 + safer-buffer@2.1.2: {} + split2@4.2.0: {} + sql-escaper@1.5.2: {} undici-types@8.9.0: {} + + xtend@4.0.2: {} diff --git a/website/scripts/build-account.mjs b/website/scripts/build-account.mjs new file mode 100644 index 00000000..3cf6eb46 --- /dev/null +++ b/website/scripts/build-account.mjs @@ -0,0 +1,7 @@ +import {readFileSync,writeFileSync,readdirSync} from 'node:fs'; +const web=new URL('../web/',import.meta.url),home=readFileSync(new URL('index.html',web),'utf8'); +const header=home.match(/
[\s\S]*?<\/header>/)[0].replace(/ aria-current="page"/g,''); +const footer=home.match(/