diff --git a/.forgejo/workflows/kit-delivery.yml b/.forgejo/workflows/kit-delivery.yml new file mode 100644 index 00000000..706b02e2 --- /dev/null +++ b/.forgejo/workflows/kit-delivery.yml @@ -0,0 +1,41 @@ +name: DuneRealms Kit Delivery CI +on: + push: + branches: [main, dev/kit-atelier-v3] + paths: + - 'DuneKits/**' + - 'network/server-control/kit*' + - 'network/server-control/player_kits.py' + - '.forgejo/workflows/kit-delivery.yml' + workflow_dispatch: +jobs: + kits: + runs-on: dune-ci + steps: + - name: Checkout + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Install Java 21 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - name: Install Gradle + uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Verify bridge and build native kit items + run: | + python3 -m unittest discover -s network/server-control -p 'test_kit_equipment.py' -v + gradle --no-daemon -p DuneKits test jar + - name: Upload verified kit plugin + uses: actions/upload-artifact@v3 + with: + name: DuneKits + path: DuneKits/build/libs/DuneKits-3.0.0.jar + if-no-files-found: error diff --git a/DuneKits/.gitignore b/DuneKits/.gitignore new file mode 100644 index 00000000..abc78ba7 --- /dev/null +++ b/DuneKits/.gitignore @@ -0,0 +1,2 @@ +/.gradle/ +/build/ diff --git a/DuneKits/build.gradle.kts b/DuneKits/build.gradle.kts new file mode 100644 index 00000000..54e83293 --- /dev/null +++ b/DuneKits/build.gradle.kts @@ -0,0 +1,14 @@ +plugins { java } +group = "com.example" +version = "3.0.0" +repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/") } +dependencies { + compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + testImplementation("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} +tasks.withType { options.encoding = "UTF-8"; options.release.set(21) } +tasks.processResources { from("../network/server-control/kit-equipment-contract.json") } +tasks.test { useJUnitPlatform() } +tasks.jar { archiveFileName.set("DuneKits-3.0.0.jar") } diff --git a/DuneKits/settings.gradle.kts b/DuneKits/settings.gradle.kts new file mode 100644 index 00000000..f5cc4413 --- /dev/null +++ b/DuneKits/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "DuneKits" diff --git a/DuneKits/src/main/java/com/example/dunekits/DuneKits.java b/DuneKits/src/main/java/com/example/dunekits/DuneKits.java new file mode 100644 index 00000000..43c88fc4 --- /dev/null +++ b/DuneKits/src/main/java/com/example/dunekits/DuneKits.java @@ -0,0 +1,214 @@ +package com.example.dunekits; + +import com.google.gson.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.*; +import java.util.*; +import java.util.function.Consumer; +import java.util.logging.Level; +import org.bukkit.*; +import org.bukkit.command.*; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +/** Receipt delivery commits with DuneCore's authoritative inventory checkpoint. */ +public final class DuneKits extends JavaPlugin implements CommandExecutor, org.bukkit.event.Listener { + private JavaPlugin core; + private Method transaction, factionOf, baseFactory; + private final Set inflight = new HashSet<>(); + private final Map notices = new HashMap<>(); + + @Override public void onEnable() { + Objects.requireNonNull(getCommand("kitclaim")).setExecutor(this); + Objects.requireNonNull(getCommand("dunekit")).setExecutor(this); + Plugin dependency = getServer().getPluginManager().getPlugin("DuneCore"); + if (!(dependency instanceof JavaPlugin candidate) || !dependency.isEnabled()) { + getLogger().info("Verification mode: DuneCore is unavailable; no deliveries will run."); + return; + } + try { + core = candidate; + transaction = core.getClass().getMethod("transactNetworkInventory", Player.class, Consumer.class); + factionOf = core.getClass().getMethod("factionOf", Player.class); + baseFactory = core.getClass().getMethod("createFactionKit", String.class); + } catch (ReflectiveOperationException ex) { + core = null; + getLogger().severe("DuneCore lacks atomic inventory delivery support; claims remain queued."); + return; + } + getServer().getPluginManager().registerEvents(this, this); + getServer().getScheduler().runTaskTimer(this, () -> { + for (Player player : getServer().getOnlinePlayers()) { upgradeFactionIssues(player); request(player); } + }, 100L, 200L); + getServer().getScheduler().runTaskAsynchronously(this, () -> { + try (Connection connection = connect(); PreparedStatement query = connection.prepareStatement(KitDeliverySQL.pending(mysql(connection)))) { + identity(query, 1, new UUID(0, 0), mysql(connection)); + try (ResultSet ignored = query.executeQuery()) { + getLogger().info("Paid kit delivery ready (" + connection.getMetaData().getDatabaseProductName() + " inventory)."); + } + } catch (Exception ex) { getLogger().severe("Paid kit delivery database unavailable; claims will remain queued: " + ex.getClass().getSimpleName()); } + }); + } + + @Override public void onDisable() { inflight.clear(); notices.clear(); } + + private static boolean mysql(Connection connection) throws SQLException { return connection.getMetaData().getDatabaseProductName().equalsIgnoreCase("MySQL"); } + private static void identity(PreparedStatement statement, int index, UUID value, boolean mysql) throws SQLException { + if (mysql) statement.setString(index, value.toString()); else statement.setObject(index, value); + } + + private Connection connect() throws Exception { + String url = core.getConfig().getString("database.jdbc-url", ""); + if (!url.startsWith("jdbc:postgresql://") && !url.startsWith("jdbc:mysql://")) throw new SQLException("Private shared inventory database required"); + Properties settings = new Properties(); + settings.setProperty("user", core.getConfig().getString("database.username", "")); + settings.setProperty("password", core.getConfig().getString("database.password", "")); + settings.setProperty("connectTimeout", "3"); settings.setProperty("socketTimeout", "5"); + settings.setProperty("ApplicationName", "DuneKits"); + // The running DuneCore already contains its matching PostgreSQL driver. + Driver driver = (Driver) Class.forName(url.startsWith("jdbc:mysql://") ? "com.mysql.cj.jdbc.Driver" : "org.postgresql.Driver", true, core.getClass().getClassLoader()) + .getDeclaredConstructor().newInstance(); + Connection connection = driver.connect(url, settings); + if (connection == null) throw new SQLException("Private inventory connection unavailable"); + return connection; + } + + private void request(Player player) { + if (core == null || !core.isEnabled() || !inflight.add(player.getUniqueId())) return; + UUID buyer = player.getUniqueId(); + getServer().getScheduler().runTaskAsynchronously(this, () -> { + List pending = new ArrayList<>(); + try (Connection connection = connect(); PreparedStatement q = connection.prepareStatement( + KitDeliverySQL.pending(mysql(connection)))) { + identity(q, 1, buyer, mysql(connection)); + try (ResultSet rows = q.executeQuery()) { while (rows.next()) pending.add(UUID.fromString(rows.getString(1))); } + } catch (Exception ex) { + // Never log credentials, snapshot contents or private item codes. + getLogger().fine("Pending kit read unavailable: " + ex.getClass().getSimpleName()); + } + if (!isEnabled()) return; + getServer().getScheduler().runTask(this, () -> { + try { + Player current = getServer().getPlayer(buyer); + if (current != null && current.isOnline()) for (UUID id : pending) if (!deliver(current, id)) break; + } finally { inflight.remove(buyer); } + }); + }); + } + + // Older DuneCore versions accept only leather in their existing wing-upgrade command. + // Reuse that exact executor and its price/consent checks, restoring the suit on refusal. + @org.bukkit.event.EventHandler(priority=org.bukkit.event.EventPriority.HIGHEST, ignoreCancelled=true) + public void onWingCommand(org.bukkit.event.player.PlayerCommandPreprocessEvent event) { + String[] words = event.getMessage().trim().split("\\s+"); + if (core == null || words.length != 2 || !words[1].equalsIgnoreCase("elytra") + || !Set.of("/dune", "/dunecore:dune").contains(words[0].toLowerCase(Locale.ROOT))) return; + PluginCommand command = getServer().getPluginCommand("dune"); + Player player = event.getPlayer(); ItemStack current = player.getInventory().getChestplate(); + if (command == null || command.getPlugin() != core || current == null || current.getType() != Material.NETHERITE_CHESTPLATE + || !"stillsuit".equals(current.getItemMeta().getPersistentDataContainer().get(new NamespacedKey("dunerealms", "item"), org.bukkit.persistence.PersistentDataType.STRING))) return; + event.setCancelled(true); + ItemStack original = current.clone(), compatible = current.clone(); compatible.setType(Material.LEATHER_CHESTPLATE); + player.getInventory().setChestplate(compatible); + try { command.execute(player, "dune", new String[]{"elytra"}); } + finally { ItemStack after = player.getInventory().getChestplate(); if (after != null && after.isSimilar(compatible)) player.getInventory().setChestplate(original); } + } + + private void upgradeFactionIssues(Player player) { + if (Arrays.stream(player.getInventory().getContents()).noneMatch(FactionSuitUpgrade::candidate)) return; + try { + String faction = (String) factionOf.invoke(core, player); + transaction.invoke(core, player, (Consumer) connection -> { + ItemStack[] inventory = player.getInventory().getContents(); + for (int i = 0; i < inventory.length; i++) if (FactionSuitUpgrade.candidate(inventory[i])) + player.getInventory().setItem(i, FactionSuitUpgrade.upgrade(inventory[i], faction)); + }); + } catch (Exception ex) { getLogger().fine("Faction suit conversion retained for retry: " + ex.getClass().getSimpleName()); } + } + + private boolean deliver(Player player, UUID id) { + final boolean[] delivered = {false}; + try { + Consumer operation = connection -> { + try (PreparedStatement q = connection.prepareStatement( + KitDeliverySQL.lock(mysql(connection)))) { + identity(q, 1, id, mysql(connection)); identity(q, 2, player.getUniqueId(), mysql(connection)); + String raw, hash; + try (ResultSet rows = q.executeQuery()) { + if (!rows.next()) return; + raw = rows.getString(1); hash = rows.getString(2); + } + if (raw == null || raw.getBytes(StandardCharsets.UTF_8).length > 65536 || !digest(raw).equals(hash)) throw KitSpec.invalid(); + JsonObject snapshot = JsonParser.parseString(raw).getAsJsonObject(); + Map base = factionBase(player); + List items = KitItemFactory.create(snapshot, base); + if (!player.getInventory().addItem(items.toArray(ItemStack[]::new)).isEmpty()) + throw new NoRoom(); + try (PreparedStatement update = connection.prepareStatement( + KitDeliverySQL.acknowledge(mysql(connection)))) { + identity(update, 1, id, mysql(connection)); identity(update, 2, player.getUniqueId(), mysql(connection)); + if (update.executeUpdate() != 1) throw new SQLException("Delivery changed"); + } + delivered[0] = true; + } catch (Exception ex) { throw new DeliveryFailure(ex); } + }; + transaction.invoke(core, player, operation); + if (delivered[0]) player.sendMessage(ChatColor.GOLD + "Your redeemed DuneRealms kit has arrived."); + return true; + } catch (Exception ex) { + Throwable cause = ex instanceof InvocationTargetException invocation ? invocation.getCause() : ex; + while (cause.getCause() != null && cause instanceof DeliveryFailure) cause = cause.getCause(); + long now = System.currentTimeMillis(); + if (now - notices.getOrDefault(player.getUniqueId(), 0L) > 60000) { + player.sendMessage(ChatColor.YELLOW + (cause instanceof NoRoom + ? "Make room for the complete kit. Your claim is still queued." + : "Kit delivery is pending. Your claim has been retained.")); + notices.put(player.getUniqueId(), now); + } + getLogger().log(Level.FINE, "Kit delivery retained: " + cause.getClass().getSimpleName()); + return false; + } + } + + private Map factionBase(Player player) throws ReflectiveOperationException { + String faction = (String) factionOf.invoke(core, player); + if (faction == null || faction.isBlank()) throw KitSpec.invalid(); + Object result = baseFactory.invoke(core, faction); + if (!(result instanceof List items)) throw KitSpec.invalid(); + Map base = new HashMap<>(); + for (Object value : items) if (value instanceof ItemStack item) + for (String slot : KitSpec.SLOTS) if (item.getType().name().endsWith("_" + slot.toUpperCase(Locale.ROOT))) base.put(slot, item); + if (base.size() != 4) throw KitSpec.invalid(); + return base; + } + + static String digest(String raw) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(raw.getBytes(StandardCharsets.UTF_8))); + } + + @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (command.getName().equals("kitclaim")) { + if (!(sender instanceof Player player)) { sender.sendMessage("Use this command in Minecraft."); return true; } + if (core == null) player.sendMessage("Kit delivery is unavailable. Your claim is retained."); + else { request(player); player.sendMessage("Checking your redeemed kits. Keep room for the complete set."); } + return true; + } + if (!sender.hasPermission("dunekits.verify")) return true; + if (args.length != 1 || !args[0].equals("verify")) return false; + try { + int checked = KitVerification.verify(); + sender.sendMessage("DUNEKITS_VERIFY_OK: " + checked + " item metadata checks; no items issued."); + } catch (Exception ex) { + sender.sendMessage("DUNEKITS_VERIFY_FAILED: " + ex.getClass().getSimpleName()); + getLogger().log(Level.WARNING, "Kit metadata verification failed", ex); + } + return true; + } + + private static final class NoRoom extends RuntimeException {} + private static final class DeliveryFailure extends RuntimeException { DeliveryFailure(Throwable cause) { super(cause); } } +} diff --git a/DuneKits/src/main/java/com/example/dunekits/FactionSuitUpgrade.java b/DuneKits/src/main/java/com/example/dunekits/FactionSuitUpgrade.java new file mode 100644 index 00000000..52348dfa --- /dev/null +++ b/DuneKits/src/main/java/com/example/dunekits/FactionSuitUpgrade.java @@ -0,0 +1,52 @@ +package com.example.dunekits; + +import java.util.*; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.*; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ArmorMeta; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.trim.*; +import org.bukkit.persistence.PersistentDataType; + +/** Upgrade only native faction issues, never a purchased historical contract. */ +final class FactionSuitUpgrade { + static final NamespacedKey CONTRACT = new NamespacedKey("dunekits", "contract_version"); + private static final NamespacedKey ITEM = new NamespacedKey("dunerealms", "item"); + private static final NamespacedKey FACTION = new NamespacedKey("dunerealms", "armor_faction"); + + static boolean candidate(ItemStack item) { + if (item == null || !item.getType().name().startsWith("LEATHER_") || !KitSpec.SLOTS.contains(item.getType().name().substring(8).toLowerCase(Locale.ROOT))) return false; + ItemMeta meta = item.getItemMeta(); + return meta instanceof ArmorMeta && "stillsuit".equals(meta.getPersistentDataContainer().get(ITEM, PersistentDataType.STRING)) + && !meta.getPersistentDataContainer().has(CONTRACT, PersistentDataType.INTEGER); + } + + static ItemStack upgrade(ItemStack original, String fallbackFaction) { + if (!candidate(original)) return original; + ItemStack item = original.clone(); + item.setType(Material.valueOf("NETHERITE_" + original.getType().name().substring(8))); + ArmorMeta meta = (ArmorMeta) item.getItemMeta(); + String faction = meta.getPersistentDataContainer().get(FACTION, PersistentDataType.STRING); + faction = (faction == null ? Objects.requireNonNullElse(fallbackFaction, "fremen") : faction).toLowerCase(Locale.ROOT); + TrimPattern pattern; TrimMaterial material; String story; NamedTextColor color; + switch (faction) { + case "harkonnen" -> { pattern = TrimPattern.RIB; material = TrimMaterial.REDSTONE; story = "Strength leaves its mark."; color = NamedTextColor.RED; } + case "atreides" -> { pattern = TrimPattern.COAST; material = TrimMaterial.EMERALD; story = "Honor above ambition."; color = NamedTextColor.GREEN; } + case "corrino" -> { pattern = TrimPattern.SPIRE; material = TrimMaterial.GOLD; story = "By imperial decree. The Golden Lion endures."; color = NamedTextColor.GOLD; } + case "ordos" -> { pattern = TrimPattern.SENTRY; material = TrimMaterial.AMETHYST; story = "Every secret has its price."; color = NamedTextColor.LIGHT_PURPLE; } + case "guild", "spacing_guild" -> { pattern = TrimPattern.EYE; material = TrimMaterial.QUARTZ; story = "The spice must flow."; color = NamedTextColor.AQUA; } + default -> { pattern = TrimPattern.DUNE; material = TrimMaterial.LAPIS; story = "Your water belongs to the tribe."; color = NamedTextColor.BLUE; } + } + if (!meta.hasTrim()) meta.setTrim(new ArmorTrim(material, pattern)); + if (!meta.hasLore()) meta.lore(List.of( + Component.text(story, color).decoration(TextDecoration.ITALIC, false), + Component.empty().decoration(TextDecoration.ITALIC, false), + Component.text("Faction issue · Netherite stillsuit", NamedTextColor.GRAY).decoration(TextDecoration.ITALIC, false))); + meta.getPersistentDataContainer().set(CONTRACT, PersistentDataType.INTEGER, 3); + item.setItemMeta(meta); + return item; + } +} diff --git a/DuneKits/src/main/java/com/example/dunekits/KitDeliverySQL.java b/DuneKits/src/main/java/com/example/dunekits/KitDeliverySQL.java new file mode 100644 index 00000000..81d46720 --- /dev/null +++ b/DuneKits/src/main/java/com/example/dunekits/KitDeliverySQL.java @@ -0,0 +1,18 @@ +package com.example.dunekits; + +/** MySQL receipts commit directly with the active network inventory checkpoint. */ +final class KitDeliverySQL { + static final String PAID = "delivered_at IS NULL AND redeem_requested_at IS NOT NULL AND redeem_requested_at>0 AND quantity=1 AND gross_cents>0 AND completed_at>0"; + static String pending(boolean mysql) { + return mysql ? "SELECT id FROM dune_kit_sales WHERE buyer_uuid=? AND " + PAID + " ORDER BY redeem_requested_at,id LIMIT 5" + : "SELECT id FROM dune_kit_deliveries WHERE buyer_uuid=? AND delivered_at IS NULL ORDER BY created_at,id LIMIT 5"; + } + static String lock(boolean mysql) { + return mysql ? "SELECT snapshot_json,SHA2(snapshot_json,256) FROM dune_kit_sales WHERE id=? AND buyer_uuid=? AND " + PAID + " FOR UPDATE" + : "SELECT snapshot_json,snapshot_hash FROM dune_kit_deliveries WHERE id=? AND buyer_uuid=? AND delivered_at IS NULL FOR UPDATE"; + } + static String acknowledge(boolean mysql) { + return mysql ? "UPDATE dune_kit_sales SET delivered_at=CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS UNSIGNED) WHERE id=? AND buyer_uuid=? AND " + PAID + : "UPDATE dune_kit_deliveries SET delivered_at=(EXTRACT(EPOCH FROM clock_timestamp())*1000)::bigint WHERE id=? AND buyer_uuid=? AND delivered_at IS NULL"; + } +} diff --git a/DuneKits/src/main/java/com/example/dunekits/KitItemFactory.java b/DuneKits/src/main/java/com/example/dunekits/KitItemFactory.java new file mode 100644 index 00000000..242efd1d --- /dev/null +++ b/DuneKits/src/main/java/com/example/dunekits/KitItemFactory.java @@ -0,0 +1,105 @@ +package com.example.dunekits; + +import com.google.gson.JsonObject; +import java.util.*; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.*; +import org.bukkit.block.banner.Pattern; +import org.bukkit.block.banner.PatternType; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.*; +import org.bukkit.inventory.meta.trim.ArmorTrim; +import org.bukkit.inventory.meta.trim.TrimMaterial; +import org.bukkit.inventory.meta.trim.TrimPattern; + +final class KitItemFactory { + private KitItemFactory() {} + + /** Base items come from DuneCore's buyer-faction factory, preserving its tags and attributes. */ + static List create(JsonObject snapshot, Map base) { + KitSpec kit = new KitSpec(snapshot); + List items = new ArrayList<>(); + for (String slot : KitSpec.SLOTS) { + KitSpec.Piece piece = kit.armor.get(slot); + Material material = Material.valueOf((kit.modern ? "NETHERITE_" : "LEATHER_") + slot.toUpperCase(Locale.ROOT)); + ItemStack item = base.containsKey(slot) ? base.get(slot).clone() : new ItemStack(material); + item.setType(material); + item.setAmount(1); + ItemMeta meta = item.getItemMeta(); + if (!(meta instanceof ArmorMeta armor)) throw KitSpec.invalid(); + if (kit.modern) { + TrimPattern pattern = Registry.TRIM_PATTERN.get(NamespacedKey.minecraft(piece.trim().pattern())); + TrimMaterial trimMaterial = Registry.TRIM_MATERIAL.get(NamespacedKey.minecraft(piece.trim().material())); + if (pattern == null || trimMaterial == null) throw KitSpec.invalid(); + armor.setTrim(new ArmorTrim(trimMaterial, pattern)); + } else if (meta instanceof LeatherArmorMeta leather) { + leather.setColor(Color.fromRGB(Integer.parseInt(kit.legacyColor.substring(1), 16))); + } + meta.getPersistentDataContainer().set(FactionSuitUpgrade.CONTRACT, org.bukkit.persistence.PersistentDataType.INTEGER, kit.modern ? 3 : 1); + meta.displayName(name(piece.name().isBlank() ? kit.name + " " + title(slot) : piece.name())); + meta.lore(piece.lore().stream().map(KitSpec.Lore::component).toList()); + if (!kit.kind.equals("faction_sale")) { + // Rarity remains authoritative. Designers cannot supply enchantment or attribute data. + for (Enchantment enchantment : Set.copyOf(meta.getEnchants().keySet())) meta.removeEnchant(enchantment); + enchantments(meta, slot, kit.quality); + } + for (KitSpec.Bonus bonus : kit.bonuses) if (bonus.piece().equals(slot)) { + Enchantment enchantment = Registry.ENCHANTMENT.get(NamespacedKey.minecraft(bonus.enchantment())); + if (enchantment == null) throw KitSpec.invalid(); + meta.addEnchant(enchantment, meta.getEnchantLevel(enchantment) + bonus.levels(), true); + } + item.setItemMeta(meta); + items.add(item); + } + if (kit.banner.enabled()) { + ItemStack item = new ItemStack(Material.valueOf(kit.banner.base().toUpperCase(Locale.ROOT) + "_BANNER")); + BannerMeta meta = (BannerMeta) item.getItemMeta(); + List layers = new ArrayList<>(); + for (KitSpec.Layer layer : kit.banner.patterns()) { + PatternType pattern = Registry.BANNER_PATTERN.get(NamespacedKey.minecraft(layer.pattern())); + if (pattern == null) throw KitSpec.invalid(); + layers.add(new Pattern(DyeColor.valueOf(layer.color().toUpperCase(Locale.ROOT)), pattern)); + } + meta.setPatterns(layers); + meta.displayName(name(kit.banner.name().isBlank() ? kit.name + " Standard" : kit.banner.name())); + meta.lore(kit.banner.lore().stream().map(KitSpec.Lore::component).toList()); + item.setItemMeta(meta); + items.add(item); + } + return List.copyOf(items); + } + + private static Component name(String text) { + return Component.text(text, NamedTextColor.GOLD).decoration(TextDecoration.ITALIC, false); + } + + private static String title(String text) { + return Character.toUpperCase(text.charAt(0)) + text.substring(1); + } + + private static void enchantments(ItemMeta meta, String slot, String quality) { + int tier = List.of("common", "uncommon", "rare", "very_rare", "legendary").indexOf(quality); + if (tier == 0) return; + add(meta, Enchantment.PROTECTION, tier); + add(meta, Enchantment.UNBREAKING, Math.min(tier, 3)); + if (tier >= 3) add(meta, Enchantment.MENDING, 1); + if (tier == 4) add(meta, Enchantment.THORNS, 3); + if (slot.equals("helmet") && tier >= 2) { + add(meta, Enchantment.RESPIRATION, tier - 1); + add(meta, Enchantment.AQUA_AFFINITY, 1); + } + if (slot.equals("leggings") && tier >= 3) add(meta, Enchantment.SWIFT_SNEAK, tier - 1); + if (slot.equals("boots")) { + add(meta, Enchantment.FEATHER_FALLING, tier); + if (tier >= 2) add(meta, Enchantment.DEPTH_STRIDER, tier - 1); + if (tier == 4) add(meta, Enchantment.SOUL_SPEED, 3); + } + } + + private static void add(ItemMeta meta, Enchantment enchantment, int level) { + meta.addEnchant(enchantment, level, true); + } +} diff --git a/DuneKits/src/main/java/com/example/dunekits/KitSpec.java b/DuneKits/src/main/java/com/example/dunekits/KitSpec.java new file mode 100644 index 00000000..fab3faa0 --- /dev/null +++ b/DuneKits/src/main/java/com/example/dunekits/KitSpec.java @@ -0,0 +1,149 @@ +package com.example.dunekits; + +import com.google.gson.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.TextColor; +import net.kyori.adventure.text.format.TextDecoration; + +/** Literal metadata only. No command, MiniMessage or arbitrary component parser. */ +final class KitSpec { + static final List SLOTS = List.of("helmet", "chestplate", "leggings", "boots"); + static final Set QUALITIES = Set.of("common", "uncommon", "rare", "very_rare", "legendary"); + static final Set KINDS = Set.of("personal_sale", "official_sale", "faction_sale", "server_sale"); + private static final JsonObject CONTRACT; + static { + try (InputStream input = KitSpec.class.getResourceAsStream("/kit-equipment-contract.json")) { + if (input == null) throw new IOException("Missing kit contract"); + CONTRACT = JsonParser.parseReader(new InputStreamReader(input, StandardCharsets.UTF_8)).getAsJsonObject(); + } catch (IOException ex) { throw new ExceptionInInitializerError(ex); } + } + record Lore(String text, String color, boolean bold, boolean italic) { + Component component() { + return Component.text(text, Objects.requireNonNull(TextColor.fromHexString(color))) + .decoration(TextDecoration.BOLD, bold).decoration(TextDecoration.ITALIC, italic); + } + } + record Trim(String pattern, String material) {} + record Piece(String name, List lore, Trim trim) {} + record Layer(String pattern, String color) {} + record Bonus(String piece, String enchantment, int levels) {} + record Banner(boolean enabled, String name, String base, List patterns, List lore) {} + final String name, quality, kind, legacyColor; + final boolean modern; + final Map armor; + final Banner banner; + final List bonuses; + + KitSpec(JsonObject snapshot) { + name = text(snapshot.get("name"), 64); + if (name.isBlank()) throw invalid(); + quality = text(snapshot.get("quality"), 16); + kind = snapshot.has("commerceKind") ? text(snapshot.get("commerceKind"), 16) : "personal_sale"; + if (!QUALITIES.contains(quality) || !KINDS.contains(kind)) throw invalid(); + modern = snapshot.has("equipment"); + legacyColor = snapshot.has("color") ? text(snapshot.get("color"), 7) : "#385B49"; + if (!legacyColor.matches("#[A-Fa-f0-9]{6}")) throw invalid(); + Map pieces = new LinkedHashMap<>(); + if (modern) { + JsonObject equipment = object(snapshot.get("equipment"), "version", "armor", "banner"); + if (integer(equipment.get("version")) != 3) throw invalid(); + JsonObject items = object(equipment.get("armor"), SLOTS.toArray(String[]::new)); + for (String slot : SLOTS) { + JsonObject item = object(items.get(slot), "material", "name", "lore", "trim"); + if (!text(item.get("material"), 16).equals("netherite")) throw invalid(); + JsonObject trim = object(item.get("trim"), "pattern", "material"); + pieces.put(slot, new Piece(text(item.get("name"), 64), lore(item.get("lore")), + new Trim(choice(trim.get("pattern"), "trimPatterns"), choice(trim.get("material"), "trimMaterials")))); + } + JsonObject standard = object(equipment.get("banner"), "enabled", "name", "base", "patterns", "lore"); + List layers = new ArrayList<>(); + for (JsonElement value : array(standard.get("patterns"), 6)) { + JsonObject layer = object(value, "pattern", "color"); + layers.add(new Layer(choice(layer.get("pattern"), "bannerPatterns"), choice(layer.get("color"), "bannerColors"))); + } + banner = new Banner(bool(standard.get("enabled")), text(standard.get("name"), 64), + choice(standard.get("base"), "bannerColors"), List.copyOf(layers), lore(standard.get("lore"))); + } else { + // Paid historical snapshots keep their original leather material and plain lore. + List lines = new ArrayList<>(); + if (snapshot.has("lore")) for (JsonElement line : array(snapshot.get("lore"), 6)) + lines.add(new Lore(text(line, 120), "#AAAAAA", false, false)); + JsonObject names = snapshot.has("itemNames") && snapshot.get("itemNames").isJsonObject() + ? snapshot.getAsJsonObject("itemNames") : new JsonObject(); + for (String slot : SLOTS) pieces.put(slot, new Piece(names.has(slot) ? text(names.get(slot), 64) : "", List.copyOf(lines), null)); + banner = new Banner(false, "", "black", List.of(), List.of()); + } + armor = Collections.unmodifiableMap(pieces); + List upgrade = new ArrayList<>(); + if (snapshot.has("upgrade")) { + if (!quality.equals("legendary") || !kind.equals("personal_sale")) throw invalid(); + JsonObject value = object(snapshot.get("upgrade"), "policy", "points", "bonuses"); + if (!text(value.get("policy"), 40).equals("legendary-player-v1")) throw invalid(); + int points = integer(value.get("points")), total = 0; + Set selected = new HashSet<>(); + for (JsonElement entry : array(value.get("bonuses"), 3)) { + JsonObject bonus = object(entry, "piece", "enchantment", "levels"); + String slot = text(bonus.get("piece"), 16), enchantment = text(bonus.get("enchantment"), 32); + Set allowed = new HashSet<>(Set.of("protection", "unbreaking", "mending", "thorns")); + if (slot.equals("helmet")) allowed.addAll(Set.of("respiration", "aqua_affinity")); + if (slot.equals("leggings")) allowed.add("swift_sneak"); + if (slot.equals("boots")) allowed.addAll(Set.of("feather_falling", "depth_strider", "soul_speed")); + int levels = integer(bonus.get("levels")); + if (!SLOTS.contains(slot) || !allowed.contains(enchantment) || levels < 1 || levels > 3 || !selected.add(slot + ":" + enchantment)) throw invalid(); + total += levels; upgrade.add(new Bonus(slot, enchantment, levels)); + } + if (points < 1 || points > 3 || total != points || upgrade.isEmpty()) throw invalid(); + } + bonuses = List.copyOf(upgrade); + } + static JsonObject object(JsonElement value, String... keys) { + if (value == null || !value.isJsonObject()) throw invalid(); + JsonObject object = value.getAsJsonObject(); + if (!object.keySet().equals(Set.of(keys))) throw invalid(); + return object; + } + static String text(JsonElement value, int max) { + if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) throw invalid(); + String text = value.getAsString(); + if (text.length() > max) throw invalid(); + for (int i = 0; i < text.length(); i++) { + char ch = text.charAt(i); + if (ch < 32 || ch == 127 || ch == '<' || ch == '>' || ch == '§') throw invalid(); + if (Character.isHighSurrogate(ch)) { + if (++i >= text.length() || !Character.isLowSurrogate(text.charAt(i))) throw invalid(); + } else if (Character.isLowSurrogate(ch)) throw invalid(); + } + return text; + } + static int integer(JsonElement value) { + if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isNumber()) throw invalid(); + try { return value.getAsBigDecimal().intValueExact(); } catch (ArithmeticException ex) { throw invalid(); } + } + static boolean bool(JsonElement value) { + if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isBoolean()) throw invalid(); + return value.getAsBoolean(); + } + static JsonArray array(JsonElement value, int max) { + if (value == null || !value.isJsonArray() || value.getAsJsonArray().size() > max) throw invalid(); + return value.getAsJsonArray(); + } + static String choice(JsonElement value, String set) { + String result = text(value, 40); + if (!CONTRACT.getAsJsonArray(set).contains(new JsonPrimitive(result))) throw invalid(); + return result; + } + static List lore(JsonElement value) { + List result = new ArrayList<>(); + for (JsonElement entry : array(value, 6)) { + JsonObject line = object(entry, "text", "color", "bold", "italic"); + String color = text(line.get("color"), 7); + if (!color.matches("#[A-Fa-f0-9]{6}")) throw invalid(); + result.add(new Lore(text(line.get("text"), 120), color.toUpperCase(Locale.ROOT), bool(line.get("bold")), bool(line.get("italic")))); + } + return List.copyOf(result); + } + static IllegalArgumentException invalid() { return new IllegalArgumentException("Invalid bounded kit item metadata"); } +} diff --git a/DuneKits/src/main/java/com/example/dunekits/KitVerification.java b/DuneKits/src/main/java/com/example/dunekits/KitVerification.java new file mode 100644 index 00000000..7c471a5b --- /dev/null +++ b/DuneKits/src/main/java/com/example/dunekits/KitVerification.java @@ -0,0 +1,98 @@ +package com.example.dunekits; + +import com.google.gson.*; +import java.io.*; +import java.util.*; +import net.kyori.adventure.text.format.TextDecoration; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import org.bukkit.*; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.*; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; + +/** Runs on a real Paper server, without adding anything to a player inventory. */ +final class KitVerification { + static JsonObject example(String quality, String pattern, String material) { + JsonObject snapshot = new JsonObject(); + snapshot.addProperty("name", "Imperial Sentinel"); snapshot.addProperty("quality", quality); + snapshot.addProperty("commerceKind", "personal_sale"); snapshot.addProperty("color", "#BCA05B"); + JsonObject equipment = new JsonObject(), armor = new JsonObject(); equipment.addProperty("version", 3); + for (String slot : KitSpec.SLOTS) { + JsonObject piece = new JsonObject(), trim = new JsonObject(); + piece.addProperty("material", "netherite"); piece.addProperty("name", "Sentinel " + slot); + JsonArray lore = new JsonArray(); + for (String text : List.of("By imperial decree.", "", "Duty endures beyond the dunes.")) { + JsonObject line = new JsonObject(); line.addProperty("text", text); line.addProperty("color", "#BCA05B"); + line.addProperty("bold", false); line.addProperty("italic", false); lore.add(line); + } + piece.add("lore", lore); trim.addProperty("pattern", pattern); trim.addProperty("material", material); + piece.add("trim", trim); armor.add(slot, piece); + } + JsonObject banner = new JsonObject(); banner.addProperty("enabled", true); + banner.addProperty("name", "Imperial Standard"); banner.addProperty("base", "purple"); + JsonArray layers = new JsonArray(); + for (String[] values : List.of(new String[]{"border", "yellow"}, new String[]{"rhombus", "red"})) { + JsonObject layer = new JsonObject(); layer.addProperty("pattern", values[0]); layer.addProperty("color", values[1]); layers.add(layer); + } + banner.add("patterns", layers); banner.add("lore", new JsonArray()); + equipment.add("armor", armor); equipment.add("banner", banner); snapshot.add("equipment", equipment); + return snapshot; + } + + static int verify() throws Exception { + int checked = 0; + for (String quality : KitSpec.QUALITIES) { + List items = KitItemFactory.create(example(quality, "dune", "gold"), Map.of()); + if (items.size() != 5) throw new IllegalStateException("Missing armour or banner"); + for (int i = 0; i < 4; i++) { + ItemStack item = items.get(i); ItemMeta meta = item.getItemMeta(); + if (!item.getType().name().startsWith("NETHERITE_") || !(meta instanceof ArmorMeta armor) || !armor.hasTrim()) throw new IllegalStateException("Missing netherite trim"); + if (meta.lore() == null || meta.lore().size() != 3 || !PlainTextComponentSerializer.plainText().serialize(meta.lore().get(1)).isEmpty() + || meta.lore().get(0).decoration(TextDecoration.ITALIC) != TextDecoration.State.FALSE) throw new IllegalStateException("Lore formatting lost"); + if (!item.isSimilar(roundTrip(item))) throw new IllegalStateException("Inventory serialization lost armour metadata"); + checked++; + } + BannerMeta banner = (BannerMeta) items.get(4).getItemMeta(); + if (banner.numberOfPatterns() != 2 || banner.getPattern(0).getColor() != DyeColor.YELLOW || banner.getPattern(1).getColor() != DyeColor.RED) + throw new IllegalStateException("Banner layer order lost"); + if (!items.get(4).isSimilar(roundTrip(items.get(4)))) throw new IllegalStateException("Inventory serialization lost banner metadata"); + checked++; + } + try (InputStream input = KitVerification.class.getResourceAsStream("/kit-equipment-contract.json")) { + JsonObject contract = JsonParser.parseReader(new InputStreamReader(Objects.requireNonNull(input), java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject(); + for (JsonElement pattern : contract.getAsJsonArray("trimPatterns")) for (JsonElement material : contract.getAsJsonArray("trimMaterials")) { + KitItemFactory.create(example("common", pattern.getAsString(), material.getAsString()), Map.of()); checked++; + } + for (JsonElement pattern : contract.getAsJsonArray("bannerPatterns")) { + JsonObject snapshot = example("common", "dune", "gold"); + snapshot.getAsJsonObject("equipment").getAsJsonObject("banner").getAsJsonArray("patterns").get(0).getAsJsonObject().addProperty("pattern", pattern.getAsString()); + KitItemFactory.create(snapshot, Map.of()); checked++; + } + } + JsonObject upgraded = example("legendary", "silence", "gold"); + upgraded.add("upgrade", JsonParser.parseString("{\"policy\":\"legendary-player-v1\",\"points\":3,\"bonuses\":[{\"piece\":\"helmet\",\"enchantment\":\"protection\",\"levels\":2},{\"piece\":\"boots\",\"enchantment\":\"soul_speed\",\"levels\":1}]}")); + List upgradedItems = KitItemFactory.create(upgraded, Map.of()); + if (upgradedItems.get(0).getEnchantmentLevel(org.bukkit.enchantments.Enchantment.PROTECTION) != 6 || upgradedItems.get(3).getEnchantmentLevel(org.bukkit.enchantments.Enchantment.SOUL_SPEED) != 4) + throw new IllegalStateException("Saved Legendary upgrade was not applied exactly"); + checked++; + ItemStack nativeSuit = new ItemStack(Material.LEATHER_CHESTPLATE); + ItemMeta nativeMeta = nativeSuit.getItemMeta(); + nativeMeta.getPersistentDataContainer().set(new NamespacedKey("dunerealms", "item"), org.bukkit.persistence.PersistentDataType.STRING, "stillsuit"); + nativeMeta.addEnchant(org.bukkit.enchantments.Enchantment.MENDING, 1, true); nativeSuit.setItemMeta(nativeMeta); + ItemStack converted = FactionSuitUpgrade.upgrade(nativeSuit, "corrino"); + if (converted.getType() != Material.NETHERITE_CHESTPLATE || converted.getEnchantmentLevel(org.bukkit.enchantments.Enchantment.MENDING) != 1 || nativeSuit.getType() != Material.LEATHER_CHESTPLATE) + throw new IllegalStateException("Faction conversion changed source or enchantments"); + if (!converted.isSimilar(roundTrip(converted))) throw new IllegalStateException("Faction conversion metadata was not durable"); + nativeMeta.getPersistentDataContainer().set(FactionSuitUpgrade.CONTRACT, org.bukkit.persistence.PersistentDataType.INTEGER, 1); nativeSuit.setItemMeta(nativeMeta); + if (FactionSuitUpgrade.candidate(nativeSuit)) throw new IllegalStateException("Historical purchased armour must remain unchanged"); + checked += 3; + return checked; + } + + private static ItemStack roundTrip(ItemStack item) throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (BukkitObjectOutputStream output = new BukkitObjectOutputStream(bytes)) { output.writeObject(item); } + try (BukkitObjectInputStream input = new BukkitObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { return (ItemStack) input.readObject(); } + } +} diff --git a/DuneKits/src/main/resources/plugin.yml b/DuneKits/src/main/resources/plugin.yml new file mode 100644 index 00000000..bbf25a50 --- /dev/null +++ b/DuneKits/src/main/resources/plugin.yml @@ -0,0 +1,17 @@ +name: DuneKits +version: 3.0.0 +main: com.example.dunekits.DuneKits +api-version: '1.21.4' +softdepend: [DuneCore] +description: Versioned kit item metadata and receipt-bound delivery +commands: + kitclaim: + description: Check for redeemed kits awaiting delivery + usage: /kitclaim + dunekit: + description: Verify the kit item format without issuing items + usage: /dunekit verify + permission: dunekits.verify +permissions: + dunekits.verify: + default: op diff --git a/DuneKits/src/test/java/com/example/dunekits/KitDeliverySQLTest.java b/DuneKits/src/test/java/com/example/dunekits/KitDeliverySQLTest.java new file mode 100644 index 00000000..7c844fbf --- /dev/null +++ b/DuneKits/src/test/java/com/example/dunekits/KitDeliverySQLTest.java @@ -0,0 +1,22 @@ +package com.example.dunekits; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class KitDeliverySQLTest { + @Test void mysqlRequiresPaidRequestedBuyerBoundReceiptsThroughoutTheTransaction() { + for (String sql : new String[]{KitDeliverySQL.pending(true), KitDeliverySQL.lock(true), KitDeliverySQL.acknowledge(true)}) { + assertTrue(sql.contains("dune_kit_sales"));assertTrue(sql.contains("buyer_uuid=?")); + assertTrue(sql.contains("quantity=1"));assertTrue(sql.contains("gross_cents>0")); + assertTrue(sql.contains("completed_at>0"));assertTrue(sql.contains("redeem_requested_at>0")); + assertTrue(sql.contains("delivered_at IS NULL")); + } + assertTrue(KitDeliverySQL.lock(true).endsWith("FOR UPDATE")); + assertTrue(KitDeliverySQL.lock(true).contains("SHA2(snapshot_json,256)")); + assertFalse(KitDeliverySQL.acknowledge(true).contains("dune_kit_deliveries")); + } + @Test void postgresKeepsItsBuyerBoundInventoryOutboxSeparate() { + assertTrue(KitDeliverySQL.lock(false).endsWith("FOR UPDATE")); + assertTrue(KitDeliverySQL.acknowledge(false).contains("buyer_uuid=? AND delivered_at IS NULL")); + assertFalse(KitDeliverySQL.pending(false).contains("dune_kit_sales")); + } +} diff --git a/DuneKits/src/test/java/com/example/dunekits/KitSpecTest.java b/DuneKits/src/test/java/com/example/dunekits/KitSpecTest.java new file mode 100644 index 00000000..06ebfc3b --- /dev/null +++ b/DuneKits/src/test/java/com/example/dunekits/KitSpecTest.java @@ -0,0 +1,37 @@ +package com.example.dunekits; + +import com.google.gson.*; +import net.kyori.adventure.text.format.TextDecoration; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class KitSpecTest { + @Test void loreIsLiteralAndPreservesBlankLines() { + KitSpec spec = new KitSpec(KitVerification.example("legendary", "silence", "gold")); + assertEquals("netherite", KitVerification.example("legendary", "silence", "gold").getAsJsonObject("equipment").getAsJsonObject("armor").getAsJsonObject("helmet").get("material").getAsString()); + assertEquals(3, spec.armor.get("helmet").lore().size()); + assertEquals("", PlainTextComponentSerializer.plainText().serialize(spec.armor.get("helmet").lore().get(1).component())); + assertEquals(TextDecoration.State.FALSE, spec.armor.get("helmet").lore().get(0).component().decoration(TextDecoration.ITALIC)); + assertEquals("#bca05b", spec.armor.get("helmet").lore().get(0).component().color().asHexString()); + assertEquals("border", spec.banner.patterns().get(0).pattern()); + assertEquals("rhombus", spec.banner.patterns().get(1).pattern()); + } + + @Test void arbitraryComponentsAndOversizedLoreAreRejected() { + JsonObject value = KitVerification.example("rare", "dune", "gold"); + value.getAsJsonObject("equipment").getAsJsonObject("armor").getAsJsonObject("helmet").getAsJsonArray("lore").get(0).getAsJsonObject().add("clickEvent", new JsonObject()); + assertThrows(IllegalArgumentException.class, () -> new KitSpec(value)); + JsonObject oversized = KitVerification.example("rare", "dune", "gold"); + oversized.getAsJsonObject("equipment").getAsJsonObject("armor").getAsJsonObject("boots").getAsJsonArray("lore").get(0).getAsJsonObject().addProperty("text", "😀".repeat(61)); + assertThrows(IllegalArgumentException.class, () -> new KitSpec(oversized)); + } + + @Test void historicalReceiptsStayLegacyAndDoNotGainBanners() { + JsonObject value = JsonParser.parseString("{\"name\":\"Original suit\",\"quality\":\"uncommon\",\"color\":\"#385B49\",\"lore\":[\"Original story\",\"\"]}").getAsJsonObject(); + KitSpec spec = new KitSpec(value); + assertFalse(spec.modern); assertFalse(spec.banner.enabled()); + assertEquals("Original story", spec.armor.get("chestplate").lore().get(0).text()); + assertEquals("", spec.armor.get("chestplate").lore().get(1).text()); + } +} diff --git a/network/server-control/install-kit-equipment.py b/network/server-control/install-kit-equipment.py new file mode 100644 index 00000000..75b0be6a --- /dev/null +++ b/network/server-control/install-kit-equipment.py @@ -0,0 +1,79 @@ +"""Install only the reviewed kit bridge modules; refuse unrelated source changes.""" +import ast +import hashlib +import os +from pathlib import Path +import py_compile +import sys + +BASELINES = { + 'player_kits.py': 'fa76420423941189ba08b94382274e40762121e30b008ec0d08e35aa1a00fda3', + 'kit_commerce.py': '29395a483fdb3f6d94b36fa57587e3a1391d6e4ed8a44159cbb488dd47d960e6', +} +FILES = ['player_kits.py', 'kit_commerce.py', 'kit_equipment.py', 'kit-equipment-contract.json'] + + +def kit_body_limit(source): + tree = ast.parse(source) + candidates = [node for node in tree.body if isinstance(node, ast.FunctionDef) + and any(isinstance(value, ast.Constant) and value.value == '/kits/player/definition' for value in ast.walk(node))] + if len(candidates) != 1: + raise RuntimeError('Native office kit handler changed') + node = candidates[0] + lines = source.splitlines(keepends=True) + section = ''.join(lines[node.lineno - 1:node.end_lineno]) + old, new = 'if not 0 < length <= 8192:', 'if not 0 < length <= 32768:' + if section.count(new) == 1 and old not in section: + return source + if section.count(old) != 1: + raise RuntimeError('Native office body limit changed') + lines[node.lineno - 1:node.end_lineno] = [section.replace(old, new)] + return ''.join(lines) + + +def install(apply=False): + source = Path(__file__).resolve().parent + target = Path('/opt/dunerealms/server-control') + plans = {} + for name in FILES: + content = (source / name).read_bytes() + destination = target / name + before = destination.read_bytes() if destination.exists() else None + if before == content: + continue + if before is not None and hashlib.sha256(before).hexdigest() != BASELINES.get(name): + raise RuntimeError('Concurrent native change detected in ' + name) + plans[destination] = content + agent = target / 'agent.py' + before = agent.read_text() + after = kit_body_limit(before) + if after != before: + plans[agent] = after.encode() + for name in ['player_kits.py', 'kit_commerce.py', 'kit_equipment.py']: + py_compile.compile(str(source / name), doraise=True) + if not apply: + print('Plan: install', len(plans), 'exact kit module/body-limit changes; no files changed') + return + originals = {path: path.read_bytes() if path.exists() else None for path in plans} + changed = [] + try: + for path, content in plans.items(): + temporary = path.with_name(path.name + '.kit-v3-new') + temporary.write_bytes(content) + temporary.chmod(path.stat().st_mode & 0o777 if path.exists() else 0o644) + if path.suffix == '.py': + py_compile.compile(str(temporary), doraise=True) + os.replace(temporary, path) + changed.append(path) + except Exception: + for path in reversed(changed): + if originals[path] is None: + path.unlink() + else: + path.write_bytes(originals[path]) + raise + print('Installed reviewed kit metadata modules; restart the private control service to activate') + + +if __name__ == '__main__': + install('--apply' in sys.argv) diff --git a/network/server-control/kit-delivery-schema.sql b/network/server-control/kit-delivery-schema.sql new file mode 100644 index 00000000..0fb8d8ba --- /dev/null +++ b/network/server-control/kit-delivery-schema.sql @@ -0,0 +1,9 @@ +CREATE TABLE IF NOT EXISTS dune_kit_deliveries ( + id UUID PRIMARY KEY, + buyer_uuid UUID NOT NULL, + snapshot_json TEXT NOT NULL CHECK (octet_length(snapshot_json) <= 65536), + snapshot_hash CHAR(64) NOT NULL CHECK (snapshot_hash ~ '^[a-f0-9]{64}$'), + created_at BIGINT NOT NULL CHECK (created_at > 0), + delivered_at BIGINT NULL CHECK (delivered_at IS NULL OR delivered_at > 0) +); +CREATE INDEX IF NOT EXISTS dune_kit_deliveries_pending ON dune_kit_deliveries(buyer_uuid,created_at,id) WHERE delivered_at IS NULL; diff --git a/network/server-control/kit-equipment-contract.json b/network/server-control/kit-equipment-contract.json new file mode 100644 index 00000000..40818221 --- /dev/null +++ b/network/server-control/kit-equipment-contract.json @@ -0,0 +1,104 @@ +{ + "version": 3, + "slots": [ + "helmet", + "chestplate", + "leggings", + "boots" + ], + "trimPatterns": [ + "sentry", + "dune", + "coast", + "wild", + "ward", + "eye", + "vex", + "tide", + "snout", + "rib", + "spire", + "wayfinder", + "shaper", + "silence", + "raiser", + "host", + "flow", + "bolt" + ], + "trimMaterials": [ + "quartz", + "iron", + "netherite", + "redstone", + "copper", + "gold", + "emerald", + "diamond", + "lapis", + "amethyst", + "resin" + ], + "bannerColors": [ + "white", + "orange", + "magenta", + "light_blue", + "yellow", + "lime", + "pink", + "gray", + "light_gray", + "cyan", + "purple", + "blue", + "brown", + "green", + "red", + "black" + ], + "bannerPatterns": [ + "square_bottom_left", + "square_bottom_right", + "square_top_left", + "square_top_right", + "stripe_bottom", + "stripe_top", + "stripe_left", + "stripe_right", + "stripe_center", + "stripe_middle", + "stripe_downright", + "stripe_downleft", + "small_stripes", + "cross", + "straight_cross", + "triangle_bottom", + "triangle_top", + "triangles_bottom", + "triangles_top", + "diagonal_left", + "diagonal_up_right", + "diagonal_up_left", + "diagonal_right", + "circle", + "rhombus", + "half_vertical", + "half_horizontal", + "half_vertical_right", + "half_horizontal_bottom", + "border", + "curly_border", + "gradient", + "gradient_up", + "bricks", + "globe", + "creeper", + "skull", + "flower", + "mojang", + "piglin", + "flow", + "guster" + ] +} diff --git a/network/server-control/kit-equipment-fixtures.json b/network/server-control/kit-equipment-fixtures.json new file mode 100644 index 00000000..3ff76f08 --- /dev/null +++ b/network/server-control/kit-equipment-fixtures.json @@ -0,0 +1,968 @@ +{ + "valid": { + "version": 3, + "armor": { + "helmet": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "chestplate": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "leggings": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "boots": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + } + }, + "banner": { + "enabled": true, + "name": "Imperial Standard", + "base": "purple", + "patterns": [ + { + "pattern": "border", + "color": "yellow" + }, + { + "pattern": "rhombus", + "color": "red" + } + ], + "lore": [ + { + "text": "Duty endures.", + "color": "#bca05b", + "bold": true, + "italic": false + } + ] + } + }, + "normalized": { + "version": 3, + "armor": { + "helmet": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "chestplate": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "leggings": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "boots": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + } + }, + "banner": { + "enabled": true, + "name": "Imperial Standard", + "base": "purple", + "patterns": [ + { + "pattern": "border", + "color": "yellow" + }, + { + "pattern": "rhombus", + "color": "red" + } + ], + "lore": [ + { + "text": "Duty endures.", + "color": "#BCA05B", + "bold": true, + "italic": false + } + ] + } + }, + "invalid": [ + { + "version": 3, + "armor": { + "helmet": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "Text", + "color": "#AAAAAA", + "bold": false, + "italic": false, + "clickEvent": { + "action": "run_command", + "value": "/op" + } + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "chestplate": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "leggings": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "boots": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + } + }, + "banner": { + "enabled": true, + "name": "Imperial Standard", + "base": "purple", + "patterns": [ + { + "pattern": "border", + "color": "yellow" + }, + { + "pattern": "rhombus", + "color": "red" + } + ], + "lore": [ + { + "text": "Duty endures.", + "color": "#bca05b", + "bold": true, + "italic": false + } + ] + } + }, + { + "version": 3, + "armor": { + "helmet": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "chestplate": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "leggings": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "boots": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + } + }, + "banner": { + "enabled": true, + "name": "Imperial Standard", + "base": "purple", + "patterns": [ + { + "pattern": "border", + "color": "yellow" + }, + { + "pattern": "rhombus", + "color": "red" + } + ], + "lore": [ + { + "text": "Duty endures.", + "color": "#bca05b", + "bold": true, + "italic": false + } + ] + } + }, + { + "version": 3, + "armor": { + "helmet": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "chestplate": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "leggings": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "boots": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + } + }, + "banner": { + "enabled": true, + "name": "Imperial Standard", + "base": "purple", + "patterns": [ + { + "pattern": "border", + "color": "yellow" + }, + { + "pattern": "rhombus", + "color": "red" + }, + { + "pattern": "invalid", + "color": "red" + } + ], + "lore": [ + { + "text": "Duty endures.", + "color": "#bca05b", + "bold": true, + "italic": false + } + ] + } + }, + { + "version": 3, + "armor": { + "helmet": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "chestplate": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "leggings": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "command_block" + } + }, + "boots": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + } + }, + "banner": { + "enabled": true, + "name": "Imperial Standard", + "base": "purple", + "patterns": [ + { + "pattern": "border", + "color": "yellow" + }, + { + "pattern": "rhombus", + "color": "red" + } + ], + "lore": [ + { + "text": "Duty endures.", + "color": "#bca05b", + "bold": true, + "italic": false + } + ] + } + }, + { + "version": true, + "armor": { + "helmet": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "chestplate": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "leggings": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + }, + "boots": { + "material": "netherite", + "name": "", + "lore": [ + { + "text": "First line", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "", + "color": "#AAAAAA", + "bold": false, + "italic": false + }, + { + "text": "Last line", + "color": "#AAAAAA", + "bold": false, + "italic": false + } + ], + "trim": { + "pattern": "dune", + "material": "gold" + } + } + }, + "banner": { + "enabled": true, + "name": "Imperial Standard", + "base": "purple", + "patterns": [ + { + "pattern": "border", + "color": "yellow" + }, + { + "pattern": "rhombus", + "color": "red" + } + ], + "lore": [ + { + "text": "Duty endures.", + "color": "#bca05b", + "bold": true, + "italic": false + } + ] + } + } + ] +} diff --git a/network/server-control/kit_commerce.py b/network/server-control/kit_commerce.py new file mode 100644 index 00000000..69eb372c --- /dev/null +++ b/network/server-control/kit_commerce.py @@ -0,0 +1,553 @@ +"""Private Dunemarks kit commerce; paid orders become bound, one-use deliveries.""" +import base64 +import hashlib +import hmac +import json +from pathlib import Path +from functools import lru_cache +from decimal import Decimal +from player_bank import identity +from kit_equipment import validate_equipment, validate_upgrade + +TIERS = ('common', 'uncommon', 'rare', 'very_rare', 'legendary') +KINDS = ('personal_sale', 'official_sale', 'faction_sale', 'server_sale') +FACTIONS = {'fremen': 'Fremen', 'atreides': 'Atreides', 'harkonnen': 'Harkonnen', 'corrino': 'Corrino', 'ordos': 'Ordos'} +MINIMUM_CENTS = (10000, 20000, 40000, 80000, 160000) +TARGETS = (3, 5, 10, 15, 25) +REWARDS_CENTS = (1000, 2500, 5000, 10000, 20000) +TITLES = ('A Stitch in the Sand', 'Colours of the Caravan', "The Caravan’s Trust", 'Patterns of Influence', 'A Legacy in Gold') + +@lru_cache(maxsize=1) +def arc_definition(): + path=Path(__file__).with_name('kit-quest-arc-v1.json') + if not path.is_file(): + path=Path(__file__).resolve().parents[2]/'website'/'content'/'kit-quest-arc-v1.json' + data=json.loads(path.read_text(encoding='utf-8')) + if len(data.get('chapters',[]))!=5:raise RuntimeError('Invalid canonical quest arc') + for i,row in enumerate(data['chapters']): + if (row['index'],row['quality'],row['targetSales'],row['minimumPriceDunemarks']*100,row['rewardDunemarks']*100)!=(i,TIERS[i],TARGETS[i],MINIMUM_CENTS[i],REWARDS_CENTS[i]): + raise RuntimeError('Quest economy differs from the canonical arc') + return data + +class Conflict(Exception): + pass + +class InsufficientFunds(Exception): + pass + +def allocation_cents(gross, kind='personal_sale'): + if type(gross) is not int or not 1 <= gross <= 100000000: + raise ValueError('Invalid kit price') + if kind not in KINDS: + raise ValueError('Invalid kit commerce kind') + faction = gross * 25 // 100 if kind == 'faction_sale' else 0 + server = gross if kind == 'server_sale' else gross * (15 if kind == 'faction_sale' else 20 if kind == 'official_sale' else 25) // 100 + return faction, server, gross - faction - server + + +def split_cents(gross, kind='personal_sale'): + faction, server, seller = allocation_cents(gross, kind) + if kind == 'faction_sale': + raise ValueError('Faction sales require the three-way allocation') + return server, seller + +def receipt_code(key, line_id): + identity(line_id) + if not isinstance(key, bytes) or len(key) < 32: + raise RuntimeError('Private item-code key unavailable') + digest = hmac.new(key, b'dunerealms-kit-v1:' + line_id.encode('ascii'), hashlib.sha256).digest()[:20] + return 'DRK-' + base64.b32encode(digest).decode('ascii').rstrip('=') + +def code_hash(code): + if not isinstance(code, str) or len(code) != 36 or not code.startswith('DRK-') or any(c not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' for c in code[4:]): + raise ValueError('Invalid item code') + return hashlib.sha256(code.encode('ascii')).hexdigest() + +def initialize(cur): + cur.execute('''CREATE TABLE IF NOT EXISTS dune_kit_carts ( + id VARCHAR(36) PRIMARY KEY,buyer_uuid VARCHAR(36) NOT NULL,payload_hash CHAR(64) NOT NULL, + lines_json TEXT NOT NULL,paid_at BIGINT NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''') + cur.execute('''CREATE TABLE IF NOT EXISTS dune_kit_sales ( + id VARCHAR(36) PRIMARY KEY,buyer_uuid VARCHAR(36) NOT NULL,seller_uuid VARCHAR(36) NOT NULL, + kit_id VARCHAR(36) NOT NULL,kit_version BIGINT NOT NULL,listing_id VARCHAR(36) NOT NULL, + listing_version BIGINT NOT NULL,rarity VARCHAR(16) NOT NULL,shop_type VARCHAR(8) NOT NULL, + commerce_kind VARCHAR(16) NOT NULL DEFAULT 'personal_sale', + quantity INT NOT NULL,gross_cents BIGINT NOT NULL,server_tax_cents BIGINT NOT NULL, + faction_tax_cents BIGINT NOT NULL DEFAULT 0,seller_net_cents BIGINT NOT NULL, + snapshot_json TEXT NOT NULL,code_hash CHAR(64) NOT NULL UNIQUE, + completed_at BIGINT NOT NULL,redeem_requested_at BIGINT NULL,delivered_at BIGINT NULL, + INDEX dune_kit_sales_progress(seller_uuid,rarity,delivered_at), + INDEX dune_kit_sales_pending(buyer_uuid,redeem_requested_at,delivered_at), + CHECK(quantity=1),CHECK(gross_cents>0),CHECK(server_tax_cents>=0), + CONSTRAINT dune_kit_sales_faction_nonnegative CHECK(faction_tax_cents>=0),CHECK(seller_net_cents>=0), + CONSTRAINT dune_kit_sales_conservation CHECK(gross_cents=server_tax_cents+faction_tax_cents+seller_net_cents), + CONSTRAINT dune_kit_sales_kind CHECK(commerce_kind IN ('personal_sale','official_sale','faction_sale','server_sale')) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''') + cur.execute('''CREATE TABLE IF NOT EXISTS dune_kit_arc_claims ( + player_uuid VARCHAR(36) NOT NULL,stage_index INT NOT NULL, + reward_cents BIGINT NOT NULL,claimed_at BIGINT NOT NULL, + PRIMARY KEY(player_uuid,stage_index),CHECK(stage_index BETWEEN 0 AND 4),CHECK(reward_cents>0) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''') + + +def sales_constraint_migration(cur): + """Return one atomic MySQL8 ALTER; caller must stop checkout and back up before applying it.""" + import re + cur.execute('''SELECT tc.CONSTRAINT_NAME AS name,cc.CHECK_CLAUSE AS clause + FROM information_schema.TABLE_CONSTRAINTS tc + JOIN information_schema.CHECK_CONSTRAINTS cc + ON cc.CONSTRAINT_SCHEMA=tc.CONSTRAINT_SCHEMA AND cc.CONSTRAINT_NAME=tc.CONSTRAINT_NAME + WHERE tc.TABLE_SCHEMA=DATABASE() AND tc.TABLE_NAME='dune_kit_sales' AND tc.CONSTRAINT_TYPE='CHECK' ''') + checks = cur.fetchall() + def normalize(value): + # MySQL's metadata adds character-set introducers to string CHECK literals. + value = value.replace("\\'", "'") + value = re.sub(r'_(?:utf8mb4|utf8mb3|utf8|ascii|latin1|binary)(?=\')', '', value, flags=re.I) + return re.sub(r'[\s`()]+', '', value).lower() + legacy = {'faction_tax_cents=0', 'gross_cents=server_tax_cents+seller_net_cents'} + desired = {'faction_tax_cents>=0': ('dune_kit_sales_faction_nonnegative', 'faction_tax_cents>=0'), + 'gross_cents=server_tax_cents+faction_tax_cents+seller_net_cents': + ('dune_kit_sales_conservation', 'gross_cents=server_tax_cents+faction_tax_cents+seller_net_cents'), + "commerce_kindin'personal_sale','official_sale','faction_sale','server_sale'": + ('dune_kit_sales_kind', "commerce_kind IN ('personal_sale','official_sale','faction_sale','server_sale')")} + clauses = {normalize(row['clause']) for row in checks} + changes = [] + cur.execute("SELECT COUNT(*) AS n FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='dune_kit_sales' AND COLUMN_NAME='commerce_kind'") + count = cur.fetchone() + if not count or type(count['n']) is not int or count['n'] not in (0, 1): + raise RuntimeError('Kit classification schema unavailable') + if count['n'] == 0: + changes.append("ADD COLUMN commerce_kind VARCHAR(16) NOT NULL DEFAULT 'personal_sale' AFTER shop_type") + for row in checks: + if normalize(row['clause']) in legacy: + if not re.fullmatch(r'[A-Za-z0-9_]{1,64}', row['name']): + raise RuntimeError('Unexpected kit constraint identity') + changes.append('DROP CHECK `' + row['name'] + '`') + names = {row['name'] for row in checks if normalize(row['clause']) not in legacy} + for normalized, (name, expression) in desired.items(): + if normalized not in clauses: + if name in names: + raise RuntimeError('Conflicting kit constraint identity') + changes.append('ADD CONSTRAINT `' + name + '` CHECK(' + expression + ')') + return 'ALTER TABLE dune_kit_sales ' + ', '.join(changes) if changes else None + +def listing_context(cur, buyer, listing): + cur.execute('CALL dune_kit_listing_lock(%s,%s)', (buyer,listing)) + rows = cur.fetchall() + while cur.nextset(): + pass + if len(rows) != 1: + raise PermissionError('Published kit listing unavailable') + return rows[0] + +def listing_snapshot(row): + import re + def plain(value, limit): + if not isinstance(value,str) or not 1 <= len(value.strip()) <= limit or re.search(r'[\x00-\x1f\x7f<>§]',value): + raise ValueError('Invalid kit cosmetic text') + return value.strip() + quality = str(row.get('quality','')).lower() + kind = row.get('commerce_kind') + if quality not in TIERS or kind not in KINDS or row.get('shop_type') not in ('player','clan','official','faction','server'): + raise ValueError('Invalid listing type or quality') + shop_types = {'personal_sale': ('player','clan'), 'official_sale': ('official',), 'faction_sale': ('faction',), 'server_sale': ('server',)} + if row['shop_type'] not in shop_types[kind]: + raise ValueError('The listing category does not match its authoritative commerce kind') + color = row.get('kit_color') + if not isinstance(color,str) or not re.fullmatch(r'#[0-9a-fA-F]{6}',color): + raise ValueError('Invalid kit colour') + lore = json.loads(row.get('kit_lore_json','')) + if not isinstance(lore,list) or len(lore)>6: + raise ValueError('Invalid kit lore') + for field in ('listing_version','blueprint_version','price_cents'): + if type(row.get(field)) is not int or row[field]<1: + raise ValueError('Invalid listing revision or price') + if kind == 'personal_sale' and row['price_cents'] < MINIMUM_CENTS[TIERS.index(quality)]: + raise ValueError('Listing is below the tier minimum') + allocation_cents(row['price_cents'], kind) + seller = identity(row['seller_uuid']) + import uuid + if uuid.UUID(seller).int == 0: + raise ValueError('A real verified designer or publisher is required') + item = {'listingId':identity(row['listing_id']),'listingVersion':row['listing_version'], + 'blueprintId':identity(row['blueprint_id']),'blueprintVersion':row['blueprint_version'], + 'sellerUuid':seller,'clanId':identity(row['clan_id']) if row.get('clan_id') else None, + 'shopType':row['shop_type'],'commerceKind':kind,'quality':quality, + 'priceCents':row['price_cents'],'name':plain(row['kit_name'],64),'color':color.upper(), + 'lore':[plain(line,120) for line in lore]} + equipment = row.get('kit_equipment_json') + if equipment is not None: + item['equipment'] = validate_equipment(json.loads(equipment) if isinstance(equipment, str) else equipment) + names = row.get('kit_item_names_json') + if names is not None: + names = json.loads(names) if isinstance(names, str) else names + if not isinstance(names, dict) or set(names) - {'helmet', 'chestplate', 'leggings', 'boots'} or any(not isinstance(value, str) or len(value) > 64 or re.search(r'[<>§\x00-\x1f\x7f]', value) for value in names.values()): + raise ValueError('Invalid individual item names') + item['itemNames'] = names + upgrade = row.get('kit_upgrade_json') + if upgrade is not None: + item['upgrade'] = validate_upgrade(json.loads(upgrade) if isinstance(upgrade, str) else upgrade, quality, kind) + override = row.get('seller_tier_override', 0) + if type(override) is not int or override not in (0, 1) or (kind != 'personal_sale' and override != 0): + raise ValueError('Invalid authoritative designer tier override') + item['sellerTierOverride'] = override + if kind in ('official_sale', 'faction_sale'): + office, term = row.get('office_key'), row.get('office_term') + if not isinstance(office, str) or not re.fullmatch(r'emperor|(?:house-leader|water-steward|spice-steward):(Fremen|Atreides|Harkonnen|Corrino|Ordos)', office): + raise ValueError('Canonical elected office required') + if not isinstance(term, str) or not 1 <= len(term) <= 190 or not re.fullmatch(r'[A-Za-z0-9:._-]+',term): + raise ValueError('Canonical elected term required') + item.update(officeKey=office, officeTerm=term) + if kind == 'faction_sale': + faction = row.get('faction_id') + if faction not in FACTIONS or item['officeKey'] != 'house-leader:' + FACTIONS[faction]: + raise ValueError('The owning faction and leader office must match') + item['factionId'] = faction + if kind == 'server_sale' and (type(row.get('server_authorized')) is not int or row['server_authorized'] != 1): + raise PermissionError('Current protected publisher authority required') + return item + + +def current_listing_authority(cur, item, locking=True, cache=None): + if item['commerceKind'] in ('official_sale', 'faction_sale'): + from player_kits import authority + owner = item['sellerUuid'] + if cache is None: + offices = authority(cur, owner, locking=locking) + else: + if owner not in cache: + cache[owner] = authority(cur, owner, locking=locking) + offices = cache[owner] + if offices.get(item['officeKey']) != item['officeTerm']: + raise PermissionError('The listing belongs to an expired elected term') + + +def credit_sale_bank(cur, kind, owner, amount, actor, stamp, reference): + """Fixed destinations only. Uses the enclosing checkout transaction and unique sale reference.""" + import uuid + if amount == 0: + return + if kind == 'personal': + table, key, ledger = 'dune_player_banks', 'player_uuid', 'dune_player_bank_ledger' + elif kind == 'faction' and owner in FACTIONS: + table, key, ledger = 'dune_faction_bank_wallet', 'faction_id', 'dune_faction_bank_ledger' + else: + raise ValueError('Invalid sale bank destination') + cur.execute('INSERT INTO '+table+'('+key+',balance,updated_at) VALUES(%s,0,%s) ON DUPLICATE KEY UPDATE '+key+'='+key,(owner,stamp)) + cur.execute('SELECT balance FROM '+table+' WHERE '+key+'=%s FOR UPDATE',(owner,)) + row=cur.fetchone() + if row is None: + raise RuntimeError('Sale bank unavailable') + before=Decimal(row['balance']);after=before+amount + if before<0 or after>Decimal('1000000000000'): + raise ValueError('A sale bank limit was reached') + cur.execute('UPDATE '+table+' SET balance=%s,updated_at=%s WHERE '+key+'=%s',(after,stamp,owner)) + if kind == 'personal': + cur.execute('INSERT INTO '+ledger+'(id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s)',(str(uuid.uuid4()),owner,'faction-kit-sale',amount,after,stamp,reference)) + else: + cur.execute('INSERT INTO '+ledger+'(id,faction_id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)',(str(uuid.uuid4()),owner,actor,'faction-kit-sale',amount,after,stamp,reference)) + +def checkout(connect, key, payload, context=listing_context): + fields={'buyerUuid','listingId','orderLineId','listingVersion','blueprintVersion','priceCents'} + if not isinstance(payload,dict) or set(payload)!=fields: + raise ValueError('Invalid checkout fields') + buyer=identity(payload['buyerUuid']);listing=identity(payload['listingId']);line=identity(payload['orderLineId']) + for field in ('listingVersion','blueprintVersion','priceCents'): + if type(payload[field]) is not int or payload[field]<1: + raise ValueError('Review the current listing before purchasing') + code=receipt_code(key,line);digest=code_hash(code) + with connect() as con: + try: + con.begin() + with con.cursor() as cur: + cur.execute('SELECT buyer_uuid,listing_id,listing_version,kit_version,gross_cents,code_hash FROM dune_kit_sales WHERE id=%s FOR UPDATE',(line,)) + old=cur.fetchone() + if old: + if (old['buyer_uuid'],old['listing_id'],old['listing_version'],old['kit_version'],old['gross_cents']) != (buyer,listing,payload['listingVersion'],payload['blueprintVersion'],payload['priceCents']): + raise Conflict('Order line already belongs to a different purchase') + if not hmac.compare_digest(old['code_hash'],digest): + raise RuntimeError('Item-code key differs from the original receipt') + con.rollback() + return {'ok':True,'alreadyPaid':True,'orderLineId':line,'code':code,'delivery':'redeem-code'} + authority=context(cur,buyer,listing) + if authority.get('buyer_uuid') != buyer or authority.get('commerce_kind') not in KINDS: + raise PermissionError('Current verified buyer and supported listing required') + item=listing_snapshot(authority) + current_listing_authority(cur,item) + if (item['listingId'],item['listingVersion'],item['blueprintVersion'],item['priceCents']) != (listing,payload['listingVersion'],payload['blueprintVersion'],payload['priceCents']): + raise Conflict('The listing changed; review its current price and design') + seller=item['sellerUuid'];tier=TIERS.index(item['quality']) + kind=item['commerceKind'] + if kind == 'personal_sale' and not item['sellerTierOverride'] and tier > len(claimed(cur,seller)): + raise PermissionError('Designer has not unlocked this kit tier') + wallets={} + for player in sorted({buyer,seller} if kind in ('personal_sale','official_sale') else {buyer}): + cur.execute('SELECT balance FROM dune_economy_balances WHERE uuid=%s FOR UPDATE',(player,)) + row=cur.fetchone() + if row is None: + raise PermissionError('Existing buyer and designer Minecraft wallets are required') + wallets[player]=Decimal(row['balance']) + gross=Decimal(item['priceCents'])/100 + if wallets[buyer]Decimal('1000000000000') or any(v>Decimal('1000000000000') for v in wallets.values()): + raise ValueError('A wallet or treasury limit was reached') + stamp=now(cur) + if kind == 'faction_sale': + credit_sale_bank(cur,'personal',seller,Decimal(net_cents)/100,buyer,stamp,'kit-sale:'+line) + credit_sale_bank(cur,'faction',item['factionId'],Decimal(faction_cents)/100,buyer,stamp,'kit-sale:'+line) + cur.execute('''INSERT INTO dune_kit_sales(id,buyer_uuid,seller_uuid,kit_id,kit_version,listing_id,listing_version,rarity,shop_type,commerce_kind,quantity,gross_cents,server_tax_cents,faction_tax_cents,seller_net_cents,snapshot_json,code_hash,completed_at) + VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,1,%s,%s,%s,%s,%s,%s,%s)''', + (line,buyer,seller,item['blueprintId'],item['blueprintVersion'],listing,item['listingVersion'],item['quality'],item['shopType'],kind,item['priceCents'],tax_cents,faction_cents,net_cents,json.dumps(item),digest,stamp)) + for player,balance in wallets.items(): + cur.execute('UPDATE dune_economy_balances SET balance=%s WHERE uuid=%s',(balance,player)) + cur.execute("UPDATE dune_staff_bank_wallet SET balance=%s,updated_at=%s WHERE account_key='network'",(treasury,stamp)) + import uuid + cur.execute('INSERT INTO dune_staff_bank_ledger(id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s)',(str(uuid.uuid4()),buyer,'kit-sale-tax',tax,treasury,stamp,'kit-sale:'+line)) + con.commit() + return {'ok':True,'alreadyPaid':False,'orderLineId':line,'code':code,'delivery':'redeem-code'} + except Exception: + con.rollback();raise + +def now(cur): + cur.execute('SELECT CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS SIGNED) AS now') + return int(cur.fetchone()['now']) + +def cart_input(payload): + if not isinstance(payload,dict) or set(payload)!={'buyerUuid','cartId','lines'}: + raise ValueError('Invalid cart fields') + buyer=identity(payload['buyerUuid']);cart=identity(payload['cartId']) + if not isinstance(payload['lines'],list) or not 1<=len(payload['lines'])<=20: + raise ValueError('A cart must contain one to twenty kit lines') + lines=[] + for row in payload['lines']: + if not isinstance(row,dict) or set(row)!={'listingId','orderLineId','listingVersion','blueprintVersion','priceCents'}: + raise ValueError('Invalid cart line') + for field in ('listingVersion','blueprintVersion','priceCents'): + if type(row[field]) is not int or row[field]<1:raise ValueError('Invalid cart revision or price') + split_cents(row['priceCents']) + lines.append({**row,'buyerUuid':buyer,'listingId':identity(row['listingId']),'orderLineId':identity(row['orderLineId'])}) + if len({row['orderLineId'] for row in lines})!=len(lines):raise ValueError('Duplicate order line') + lines.sort(key=lambda row:row['orderLineId']) + canonical=json.dumps({'buyerUuid':buyer,'cartId':cart,'lines':lines},sort_keys=True,separators=(',',':')) + return buyer,cart,lines,hashlib.sha256(canonical.encode()).hexdigest() + +def checkout_cart(connect,key,payload,context=listing_context): + buyer,cart,lines,fingerprint=cart_input(payload) + with connect() as con: + # Reuse the single-line engine inside ONE outer transaction. Inner boundaries cannot commit partial carts. + class SharedTransaction: + def __enter__(self):return self + def __exit__(self,*args):pass + def cursor(self):return con.cursor() + def begin(self):pass + def commit(self):pass + def rollback(self):pass + def shared():return SharedTransaction() + try: + con.begin() + with con.cursor() as cur: + cur.execute('SELECT buyer_uuid,payload_hash FROM dune_kit_carts WHERE id=%s FOR UPDATE',(cart,)) + old=cur.fetchone() + if old: + if old['buyer_uuid']!=buyer or not hmac.compare_digest(old['payload_hash'],fingerprint): + raise Conflict('This cart was already paid with different contents') + result=[checkout(shared,key,line,context) for line in lines] + if not all(row['alreadyPaid'] for row in result): + raise RuntimeError('Paid cart has an incomplete order receipt') + con.rollback() + return {'ok':True,'alreadyPaid':True,'cartId':cart,'lines':result,'delivery':'redeem-code'} + for line in lines: + cur.execute('SELECT id FROM dune_kit_sales WHERE id=%s FOR UPDATE',(line['orderLineId'],)) + if cur.fetchone():raise Conflict('An order line already belongs to another purchase') + authorities={} + for listing in sorted({line['listingId'] for line in lines}): + row=context(cur,buyer,listing) + if row.get('buyer_uuid')!=buyer or row.get('commerce_kind') not in KINDS: + raise PermissionError('Current verified buyer required') + authorities[listing]=row + sellers=set();total=Decimal(0) + for line in lines: + item=listing_snapshot(authorities[line['listingId']]) + current_listing_authority(cur,item) + if (item['listingId'],item['listingVersion'],item['blueprintVersion'],item['priceCents']) != (line['listingId'],line['listingVersion'],line['blueprintVersion'],line['priceCents']): + raise Conflict('A cart listing changed; review the entire cart') + if item['commerceKind']=='personal_sale' and not item['sellerTierOverride'] and TIERS.index(item['quality'])>len(claimed(cur,item['sellerUuid'])): + raise PermissionError('Designer has not unlocked this kit tier') + if item['commerceKind'] in ('personal_sale','official_sale'): + sellers.add(item['sellerUuid']) + total+=Decimal(item['priceCents'])/100 + # Lock every participant in a stable global order before any line is charged. + balance=None + for player in sorted(sellers|{buyer}): + cur.execute('SELECT balance FROM dune_economy_balances WHERE uuid=%s FOR UPDATE',(player,)) + row=cur.fetchone() + if not row:raise PermissionError('Existing Minecraft wallets required') + if player==buyer:balance=Decimal(row['balance']) + if balance is None or balance 5: + raise RuntimeError('Invalid quest claim sequence') + return stages + +def progress(cur, player, index): + # One buyer/tier/UTC delivery day. Quantity, self-sales and unpaid/unredeemed codes cannot inflate progress. + cur.execute('''SELECT COUNT(*) AS n FROM ( + SELECT buyer_uuid,FLOOR(delivered_at/86400000) AS utc_day FROM dune_kit_sales + WHERE seller_uuid=%s AND rarity=%s AND buyer_uuid<>seller_uuid AND commerce_kind='personal_sale' + AND delivered_at IS NOT NULL AND quantity=1 AND gross_cents>=%s + GROUP BY buyer_uuid,FLOOR(delivered_at/86400000) + ) AS qualifying''', (player, TIERS[index], MINIMUM_CENTS[index])) + return int(cur.fetchone()['n']) + +def read_arc(connect, player): + player = identity(player) + definition=arc_definition() + with connect() as con: + with con.cursor() as cur: + done = claimed(cur, player) + chapters = [] + for index in range(5): + count = progress(cur, player, index) + story=definition['chapters'][index] + chapters.append({'index': index, 'key': story['key'], 'quality':TIERS[index], 'title': story['title'], + 'description':story['description'],'kitTemplate':story['kitTemplate'],'sales': count, + 'target': TARGETS[index], 'minimumPriceDunemarks': format(Decimal(MINIMUM_CENTS[index])/100, '.2f'), + 'rewardDunemarks': format(Decimal(REWARDS_CENTS[index])/100, '.2f'), + 'claimed': index in done, 'unlocked': index <= len(done), + 'canClaim': index == len(done) and count >= TARGETS[index]}) + return {'playerUuid': player, 'title': 'The Loom of the Desert', 'chapters': chapters, + 'rewardSource': 'server-bank', 'salesRule': 'Paid, delivered sales of your own designs; one external buyer per tier per UTC day.'} + +def read_orders(connect, key, player): + player=identity(player) + with connect() as con: + with con.cursor() as cur: + cur.execute('''SELECT id,buyer_uuid,seller_uuid,kit_id,rarity,shop_type,commerce_kind,gross_cents,server_tax_cents,faction_tax_cents,seller_net_cents, + snapshot_json,code_hash,completed_at,redeem_requested_at,delivered_at FROM dune_kit_sales + WHERE buyer_uuid=%s OR seller_uuid=%s ORDER BY completed_at DESC,id DESC LIMIT 100''',(player,player)) + orders=[] + for row in cur.fetchall(): + item=json.loads(row['snapshot_json']) + entry={'orderLineId':row['id'],'side':'purchase' if row['buyer_uuid']==player else 'sale', + 'name':item['name'],'quality':row['rarity'],'shopType':row['shop_type'],'commerceKind':row['commerce_kind'], + 'grossDunemarks':format(Decimal(row['gross_cents'])/100,'.2f'), + 'serverTaxDunemarks':format(Decimal(row['server_tax_cents'])/100,'.2f'), + 'factionTaxDunemarks':format(Decimal(row['faction_tax_cents'])/100,'.2f'), + 'sellerNetDunemarks':format(Decimal(row['seller_net_cents'])/100,'.2f'), + 'sellerPayoutDestination':'personal-bank' if row['commerce_kind']=='faction_sale' else 'none' if row['commerce_kind']=='server_sale' else 'wallet', + 'completedAt':row['completed_at'],'deliveredAt':row['delivered_at'], + 'status':'delivered' if row['delivered_at'] is not None else 'pending-in-game-delivery' if row['redeem_requested_at'] is not None else 'code-ready'} + if row['buyer_uuid']==player: + code=receipt_code(key,row['id']) + if not hmac.compare_digest(code_hash(code),row['code_hash']): + raise RuntimeError('Item-code key differs from receipt') + entry['code']=code + orders.append(entry) + return {'playerUuid':player,'currency':'dunemarks','orders':orders} + +def catalogue(connect): + with connect() as con: + with con.cursor() as cur: + cur.execute('CALL dune_kit_catalogue()');rows=cur.fetchall() + while cur.nextset():pass + cur.execute('SELECT listing_id,COUNT(*) AS sales FROM dune_kit_sales WHERE delivered_at IS NOT NULL AND buyer_uuid<>seller_uuid GROUP BY listing_id') + popularity={row['listing_id']:int(row['sales']) for row in cur.fetchall()} + owners=sorted({identity(row['seller_uuid']) for row in rows if row.get('commerce_kind')=='personal_sale'}) + unlocked={owner:set() for owner in owners} + if owners: + cur.execute('SELECT player_uuid,stage_index FROM dune_kit_arc_claims WHERE player_uuid IN ('+','.join(['%s']*len(owners))+')',tuple(owners)) + for row in cur.fetchall():unlocked[row['player_uuid']].add(int(row['stage_index'])) + listings=[];office_cache={} + for row in rows: + item=listing_snapshot(row) + try: + current_listing_authority(cur,item,locking=False,cache=office_cache) + except PermissionError: + continue + if item['commerceKind']=='personal_sale': + stages=sorted(unlocked[item['sellerUuid']]) + if stages!=list(range(len(stages))) or (not item['sellerTierOverride'] and TIERS.index(item['quality'])>len(stages)):continue + item['completedSales']=popularity.get(item['listingId'],0) + item['sellerName']=str(row['seller_name'])[:64] + item['priceDunemarks']=format(Decimal(item['priceCents'])/100,'.2f') + listings.append(item) + return {'currency':'dunemarks','listings':listings} + +def queue_redemption(connect, player, code): + player = identity(player); digest = code_hash(code) + with connect() as con: + try: + con.begin() + with con.cursor() as cur: + cur.execute('SELECT id,buyer_uuid,delivered_at,redeem_requested_at FROM dune_kit_sales WHERE code_hash=%s FOR UPDATE', (digest,)) + row = cur.fetchone() + if not row or row['buyer_uuid'] != player: + raise PermissionError('Item code is unavailable for this account') + if row['delivered_at'] is None and row['redeem_requested_at'] is None: + cur.execute('UPDATE dune_kit_sales SET redeem_requested_at=%s WHERE id=%s AND redeem_requested_at IS NULL', (now(cur), row['id'])) + result = {'ok': True, 'orderLineId': row['id'], 'status': 'delivered' if row['delivered_at'] is not None else 'pending-in-game-delivery'} + con.commit() + return result + except Exception: + con.rollback();raise + +def claim_arc(connect, player, index): + player = identity(player); index = stage(index) + arc_definition() + with connect() as con: + try: + con.begin() + with con.cursor() as cur: + # Central treasury lock serializes rewards across servers and makes insufficient funding retryable. + cur.execute("SELECT balance FROM dune_staff_bank_wallet WHERE account_key='network' FOR UPDATE") + treasury = cur.fetchone() + done = claimed(cur, player) + if index in done: + con.rollback();return {'ok': True, 'alreadyClaimed': True, 'stage': index} + if index != len(done) or progress(cur, player, index) < TARGETS[index]: + raise PermissionError('Complete the current sales chapter first') + reward = Decimal(REWARDS_CENTS[index])/100 + if not treasury or Decimal(treasury['balance']) < reward: + con.rollback();return {'ok': False, 'pending': True, 'reason': 'server-bank-funding', 'stage': index} + cur.execute('SELECT balance FROM dune_economy_balances WHERE uuid=%s FOR UPDATE', (player,)) + wallet = cur.fetchone() + if wallet is None: + raise PermissionError('An existing Minecraft wallet is required') + amount = Decimal(wallet['balance']) + reward + if amount > Decimal('1000000000000'): + raise ValueError('Wallet limit reached') + stamp = now(cur) + cur.execute('INSERT INTO dune_kit_arc_claims(player_uuid,stage_index,reward_cents,claimed_at) VALUES(%s,%s,%s,%s)', (player,index,REWARDS_CENTS[index],stamp)) + balance = Decimal(treasury['balance'])-reward + cur.execute("UPDATE dune_staff_bank_wallet SET balance=%s,updated_at=%s WHERE account_key='network'", (balance,stamp)) + cur.execute('UPDATE dune_economy_balances SET balance=%s WHERE uuid=%s', (amount,player)) + import uuid + reference = 'kit-arc:'+player+':'+str(index) + cur.execute('INSERT INTO dune_staff_bank_ledger(id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(%s,%s,%s,%s,%s,%s,%s)', (str(uuid.uuid4()),player,'kit-arc-reward',-reward,balance,stamp,reference)) + con.commit() + return {'ok': True, 'alreadyClaimed': False, 'stage': index, 'rewardDunemarks': format(reward,'.2f')} + except Exception: + con.rollback();raise diff --git a/network/server-control/kit_equipment.py b/network/server-control/kit_equipment.py new file mode 100644 index 00000000..2cc6edbe --- /dev/null +++ b/network/server-control/kit_equipment.py @@ -0,0 +1,73 @@ +"""Versioned kit cosmetics; only bounded literal text and vanilla item metadata.""" +import copy +import json +import re +from pathlib import Path + +CONTRACT = json.loads(Path(__file__).with_name('kit-equipment-contract.json').read_text()) + + +def exact(value, fields): + return isinstance(value, dict) and set(value) == set(fields) + + +def text(value, maximum): + return isinstance(value, str) and len(value.encode('utf-16-le')) // 2 <= maximum and not re.search(r'[\x00-\x1f\x7f<>§]', value) + + +def validate_lore(value): + if not isinstance(value, list) or len(value) > 6: + raise ValueError('Use at most six item lore lines') + result = [] + for line in value: + if (not exact(line, ['text', 'color', 'bold', 'italic']) or not text(line['text'], 120) + or not isinstance(line['color'], str) or not re.fullmatch(r'#[a-f0-9]{6}', line['color'], re.I) + or type(line['bold']) is not bool or type(line['italic']) is not bool): + raise ValueError('Invalid literal item lore') + result.append({**line, 'color': line['color'].upper()}) + return result + + +def validate_equipment(value): + if not exact(value, ['version', 'armor', 'banner']) or type(value['version']) is not int or value['version'] != 3 or not exact(value['armor'], CONTRACT['slots']): + raise ValueError('Complete version 3 kit required') + armor = {} + for slot in CONTRACT['slots']: + piece = value['armor'][slot] + if (not exact(piece, ['material', 'name', 'lore', 'trim']) or piece['material'] != 'netherite' + or not text(piece['name'], 64) or not exact(piece['trim'], ['pattern', 'material']) + or piece['trim']['pattern'] not in CONTRACT['trimPatterns'] or piece['trim']['material'] not in CONTRACT['trimMaterials']): + raise ValueError('Invalid armour piece or trim') + armor[slot] = {**piece, 'name': piece['name'].strip(), 'lore': validate_lore(piece['lore']), 'trim': dict(piece['trim'])} + banner = value['banner'] + if (not exact(banner, ['enabled', 'name', 'base', 'patterns', 'lore']) or type(banner['enabled']) is not bool + or not text(banner['name'], 64) or banner['base'] not in CONTRACT['bannerColors'] + or not isinstance(banner['patterns'], list) or len(banner['patterns']) > 6): + raise ValueError('Invalid banner') + for layer in banner['patterns']: + if not exact(layer, ['pattern', 'color']) or layer['pattern'] not in CONTRACT['bannerPatterns'] or layer['color'] not in CONTRACT['bannerColors']: + raise ValueError('Invalid banner layer') + return {'version': 3, 'armor': armor, 'banner': {**banner, 'name': banner['name'].strip(), 'patterns': copy.deepcopy(banner['patterns']), 'lore': validate_lore(banner['lore'])}} + + +def default_equipment(legacy): + lore = [{'text': line, 'color': '#AAAAAA', 'bold': False, 'italic': False} for line in legacy.get('lore', [])[:6]] + return validate_equipment({'version': 3, 'armor': {slot: {'material': 'netherite', 'name': legacy.get('itemNames', {}).get(slot, ''), 'lore': copy.deepcopy(lore), 'trim': {'pattern': 'dune', 'material': 'gold'}} for slot in CONTRACT['slots']}, 'banner': {'enabled': False, 'name': '', 'base': 'black', 'patterns': [], 'lore': []}}) + + +def validate_upgrade(value, quality, kind): + if quality != 'legendary' or kind != 'personal_sale' or not exact(value, ['policy', 'points', 'bonuses']) or value['policy'] != 'legendary-player-v1' or type(value['points']) is not int or not 1 <= value['points'] <= 3 or not isinstance(value['bonuses'], list) or not 1 <= len(value['bonuses']) <= 3: + raise ValueError('Invalid Legendary Player Kit upgrade') + selected, total = set(), 0 + for bonus in value['bonuses']: + if not exact(bonus, ['piece', 'enchantment', 'levels']) or bonus['piece'] not in CONTRACT['slots']: + raise ValueError('Invalid upgrade piece') + allowed = {'protection', 'unbreaking', 'mending', 'thorns'} + allowed.update({'helmet': ['respiration', 'aqua_affinity'], 'leggings': ['swift_sneak'], 'boots': ['feather_falling', 'depth_strider', 'soul_speed']}.get(bonus['piece'], [])) + if bonus['enchantment'] not in allowed or type(bonus['levels']) is not int or not 1 <= bonus['levels'] <= 3 or (bonus['piece'], bonus['enchantment']) in selected: + raise ValueError('Invalid upgrade distribution') + selected.add((bonus['piece'], bonus['enchantment'])) + total += bonus['levels'] + if total != value['points']: + raise ValueError('Upgrade points do not balance') + return copy.deepcopy(value) diff --git a/network/server-control/player_kits.py b/network/server-control/player_kits.py new file mode 100644 index 00000000..9291684d --- /dev/null +++ b/network/server-control/player_kits.py @@ -0,0 +1,152 @@ +"""Term-bound office blueprints. Private bridge only; authority comes from game SQL.""" +import json +import re +import uuid +import time +from kit_equipment import validate_equipment, default_equipment + +HOUSES = ('Fremen', 'Harkonnen', 'Corrino', 'Atreides', 'Ordos') + +class Conflict(Exception): + pass + +def identity(value): + if not isinstance(value, str) or not re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', value): + raise ValueError('Verified Minecraft UUID required') + return str(uuid.UUID(value)) + +def winner(election): + tally = election.get('tally', {}) if isinstance(election, dict) else {} + valid = [] + for key, count in tally.items(): + try: + player = identity(key) + except (ValueError, TypeError): + continue + if type(count) is int and count > 0: + valid.append((player, count)) + return sorted(valid, key=lambda row: (-row[1], row[0]))[0][0] if valid else '' + +def at(record, *keys): + for key in keys: + if not isinstance(record, dict): + return {} + record = record.get(key, record.get(str(key), {})) + return record + +def interim_winner(record, kind, faction=None, now=None): + now = int(time.time() * 1000) if now is None else now + entry = at(record, 'interim', kind) if kind == 'emperor' else at(record, 'interim', 'house', faction) + try: + player = identity(entry.get('uuid')) + start, end = entry.get('startsAt'), entry.get('expiresAt') + return player if type(start) is int and type(end) is int and start <= now < end else '' + except (ValueError, TypeError, AttributeError): + return '' + +def offices(record, week, player, faction): + result = {} + emperor = interim_winner(record, 'emperor') or winner(at(record, 'votes', 'emperor', week)) + if player == emperor: + result['emperor'] = f'emperor:{week}:{player}' + if faction in HOUSES and player == (interim_winner(record, 'house', faction) or winner(at(record, 'votes', 'house', week, faction))): + result['house-leader:' + faction] = f'house-leader:{faction}:{week}:{player}' + for appointment, office in (('water', 'water-steward'), ('steward', 'spice-steward')): + entry = at(record, 'appointments', appointment) + if emperor and at(entry, 'week') == week and at(entry, 'emperor') == emperor and at(entry, 'house') == faction: + result[office + ':' + faction] = f'{office}:{faction}:{week}:{player}:{emperor}' + return result + +def initialize(cursor): + cursor.execute('''CREATE TABLE IF NOT EXISTS dune_office_kit_definitions ( + owner_uuid VARCHAR(36) NOT NULL,office_key VARCHAR(96) NOT NULL, + term_id VARCHAR(190) NOT NULL,version INTEGER NOT NULL, + kit_name VARCHAR(64) NOT NULL,color VARCHAR(7) NOT NULL,lore_json TEXT NOT NULL, + updated_at BIGINT NOT NULL,PRIMARY KEY(owner_uuid,office_key,term_id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4''') + + cursor.execute("SELECT COUNT(*) AS n FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='dune_office_kit_definitions' AND COLUMN_NAME='equipment_json'") + if cursor.fetchone()['n'] == 0: + cursor.execute('ALTER TABLE dune_office_kit_definitions ADD COLUMN equipment_json JSON NULL') + +def authority(cursor, player, locking=False): + import yaml + suffix = ' FOR SHARE' if locking else '' + cursor.execute('SELECT yaml FROM dune_politics WHERE id=1' + suffix) + row = cursor.fetchone() + if not row or not isinstance(row['yaml'], str) or len(row['yaml']) > 2097152: + raise RuntimeError('Political authority unavailable') + record = yaml.safe_load(row['yaml']) or {} + cursor.execute('SELECT faction FROM dune_players WHERE uuid=%s' + suffix, (player,)) + row = cursor.fetchone() + faction = row['faction'] if row else '' + cursor.execute('SELECT FLOOR(UNIX_TIMESTAMP(CURRENT_TIMESTAMP)/604800) AS week') + week = int(cursor.fetchone()['week']) + return offices(record, week, player, faction) + +def validate(data): + if not isinstance(data, dict) or set(data) != ({'uuid', 'office', 'term', 'version', 'name', 'color', 'lore'} | ({'equipment'} if 'equipment' in data else set())): + raise ValueError('Invalid blueprint fields') + if 'equipment' in data: + data = {**data, 'equipment': validate_equipment(data['equipment'])} + player = identity(data['uuid']) + if data['office'] != 'emperor' and not (isinstance(data['office'], str) and re.fullmatch(r'(house-leader|water-steward|spice-steward):(Fremen|Harkonnen|Corrino|Atreides|Ordos)', data['office'])): + raise ValueError('Invalid office') + if not isinstance(data['term'], str) or not 1 <= len(data['term']) <= 190: + raise ValueError('Invalid elected term') + if type(data['version']) is not int or not 0 <= data['version'] < 2147483647: + raise ValueError('Invalid blueprint version') + def text(value, limit): + if not isinstance(value, str) or not 1 <= len(value.strip()) <= limit or re.search(r'[\x00-\x1f\x7f<>§]', value): + raise ValueError('Use plain text for kit names and lore') + return value.strip() + name = text(data['name'], 64) + if not isinstance(data['color'], str) or not re.fullmatch(r'#[0-9A-Fa-f]{6}', data['color']): + raise ValueError('Use a six-digit colour') + if not isinstance(data['lore'], list) or len(data['lore']) > 6: + raise ValueError('Use at most six lore lines') + return {**data, 'uuid': player, 'name': name, 'color': data['color'].upper(), 'lore': [text(line, 120) for line in data['lore']]} + +def read(connect, player): + player = identity(player) + with connect() as con: + with con.cursor() as cursor: + current = authority(cursor, player) + cursor.execute('SELECT office_key,term_id,version,kit_name,color,lore_json,equipment_json FROM dune_office_kit_definitions WHERE owner_uuid=%s', (player,)) + definitions = {row['office_key']: row for row in cursor.fetchall() if current.get(row['office_key']) == row['term_id']} + rows = [] + for office, term in current.items(): + row = definitions.get(office) + rows.append({'office': office, 'term': term, 'version': row['version'] if row else 0, 'name': row['kit_name'] if row else 'Imperial Stillsuit', 'color': row['color'] if row else '#571F82', 'lore': json.loads(row['lore_json']) if row else [], 'quality': 'uncommon', 'equipment': validate_equipment(json.loads(row['equipment_json'])) if row and row.get('equipment_json') else None}) + return {'playerUuid': player, 'canDesign': bool(rows), 'offices': rows} + +def save(connect, payload): + data = validate(payload) + with connect() as con: + try: + con.begin() + with con.cursor() as cursor: + if authority(cursor, data['uuid'], True).get(data['office']) != data['term']: + raise PermissionError('Current elected office required') + args = (data['uuid'], data['office'], data['term']) + cursor.execute('SELECT version,equipment_json FROM dune_office_kit_definitions WHERE owner_uuid=%s AND office_key=%s AND term_id=%s FOR UPDATE', args) + row = cursor.fetchone() + if (row['version'] if row else 0) != data['version']: + raise Conflict('Blueprint changed; reload before saving') + equipment = data.get('equipment') or (validate_equipment(json.loads(row['equipment_json'])) if row and row.get('equipment_json') else default_equipment(data)) + if row: + cursor.execute('''UPDATE dune_office_kit_definitions SET version=%s,kit_name=%s,color=%s,lore_json=%s,equipment_json=%s, + updated_at=CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS SIGNED) + WHERE owner_uuid=%s AND office_key=%s AND term_id=%s AND version=%s''', + (data['version'] + 1, data['name'], data['color'], json.dumps(data['lore']), json.dumps(equipment)) + args + (data['version'],)) + if cursor.rowcount != 1: + raise Conflict('Blueprint changed; reload before saving') + else: + cursor.execute('''INSERT INTO dune_office_kit_definitions(owner_uuid,office_key,term_id,version,kit_name,color,lore_json,equipment_json,updated_at) + VALUES(%s,%s,%s,%s,%s,%s,%s,%s,CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000 AS SIGNED))''', + args + (1, data['name'], data['color'], json.dumps(data['lore']), json.dumps(equipment))) + con.commit() + except Exception: + con.rollback() + raise + return {'ok': True, 'uuid': data['uuid'], 'office': data['office'], 'term': data['term'], 'version': data['version'] + 1} diff --git a/network/server-control/test_kit_equipment.py b/network/server-control/test_kit_equipment.py new file mode 100644 index 00000000..94a815d5 --- /dev/null +++ b/network/server-control/test_kit_equipment.py @@ -0,0 +1,53 @@ +import copy +import json +from pathlib import Path +import unittest +from kit_equipment import default_equipment, validate_equipment, validate_upgrade +import player_kits + + +class KitEquipmentTest(unittest.TestCase): + def test_upgrades_reject_wrong_kind_duplicates_and_unbalanced_points(self): + value = {'policy': 'legendary-player-v1', 'points': 2, + 'bonuses': [{'piece': 'helmet', 'enchantment': 'protection', 'levels': 2}]} + self.assertEqual(validate_upgrade(value, 'legendary', 'personal_sale'), value) + for quality, kind in [('rare', 'personal_sale'), ('legendary', 'server_sale')]: + with self.assertRaises(ValueError): + validate_upgrade(value, quality, kind) + for change in [dict(value, points=3), dict(value, bonuses=value['bonuses'] * 2)]: + with self.assertRaises(ValueError): + validate_upgrade(change, 'legendary', 'personal_sale') + + def setUp(self): + self.fixtures = json.loads(Path(__file__).with_name('kit-equipment-fixtures.json').read_text()) + + def test_browser_and_native_contracts_agree(self): + self.assertEqual(validate_equipment(self.fixtures['valid']), self.fixtures['normalized']) + for value in self.fixtures['invalid']: + with self.subTest(value=value), self.assertRaises(ValueError): + validate_equipment(value) + + def test_lore_keeps_blank_lines_and_independent_piece_edits(self): + item = default_equipment({'lore': ['First', '', 'Third']}) + item['armor']['helmet']['lore'][0]['text'] = 'Edited' + self.assertEqual(item['armor']['boots']['lore'][0]['text'], 'First') + self.assertEqual(item['armor']['boots']['lore'][1]['text'], '') + self.assertFalse(item['armor']['boots']['lore'][0]['italic']) + + def test_office_blueprints_validate_equipment_without_accepting_identity_overrides(self): + body = {'uuid': '11111111-1111-4111-8111-111111111111', 'office': 'emperor', + 'term': 'current-term', 'version': 1, 'name': 'Imperial Regalia', + 'color': '#bca05b', 'lore': ['Duty endures.'], 'equipment': self.fixtures['valid']} + self.assertEqual(player_kits.validate(body)['equipment'], self.fixtures['normalized']) + invalid = copy.deepcopy(body) + invalid['buyerUuid'] = '22222222-2222-4222-8222-222222222222' + with self.assertRaises(ValueError): + player_kits.validate(invalid) + invalid = copy.deepcopy(body) + invalid['equipment']['armor']['helmet']['lore'][0]['clickEvent'] = {'action': 'run_command'} + with self.assertRaises(ValueError): + player_kits.validate(invalid) + + +if __name__ == '__main__': + unittest.main() diff --git a/website/control-panel/clan-shop.mjs b/website/control-panel/clan-shop.mjs index 1fdc62d4..febe14a0 100644 --- a/website/control-panel/clan-shop.mjs +++ b/website/control-panel/clan-shop.mjs @@ -55,7 +55,7 @@ export function createClanShop(db,settings={},dependencies={}){ if(request.method!=='POST')return reply({message:'Method not allowed'},405); if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); if(!['owner','officer'].includes(clan.clan_role))return reply({message:'Only clan owners and officers may design clan kits.'},403); - let body;try{const raw=await request.text();if(Buffer.byteLength(raw)>4096)throw Error();body=validateClanKit(JSON.parse(raw));}catch{}if(!body)return reply({message:'Use a name of 3–60 characters, a colour and up to four lore lines of 80 characters.'},400); + let body;try{const raw=await request.text();if(Buffer.byteLength(raw)>32768)throw Error();body=validateClanKit(JSON.parse(raw));}catch{}if(!body)return reply({message:'Use a name of 3–60 characters, a colour and up to four lore lines of 80 characters.'},400); try{const saved=await saveHouseKit(db,user,clan,link.minecraft_uuid,body,await blueprint(clan));return reply({ok:true,version:saved.version,blueprint:saved});}catch(error){if([403,409].includes(error.status))return reply({message:error.message},error.status);throw error;} }; diff --git a/website/control-panel/house-tailor.mjs b/website/control-panel/house-tailor.mjs index 3619583f..96977e06 100644 --- a/website/control-panel/house-tailor.mjs +++ b/website/control-panel/house-tailor.mjs @@ -1,3 +1,5 @@ +import {validateKitEquipment} from './public/kit-design-model.mjs'; +import {kitEquipmentRegister,saveKitEquipment} from './kit-equipment-store.mjs'; import {randomUUID} from 'node:crypto'; export const HOUSE_QUALITIES=Object.freeze(['common','uncommon','rare','very_rare','legendary']); @@ -23,14 +25,15 @@ export async function initializeHouseTailor(db){ const plain=(value,limit)=>typeof value==='string'&&value.length<=limit&&!/[<>§\x00-\x1f\x7f]/.test(value); export function validateHouseKit(body){ - const fields=['name','color','lore','version','shopPriceDunemarks','quality','itemNames']; + const fields=['name','color','lore','version','shopPriceDunemarks','quality','itemNames','equipment']; if(!body||typeof body!=='object'||Array.isArray(body)||Object.keys(body).some(key=>!fields.includes(key)))return null; + if(body.equipment!==undefined){try{validateKitEquipment(body.equipment);}catch{return null;}} const quality=body.quality??'uncommon'; if(!HOUSE_QUALITIES.includes(quality)||!plain(body.name,60)||body.name.trim().length<3||typeof body.color!=='string'||!/^#[a-f0-9]{6}$/i.test(body.color)||!Array.isArray(body.lore)||body.lore.length>4||body.lore.some(line=>!plain(line,80))||!Number.isSafeInteger(body.version)||body.version<0||body.version>2147483646)return null; if(body.shopPriceDunemarks!==undefined&&(!Number.isSafeInteger(body.shopPriceDunemarks)||body.shopPriceDunemarks1000000))return null; const names=body.itemNames??{}; if(!names||typeof names!=='object'||Array.isArray(names)||Object.keys(names).some(key=>!['helmet','chestplate','leggings','boots'].includes(key))||Object.values(names).some(value=>!plain(value,64))||(!['rare','very_rare','legendary'].includes(quality)&&Object.keys(names).length))return null; - return {name:body.name.trim(),color:body.color.toUpperCase(),lore:body.lore.map(line=>line.trim()),version:body.version,quality,itemNames:Object.fromEntries(Object.entries(names).map(([key,value])=>[key,value.trim()])),shopPriceDunemarks:body.shopPriceDunemarks}; + return {...(body.equipment!==undefined?{equipment:validateKitEquipment(body.equipment)}:{}),name:body.name.trim(),color:body.color.toUpperCase(),lore:body.lore.map(line=>line.trim()),version:body.version,quality,itemNames:Object.fromEntries(Object.entries(names).map(([key,value])=>[key,value.trim()])),shopPriceDunemarks:body.shopPriceDunemarks}; } const ownerRank=`EXISTS (SELECT 1 FROM site_accounts a WHERE a.id=m.user_id AND @@ -43,7 +46,7 @@ function fence(quality,userId,uuid,clanId){ return{sql:base+` AND (EXISTS (SELECT 1 FROM site_clan_kit_quality_unlocks uq WHERE uq.clan_id=c.id AND uq.quality=?) OR (EXISTS (SELECT 1 FROM site_kit_design_unlocks eu WHERE eu.user_id=m.user_id AND eu.quality=?) AND ${ownerRank})))`,values:[userId,uuid,clanId,quality,quality]}; } -const serialized=row=>row?{id:row.id,name:row.name,color:row.color,lore:JSON.parse(row.lore_json),itemNames:JSON.parse(row.item_names_json||'{}'),version:Number(row.version),quality:row.quality,shopPriceDunemarks:Number(row.shop_price_cents)/100,pieces:4}:null; +const serialized=row=>row?{id:row.id,name:row.name,color:row.color,lore:JSON.parse(row.lore_json),equipment:row.equipment,itemNames:JSON.parse(row.item_names_json||'{}'),version:Number(row.version),quality:row.quality,shopPriceDunemarks:Number(row.shop_price_cents)/100,pieces:4}:null; export async function houseTailorState(db,user,clan,legacy){ const [{results:rows},{results:unlocks},{results:overrides}]=await Promise.all([ @@ -53,10 +56,11 @@ export async function houseTailorState(db,user,clan,legacy){ AND (a.role='owners' OR EXISTS (SELECT 1 FROM cp_account_ranks ar WHERE ar.user_id=a.id AND ar.rank_key='owners')) AND EXISTS (SELECT 1 FROM cp_ranks r WHERE r.rank_key='owners' AND r.kind='access' AND r.rank_level>0)`).bind(user.id).all() ]); + const equipment=await kitEquipmentRegister(db,[...rows.map(row=>({...row,lore:JSON.parse(row.lore_json),itemNames:JSON.parse(row.item_names_json||'{}')})),...(legacy?[legacy]:[])]);for(const row of rows)row.equipment=equipment.get(row.id); const allowed=new Set(['common','uncommon',...unlocks.map(row=>row.quality),...overrides.map(row=>row.quality)]),stored=new Map(rows.map(row=>[row.quality,row])); return {stored,tiers:HOUSE_QUALITIES.map(quality=>({quality,unlocked:allowed.has(quality),minimumShopPriceDunemarks:HOUSE_MINIMUM_DM[quality],isLegacyGameKit:quality==='uncommon', // The original Uncommon row remains the native consumer's authority. - blueprint:quality==='uncommon'?(legacy?{...legacy,quality:'uncommon',itemNames:{}}:null):serialized(stored.get(quality))}))}; + blueprint:quality==='uncommon'?(legacy?{...legacy,equipment:equipment.get(legacy.id),quality:'uncommon',itemNames:{}}:null):serialized(stored.get(quality))}))}; } export class HouseKitConflict extends Error{constructor(message='Clan membership, quality access or design changed. Refresh before saving.'){super(message);this.status=409;}} @@ -69,13 +73,15 @@ export async function saveHouseKit(db,user,clan,uuid,body,legacy){ const guard=fence(body.quality,user.id,uuid,clan.id),values=[body.name,body.color,JSON.stringify(body.lore),JSON.stringify(body.itemNames),price*100,version,now,user.id]; const update=stored?db.prepare(`UPDATE site_clan_kit_designs SET name=?,color=?,lore_json=?,item_names_json=?,shop_price_cents=?,version=?,updated_at=?,updated_by=? WHERE id=? AND clan_id=? AND quality=? AND version=? AND ${guard.sql}`).bind(...values,id,clan.id,body.quality,Number(stored.version),...guard.values) :db.prepare(`INSERT INTO site_clan_kit_designs(id,clan_id,quality,name,color,lore_json,item_names_json,shop_price_cents,version,updated_at,updated_by) SELECT ?,?,?,?,?,?,?,?,?,?,? WHERE ${guard.sql}`).bind(id,clan.id,body.quality,...values,...guard.values); + let savedEquipment; const checked=statement=>({async run(c){const result=await statement.run(c);if(result.meta.changes!==1)throw new HouseKitConflict();return result;}}),operations=[checked(update)]; if(body.quality==='uncommon'){ const mirror=current?db.prepare(`UPDATE site_clan_kits SET name=?,color=?,lore_json=?,shop_price_cents=?,version=?,updated_at=?,updated_by=? WHERE id=? AND clan_id=? AND version=? AND ${guard.sql}`).bind(body.name,body.color,JSON.stringify(body.lore),price*100,version,now,user.id,id,clan.id,body.version,...guard.values) :db.prepare(`INSERT INTO site_clan_kits(id,clan_id,name,color,lore_json,shop_price_cents,version,updated_at,updated_by) SELECT ?,?,?,?,?,?,?,?,? WHERE ${guard.sql}`).bind(id,clan.id,body.name,body.color,JSON.stringify(body.lore),price*100,version,now,user.id,...guard.values); operations.push(checked(mirror)); } + operations.push({async run(c){savedEquipment=await saveKitEquipment(async(sql,values)=>(await c.execute(sql,values))[0],id,version,body.equipment,body);return {meta:{changes:1}};}}); operations.push(db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'clan-kit-design',JSON.stringify({clanId:clan.id,quality:body.quality,kitId:id,version}),now)); try{await db.batch(operations);}catch(error){if(error.code==='ER_DUP_ENTRY'||error.code?.startsWith('SQLITE_CONSTRAINT'))throw new HouseKitConflict();throw error;} - return {id,quality:body.quality,name:body.name,color:body.color,lore:body.lore,itemNames:body.itemNames,version,shopPriceDunemarks:price,pieces:4}; + return {id,equipment:savedEquipment,quality:body.quality,name:body.name,color:body.color,lore:body.lore,itemNames:body.itemNames,version,shopPriceDunemarks:price,pieces:4}; } diff --git a/website/control-panel/imperial-atelier.mjs b/website/control-panel/imperial-atelier.mjs index e9f2565c..283a5554 100644 --- a/website/control-panel/imperial-atelier.mjs +++ b/website/control-panel/imperial-atelier.mjs @@ -1,3 +1,4 @@ +import {validateKitEquipment} from './public/kit-design-model.mjs'; import {randomUUID} from 'node:crypto'; import {identity} from '../node/auth.mjs'; import {accessFor} from '../node/permissions.mjs'; @@ -7,10 +8,10 @@ export function createImperialAtelier(db,settings={},dependencies={}){const auth const url=new URL(request.url);if(url.search)return reply({message:'Player overrides are not accepted.'},400);const user=await auth(request);if(!user)return reply({message:'Sign in first.'},401);if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403); const link=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first();if(!link)return reply({linked:false,canDesign:false,offices:[]});const player=link.minecraft_uuid;if(!uuid.test(player))return reply({message:'Verified game identity unavailable.'},503); try{if((settings.SERVER_CONTROL_TOKEN||'').length<64)throw Error();let path='/kits/player?uuid='+encodeURIComponent(player),body; - if(request.method==='POST'){if(request.headers.get('origin')!==new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin)return reply({message:'Origin rejected.'},403);let b;try{const text=await request.text();if(Buffer.byteLength(text)>8192)throw Error();b=JSON.parse(text);}catch{return reply({message:'Invalid design.'},400);}const plain=(v,n)=>typeof v==='string'&&v.length>0&&v.length<=n&&!/[<>§\x00-\x1f\x7f]/.test(v);if(!plain(b.office,64)||!plain(b.term,200)||!Number.isSafeInteger(b.version)||b.version<0||!plain(b.name,64)||!/^#[a-f0-9]{6}$/i.test(b.color)||!Array.isArray(b.lore)||b.lore.length>6||b.lore.some(l=>!plain(l,120)))return reply({message:'Check the kit name, colour and lore.'},400);body={uuid:player,office:b.office,term:b.term,version:b.version,name:b.name,color:b.color,lore:b.lore};path='/kits/player/definition';await db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'office-kit-design-requested',JSON.stringify({office:b.office,term:b.term,version:b.version}),Date.now()).run(); + if(request.method==='POST'){if(request.headers.get('origin')!==new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin)return reply({message:'Origin rejected.'},403);let b;try{const text=await request.text();if(Buffer.byteLength(text)>32768)throw Error();b=JSON.parse(text);}catch{return reply({message:'Invalid design.'},400);}const plain=(v,n)=>typeof v==='string'&&v.length>0&&v.length<=n&&!/[<>§\x00-\x1f\x7f]/.test(v);if(!plain(b.office,64)||!plain(b.term,200)||!Number.isSafeInteger(b.version)||b.version<0||!plain(b.name,64)||!/^#[a-f0-9]{6}$/i.test(b.color)||!Array.isArray(b.lore)||b.lore.length>6||b.lore.some(l=>!plain(l,120)))return reply({message:'Check the kit name, colour and lore.'},400);let equipment;if(b.equipment!==undefined){try{equipment=validateKitEquipment(b.equipment);}catch{return reply({message:'Check the armour, banner and item lore.'},400);}}body={...(equipment?{equipment}:{}),uuid:player,office:b.office,term:b.term,version:b.version,name:b.name,color:b.color,lore:b.lore};path='/kits/player/definition';await db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'office-kit-design-requested',JSON.stringify({office:b.office,term:b.term,version:b.version}),Date.now()).run(); }else if(request.method!=='GET')return reply({message:'Method not allowed.'},405); const r=await(dependencies.fetcher||fetch)('http://127.0.0.1:15433'+path,{method:body?'POST':'GET',headers:{Authorization:'Bearer '+settings.SERVER_CONTROL_TOKEN,...(body?{'Content-Type':'application/json'}:{})},...(body?{body:JSON.stringify(body)}:{}),signal:AbortSignal.timeout(8000)});const d=await r.json();if(r.status===403)return reply({message:'This office is no longer held by your linked game account.'},403);if(r.status===409)return reply({message:'The office term or design changed. Refresh before saving.'},409);if(!r.ok)throw Error(); if(body){if(d.ok!==true||d.uuid?.toLowerCase()!==player.toLowerCase()||d.office!==body.office||d.term!==body.term||d.version!==body.version+1)throw Error();return reply({ok:true,version:d.version});} - if(d.playerUuid?.toLowerCase()!==player.toLowerCase()||typeof d.canDesign!=='boolean'||!Array.isArray(d.offices)||d.offices.length>20)throw Error();return reply({linked:true,canDesign:d.canDesign,offices:d.offices.map(o=>({office:o.office,term:o.term,version:o.version,name:o.name,color:o.color,lore:o.lore,quality:o.quality}))}); + if(d.playerUuid?.toLowerCase()!==player.toLowerCase()||typeof d.canDesign!=='boolean'||!Array.isArray(d.offices)||d.offices.length>20)throw Error();return reply({linked:true,canDesign:d.canDesign,offices:d.offices.map(o=>({office:o.office,term:o.term,version:o.version,name:o.name,color:o.color,lore:o.lore,quality:o.quality,equipment:o.equipment?validateKitEquipment(o.equipment):undefined}))}); }catch{return reply({message:'The Imperial Atelier is temporarily unavailable. Refresh to check your current office.'},503);} };} diff --git a/website/control-panel/kit-equipment-store.mjs b/website/control-panel/kit-equipment-store.mjs new file mode 100644 index 00000000..e46a91fe --- /dev/null +++ b/website/control-panel/kit-equipment-store.mjs @@ -0,0 +1,17 @@ +import {defaultKitEquipment,remakeKitEquipment,validateKitEquipment} from './public/kit-design-model.mjs'; + +export async function kitEquipmentRegister(db,designs){ + if(!designs.length)return new Map(); + const {results}=await db.prepare('SELECT kit_id,blueprint_version,equipment_json FROM site_kit_equipment WHERE kit_id IN ('+designs.map(()=>'?').join(',')+')').bind(...designs.map(d=>d.id)).all(); + const rows=new Map(results.map(r=>[r.kit_id,r])); + return new Map(designs.map(d=>{const row=rows.get(d.id);return[d.id,row&&Number(row.blueprint_version)===Number(d.version)?validateKitEquipment(JSON.parse(row.equipment_json)):remakeKitEquipment(d)];})); +} + +// Called in the same transaction as the revision update and its audit event. +export async function saveKitEquipment(query,kitId,version,equipment,legacy){ + let saved=equipment; + if(saved===undefined){const rows=await query('SELECT equipment_json FROM site_kit_equipment WHERE kit_id=? AND blueprint_version=?',[kitId,version-1]);saved=rows[0]?JSON.parse(rows[0].equipment_json):defaultKitEquipment(legacy);} + saved=validateKitEquipment(saved); + await query('INSERT INTO site_kit_equipment(kit_id,blueprint_version,equipment_json) VALUES(?,?,?) ON DUPLICATE KEY UPDATE blueprint_version=VALUES(blueprint_version),equipment_json=VALUES(equipment_json)',[kitId,version,JSON.stringify(saved)]); + return saved; +} diff --git a/website/control-panel/kit-studio.mjs b/website/control-panel/kit-studio.mjs index 1feaf46a..e043d41a 100644 --- a/website/control-panel/kit-studio.mjs +++ b/website/control-panel/kit-studio.mjs @@ -1,3 +1,5 @@ +import {validateKitEquipment} from './public/kit-design-model.mjs'; +import {kitEquipmentRegister,saveKitEquipment} from './kit-equipment-store.mjs'; import {randomUUID} from 'node:crypto'; import {identity} from '../node/auth.mjs'; import {accessFor} from '../node/permissions.mjs'; @@ -13,8 +15,8 @@ export function validateStudioRequest(b){ return validated&&listing?{...validated,action:'save_publish',listingVersion,shopType,priceCents}:null; } if(['archive','restore'].includes(b?.action))return exact(b,['action','quality','version'])&&tiers.includes(b.quality)&&kinds.includes(b.kind||'personal_sale')&&Number.isSafeInteger(b.version)&&b.version>0?{...b,kind:b.kind||'personal_sale'}:null; -const itemNames=b?.itemNames;if(itemNames!==undefined&&(!['rare','very_rare','legendary'].includes(b?.quality)||!itemNames||typeof itemNames!=='object'||Array.isArray(itemNames)||Object.keys(itemNames).some(k=>!['helmet','chestplate','leggings','boots'].includes(k))||Object.values(itemNames).some(v=>typeof v!=='string'||v.trim().length>64||/[<>§\x00-\x1f\x7f]/.test(v))))return null;const kind=b?.kind||'personal_sale';if(!kinds.includes(kind)||b?.officeKey!==undefined&&(typeof b.officeKey!=='string'||b.officeKey.length>96||/[<>§\x00-\x1f\x7f]/.test(b.officeKey)))return null;if(kind==='personal_sale'&&b?.officeKey!==undefined)return null; - if(b?.action==='save'&&exact(b,['action','quality','version','name','color','lore',...(itemNames!==undefined?['itemNames']:[])])&&tiers.includes(b.quality)&&Number.isSafeInteger(b.version)&&b.version>=0&&typeof b.name==='string'&&b.name.trim().length>=3&&b.name.trim().length<=64&&!/[\x00-\x1f\x7f§]/.test(b.name)&&/^#[a-f0-9]{6}$/i.test(b.color||'')&&Array.isArray(b.lore)&&b.lore.length<=4&&b.lore.every(s=>typeof s==='string'&&s.length<=80&&!/[\x00-\x1f\x7f§]/.test(s)))return{...b,kind,name:b.name.trim(),color:b.color.toUpperCase(),lore:b.lore.map(s=>s.trim())}; +const equipment=b?.equipment;if(equipment!==undefined){try{validateKitEquipment(equipment);}catch{return null;}}const itemNames=b?.itemNames;if(itemNames!==undefined&&(!['rare','very_rare','legendary'].includes(b?.quality)||!itemNames||typeof itemNames!=='object'||Array.isArray(itemNames)||Object.keys(itemNames).some(k=>!['helmet','chestplate','leggings','boots'].includes(k))||Object.values(itemNames).some(v=>typeof v!=='string'||v.trim().length>64||/[<>§\x00-\x1f\x7f]/.test(v))))return null;const kind=b?.kind||'personal_sale';if(!kinds.includes(kind)||b?.officeKey!==undefined&&(typeof b.officeKey!=='string'||b.officeKey.length>96||/[<>§\x00-\x1f\x7f]/.test(b.officeKey)))return null;if(kind==='personal_sale'&&b?.officeKey!==undefined)return null; + if(b?.action==='save'&&exact(b,['action','quality','version','name','color','lore',...(itemNames!==undefined?['itemNames']:[]),...(equipment!==undefined?['equipment']:[])])&&tiers.includes(b.quality)&&Number.isSafeInteger(b.version)&&b.version>=0&&typeof b.name==='string'&&b.name.trim().length>=3&&b.name.trim().length<=64&&!/[<>\x00-\x1f\x7f§]/.test(b.name)&&/^#[a-f0-9]{6}$/i.test(b.color||'')&&Array.isArray(b.lore)&&b.lore.length<=4&&b.lore.every(s=>typeof s==='string'&&s.length<=80&&!/[\x00-\x1f\x7f§]/.test(s)))return{...b,kind,name:b.name.trim(),color:b.color.toUpperCase(),lore:b.lore.map(s=>s.trim())}; if(['publish','unpublish'].includes(b?.action)&&exact(b,['action','quality','blueprintVersion','listingVersion','shopType','priceCents'])&&tiers.includes(b.quality)&&Number.isSafeInteger(b.blueprintVersion)&&b.blueprintVersion>0&&Number.isSafeInteger(b.listingVersion)&&b.listingVersion>=0&&(kind==='personal_sale'?['player','clan'].includes(b.shopType):b.shopType===({official_sale:'official',faction_sale:'faction',server_sale:'server'})[kind])&&Number.isSafeInteger(b.priceCents)&&b.priceCents>=(kind==='personal_sale'?minimum[tiers.indexOf(b.quality)]:1)&&b.priceCents<=100000000)return{...b,kind}; return null; } @@ -28,10 +30,11 @@ export function createKitStudio(db,settings={},dependencies={}){const authentica const upgradeReady=(await db.prepare("SELECT setting_value FROM website_settings WHERE setting_key='kit-legendary-upgrade-delivery-ready'").first())?.setting_value==='true'; if(request.method==='GET'){ const {results:designs}=await db.prepare('SELECT id,quality,commerce_kind,name,color,lore_json,item_names_json,upgrade_json,version,active FROM site_kit_blueprints WHERE owner_user_id=?').bind(user.id).all(); + const equipmentRegister=await kitEquipmentRegister(db,designs.map(d=>({...d,lore:JSON.parse(d.lore_json),itemNames:typeof d.item_names_json==='string'?JSON.parse(d.item_names_json):d.item_names_json||{}}))); const {results:listings}=await db.prepare('SELECT l.id,l.clan_id,l.office_key,l.office_term,l.faction_id,l.blueprint_id,l.blueprint_version,l.shop_type,l.price_cents,l.version,l.published,l.active FROM site_kit_listings l JOIN site_kit_blueprints b ON b.id=l.blueprint_id WHERE b.owner_user_id=?').bind(user.id).all(); const clan=await db.prepare("SELECT c.id,c.name,m.clan_role FROM site_clan_members m JOIN site_clans c ON c.id=m.clan_id AND c.active=1 JOIN site_game_links g ON g.user_id=m.user_id AND g.minecraft_uuid=m.minecraft_uuid WHERE m.user_id=? AND m.clan_role IN ('owner','officer')").bind(user.id).first(); - return reply({tiers:arc.chapters.map((c,i)=>({quality:tiers[i],unlocked:serverMode||c.unlocked||override.has(tiers[i]),minimumPriceCents:minimum[i],template:c.kitTemplate})),serverMode,nonPersonalPublishingEnabled:serverMode||enabled?.setting_value==='true',canManageServer:protectedAccess,offices:offices.map(o=>({office:o.office,term:o.term})),designs:designs.filter(d=>serverMode?d.commerce_kind==='server_sale':d.commerce_kind!=='server_sale').map(({lore_json,item_names_json,upgrade_json,...d})=>({...d,upgrade:typeof upgrade_json==='string'?JSON.parse(upgrade_json):upgrade_json||null,version:Number(d.version),lore:JSON.parse(lore_json),itemNames:typeof item_names_json==='string'?JSON.parse(item_names_json):item_names_json||{}})),listings:listings.map(l=>({...l,version:Number(l.version),blueprint_version:Number(l.blueprint_version),price_cents:Number(l.price_cents)})),clan:clan?{id:clan.id,name:clan.name}:null});} - let b;try{const raw=await request.text();if(Buffer.byteLength(raw)>4096)throw Error();b=validateStudioRequest(JSON.parse(raw));}catch{}if(!b)return reply({message:'Use a valid design, revision and tier price. Names support 3–64 characters and lore supports four lines of 80 characters.'},400);if(['publish','save_publish'].includes(b.action)&&b.kind!=='personal_sale'&&b.kind!=='server_sale'&&enabled?.setting_value!=='true')return reply({message:'This kit category is still being connected. Save your draft; publishing will open after the game-side rollout.'},409);if(serverMode?b.kind!=='server_sale':b.kind==='server_sale')return reply({message:'Use the protected server-kit controls for this design.'},403);if(b.kind==='personal_sale'&&!override.has(b.quality)&&!arc.chapters[tiers.indexOf(b.quality)].unlocked)return reply({message:'Complete the previous kit quest to unlock this rarity.'},403); + return reply({tiers:arc.chapters.map((c,i)=>({quality:tiers[i],unlocked:serverMode||c.unlocked||override.has(tiers[i]),minimumPriceCents:minimum[i],template:c.kitTemplate})),serverMode,nonPersonalPublishingEnabled:serverMode||enabled?.setting_value==='true',canManageServer:protectedAccess,offices:offices.map(o=>({office:o.office,term:o.term})),designs:designs.filter(d=>serverMode?d.commerce_kind==='server_sale':d.commerce_kind!=='server_sale').map(({lore_json,item_names_json,upgrade_json,...d})=>({...d,equipment:equipmentRegister.get(d.id),upgrade:typeof upgrade_json==='string'?JSON.parse(upgrade_json):upgrade_json||null,version:Number(d.version),lore:JSON.parse(lore_json),itemNames:typeof item_names_json==='string'?JSON.parse(item_names_json):item_names_json||{}})),listings:listings.map(l=>({...l,version:Number(l.version),blueprint_version:Number(l.blueprint_version),price_cents:Number(l.price_cents)})),clan:clan?{id:clan.id,name:clan.name}:null});} + let b;try{const raw=await request.text();if(Buffer.byteLength(raw)>32768)throw Error();b=validateStudioRequest(JSON.parse(raw));}catch{}if(!b)return reply({message:'Use a valid design, revision and tier price. Names support 3–64 characters and lore supports four lines of 80 characters.'},400);if(['publish','save_publish'].includes(b.action)&&b.kind!=='personal_sale'&&b.kind!=='server_sale'&&enabled?.setting_value!=='true')return reply({message:'This kit category is still being connected. Save your draft; publishing will open after the game-side rollout.'},409);if(serverMode?b.kind!=='server_sale':b.kind==='server_sale')return reply({message:'Use the protected server-kit controls for this design.'},403);if(b.kind==='personal_sale'&&!override.has(b.quality)&&!arc.chapters[tiers.indexOf(b.quality)].unlocked)return reply({message:'Complete the previous kit quest to unlock this rarity.'},403); if(['save','save_publish','restore'].includes(b.action)&&b.kind==='official_sale'&&!offices.length)return reply({message:'A current elected office is required for official kit designs.'},403);if(['save','save_publish','restore'].includes(b.action)&&b.kind==='faction_sale'&&!offices.some(o=>/^house-leader:(Fremen|Harkonnen|Corrino|Atreides|Ordos)$/.test(o.office)))return reply({message:'Only a current faction leader can design faction kits.'},403); let officeKey=null,officeTerm=null,factionId=null;if(['official_sale','faction_sale'].includes(b.kind)&&['publish','save_publish'].includes(b.action)){const office=offices.find(o=>o.office===b.officeKey);if(!office||b.kind==='faction_sale'&&!/^house-leader:(Fremen|Harkonnen|Corrino|Atreides|Ordos)$/.test(office.office))return reply({message:'Your current elected office could not authorize this listing.'},403);officeKey=office.office;officeTerm=office.term;if(b.kind==='faction_sale')factionId=officeKey.split(':')[1].toLowerCase();} try{await db.batch([{async run(c){const query=async(sql,v=[]) =>(await c.execute(sql,v))[0];if(serverMode){const actual=await query('SELECT role FROM site_accounts WHERE id=? FOR SHARE',[actor.id]);const extra=await query('SELECT rank_key FROM cp_account_ranks WHERE user_id=? FOR SHARE',[actor.id]);if(!protectedRanks.has(actual[0]?.role)&&!extra.some(r=>protectedRanks.has(r.rank_key)))throw Error('conflict');}const locked=await query('SELECT minecraft_uuid,linked_at FROM site_game_links WHERE user_id=? FOR SHARE',[user.id]);if(locked[0]?.minecraft_uuid?.toLowerCase()!==link.minecraft_uuid.toLowerCase())throw Error('conflict');const rows=await query('SELECT id,version,upgrade_json,active FROM site_kit_blueprints WHERE owner_user_id=? AND quality=? AND commerce_kind=? FOR UPDATE',[user.id,b.quality,b.kind]);if(rows.length>1)throw Error('conflict');const current=rows[0];const now=Date.now();let designId=current?.id; @@ -40,6 +43,7 @@ export function createKitStudio(db,settings={},dependencies={}){const authentica if(['archive','restore'].includes(b.action)){ if(!current||Boolean(Number(current.active))!==(b.action==='archive'))throw Error('conflict'); await query('UPDATE site_kit_blueprints SET active=?,version=version+1,updated_at=? WHERE id=?',[b.action==='restore'?1:0,now,current.id]); + await query('UPDATE site_kit_equipment SET blueprint_version=? WHERE kit_id=? AND blueprint_version=?',[Number(current.version)+1,current.id,Number(current.version)]); if(b.action==='archive')await query('UPDATE site_kit_listings SET active=0,published=0,version=version+1,updated_at=? WHERE blueprint_id=? AND (active=1 OR published=1)',[now,current.id]); }else{ if(current&&Number(current.active)===0)throw Error('archived'); @@ -61,6 +65,7 @@ export function createKitStudio(db,settings={},dependencies={}){const authentica if(b.action==='save')await query('UPDATE site_kit_listings SET published=0,version=version+1,updated_at=? WHERE blueprint_id=? AND published=1',[now,current.id]); }else{designId=randomUUID();await query('INSERT INTO site_kit_blueprints(id,owner_user_id,quality,name,color,lore_json,item_names_json,version,active,created_at,updated_at,commerce_kind) VALUES(?,?,?,?,?,?,?,1,1,?,?,?)',[designId,user.id,b.quality,b.name,b.color,JSON.stringify(b.lore),JSON.stringify(b.itemNames||{}),now,now,b.kind]);} } + if(['save','save_publish'].includes(b.action))await saveKitEquipment(query,designId,version,b.equipment,b); if(['publish','save_publish','unpublish'].includes(b.action)){ if(!designId)throw Error('conflict'); if(listing){const updated=b.action==='unpublish'?await query('UPDATE site_kit_listings SET version=version+1,published=0,updated_at=? WHERE id=? AND version=? AND published=1',[now,listing.id,b.listingVersion]):await query('UPDATE site_kit_listings SET blueprint_version=?,price_cents=?,version=version+1,published=1,active=1,updated_at=?,office_key=?,office_term=?,faction_id=? WHERE id=? AND version=?',[version,b.priceCents,now,officeKey,officeTerm,factionId,listing.id,b.listingVersion]);if(updated.affectedRows!==1)throw Error('conflict');} diff --git a/website/control-panel/public/cp-v2/cp-v2-kit-directorate.mjs b/website/control-panel/public/cp-v2/cp-v2-kit-directorate.mjs index 0dd14d1e..83447314 100644 --- a/website/control-panel/public/cp-v2/cp-v2-kit-directorate.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-kit-directorate.mjs @@ -1,3 +1,5 @@ +import {createKitGenerator} from '../kit-generator.mjs'; +import {validateKitEquipment} from '../kit-design-model.mjs'; import {createCPV2Page,element as el} from './cp-v2-page-template.mjs'; const qualities=['common','uncommon','rare','very_rare','legendary']; const title=value=>String(value).replaceAll('_',' ').replace(/\b\w/g,c=>c.toUpperCase()); @@ -9,8 +11,8 @@ export function serverKitPayload(action,input,design,listing){ } if(['save','save_publish'].includes(action)){ const name=String(input.name||'').trim(),color=String(input.color||'').toUpperCase(),lore=String(input.lore||'').split('\n').map(s=>s.trim()).filter(Boolean); - if(name.length<3||name.length>64||/[\x00-\x1f\x7f§]/.test(name)||!/^#[A-F0-9]{6}$/.test(color)||lore.length>4||lore.some(s=>s.length>80||/[\x00-\x1f\x7f§]/.test(s)))throw Error('Use a name of 3–64 characters, a colour and up to four lore lines of 80 characters.'); - Object.assign(base,{version:design?.version||0,name,color,lore}); + if(name.length<3||name.length>64||/[<>\x00-\x1f\x7f§]/.test(name)||!/^#[A-F0-9]{6}$/.test(color)||lore.length>4||lore.some(s=>s.length>80||/[\x00-\x1f\x7f§]/.test(s)))throw Error('Use a name of 3–64 characters, a colour and up to four lore lines of 80 characters.'); + Object.assign(base,{version:design?.version||0,name,color,lore,...(input.equipment?{equipment:validateKitEquipment(input.equipment)}:{})}); if(['rare','very_rare','legendary'].includes(input.quality))base.itemNames=Object.fromEntries(['helmet','chestplate','leggings','boots'].map(k=>[k,String(input[k]||'').trim()])); if(base.itemNames&&Object.values(base.itemNames).some(v=>v.length>64||/[<>§\x00-\x1f\x7f]/.test(v)))throw Error('Armour-piece names support up to 64 plain characters.'); } @@ -32,14 +34,14 @@ export function serverKitRegister(data){ return data; } export function mountKitDirectorate(host,id,{fetcher=fetch}={}){ - let active=true,state=null,selected=null,selectedQuality='common',busy=false,uncertain=false,controller=null; + let active=true,state=null,selected=null,selectedQuality='common',busy=false,uncertain=false,controller=null,generator=null; const status=el('p','Loading the protected server-kit workshop…','cp-v2-news-status');status.setAttribute('role','status'); const register=el('section',undefined,'cp-v2-company-section'),editor=el('section',undefined,'cp-v2-company-section'),catalogue=el('section',undefined,'cp-v2-company-section'); const search=el('input');search.type='search';search.placeholder='Search server kits';search.setAttribute('aria-label','Search server kits'); const refresh=el('button','Refresh workshop');refresh.type='button';const tools=el('div',undefined,'cp-v2-company-actions');tools.append(search,refresh);const rows=el('div');register.append(tools,rows); const form=el('form',undefined,'cp-v2-news-form'),fields={}; for(const [key,label,type]of [['quality','Rarity','select'],['name','Kit name','text'],['color','Armour colour','color'],['lore','Lore · four lines maximum','textarea'],['helmet','Helmet name · Rare and above','text'],['chestplate','Chestplate name · Rare and above','text'],['leggings','Leggings name · Rare and above','text'],['boots','Boots name · Rare and above','text'],['price','Sale price · DM','text']]){ - const labelNode=el('label',label),input=el(['select','textarea'].includes(type)?type:'input');if(!['select','textarea'].includes(type))input.type=type;input.name=key;fields[key]=input;labelNode.append(input);form.append(labelNode); + const labelNode=el('label',label),input=el(['select','textarea'].includes(type)?type:'input');if(!['select','textarea'].includes(type))input.type=type;input.name=key;fields[key]=input;labelNode.append(input);if(!['quality','price'].includes(key))labelNode.style.display='none';form.append(labelNode); } for(const q of qualities){const option=el('option',title(q));option.value=q;fields.quality.append(option);}fields.name.maxLength=64;fields.lore.maxLength=324;fields.price.inputMode='decimal'; const action=el('select');action.setAttribute('aria-label','Kit operation');for(const [value,label]of [['save','Save draft'],['save_publish','Save and publish'],['publish','Publish saved revision'],['unpublish','Withdraw listing'],['archive','Archive design'],['restore','Restore as draft']]){const o=el('option',label);o.value=value;action.append(o);} @@ -49,11 +51,11 @@ export function mountKitDirectorate(host,id,{fetcher=fetch}={}){ function lock(){search.disabled=!state;for(const control of form.querySelectorAll('input,select,textarea,button'))control.disabled=busy||uncertain||!state;submit.disabled=submit.disabled||!consent.checked;} function table(target,headers,data){const t=el('table',undefined,'cp-v2-company-table'),head=el('thead'),hr=el('tr'),body=el('tbody');for(const label of headers){const th=el('th',label);th.scope='col';hr.append(th);}head.append(hr);for(const values of data){const tr=el('tr');for(const value of values){const td=el('td');if(typeof value==='object')td.append(value);else td.textContent=String(value??'—');tr.append(td);}body.append(tr);}if(!data.length){const tr=el('tr'),td=el('td','No matching records.');td.colSpan=headers.length;tr.append(td);body.append(tr);}t.append(head,body);const wrap=el('div',undefined,'cp-v2-company-table-wrap');wrap.append(t);target.replaceChildren(wrap);} function listingFor(design){return state?.listings.find(l=>l.blueprint_id===design?.id&&l.shop_type==='server');} - function edit(q){if(form.dataset.dirty==='true'&&!window.confirm('Discard unsaved changes?')){fields.quality.value=selectedQuality;return;}selectedQuality=q;selected=state.designs.find(d=>d.quality===q);const template=state.tiers.find(t=>t.quality===q)?.template||{},design=selected||template;fields.quality.value=q;fields.name.value=design.name||'';fields.color.value=design.color||'#385B49';fields.lore.value=(design.lore||[]).join('\n');for(const k of ['helmet','chestplate','leggings','boots'])fields[k].value=design.itemNames?.[k]||'';fields.price.value=String((listingFor(selected)?.price_cents||100)/100);consent.checked=false;action.value=Number(selected?.active)===0?'restore':'save';form.dataset.dirty='false';result.textContent=selected?'Editing saved revision '+selected.version:'New '+title(q)+' design';activate('server-kit-editor');lock();} + function edit(q){if((form.dataset.dirty==='true'||generator?.isDirty())&&!window.confirm('Discard unsaved changes?')){fields.quality.value=selectedQuality;return;}selectedQuality=q;selected=state.designs.find(d=>d.quality===q);const template=state.tiers.find(t=>t.quality===q)?.template||{},design=selected||template;fields.quality.value=q;fields.name.value=design.name||'';fields.color.value=design.color||'#385B49';fields.lore.value=(design.lore||[]).join('\n');for(const k of ['helmet','chestplate','leggings','boots'])fields[k].value=design.itemNames?.[k]||'';fields.price.value=String((listingFor(selected)?.price_cents||100)/100);consent.checked=false;action.value=Number(selected?.active)===0?'restore':'save';form.dataset.dirty='false';generator=createKitGenerator({kind:'server_sale',context:'Imperial Kit Directorate',quality:q,initial:design,onSave:async()=>{throw Error('Use Confirm operation below to save this design.');}});generator.submitButton.hidden=true;editor.replaceChildren(generator.element,form);result.textContent=selected?'Editing saved revision '+selected.version:'New '+title(q)+' design';activate('server-kit-editor');lock();} function render(){if(!state)return;const query=search.value.trim().toLowerCase();table(rows,['Rarity','Design','Revision','Publication','Details'],state.tiers.filter(t=>[t.quality,state.designs.find(d=>d.quality===t.quality)?.name].join(' ').toLowerCase().includes(query)).map(t=>{const d=state.designs.find(d=>d.quality===t.quality),l=listingFor(d),button=el('button',d?'Edit design':'Create design');button.type='button';button.onclick=()=>edit(t.quality);return[title(t.quality),d?.name||'Not designed',d?.version||'—',d&&Number(d.active)===0?'Archived':l&&Number(l.published)===1&&Number(l.active)===1&&l.blueprint_version===d?.version?'Published':'Draft',button];}));} async function load(){controller?.abort();controller=new AbortController();const c=controller,timer=setTimeout(()=>c.abort(),15000);refresh.disabled=true;state=null;lock();try{const r=await fetcher('/api/kits/server-studio',{credentials:'same-origin',cache:'no-store',signal:c.signal}),data=await r.json();if(!r.ok)throw Error(data.message||'The workshop is unavailable.');const confirmed=serverKitRegister(data);if(!active||c!==controller)return;state=confirmed;uncertain=false;render();status.textContent=state.designs.length+' saved server designs confirmed. Existing paid receipts remain unchanged.';}catch(error){if(active&&c===controller){rows.replaceChildren();status.textContent=c.signal.aborted?'Workshop read timed out. Refresh to retry.':error.message;}}finally{clearTimeout(timer);if(active&&c===controller){refresh.disabled=false;lock();}}} async function loadCatalogue(){try{const r=await fetcher('/api/kits/catalogue',{credentials:'same-origin',cache:'no-store',signal:AbortSignal.timeout(15000)}),d=await r.json();if(!r.ok||d.currency!=='dunemarks'||!Array.isArray(d.listings)||d.listings.length>1000)throw Error(d.message||'The public kit catalogue is unavailable.');if(active)table(catalogue,['Kit','Seller','Rarity','Price · DM'],d.listings.map(l=>[l.name,l.sellerName,title(l.quality),(Number(l.priceCents)/100).toFixed(2)]));}catch(error){if(active)catalogue.replaceChildren(el('p',error.message));}} form.oninput=()=>{form.dataset.dirty='true';lock();};consent.onchange=lock;fields.quality.onchange=()=>edit(fields.quality.value); - form.onsubmit=async event=>{event.preventDefault();if(!state||busy||uncertain||!consent.checked)return;let payload;try{const input=Object.fromEntries(Object.entries(fields).map(([k,v])=>[k,v.value]));payload=serverKitPayload(action.value,input,selected,listingFor(selected));}catch(error){result.textContent=error.message;return;}busy=true;lock();const quality=fields.quality.value;try{const r=await fetcher('/api/kits/server-studio',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),signal:AbortSignal.timeout(20000)}),d=await r.json();if(!r.ok)throw Object.assign(Error(d.message||'The operation was rejected.'),{status:r.status});if(d.ok!==true)throw Error('The operation was not confirmed.');if(!active)return;form.dataset.dirty='false';await load();if(state)edit(quality);result.textContent=d.message||'Kit operation confirmed.';void loadCatalogue();}catch(error){if(active){uncertain=error.status!==409&&error.status!==400&&error.status!==403;result.textContent=error.message+' Refresh the workshop before retrying.';}}finally{busy=false;if(active)lock();}}; - search.oninput=render;refresh.onclick=()=>{if(form.dataset.dirty==='true'&&!window.confirm('Refresh workshop state? Unsaved form input is retained; reopen the latest design before saving.'))return;uncertain=true;void load();};lock();void load();void loadCatalogue();return()=>{active=false;controller?.abort();box.remove();}; + form.onsubmit=async event=>{event.preventDefault();if(!state||busy||uncertain||!consent.checked)return;let payload;try{if(generator&&!generator.form.reportValidity())return;const values=generator?.value();const input={...Object.fromEntries(Object.entries(fields).map(([k,v])=>[k,v.value])),...(values?{...values,lore:values.lore.join('\n'),...values.itemNames}:{})};payload=serverKitPayload(action.value,input,selected,listingFor(selected));}catch(error){result.textContent=error.message;return;}busy=true;lock();const quality=fields.quality.value;try{const r=await fetcher('/api/kits/server-studio',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),signal:AbortSignal.timeout(20000)}),d=await r.json();if(!r.ok)throw Object.assign(Error(d.message||'The operation was rejected.'),{status:r.status});if(d.ok!==true)throw Error('The operation was not confirmed.');if(!active)return;form.dataset.dirty='false';await load();if(state)edit(quality);result.textContent=d.message||'Kit operation confirmed.';void loadCatalogue();}catch(error){if(active){uncertain=error.status!==409&&error.status!==400&&error.status!==403;result.textContent=error.message+' Refresh the workshop before retrying.';}}finally{busy=false;if(active)lock();}}; + search.oninput=render;refresh.onclick=()=>{if((form.dataset.dirty==='true'||generator?.isDirty())&&!window.confirm('Refresh workshop state? Unsaved form input is retained; reopen the latest design before saving.'))return;uncertain=true;void load();};lock();void load();void loadCatalogue();return()=>{active=false;controller?.abort();box.remove();}; } diff --git a/website/control-panel/public/kit-design-model.mjs b/website/control-panel/public/kit-design-model.mjs new file mode 100644 index 00000000..82bf65c4 --- /dev/null +++ b/website/control-panel/public/kit-design-model.mjs @@ -0,0 +1,56 @@ +// Shared browser/server contract. Formatting is data, never HTML or commands. +export const KIT_SLOTS=['helmet','chestplate','leggings','boots']; +export const TRIM_PATTERNS=['sentry','dune','coast','wild','ward','eye','vex','tide','snout','rib','spire','wayfinder','shaper','silence','raiser','host','flow','bolt']; +export const TRIM_MATERIALS=['quartz','iron','netherite','redstone','copper','gold','emerald','diamond','lapis','amethyst','resin']; +export const BANNER_COLORS=['white','orange','magenta','light_blue','yellow','lime','pink','gray','light_gray','cyan','purple','blue','brown','green','red','black']; +export const BANNER_PATTERNS=['square_bottom_left','square_bottom_right','square_top_left','square_top_right','stripe_bottom','stripe_top','stripe_left','stripe_right','stripe_center','stripe_middle','stripe_downright','stripe_downleft','small_stripes','cross','straight_cross','triangle_bottom','triangle_top','triangles_bottom','triangles_top','diagonal_left','diagonal_up_right','diagonal_up_left','diagonal_right','circle','rhombus','half_vertical','half_horizontal','half_vertical_right','half_horizontal_bottom','border','curly_border','gradient','gradient_up','bricks','globe','creeper','skull','flower','mojang','piglin','flow','guster']; +const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v); +const exact=(v,keys)=>object(v)&&Object.keys(v).length===keys.length&&keys.every(k=>Object.hasOwn(v,k)); +const text=(v,max)=>typeof v==='string'&&v.length<=max&&!/[\x00-\x1f\x7f<>§]/.test(v); +export function loreLine(text='',color='#AAAAAA',bold=false,italic=false){return {text,color,bold,italic};} +export function validateItemLore(value){ + if(!Array.isArray(value)||value.length>6)throw Error('Use up to six lore lines.'); + return value.map(line=>{ + if(!exact(line,['text','color','bold','italic'])||!text(line.text,120)||!/^#[a-f0-9]{6}$/i.test(line.color)||typeof line.bold!=='boolean'||typeof line.italic!=='boolean')throw Error('Use lore lines of up to 120 characters with valid colours and formatting.'); + return {...line,color:line.color.toUpperCase()}; + }); +} +export function defaultKitEquipment(legacy={}){ + const lore=(legacy.lore||[]).slice(0,6).map(line=>loreLine(line)); + return {version:3,armor:Object.fromEntries(KIT_SLOTS.map(slot=>[slot,{material:'netherite',name:legacy.itemNames?.[slot]||'',lore:structuredClone(lore),trim:{pattern:'dune',material:'gold'}}])),banner:{enabled:false,name:'',base:'black',patterns:[],lore:[]}}; +} +// Explicit remakes use distinct rarity/faction heraldry; paid snapshots never call this. +export function remakeKitEquipment(legacy={}){ + const result=defaultKitEquipment(legacy),quality=String(legacy.quality||'uncommon').toLowerCase().replaceAll(' ','_'); + const styles={common:['sentry','iron','gray','white'],uncommon:['dune','copper','brown','orange'],rare:['spire','emerald','green','lime'],very_rare:['eye','amethyst','purple','magenta'],legendary:['silence','gold','black','yellow']}; + let [pattern,material,base,color]=styles[quality]||styles.uncommon,emblem='rhombus'; + const identity=[legacy.factionId,legacy.office,legacy.name].filter(Boolean).join(' ').toLowerCase(); + if(/corrino|aerdrecht|emperor/.test(identity)){pattern='spire';material='gold';base='purple';color='yellow';emblem='flower';} + else if(/atreides|korenholt/.test(identity)){pattern='coast';material='emerald';base='green';color='white';emblem='flower';} + else if(/harkonnen|harkveen/.test(identity)){pattern='rib';material='redstone';base='black';color='red';emblem='skull';} + else if(/ordos|oordwijk/.test(identity)){pattern='sentry';material='amethyst';base='green';color='purple';emblem='creeper';} + else if(/fremen|vrijduin/.test(identity)){pattern='dune';material='lapis';base='blue';color='light_blue';emblem='rhombus';} + else if(/spacing|guild/.test(identity)){pattern='eye';material='quartz';base='black';color='white';emblem='globe';} + const accent={iron:'#D8D8D8',copper:'#C77C58',emerald:'#42BD72',amethyst:'#B488D8',gold:'#E5C66D',redstone:'#DE5959',lapis:'#6D93E2',quartz:'#F1EBDC'}[material]||'#D8C58C'; + for(const slot of KIT_SLOTS){ + const item=result.armor[slot];item.trim={pattern,material}; + if(!item.name)item.name=((legacy.name||'Desert Stillsuit')+' · '+slot[0].toUpperCase()+slot.slice(1)).slice(0,64); + if(!item.lore.length)item.lore=[loreLine('A second skin against the desert.',accent),loreLine(''),loreLine('Woven for the journeys still to come.')]; + else {item.lore[0].color=accent;item.lore[0].bold=true;} + } + result.banner={enabled:true,name:((legacy.name||'Desert')+' Standard').slice(0,64),base,patterns:[{pattern:'border',color},{pattern:emblem,color}],lore:[loreLine('The colours of '+(legacy.name||'the caravan')+'.',accent,true),loreLine('Carried in service of the realm.')]}; + return validateKitEquipment(result); +} +export function validateKitEquipment(value){ + if(!exact(value,['version','armor','banner'])||value.version!==3||!exact(value.armor,KIT_SLOTS))throw Error('Choose a complete version 3 kit design.'); + const armor={}; + for(const slot of KIT_SLOTS){ + const piece=value.armor[slot]; + if(!exact(piece,['material','name','lore','trim'])||piece.material!=='netherite'||!text(piece.name,64)||!exact(piece.trim,['pattern','material'])||!TRIM_PATTERNS.includes(piece.trim.pattern)||!TRIM_MATERIALS.includes(piece.trim.material))throw Error('Choose valid netherite armour, trim pattern and trim material.'); + armor[slot]={material:'netherite',name:piece.name.trim(),lore:validateItemLore(piece.lore),trim:{...piece.trim}}; + } + const banner=value.banner; + if(!exact(banner,['enabled','name','base','patterns','lore'])||typeof banner.enabled!=='boolean'||!text(banner.name,64)||!BANNER_COLORS.includes(banner.base)||!Array.isArray(banner.patterns)||banner.patterns.length>6)throw Error('Use a banner with a valid base colour and up to six pattern layers.'); + const patterns=banner.patterns.map(layer=>{if(!exact(layer,['pattern','color'])||!BANNER_PATTERNS.includes(layer.pattern)||!BANNER_COLORS.includes(layer.color))throw Error('Choose a valid banner pattern and colour.');return {...layer};}); + return {version:3,armor,banner:{enabled:banner.enabled,name:banner.name.trim(),base:banner.base,patterns,lore:validateItemLore(banner.lore)}}; +} diff --git a/website/control-panel/public/kit-equipment-editor.mjs b/website/control-panel/public/kit-equipment-editor.mjs new file mode 100644 index 00000000..9303652e --- /dev/null +++ b/website/control-panel/public/kit-equipment-editor.mjs @@ -0,0 +1,44 @@ +import {KIT_SLOTS,TRIM_PATTERNS,TRIM_MATERIALS,BANNER_COLORS,BANNER_PATTERNS,defaultKitEquipment,remakeKitEquipment,validateKitEquipment,loreLine} from './kit-design-model.mjs'; +import {createKitTexturePreview} from './kit-texture-preview.mjs'; +const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;}; +const title=s=>s.replaceAll('_',' ').replace(/\b[a-z]/g,c=>c.toUpperCase()); +function field(parent,label,input){const wrap=el('label'),caption=el('span',label);wrap.append(caption,input);parent.append(wrap);return input;} +function select(parent,label,values,value,change){const s=el('select');for(const v of values){const o=el('option',title(v));o.value=v;s.append(o);}s.value=value;s.onchange=()=>change(s.value);return field(parent,label,s);} +export function createKitEquipmentEditor(initial,{onChange=()=>{},kitName=()=>initial.name||'Stillsuit'}={}){ + let equipment=initial.equipment?validateKitEquipment(initial.equipment):remakeKitEquipment(initial),selected='helmet'; + const root=el('section'),nav=el('nav'),panel=el('section'),tooltip=el('aside'),preview=createKitTexturePreview();root.className='kit-equipment-editor';nav.className='kit-equipment-slots';nav.setAttribute('aria-label','Choose a kit item');tooltip.className='kit-minecraft-tooltip';tooltip.setAttribute('aria-live','polite'); + const buttons=new Map();for(const slot of [...KIT_SLOTS,'banner']){const b=el('button',title(slot));b.type='button';b.onclick=()=>{selected=slot;render();};nav.append(b);buttons.set(slot,b);} + root.append(el('h3','Netherite equipment & heraldry'),el('p','Select each item to choose its name, lore and smithing trim. Banner layers are applied from top to bottom.'),nav,panel); + function changed(){updatePreview();onChange();} + function text(parent,label,value,change,max=64){const input=el('input');input.type='text';input.maxLength=max;input.value=value;input.oninput=()=>{input.setCustomValidity('');change(input.value);};return field(parent,label,input);} + function lore(parent,item){ + const group=el('fieldset'),lines=el('div'),add=el('button','+ Lore line');group.className='kit-item-lore';group.append(el('legend','Item lore'),el('p','Each row is one in-game line. Empty rows preserve spacing.'),lines,add);parent.append(group);add.type='button'; + function renderLines(){lines.replaceChildren();add.disabled=item.lore.length>=6; + item.lore.forEach((line,index)=>{const row=el('div');row.className='kit-lore-line';const input=text(row,'Line '+(index+1),line.text,value=>{line.text=value;changed();},120);input.placeholder='Lore text · blank for a spacer';input.onpaste=event=>{const pasted=event.clipboardData?.getData('text/plain');if(!pasted?.includes('\n'))return;event.preventDefault();const values=pasted.replaceAll('\r','').split('\n');if(item.lore.length-1+values.length>6||values.some(v=>v.length>120)){input.setCustomValidity('Paste up to six lines of 120 characters.');input.reportValidity();return;}input.setCustomValidity('');item.lore.splice(index,1,...values.map(text=>({...line,text})));renderLines();changed();};const color=el('input');color.type='color';color.value=line.color;color.oninput=()=>{line.color=color.value;changed();};field(row,'Colour',color); + for(const [key,label] of [['bold','Bold'],['italic','Italic']]){const checkbox=el('input');checkbox.type='checkbox';checkbox.checked=line[key];checkbox.onchange=()=>{line[key]=checkbox.checked;changed();};field(row,label,checkbox);} + const remove=el('button','Remove');remove.type='button';remove.setAttribute('aria-label','Remove lore line '+(index+1));remove.onclick=()=>{item.lore.splice(index,1);renderLines();changed();};row.append(remove);lines.append(row); + }); + } + add.onclick=()=>{if(item.lore.length<6){item.lore.push(loreLine());renderLines();changed();}};renderLines(); + } + function render(){ + panel.replaceChildren();for(const [slot,button]of buttons)button.setAttribute('aria-pressed',String(selected===slot)); + const item=selected==='banner'?equipment.banner:equipment.armor[selected];panel.append(el('h4',title(selected))); + text(panel,'Item name',item.name,value=>{item.name=value;changed();}); + if(selected==='banner'){ + const enabled=el('input');enabled.type='checkbox';enabled.checked=item.enabled;enabled.onchange=()=>{item.enabled=enabled.checked;changed();};field(panel,'Include this banner in the kit',enabled); + select(panel,'Base colour',BANNER_COLORS,item.base,value=>{item.base=value;changed();}); + const layers=el('div'),add=el('button','+ Banner pattern');add.type='button';panel.append(layers,add); + function renderLayers(){layers.replaceChildren();add.disabled=item.patterns.length>=6;item.patterns.forEach((layer,index)=>{const row=el('div');row.className='kit-banner-layer';row.append(el('strong','Layer '+(index+1)));select(row,'Pattern',BANNER_PATTERNS,layer.pattern,value=>{layer.pattern=value;changed();});select(row,'Colour',BANNER_COLORS,layer.color,value=>{layer.color=value;changed();});for(const [label,move]of [['↑',-1],['↓',1],['Remove',0]]){const b=el('button',label);b.type='button';b.setAttribute('aria-label',label==='Remove'?'Remove banner layer '+(index+1):'Move banner layer '+(index+1)+(move<0?' up':' down'));b.disabled=move<0&&index===0||move>0&&index===item.patterns.length-1;b.onclick=()=>{if(move){const target=index+move;[item.patterns[index],item.patterns[target]]=[item.patterns[target],item.patterns[index]];}else item.patterns.splice(index,1);renderLayers();changed();};row.append(b);}layers.append(row);});} + add.onclick=()=>{if(item.patterns.length<6){item.patterns.push({pattern:'border',color:'yellow'});renderLayers();changed();}};renderLayers(); + }else{ + panel.append(el('p','Netherite armour · existing quality enchantments remain fixed.')); + select(panel,'Smithing trim pattern',TRIM_PATTERNS,item.trim.pattern,value=>{item.trim.pattern=value;changed();});select(panel,'Trim material',TRIM_MATERIALS,item.trim.material,value=>{item.trim.material=value;changed();}); + const copy=el('button','Apply this trim to all armour');copy.type='button';copy.onclick=()=>{for(const slot of KIT_SLOTS)equipment.armor[slot].trim={...item.trim};changed();};panel.append(copy); + } + lore(panel,item);updatePreview(); + } + function updateTooltip(){const item=selected==='banner'?equipment.banner:equipment.armor[selected];tooltip.replaceChildren(el('strong',item.name||kitName()+' '+title(selected)));for(const line of item.lore){const p=el('p',line.text||'\u00a0');p.style.color=line.color;p.style.fontWeight=line.bold?'bold':'normal';p.style.fontStyle=line.italic?'italic':'normal';tooltip.append(p);}if(selected!=='banner')tooltip.append(el('small',title(item.trim.pattern)+' trim · '+title(item.trim.material)));} + function updatePreview(){updateTooltip();void preview.update(equipment);} + render();return {element:root,preview:preview.element,tooltip,value:()=>structuredClone(equipment),reset(value){equipment=value?validateKitEquipment(value):defaultKitEquipment(initial);render();},refresh:updateTooltip}; +} diff --git a/website/control-panel/public/kit-generator.css b/website/control-panel/public/kit-generator.css index 2efbb2f6..3530872a 100644 --- a/website/control-panel/public/kit-generator.css +++ b/website/control-panel/public/kit-generator.css @@ -31,3 +31,6 @@ body.user-service[data-service=tailor] :is(input,select,textarea){background:#df body.user-service[data-service=tailor] :is(.kit-publish-form,.kit-enchantment-profile,.kit-arc-card,.kit-order-card,.kit-cart){background:linear-gradient(140deg,#4b303a,#31222b);color:#eaddc4;border:1px solid #b19256;border-radius:10px}body.user-service[data-service=tailor] :is(h2,h3,h4,legend){color:#efd091}body.user-service[data-service=tailor] :is(.kit-enchantment-profile small,.kit-arc-card small,.kit-order-card small){color:#d7c3a2}body.user-service[data-service=tailor] .kit-publish-form select{width:100%;max-width:100%} @media(max-width:850px){.kit-generator-preview{grid-row:auto}.kit-generator{gap:20px}.kit-generator-form{padding:18px}.kit-generator .kit-collectible-card{max-width:100%}} .kit-profile-disclosure{margin:16px 0 20px;padding:12px 16px;border:1px solid #a68a5555;border-radius:7px;background:#412b35}.kit-profile-disclosure>summary{cursor:pointer;color:#efd091}.kit-profile-disclosure .kit-enchantment-profile{margin-bottom:0} + +/* Netherite equipment workshop: restrained controls and a texture-based preview. */ +.kit-generator{grid-template-columns:minmax(0,1.35fr) minmax(320px,.85fr);align-items:start}.kit-generator-form>.kit-piece-names,.kit-piece-name-preview{display:none!important}.kit-equipment-editor{border-top:1px solid #ad904b66;padding-top:22px}.kit-equipment-editor>p{color:#bdcabc;line-height:1.6}.kit-equipment-slots{display:flex;flex-wrap:wrap;gap:7px;margin:18px 0}.kit-equipment-slots button{flex:1;padding:10px 8px!important;background:#10271f;color:#e9d8a9;border:1px solid #7d7955;border-radius:7px}.kit-equipment-slots button[aria-pressed=true]{background:#b79b56;color:#10271f}.kit-equipment-editor>section{display:grid;gap:15px}.kit-generator select{width:100%;box-sizing:border-box;background:#0c261e;color:#eee1c2;border:1px solid #758461;padding:12px;border-radius:7px}.kit-generator input[type=checkbox]{width:auto;justify-self:start}.kit-item-lore{min-width:0;border:1px solid #75846166;border-radius:8px;padding:15px}.kit-item-lore>p{color:#bdcabc;font-size:13px}.kit-lore-line{display:grid;grid-template-columns:minmax(0,1fr) 70px auto auto;gap:9px;padding:13px 0;border-bottom:1px solid #75846144;align-items:end}.kit-lore-line>label:first-child{grid-column:1/-1}.kit-lore-line button{font-size:12px;padding:8px!important}.kit-banner-layer{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto auto auto;gap:9px;padding:15px 0;border-bottom:1px solid #75846144;align-items:end}.kit-banner-layer>strong{grid-column:1/-1;color:#e8cc83}.kit-banner-layer button{padding:10px!important}.kit-texture-view{margin:10px -5px}.kit-armor-canvas{display:block;width:100%;height:auto;image-rendering:pixelated;touch-action:none;cursor:grab;background:radial-gradient(ellipse at 50% 90%,#ccb75f25,transparent 45%)}.kit-armor-canvas:active{cursor:grabbing}.kit-preview-camera{display:flex;justify-content:center;gap:8px}.kit-preview-camera button{padding:8px 15px!important}.kit-texture-view>p{text-align:center;font-size:12px;color:#bdcabc}.kit-minecraft-tooltip{padding:15px;border:2px solid #342169;box-shadow:inset 0 0 0 1px #150925;background:#100712f2;border-radius:4px;font-family:monospace;font-size:14px;line-height:1.5;overflow-wrap:anywhere;text-shadow:1px 1px #000;letter-spacing:.02em}.kit-minecraft-tooltip>strong{display:block;color:#e9bd66;font-size:16px;margin-bottom:9px}.kit-minecraft-tooltip p{margin:0;white-space:pre-wrap;min-height:1.5em}.kit-minecraft-tooltip small{display:block;margin-top:10px;color:#888!important}.kit-collectible-card{max-width:520px;position:sticky!important;top:15px}.kit-generator label{font-size:14px}.kit-generator input:focus-visible,.kit-generator select:focus-visible,.kit-generator button:focus-visible,.kit-armor-canvas:focus-visible{outline:2px solid #dfbf68;outline-offset:3px}@media(max-width:1000px){.kit-generator{grid-template-columns:1fr}.kit-collectible-card{position:static!important;grid-row:1;max-width:520px}.kit-armor-canvas{max-height:440px;object-fit:contain}.kit-banner-layer{grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto auto auto}}@media(max-width:480px){.kit-generator-form{padding:16px}.kit-banner-layer>label{grid-column:1/-1}.kit-lore-line{grid-template-columns:70px auto auto auto}} diff --git a/website/control-panel/public/kit-generator.mjs b/website/control-panel/public/kit-generator.mjs index b2c203ef..fcb80378 100644 --- a/website/control-panel/public/kit-generator.mjs +++ b/website/control-panel/public/kit-generator.mjs @@ -1,20 +1,23 @@ +import {createKitEquipmentEditor} from './kit-equipment-editor.mjs'; +import {validateKitEquipment} from './kit-design-model.mjs'; const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;}; -if(!document.querySelector('link[href="/kit-generator.css"]')){const css=el('link');css.rel='stylesheet';css.href='/kit-generator.css';document.head.append(css);} +if(typeof document!=='undefined'&&!document.querySelector('link[href="/kit-generator.css"]')){const css=el('link');css.rel='stylesheet';css.href='/kit-generator.css';document.head.append(css);} const profiles={common:['No enchantments · standard vanilla armour'],uncommon:['All armour · Protection I · Unbreaking I','Boots · Feather Falling I'],rare:['All armour · Protection II · Unbreaking II','Helmet · Respiration I · Aqua Affinity I','Boots · Feather Falling II · Depth Strider I'],very_rare:['All armour · Protection III · Unbreaking III · Mending I','Helmet · Respiration II · Aqua Affinity I','Leggings · Swift Sneak II','Boots · Feather Falling III · Depth Strider II'],legendary:['All armour · Protection IV · Unbreaking III · Mending I · Thorns III','Helmet · Respiration III · Aqua Affinity I','Leggings · Swift Sneak III','Boots · Feather Falling IV · Depth Strider III · Soul Speed III']}; -export function createEnchantmentProfile(quality,kind='personal_sale'){const key=quality.toLowerCase().replaceAll(' ','_');const box=el('aside');box.className='kit-enchantment-profile';box.setAttribute('aria-label','Quality enchantment profile');box.append(el('h4','Enchantment profile'),el('p','Fixed by kit quality. Players cannot edit enchantments.'));const list=el('ul');for(const line of (kind==='faction_sale'?['Vanilla faction armour · no added enchantments']:profiles[key]||[]))list.append(el('li',line));box.append(list,el('small','Preview: game-side activation is pending.'));return box;} +export function createEnchantmentProfile(quality,kind='personal_sale'){const key=quality.toLowerCase().replaceAll(' ','_');const box=el('aside');box.className='kit-enchantment-profile';box.setAttribute('aria-label','Quality enchantment profile');box.append(el('h4','Enchantment profile'),el('p','Fixed by kit quality. Players cannot edit enchantments.'));const list=el('ul');for(const line of (kind==='faction_sale'?['Vanilla faction armour · no added enchantments']:profiles[key]||[]))list.append(el('li',line));box.append(list,el('small','Applied to your delivered kit.'));return box;} export function createKitGenerator({initial={},kind='personal_sale',onUpgrade=null,context='Personal kit',quality='Uncommon',art='clan-atelier-v1.webp',maxNameLength=64,maxLoreLines=4,maxLoreLineLength=80,submitLabel='Save design',successMessage='Design saved.',onSave=async()=>{}}={}){ - const root=el('div');root.className='kit-generator';const form=el('form'),preview=el('aside');form.className='kit-generator-form';preview.className='kit-generator-preview kit-collectible-card';preview.dataset.quality=quality.toLowerCase().replaceAll(' ','_');preview.setAttribute('aria-label','Live kit design preview');form.append(el('p',context.toUpperCase()),el('h3','Create your colours'),el('p','Choose a name, pick your colours and add a little history. The preview updates as you type.')); + const root=el('div');root.className='kit-generator';const form=el('form'),preview=el('aside');form.className='kit-generator-form';preview.className='kit-generator-preview kit-collectible-card';preview.dataset.quality=quality.toLowerCase().replaceAll(' ','_');preview.setAttribute('aria-label','Live kit design preview');form.append(el('p',context.toUpperCase()),el('h3','Forge your kit'),el('p','Design netherite armour, choose your trims and add your own heraldry and item lore.')); function field(title,type,value){const label=el('label',title),input=el(type==='textarea'?'textarea':'input');if(type!=='textarea')input.type=type;input.value=value;label.append(input);form.append(label);return input;} - const name=field('1 · Kit name','text',initial.name||'');name.required=true;name.minLength=3;name.maxLength=maxNameLength;name.placeholder='Give your stillsuit a name';const color=field('2 · Stillsuit colour','color',initial.color||'#385B49'); + const name=field('1 · Kit name','text',initial.name||'');name.required=true;name.minLength=3;name.maxLength=maxNameLength;name.placeholder='Give your stillsuit a name';const color=field('2 · Kit accent colour','color',initial.color||'#385B49'); const hex=field('Colour code · hex','text',color.value.toUpperCase());hex.maxLength=7;hex.pattern='#[A-Fa-f0-9]{6}';hex.spellcheck=false;hex.placeholder='#803C3F';hex.addEventListener('input',()=>{if(/^#[A-Fa-f0-9]{6}$/.test(hex.value)){color.value=hex.value;update(false);}}); const presets=el('div');presets.className='kit-colour-presets';for(const[label,value]of [['Emerald','#385B49'],['Imperial purple','#654478'],['Desert sand','#B09156'],['Crimson','#803C3F'],['Deep blue','#365C79']]){const b=el('button',label);b.type='button';b.style.setProperty('--swatch',value);b.onclick=()=>{color.value=value;update();};presets.append(b);}form.append(presets); - const lore=field('3 · Lore','textarea',(initial.lore||[]).join('\n'));lore.rows=5;lore.maxLength=maxLoreLines*(maxLoreLineLength+1);lore.placeholder='A story carried across the desert…';const hint=el('small',`Up to ${maxLoreLines} lines, ${maxLoreLineLength} characters per line.`);const counter=el('output');counter.className='kit-lore-counter';form.append(hint,counter); + const lore=field('3 · Kit story · catalogue description','textarea',(initial.lore||[]).join('\n'));lore.rows=5;lore.maxLength=maxLoreLines*(maxLoreLineLength+1);lore.placeholder='A story carried across the desert…';const hint=el('small',`Up to ${maxLoreLines} lines, ${maxLoreLineLength} characters per line.`);const counter=el('output');counter.className='kit-lore-counter';form.append(hint,counter); const namedPieces=['rare','very_rare','legendary'].includes(quality.toLowerCase().replaceAll(' ','_')),itemNames={}; if(namedPieces){const group=el('fieldset');group.className='kit-piece-names';group.append(el('legend','Individual armour names'),el('p','Optional names for Rare, Very Rare and Legendary kits. Leave blank to use the kit name.'));for(const[key,label]of [['helmet','Helmet'],['chestplate','Chestplate'],['leggings','Leggings'],['boots','Boots']]){const wrap=el('label',label),input=el('input');input.type='text';input.maxLength=64;input.value=initial.itemNames?.[key]||'';input.placeholder=label+' name';wrap.append(input);group.append(wrap);itemNames[key]=input;}form.append(group);} - const status=el('p');status.role='status';status.className='kit-generator-status';const save=el('button',submitLabel);save.type='submit';save.dataset.duneAction='eco';form.append(el('p','Cosmetic design only. Existing armour attributes and game eligibility still apply.'),status,save); - const image=el('img');image.src='https://www.dunerealms.com/assets/'+art;image.alt='Illustrated stillsuit atelier';image.className='kit-generator-art';const heading=el('h3'),badge=el('span',quality+' · Four-piece stillsuit'),figure=el('div');figure.className='kit-design-mannequin';figure.setAttribute('aria-label','Stillsuit colour preview');for(const part of ['head','hood','body','left-arm','right-arm','belt','left-leg','right-leg','left-boot','right-boot']){const piece=el('span');piece.className='kit-piece-'+part;figure.append(piece);}const lines=el('div');lines.className='kit-preview-lore';const state=el('p');state.className='kit-preview-state';const crest=el('div','DUNEREALMS · IMPERIAL ATELIER');crest.className='kit-card-imprint';const artPanel=el('div');artPanel.className='kit-card-art-panel';const enchants=el('section');enchants.className='kit-card-enchants';enchants.setAttribute('aria-label','Fixed quality enchantments');enchants.append(el('h4','✦ '+quality+' enchantments'));for(const line of (kind==='faction_sale'?['Vanilla faction armour · no added enchantments']:profiles[preview.dataset.quality]||[]))enchants.append(el('p',line));if(kind==='personal_sale'&&preview.dataset.quality==='legendary'){enchants.append(el('h4','Upgrade bonus'));for(const b of initial.upgrade?.bonuses||[])enchants.append(el('p',b.piece+' · '+b.enchantment.replaceAll('_',' ')+' +'+b.levels));if(!initial.upgrade)enchants.append(el('p','No Upgrade Token applied'));}enchants.append(el('small','Fixed quality profile · game activation pending'));artPanel.append(image,enchants);preview.append(crest,badge,heading,artPanel,figure,lines,state,el('small','DESIGN PREVIEW · FOUR-PIECE ARMOUR')); - function value(){return{name:name.value.trim(),color:color.value.toUpperCase(),lore:lore.value.trim()?lore.value.split('\n').map(s=>s.trim()).filter(Boolean):[],...(namedPieces?{itemNames:Object.fromEntries(Object.entries(itemNames).map(([k,v])=>[k,v.value.trim()]))}:{})};}let original=JSON.stringify(value());const baseline=structuredClone(value());const reset=el('button','Restore saved design');reset.type='button';reset.className='kit-reset-design';reset.onclick=()=>{if(form.dataset.dirty==='true'&&!window.confirm('Discard your unsaved design changes?'))return;name.value=baseline.name;color.value=baseline.color;lore.value=baseline.lore.join('\n');for(const[key,input]of Object.entries(itemNames))input.value=baseline.itemNames?.[key]||'';status.textContent='Saved design restored in the preview.';update();};form.insertBefore(reset,status); - function update(syncHex=true){const v=value();if(syncHex)hex.value=v.color;heading.textContent=v.name||'Your stillsuit';figure.style.setProperty('--kit-colour',v.color);lines.replaceChildren(...v.lore.map(s=>el('p',s)));if(namedPieces){const names=el('dl');names.className='kit-piece-name-preview';for(const[key,label]of [['helmet','Helmet'],['chestplate','Chestplate'],['leggings','Leggings'],['boots','Boots']])names.append(el('dt',label),el('dd',v.itemNames[key]||(v.name||'Your stillsuit')+' '+label.toLowerCase()));lines.append(names);}const dirty=JSON.stringify(v)!==original;form.dataset.dirty=String(dirty);reset.disabled=!dirty;counter.textContent=v.lore.length+' / '+maxLoreLines+' lore lines · longest '+Math.max(0,...v.lore.map(s=>s.length))+' / '+maxLoreLineLength+' characters';state.textContent=dirty?'Unsaved preview':Number(initial.version)>0?'Current saved design':'New design preview · not saved';state.dataset.dirty=String(dirty);const invalid=v.lore.length>maxLoreLines||v.lore.some(s=>s.length>maxLoreLineLength);lore.setCustomValidity(invalid?`Use up to ${maxLoreLines} lines of ${maxLoreLineLength} characters.`:'');} - let saving=false;for(const input of [name,color,lore,...Object.values(itemNames)])input.addEventListener('input',()=>update());form.onsubmit=async e=>{e.preventDefault();if(saving)return;update(false);if(!form.reportValidity())return;saving=true;const submitted=structuredClone(value()),controls=[...form.querySelectorAll('input,select,textarea,button')],disabled=controls.map(c=>c.disabled);for(const control of controls)control.disabled=true;status.textContent='Saving your design…';try{await onSave(submitted);original=JSON.stringify(submitted);Object.assign(baseline,submitted);status.textContent=successMessage;}catch(error){status.textContent=error.message||'The design could not be saved. Your preview is still here.';}finally{saving=false;controls.forEach((c,i)=>c.disabled=disabled[i]);update(false);}};if(kind==='personal_sale'&&preview.dataset.quality==='legendary'){const box=el('fieldset');box.className='kit-upgrade-control';box.append(el('legend','Legendary Upgrade Token'),el('p','5,000 Dunemarks per token. Each code replaces your bonus with 1–3 points spread over random enchantments. Future Player Kit sales only; paid receipts and faction kits stay unchanged.'));const label=el('label','Private Upgrade Token code'),input=el('input');input.placeholder='DRU-…';input.maxLength=52;input.autocomplete='off';input.spellcheck=false;label.append(input);const button=el('button','Use token & reroll bonus');button.type='button';button.disabled=!initial.id||!onUpgrade;const note=el('p');note.role='status';if(!initial.id)note.textContent='Save your Legendary Player Kit first.';button.onclick=async()=>{if(JSON.stringify(value())!==original){note.textContent='Save your design changes before using a token.';return;}const code=input.value.trim().toUpperCase();if(!/^DRU-[A-F0-9]{48}$/.test(code)){note.textContent='Enter your complete private Upgrade Token code.';return;}button.disabled=true;note.textContent='Applying token…';try{await onUpgrade(code);}catch(e){note.textContent=e.message;button.disabled=false;}};const shop=el('a','Buy Upgrade Tokens →');shop.href='#rewards-codes';box.append(label,button,note,shop);form.append(box);}root.append(form,preview);update();return{element:root,value,form,submitButton:save,status,isDirty:()=>form.dataset.dirty==='true'}; + const status=el('p');status.role='status';status.className='kit-generator-status';const save=el('button',submitLabel);save.type='submit';save.dataset.duneAction='eco';form.append(el('p','Your design sets the armour trims, names, lore and banner. Quality attributes and eligibility still apply.'),status,save); + const equipmentEditor=createKitEquipmentEditor(initial,{onChange:()=>update(),kitName:()=>name.value.trim()||'Stillsuit'});form.insertBefore(equipmentEditor.element,status); + const image=el('img');image.src='https://www.dunerealms.com/assets/'+art;image.alt='Illustrated stillsuit atelier';image.className='kit-generator-art';const heading=el('h3'),badge=el('span',quality+' · Netherite armour & heraldry'),figure=el('div');figure.className='kit-design-mannequin';figure.setAttribute('aria-label','Stillsuit colour preview');for(const part of ['head','hood','body','left-arm','right-arm','belt','left-leg','right-leg','left-boot','right-boot']){const piece=el('span');piece.className='kit-piece-'+part;figure.append(piece);}const lines=el('div');lines.className='kit-preview-lore';const state=el('p');state.className='kit-preview-state';const crest=el('div','DUNEREALMS · IMPERIAL ATELIER');crest.className='kit-card-imprint';const artPanel=el('div');artPanel.className='kit-card-art-panel';const enchants=el('section');enchants.className='kit-card-enchants';enchants.setAttribute('aria-label','Fixed quality enchantments');enchants.append(el('h4','✦ '+quality+' enchantments'));for(const line of (kind==='faction_sale'?['Vanilla faction armour · no added enchantments']:profiles[preview.dataset.quality]||[]))enchants.append(el('p',line));if(kind==='personal_sale'&&preview.dataset.quality==='legendary'){enchants.append(el('h4','Upgrade bonus'));for(const b of initial.upgrade?.bonuses||[])enchants.append(el('p',b.piece+' · '+b.enchantment.replaceAll('_',' ')+' +'+b.levels));if(!initial.upgrade)enchants.append(el('p','No Upgrade Token applied'));}enchants.append(el('small','Fixed quality profile · included with the kit'));artPanel.append(image,enchants);preview.append(crest,badge,heading,artPanel,equipmentEditor.preview,equipmentEditor.tooltip,lines,state,el('small','DESIGN PREVIEW · FOUR-PIECE ARMOUR')); + function value(){return{equipment:equipmentEditor.value(),name:name.value.trim(),color:color.value.toUpperCase(),lore:lore.value.trim()?lore.value.split('\n').map(s=>s.trim()).filter(Boolean):[],...(namedPieces?{itemNames:Object.fromEntries(Object.entries(equipmentEditor.value().armor).map(([k,v])=>[k,v.name.trim()]))}:{})};}let original=JSON.stringify(value());const baseline=structuredClone(value());const reset=el('button','Restore saved design');reset.type='button';reset.className='kit-reset-design';reset.onclick=()=>{if(form.dataset.dirty==='true'&&!window.confirm('Discard your unsaved design changes?'))return;name.value=baseline.name;color.value=baseline.color;lore.value=baseline.lore.join('\n');equipmentEditor.reset(baseline.equipment);for(const[key,input]of Object.entries(itemNames))input.value=baseline.itemNames?.[key]||'';status.textContent='Saved design restored in the preview.';update();};form.insertBefore(reset,status); + function update(syncHex=true){equipmentEditor.refresh();const v=value();if(syncHex)hex.value=v.color;heading.textContent=v.name||'Your stillsuit';figure.style.setProperty('--kit-colour',v.color);lines.replaceChildren(...v.lore.map(s=>el('p',s)));if(namedPieces){const names=el('dl');names.className='kit-piece-name-preview';for(const[key,label]of [['helmet','Helmet'],['chestplate','Chestplate'],['leggings','Leggings'],['boots','Boots']])names.append(el('dt',label),el('dd',v.itemNames[key]||(v.name||'Your stillsuit')+' '+label.toLowerCase()));lines.append(names);}const dirty=JSON.stringify(v)!==original;form.dataset.dirty=String(dirty);reset.disabled=!dirty;counter.textContent=v.lore.length+' / '+maxLoreLines+' lore lines · longest '+Math.max(0,...v.lore.map(s=>s.length))+' / '+maxLoreLineLength+' characters';state.textContent=dirty?'Unsaved preview':Number(initial.version)>0?'Current saved design':'New design preview · not saved';state.dataset.dirty=String(dirty);const invalid=v.lore.length>maxLoreLines||v.lore.some(s=>s.length>maxLoreLineLength);lore.setCustomValidity(invalid?`Use up to ${maxLoreLines} lines of ${maxLoreLineLength} characters.`:'');} + let saving=false;for(const input of [name,color,lore,...Object.values(itemNames)])input.addEventListener('input',()=>update());form.onsubmit=async e=>{e.preventDefault();if(saving)return;update(false);if(!form.reportValidity())return;try{validateKitEquipment(value().equipment);}catch(error){status.textContent=error.message;return;}saving=true;const submitted=structuredClone(value()),controls=[...form.querySelectorAll('input,select,textarea,button')],disabled=controls.map(c=>c.disabled);for(const control of controls)control.disabled=true;status.textContent='Saving your design…';try{await onSave(submitted);original=JSON.stringify(submitted);Object.assign(baseline,submitted);status.textContent=successMessage;}catch(error){status.textContent=error.message||'The design could not be saved. Your preview is still here.';}finally{saving=false;controls.forEach((c,i)=>c.disabled=disabled[i]);update(false);}};if(kind==='personal_sale'&&preview.dataset.quality==='legendary'){const box=el('fieldset');box.className='kit-upgrade-control';box.append(el('legend','Legendary Upgrade Token'),el('p','5,000 Dunemarks per token. Each code replaces your bonus with 1–3 points spread over random enchantments. Future Player Kit sales only; paid receipts and faction kits stay unchanged.'));const label=el('label','Private Upgrade Token code'),input=el('input');input.placeholder='DRU-…';input.maxLength=52;input.autocomplete='off';input.spellcheck=false;label.append(input);const button=el('button','Use token & reroll bonus');button.type='button';button.disabled=!initial.id||!onUpgrade;const note=el('p');note.role='status';if(!initial.id)note.textContent='Save your Legendary Player Kit first.';button.onclick=async()=>{if(JSON.stringify(value())!==original){note.textContent='Save your design changes before using a token.';return;}const code=input.value.trim().toUpperCase();if(!/^DRU-[A-F0-9]{48}$/.test(code)){note.textContent='Enter your complete private Upgrade Token code.';return;}button.disabled=true;note.textContent='Applying token…';try{await onUpgrade(code);}catch(e){note.textContent=e.message;button.disabled=false;}};const shop=el('a','Buy Upgrade Tokens →');shop.href='#rewards-codes';box.append(label,button,note,shop);form.append(box);}root.append(form,preview);update();return{element:root,value,form,submitButton:save,status,isDirty:()=>form.dataset.dirty==='true'}; } diff --git a/website/control-panel/public/kit-texture-preview.mjs b/website/control-panel/public/kit-texture-preview.mjs new file mode 100644 index 00000000..2fd0f4a6 --- /dev/null +++ b/website/control-panel/public/kit-texture-preview.mjs @@ -0,0 +1,50 @@ +const cache=new Map(); +const colors={white:'#F9FFFE',orange:'#F9801D',magenta:'#C74EBD',light_blue:'#3AB3DA',yellow:'#FED83D',lime:'#80C71F',pink:'#F38BAA',gray:'#474F52',light_gray:'#9D9D97',cyan:'#169C9C',purple:'#8932B8',blue:'#3C44AA',brown:'#835432',green:'#5E7C16',red:'#B02E26',black:'#1D1D21'}; +function texture(path){if(!cache.has(path))cache.set(path,new Promise((resolve,reject)=>{const image=new Image();image.onload=()=>resolve(image);image.onerror=()=>{cache.delete(path);reject(Error('Preview texture unavailable.'));};image.src='/kit-textures/'+path+'.png';}));return cache.get(path);} +function surface(w,h){const c=document.createElement('canvas');c.width=w;c.height=h;return c;} +function pixels(image){const c=surface(image.width,image.height),ctx=c.getContext('2d');ctx.drawImage(image,0,0);return ctx.getImageData(0,0,c.width,c.height);} +async function armorTexture(slot,trim){ + const layer=slot==='leggings'?'humanoid_leggings':'humanoid'; + const [base,pattern,original,target]=await Promise.all([texture('entity/equipment/'+layer+'/netherite'),texture('trims/entity/'+layer+'/'+trim.pattern),texture('trims/color_palettes/trim_palette'),texture('trims/color_palettes/'+trim.material+(trim.material==='netherite'?'_darker':''))]); + const palette=pixels(original).data,replacement=pixels(target).data,map=new Map(); + for(let i=0;iparseInt(v,16));for(let i=0;i{angle=delta===null?0:angle+delta;draw();};controls.append(b);} + canvas.onpointerdown=e=>{pointer={id:e.pointerId,x:e.clientX};canvas.setPointerCapture(e.pointerId);};canvas.onpointermove=e=>{if(pointer?.id===e.pointerId){angle+=(e.clientX-pointer.x)*.012;pointer.x=e.clientX;draw();}};canvas.onpointerup=canvas.onpointercancel=()=>{pointer=null;};canvas.onkeydown=e=>{if(['ArrowLeft','ArrowRight','Home'].includes(e.key)){e.preventDefault();angle=e.key==='Home'?0:angle+(e.key==='ArrowLeft'?-.15:.15);draw();}}; + function draw(){ + if(!images)return;const ctx=canvas.getContext('2d');ctx.clearRect(0,0,600,660);ctx.imageSmoothingEnabled=false; + const project=([x,y,z])=>{const rx=x*Math.cos(angle)+z*Math.sin(angle),rz=-x*Math.sin(angle)+z*Math.cos(angle);return [300+rx*16,260+y*16+rz*3.8,rz];}; + const faces=[]; + function cube(x,y,z,w,h,d,u,v,image,backing=true){ + const points=[[x,y,z],[x+w,y,z],[x+w,y+h,z],[x,y+h,z],[x,y,z+d],[x+w,y,z+d],[x+w,y+h,z+d],[x,y+h,z+d]]; + for(const [ids,uv,normal] of [ [[4,5,6,7],[u+d,v+d,w,h],[0,0,1]], [[1,0,3,2],[u+d+w+d,v+d,w,h],[0,0,-1]], [[0,4,7,3],[u,v+d,d,h],[-1,0,0]], [[5,1,2,6],[u+d+w,v+d,d,h],[1,0,0]], [[0,1,5,4],[u+d,v,w,d],[0,-1,0]] ]){ + const depth=normal[0]*-Math.sin(angle)+normal[2]*Math.cos(angle)-normal[1]*.24;if(depth<=0)continue; + const p=ids.map(i=>project(points[i]));faces.push({p,uv,image,backing,depth:p.reduce((n,p)=>n+p[2],0)/4}); + } + } + cube(-4,-12,-4,8,8,8,0,0,images.helmet); + cube(-4,-4,-2,8,12,4,16,16,images.chestplate); + cube(-8,-4,-2,4,12,4,40,16,images.chestplate);cube(4,-4,-2,4,12,4,40,16,images.chestplate); + cube(-4,8,-2,4,12,4,0,16,images.leggings);cube(0,8,-2,4,12,4,0,16,images.leggings); + cube(-4.03,8,-2.03,4.06,12.03,4.06,0,16,images.boots,false);cube(-.03,8,-2.03,4.06,12.03,4.06,0,16,images.boots,false); + faces.sort((a,b)=>a.depth-b.depth); + for(const {p,uv,image,backing} of faces){const [a,b,,d]=p,[u,v,w,h]=uv;ctx.save();ctx.transform((b[0]-a[0])/w,(b[1]-a[1])/w,(d[0]-a[0])/h,(d[1]-a[1])/h,a[0],a[1]);if(backing){ctx.fillStyle='#19161e';ctx.fillRect(0,0,w,h);}ctx.drawImage(image,u,v,w,h,0,0,w,h);ctx.restore();} + if(current?.banner.enabled&&bannerImage){ctx.fillStyle='#725735';ctx.fillRect(485,230,8,350);ctx.drawImage(bannerImage,493,235,90,180);} + } + async function update(equipment){current=equipment;const version=++revision; + try{ + const values=await Promise.all(Object.entries(equipment.armor).map(async([slot,piece])=>[slot,await armorTexture(slot,piece.trim)])); + let banner=null;if(equipment.banner.enabled){banner=surface(20,40);const c=banner.getContext('2d');c.fillStyle=colors[equipment.banner.base];c.fillRect(0,0,20,40);for(const layer of equipment.banner.patterns){const image=tint(await texture('entity/banner/'+layer.pattern),colors[layer.color]);c.drawImage(image,1,1,20,40,0,0,20,40);}} + if(version!==revision)return;images=Object.fromEntries(values);bannerImage=banner;note.textContent='Drag to rotate · arrow keys turn the armour';draw(); + }catch(error){if(version===revision)note.textContent=error.message;} + } + return {element:root,update}; +} diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 33fcf7b8..6a4a5b68 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -264,6 +264,9 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/game-link'||path.startsWith('/api/game-link/'))return links(request); if(path.startsWith('/api/community/'))return rewards(request); if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405}); + if(/^\/kit-textures\/(?:entity\/(?:banner\/[a-z_]+|equipment\/(?:humanoid|humanoid_leggings)\/netherite)|trims\/(?:color_palettes\/[a-z_]+|entity\/(?:humanoid|humanoid_leggings)\/[a-z_]+))\.png$/.test(path)){ + try{return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+path.slice(1),import.meta.url)),{headers:{'Content-Type':'image/png','Cache-Control':'public, max-age=86400'}});}catch{return new Response('Texture not found',{status:404});} + } if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});} if(path==='/federal-reserve'||path==='/federal-reserve/')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/reserve-ledger.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); // V2 shell is public; private data and writes retain their authenticated API gates. @@ -281,7 +284,7 @@ export function createPanel(db,settings={},dependencies={}){ return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); } const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1); - if(!['user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-profile-panels.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); + if(!['user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-profile-panels.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}}); }; } diff --git a/website/control-panel/upgrade-tokens.mjs b/website/control-panel/upgrade-tokens.mjs index f7024384..d952adae 100644 --- a/website/control-panel/upgrade-tokens.mjs +++ b/website/control-panel/upgrade-tokens.mjs @@ -10,7 +10,7 @@ export function createUpgradeTokens(db,settings={},deps={}){const auth=deps.auth const user=await auth(request);if(!user)return reply({message:'Sign in first.'},401); if(!(await access(user)).nodes.includes('web.menu.inventory'))return reply({message:'Inventory access required.'},403); const link=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first();if(!link||!uuid.test(link.minecraft_uuid))return reply({message:'Link Minecraft before using Upgrade Tokens.'},409); - if(request.method==='GET'){const {results}=await db.prepare('SELECT id,private_code,created_at,used_at,blueprint_id,result_json FROM site_upgrade_tokens WHERE owner_user_id=? AND minecraft_uuid=? ORDER BY created_at DESC LIMIT 100').bind(user.id,link.minecraft_uuid).all();return reply({priceDunemarks:UPGRADE_PRICE,tokens:results.map(t=>({id:t.id,code:t.used_at?undefined:t.private_code,createdAt:Number(t.created_at),usedAt:t.used_at?Number(t.used_at):null,blueprintId:t.blueprint_id,result:typeof t.result_json==='string'?JSON.parse(t.result_json):t.result_json})),gameDeliveryReady:false});} + if(request.method==='GET'){const {results}=await db.prepare('SELECT id,private_code,created_at,used_at,blueprint_id,result_json FROM site_upgrade_tokens WHERE owner_user_id=? AND minecraft_uuid=? ORDER BY created_at DESC LIMIT 100').bind(user.id,link.minecraft_uuid).all();return reply({priceDunemarks:UPGRADE_PRICE,tokens:results.map(t=>({id:t.id,code:t.used_at?undefined:t.private_code,createdAt:Number(t.created_at),usedAt:t.used_at?Number(t.used_at):null,blueprintId:t.blueprint_id,result:typeof t.result_json==='string'?JSON.parse(t.result_json):t.result_json})),gameDeliveryReady:(await db.prepare("SELECT setting_value FROM website_settings WHERE setting_key='kit-legendary-upgrade-delivery-ready'").first())?.setting_value==='true'});} if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(request.headers.get('origin')!==new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin)return reply({message:'Origin rejected.'},403); let b;try{const raw=await request.text();if(Buffer.byteLength(raw)>1024)throw Error();b=JSON.parse(raw);}catch{return reply({message:'Invalid token request.'},400);} @@ -21,7 +21,7 @@ export function createUpgradeTokens(db,settings={},deps={}){const auth=deps.auth if(b?.action==='roll'&&Object.keys(b).length===4&&uuid.test(b.blueprintId||'')&&Number.isSafeInteger(b.version)&&b.version>0&&/^DRU-[A-F0-9]{48}$/.test(b.code||'')){ let outcome;try{await db.batch([{async run(c){const q=async(s,v=[]) =>(await c.execute(s,v))[0];const linked=await q('SELECT minecraft_uuid FROM site_game_links WHERE user_id=? FOR SHARE',[user.id]);if(linked[0]?.minecraft_uuid.toLowerCase()!==link.minecraft_uuid.toLowerCase())throw Error('conflict');const tokens=await q('SELECT id,owner_user_id,minecraft_uuid,used_at,blueprint_id,result_json FROM site_upgrade_tokens WHERE code_hash=? FOR UPDATE',[hash(b.code)]),t=tokens[0];if(!t||t.owner_user_id!==user.id||t.minecraft_uuid.toLowerCase()!==link.minecraft_uuid.toLowerCase())throw Error('token');if(t.used_at){if(t.blueprint_id!==b.blueprintId)throw Error('token');outcome={replayed:true,result:typeof t.result_json==='string'?JSON.parse(t.result_json):t.result_json};return{meta:{changes:0}};} const designs=await q('SELECT owner_user_id,quality,commerce_kind,version,active FROM site_kit_blueprints WHERE id=? FOR UPDATE',[b.blueprintId]),d=designs[0];if(!d||d.owner_user_id!==user.id||d.quality!=='legendary'||d.commerce_kind!=='personal_sale'||!d.active)throw Error('design');if(Number(d.version)!==b.version)throw Error('conflict'); - const result=rollUpgrade(deps.randomInt||randomInt),now=Date.now();await q('UPDATE site_kit_blueprints SET upgrade_json=?,version=version+1,updated_at=? WHERE id=?',[JSON.stringify(result),now,b.blueprintId]);await q('UPDATE site_kit_listings SET published=0,version=version+1,updated_at=? WHERE blueprint_id=? AND published=1',[now,b.blueprintId]);await q('UPDATE site_upgrade_tokens SET used_at=?,blueprint_id=?,result_json=? WHERE id=?',[now,b.blueprintId,JSON.stringify(result),t.id]);await q('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),user.id,'legendary-upgrade-roll',JSON.stringify({tokenId:t.id,blueprintId:b.blueprintId,result}),now]);outcome={result,version:b.version+1};return{meta:{changes:1}};}}]);return reply({ok:true,...outcome});}catch(e){if(['token','design','conflict'].includes(e.message))return reply({message:e.message==='conflict'?'Your kit changed. Refresh before using this code. The code was not consumed.':e.message==='design'?'Only your saved Legendary Player Kit can be upgraded.':'This Upgrade Token is unavailable for this linked account.'},409);throw e;} + const result=rollUpgrade(deps.randomInt||randomInt),now=Date.now();await q('UPDATE site_kit_blueprints SET upgrade_json=?,version=version+1,updated_at=? WHERE id=?',[JSON.stringify(result),now,b.blueprintId]);await q('UPDATE site_kit_equipment SET blueprint_version=? WHERE kit_id=? AND blueprint_version=?',[b.version+1,b.blueprintId,b.version]);await q('UPDATE site_kit_listings SET published=0,version=version+1,updated_at=? WHERE blueprint_id=? AND published=1',[now,b.blueprintId]);await q('UPDATE site_upgrade_tokens SET used_at=?,blueprint_id=?,result_json=? WHERE id=?',[now,b.blueprintId,JSON.stringify(result),t.id]);await q('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),user.id,'legendary-upgrade-roll',JSON.stringify({tokenId:t.id,blueprintId:b.blueprintId,result}),now]);outcome={result,version:b.version+1};return{meta:{changes:1}};}}]);return reply({ok:true,...outcome});}catch(e){if(['token','design','conflict'].includes(e.message))return reply({message:e.message==='conflict'?'Your kit changed. Refresh before using this code. The code was not consumed.':e.message==='design'?'Only your saved Legendary Player Kit can be upgraded.':'This Upgrade Token is unavailable for this linked account.'},409);throw e;} } return reply({message:'Use a valid purchase or saved Legendary Player Kit and private token code.'},400); };} diff --git a/website/docs/KIT-ATELIER-V3.md b/website/docs/KIT-ATELIER-V3.md new file mode 100644 index 00000000..08eaced7 --- /dev/null +++ b/website/docs/KIT-ATELIER-V3.md @@ -0,0 +1,67 @@ +# Netherite kit atelier + +The v3 designer uses one bounded equipment contract for personal, clan, office, +faction and server kits. Every armour piece carries a netherite material, literal +name, up to six structured lore lines and a vanilla trim pattern/material. An +optional banner carries its base colour, up to six ordered pattern layers and +its own name and lore. Text components do not accept commands, click events, +HTML or arbitrary Minecraft component data. Blank lore lines are preserved; +colour, bold and italic are explicit. + +Website validation lives in `control-panel/public/kit-design-model.mjs`. The +private game bridge uses `network/server-control/kit_equipment.py` and the +checked-in matching contract and cross-language fixtures. + +Versioned equipment is saved in the same transaction as its blueprint revision +and audit entry. Updating a current design must never rewrite a paid order's +`snapshot_json`. Existing receipts retain the original purchased contract. + +The rotatable browser preview uses the Minecraft 1.21.4 netherite, trim palette +and banner textures. The exact official client URL and Mojang SHA-1 are recorded +in `web/assets/kit-textures/source.json`. Only the small required PNGs are kept; +the downloaded client archive was removed. Minecraft textures are copyright +Mojang Studios; this is an independent fan project. + +## Migration dependency corrected + +The private bridge at 2.28.33.142 previously connected gameplay SQL to the old +website host. Its kit routines join the `website` schema, so removing that schema +broke the catalogue even though the main website was healthy. The gameplay +connection now uses a separate SSH forward at local port 13308 to 91.107.196.242. +The current 41 gameplay tables / 661 rows were copied during a brief pause of +the private control service and savings timer. Both services were resumed; the +catalogue was checked successfully against current website publications. + +The LuckPerms connection remains on its existing separate port 13307. Do not +remove that tunnel or its database as part of website-file cleanup. No website +account, balance, receipt or current publication was restored from an older +website backup to make this correction. + +Native bridge modules captured here originate from the running private bridge. +Their configuration and credentials are not part of the repository. Install +the v3 bridge and verify native item delivery before publishing the new editor +or changing live kit revisions. The previous Alpha 1.0.0.5 handoff's plugin +deferral described that older task; this rebuild includes the requested native +item implementation and its verification. + +## Active inventory and activation + +The active lobby runs DuneCore 1.0.27-layout1-jobs1 with MySQL inventory. +Its game worlds share that process. The inactive Arrakis directory has a +PostgreSQL configuration; it must not be mistaken for the active inventory. +For MySQL, DuneKits locks the paid, requested, buyer-bound `dune_kit_sales` row +and commits its delivery acknowledgement inside DuneCore's inventory transaction. +The PostgreSQL dispatcher service is **not enabled** for this deployment: running +both delivery paths against independent inventory databases could duplicate kits. +Its prepared configuration and additive outbox schema remain unused. + +The lobby's existing private database credentials also match the gameplay bridge. +Before moving its connection from port 13307 to 13308, stop the empty lobby, +compare all gameplay tables, preserve any quest event delta and newer quest +schedule in a transaction, and retain a backup on the new mounted volume. +LuckPerms continues using its separate existing tunnel at port 13307. + +Apply `scripts/remake-current-kits.mjs --apply` only after native delivery is +active. It locks current revisions, backs up the affected designs, adds distinct +rarity/faction heraldry, increments publication versions, and audits each change. +It preserves existing v3 edits and never updates paid receipt snapshots. diff --git a/website/node/kit-delivery-bridge.mjs b/website/node/kit-delivery-bridge.mjs new file mode 100644 index 00000000..0e6913bb --- /dev/null +++ b/website/node/kit-delivery-bridge.mjs @@ -0,0 +1,58 @@ +import {createHash} from 'node:crypto'; +import {readFile,stat} from 'node:fs/promises'; +import {pathToFileURL} from 'node:url'; +import {setTimeout as delay} from 'node:timers/promises'; +import {validateKitEquipment} from '../control-panel/public/kit-design-model.mjs'; + +const uuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value); +const qualities=['common','uncommon','rare','very_rare','legendary']; +const kinds=['personal_sale','official_sale','faction_sale','server_sale']; + +export function validateQueuedKit(row){ + if(!uuid(row.id)||!uuid(row.buyer_uuid)||Number(row.quantity)!==1||!Number.isSafeInteger(Number(row.gross_cents))||Number(row.gross_cents)<=0||!Number.isSafeInteger(Number(row.completed_at))||Number(row.completed_at)<=0||!Number.isSafeInteger(Number(row.redeem_requested_at))||Number(row.redeem_requested_at)<=0||row.delivered_at!==null||typeof row.snapshot_json!=='string'||Buffer.byteLength(row.snapshot_json)>65536)throw Error('A paid, bound, requested kit receipt is required.'); + const snapshot=JSON.parse(row.snapshot_json); + if(!snapshot||typeof snapshot!=='object'||Array.isArray(snapshot)||typeof snapshot.name!=='string'||snapshot.name.length<1||snapshot.name.length>64||/[<>§\x00-\x1f\x7f]/.test(snapshot.name)||!qualities.includes(snapshot.quality)||snapshot.commerceKind!==undefined&&!kinds.includes(snapshot.commerceKind))throw Error('Invalid purchased kit snapshot.'); + if(snapshot.equipment!==undefined)validateKitEquipment(snapshot.equipment); + return {id:row.id.toLowerCase(),buyer:row.buyer_uuid.toLowerCase(),raw:row.snapshot_json,hash:createHash('sha256').update(row.snapshot_json).digest('hex'),createdAt:Number(row.completed_at)}; +} + +// Cross-database outbox: PostgreSQL commits delivery with the shared inventory. +// MySQL is acknowledged only after that durable commit, never when a claim is queued. +export async function syncKitDeliveries(mysql,postgres,{limit=100}={}){ + if(!Number.isSafeInteger(limit)||limit<1||limit>100)throw Error('Invalid delivery batch size.'); + const [rows]=await mysql.execute('SELECT id,buyer_uuid,quantity,gross_cents,snapshot_json,completed_at,redeem_requested_at,delivered_at FROM dune_kit_sales WHERE redeem_requested_at IS NOT NULL AND delivered_at IS NULL ORDER BY redeem_requested_at,id LIMIT ?', [limit]); + const result={queued:0,acknowledged:0,retained:0}; + for(const row of rows){ + try{ + const item=validateQueuedKit(row); + const inserted=await postgres.query('INSERT INTO dune_kit_deliveries(id,buyer_uuid,snapshot_json,snapshot_hash,created_at) VALUES($1,$2,$3,$4,$5) ON CONFLICT(id) DO NOTHING',[item.id,item.buyer,item.raw,item.hash,item.createdAt]); + result.queued+=inserted.rowCount; + const confirmed=await postgres.query('SELECT buyer_uuid,snapshot_hash,delivered_at FROM dune_kit_deliveries WHERE id=$1',[item.id]); + const delivery=confirmed.rows[0]; + if(!delivery||String(delivery.buyer_uuid).toLowerCase()!==item.buyer||delivery.snapshot_hash!==item.hash)throw Error('Delivery identity or purchased snapshot changed.'); + if(delivery.delivered_at!==null){ + const stamp=Number(delivery.delivered_at);if(!Number.isSafeInteger(stamp)||stamp<=0)throw Error('Invalid delivery acknowledgement.'); + const [updated]=await mysql.execute('UPDATE dune_kit_sales SET delivered_at=? WHERE id=? AND buyer_uuid=? AND delivered_at IS NULL AND redeem_requested_at IS NOT NULL AND SHA2(snapshot_json,256)=?',[stamp,item.id,item.buyer,item.hash]); + result.acknowledged+=updated.affectedRows; + } + }catch{result.retained++;} + } + return result; +} + +async function main(){ + const file='/home/dunerealms/.config/kit-delivery.json',mode=(await stat(file)).mode; + if(mode&0o007)throw Error('Delivery configuration must remain private.'); + const config=JSON.parse(await readFile(file,'utf8')); + if(config.mysql?.host!=='127.0.0.1'||config.mysql.port!==3306||config.mysql.database!=='dunegameplay'||config.postgres?.host!=='127.0.0.1'||config.postgres.port!==15432)throw Error('Unexpected private delivery database target.'); + const mysqlModule=await import('mysql2/promise'),pgModule=await import('pg'); + const mysql=mysqlModule.default.createPool({...config.mysql,connectionLimit:2,connectTimeout:5000,charset:'utf8mb4'}); + const postgres=new pgModule.default.Pool({...config.postgres,max:2,connectionTimeoutMillis:5000,statement_timeout:5000}); + let stopping=false;process.on('SIGTERM',()=>{stopping=true;});process.on('SIGINT',()=>{stopping=true;}); + postgres.on('error',()=>console.error('Kit delivery inventory connection interrupted; claims retained.')); + try{ + while(!stopping){try{const result=await syncKitDeliveries(mysql,postgres);if(result.queued||result.acknowledged||result.retained)console.log(JSON.stringify({kitDelivery:result}));}catch(error){console.error('Kit delivery sync unavailable; claims retained.',error.code||error.name);}if(!stopping)await delay(5000);} + }finally{await Promise.allSettled([mysql.end(),postgres.end()]);} +} + +if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)void main().catch(error=>{console.error('Kit delivery bridge did not start.',error.code||error.name);process.exitCode=1;}); diff --git a/website/node/schema.sql b/website/node/schema.sql index f9fc9cf0..d2a64b19 100644 --- a/website/node/schema.sql +++ b/website/node/schema.sql @@ -82,3 +82,5 @@ CREATE TABLE IF NOT EXISTS cp_ranks ( rank_key VARCHAR(40) PRIMARY KEY, label VARCHAR(40) NOT NULL, rank_level INTEGER NOT NULL, kind VARCHAR(16) NOT NULL, permissions_json TEXT NOT NULL, version INTEGER NOT NULL DEFAULT 1 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS site_kit_equipment (kit_id CHAR(36) PRIMARY KEY, blueprint_version INT NOT NULL, equipment_json JSON NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/website/ops/dunerealms-kit-delivery.service b/website/ops/dunerealms-kit-delivery.service new file mode 100644 index 00000000..e93eb8a3 --- /dev/null +++ b/website/ops/dunerealms-kit-delivery.service @@ -0,0 +1,19 @@ +[Unit] +Description=DuneRealms paid kit inventory delivery acknowledgement +After=network-online.target mysql.service dunerealms-inventory-tunnel.service +Requires=dunerealms-inventory-tunnel.service +RequiresMountsFor=/mnt/HC_Volume_107481500 + +[Service] +Type=simple +User=dunerealms +Group=dunerealms +WorkingDirectory=/home/dunerealms/apps/dunerealms/current +ExecStart=/home/dunerealms/.nvm/versions/node/v22.23.3/bin/node node/kit-delivery-bridge.mjs +Restart=on-failure +RestartSec=5 +TimeoutStopSec=15 +UMask=0027 + +[Install] +WantedBy=multi-user.target diff --git a/website/ops/promote-safe-v3.py b/website/ops/promote-safe-v3.py index 72a7af8d..ed2a4840 100644 --- a/website/ops/promote-safe-v3.py +++ b/website/ops/promote-safe-v3.py @@ -144,7 +144,7 @@ def main(): if run(['systemctl','is-active','--quiet',unit],check=False).returncode==0: run(['systemctl','disable','--now',unit]) pm2('save') - for unit in ('dunerealms-news-delivery.service','dunerealms-political-forum.service'): + for unit in ('dunerealms-news-delivery.service','dunerealms-political-forum.service','dunerealms-kit-delivery.service'): if run(['systemctl','is-active','--quiet',unit],check=False).returncode==0: run(['systemctl','restart',unit]) print('Retired background workers stopped; previous release retained for rollback',flush=True) diff --git a/website/scripts/install-kit-routines.mjs b/website/scripts/install-kit-routines.mjs new file mode 100644 index 00000000..c0959d6d --- /dev/null +++ b/website/scripts/install-kit-routines.mjs @@ -0,0 +1,40 @@ +import {pathToFileURL} from 'node:url'; +import {mkdir,writeFile} from 'node:fs/promises'; +import {createHash} from 'node:crypto'; + +export function kitRoutineWithEquipment(source){ + if(typeof source!=='string'||!source.includes('READS SQL DATA'))throw Error('Expected a read-only native kit routine.'); + if(source.includes('AS kit_equipment_json')){ + if(!source.includes('LEFT JOIN website.site_kit_equipment ke ON ke.kit_id=b.id AND ke.blueprint_version=b.version'))throw Error('Unexpected partially modified kit routine.'); + return source; + } + const select='b.lore_json AS kit_lore_json',join='JOIN website.site_accounts a ON a.id=b.owner_user_id'; + if(source.split(select).length!==2||source.split(join).length!==2)throw Error('Native kit routine changed; no SQL replaced.'); + return source.replace(select,select+',ke.equipment_json AS kit_equipment_json,b.item_names_json AS kit_item_names_json,b.upgrade_json AS kit_upgrade_json') + .replace(join,'LEFT JOIN website.site_kit_equipment ke ON ke.kit_id=b.id AND ke.blueprint_version=b.version '+join); +} + +async function main(apply){ + const mysql=(await import('mysql2/promise')).default; + const connection=await mysql.createConnection({user:'root',socketPath:'/var/run/mysqld/mysqld.sock'}); + try{ + const plans=[]; + for(const name of ['dune_kit_catalogue','dune_kit_listing_lock']){ + const [rows]=await connection.query('SHOW CREATE PROCEDURE dunegameplay.'+name); + const before=rows[0]?.['Create Procedure'];plans.push({name,before,after:kitRoutineWithEquipment(before)}); + } + if(!apply){console.log('Plan: version-bound equipment metadata in '+plans.filter(p=>p.before!==p.after).length+' read-only kit routines.');return;} + await connection.query('CREATE TABLE IF NOT EXISTS website.site_kit_equipment (kit_id CHAR(36) PRIMARY KEY,blueprint_version INT NOT NULL,equipment_json JSON NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'); + for(const plan of plans){ + if(plan.before===plan.after)continue; + const directory='/mnt/HC_Volume_107481500/dunegit/migration-backups';await mkdir(directory,{recursive:true,mode:0o700}); + const hash=createHash('sha256').update(plan.before).digest('hex').slice(0,16); + try{await writeFile(directory+'/'+plan.name+'-'+hash+'.sql',plan.before,{mode:0o600,flag:'wx'});}catch(error){if(error.code!=='EEXIST')throw error;} + await connection.query('USE dunegameplay');await connection.query('DROP PROCEDURE '+plan.name); + try{await connection.query(plan.after);}catch(error){await connection.query(plan.before);throw error;} + console.log('Installed versioned equipment metadata in '+plan.name); + } + }finally{await connection.end();} +} + +if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)void main(process.argv.includes('--apply')).catch(error=>{console.error('Native kit routine installation failed.',error.code||error.name);process.exitCode=1;}); diff --git a/website/scripts/remake-current-kits.mjs b/website/scripts/remake-current-kits.mjs new file mode 100644 index 00000000..76df397b --- /dev/null +++ b/website/scripts/remake-current-kits.mjs @@ -0,0 +1,47 @@ +import {pathToFileURL} from 'node:url'; +import {mkdir,writeFile} from 'node:fs/promises'; +import {randomUUID} from 'node:crypto'; +import {remakeKitEquipment,validateKitEquipment} from '../control-panel/public/kit-design-model.mjs'; + +const json=value=>typeof value==='string'?JSON.parse(value):value; +export function remadeEquipment(row){ + return remakeKitEquipment({name:row.name||row.kit_name,quality:row.quality||'legendary',office:row.office_key,factionId:row.faction_id,lore:json(row.lore_json||'[]'),itemNames:json(row.item_names_json||'{}')}); +} + +async function main(apply){ + const mysql=(await import('mysql2/promise')).default; + const db=await mysql.createConnection({user:'root',socketPath:'/var/run/mysqld/mysqld.sock'}); + try{ + await db.beginTransaction(); + const backup={blueprints:[],clan:[],office:[]},plans=[]; + for(const [table,key] of [['site_kit_blueprints','blueprints'],['site_clan_kit_designs','clan']]){ + const [rows]=await db.query('SELECT b.*,e.blueprint_version equipment_version,e.equipment_json FROM website.'+table+' b LEFT JOIN website.site_kit_equipment e ON e.kit_id=b.id FOR UPDATE'); + for(const row of rows){ + if(row.equipment_json){validateKitEquipment(json(row.equipment_json));if(Number(row.equipment_version)!==Number(row.version))throw Error('Equipment revision conflict; refresh before migration');continue;} + const equipment=remadeEquipment(row);backup[key].push(row);plans.push({table,row,equipment}); + } + } + const [offices]=await db.query('SELECT * FROM dunegameplay.dune_office_kit_definitions FOR UPDATE'); + for(const row of offices){if(row.equipment_json){validateKitEquipment(json(row.equipment_json));continue;}backup.office.push(row);plans.push({table:'office',row,equipment:remadeEquipment(row)});} + console.log(JSON.stringify({mode:apply?'apply':'plan',blueprints:backup.blueprints.length,clan:backup.clan.length,office:backup.office.length})); + if(!apply){await db.rollback();return;} + if(!plans.length){await db.rollback();return;} + const directory='/mnt/HC_Volume_107481500/dunegit/migration-backups';await mkdir(directory,{recursive:true,mode:0o700}); + await writeFile(directory+'/kit-remake-'+Date.now()+'-'+randomUUID()+'.json',JSON.stringify(backup),{flag:'wx',mode:0o600}); + for(const {table,row,equipment} of plans){ + const version=Number(row.version)+1; + if(table==='office'){ + const [result]=await db.query('UPDATE dunegameplay.dune_office_kit_definitions SET equipment_json=?,version=?,updated_at=? WHERE owner_uuid=? AND office_key=? AND term_id=? AND version=?',[JSON.stringify(equipment),version,Date.now(),row.owner_uuid,row.office_key,row.term_id,row.version]); + if(result.affectedRows!==1)throw Error('Office revision conflict'); + }else{ + const [result]=await db.query('UPDATE website.'+table+' SET version=?,updated_at=? WHERE id=? AND version=?',[version,Date.now(),row.id,row.version]);if(result.affectedRows!==1)throw Error('Blueprint revision conflict'); + await db.query('INSERT INTO website.site_kit_equipment(kit_id,blueprint_version,equipment_json) VALUES(?,?,?)',[row.id,version,JSON.stringify(equipment)]); + if(table==='site_kit_blueprints')await db.query('UPDATE website.site_kit_listings SET blueprint_version=?,version=version+1,updated_at=? WHERE blueprint_id=? AND blueprint_version=?',[version,Date.now(),row.id,row.version]); + else await db.query('UPDATE website.site_clan_kits SET version=?,updated_at=? WHERE id=? AND version=?',[version,Date.now(),row.id,row.version]); + } + await db.query('INSERT INTO website.account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),'00000000-0000-0000-0000-000000000000','kit-v3-remake',JSON.stringify({system:'verified-kit-migration',table,id:row.id||row.owner_uuid,office:row.office_key,from:Number(row.version),to:version,receiptsUnchanged:true}),Date.now()]); + } + await db.commit();console.log('Current kits remade; historical paid receipts unchanged.'); + }catch(error){await db.rollback();throw error;}finally{await db.end();} +} +if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)void main(process.argv.includes('--apply')).catch(error=>{console.error('Kit remake stopped; transaction rolled back.',error.code||error.name);process.exitCode=1;}); diff --git a/website/tests/kit-delivery-bridge.test.mjs b/website/tests/kit-delivery-bridge.test.mjs new file mode 100644 index 00000000..44b2f4b9 --- /dev/null +++ b/website/tests/kit-delivery-bridge.test.mjs @@ -0,0 +1,27 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {syncKitDeliveries,validateQueuedKit} from '../node/kit-delivery-bridge.mjs'; +import {defaultKitEquipment} from '../control-panel/public/kit-design-model.mjs'; + +const receipt=()=>({id:'11111111-1111-4111-8111-111111111111',buyer_uuid:'22222222-2222-4222-8222-222222222222',quantity:1,gross_cents:10000,completed_at:1000,redeem_requested_at:2000,delivered_at:null,snapshot_json:JSON.stringify({name:'Desert Sentinel',quality:'uncommon',commerceKind:'personal_sale',equipment:defaultKitEquipment()})}); +function fixture(){const row=receipt(),outbox=new Map();let acknowledgements=0;const mysql={async execute(sql,values){if(sql.startsWith('SELECT'))return [[...(row.delivered_at===null?[row]:[])]];assert(sql.startsWith('UPDATE dune_kit_sales SET delivered_at='));assert.equal(values[1],row.id);assert.equal(values[2],row.buyer_uuid);assert.equal(values[3],validateQueuedKit({...row,delivered_at:null}).hash);if(row.delivered_at!==null)return [{affectedRows:0}];row.delivered_at=values[0];acknowledgements++;return [{affectedRows:1}];}},postgres={async query(sql,values){if(sql.startsWith('INSERT')){if(outbox.has(values[0]))return {rowCount:0};outbox.set(values[0],{buyer_uuid:values[1],snapshot_hash:values[3],snapshot_json:values[2],delivered_at:null});return {rowCount:1};}return {rows:[outbox.get(values[0])].filter(Boolean)};}};return {row,outbox,mysql,postgres,acks:()=>acknowledgements};} + +test('queued claims remain unfulfilled until the atomic game inventory commit is acknowledged',async()=>{ + const f=fixture();assert.deepEqual(await syncKitDeliveries(f.mysql,f.postgres),{queued:1,acknowledged:0,retained:0}); + assert.equal(f.row.delivered_at,null);assert.equal(f.acks(),0); + assert.deepEqual(await syncKitDeliveries(f.mysql,f.postgres),{queued:0,acknowledged:0,retained:0});assert.equal(f.outbox.size,1); + f.outbox.get(f.row.id).delivered_at=3000; + assert.deepEqual(await syncKitDeliveries(f.mysql,f.postgres),{queued:0,acknowledged:1,retained:0});assert.equal(f.acks(),1); + await syncKitDeliveries(f.mysql,f.postgres);assert.equal(f.acks(),1); +}); + +test('a conflicting buyer or immutable snapshot cannot acknowledge another claim',async()=>{ + const f=fixture();await syncKitDeliveries(f.mysql,f.postgres);const queued=f.outbox.get(f.row.id);queued.buyer_uuid='33333333-3333-4333-8333-333333333333';queued.delivered_at=3000; + assert.deepEqual(await syncKitDeliveries(f.mysql,f.postgres),{queued:0,acknowledged:0,retained:1});assert.equal(f.acks(),0); + queued.buyer_uuid=f.row.buyer_uuid;queued.snapshot_hash='0'.repeat(64); + assert.equal((await syncKitDeliveries(f.mysql,f.postgres)).retained,1);assert.equal(f.acks(),0); +}); + +test('unpaid, unrequested and invalid item metadata never enter the delivery outbox',async()=>{ + for(const change of [r=>r.gross_cents=0,r=>r.redeem_requested_at=null,r=>r.quantity=2,r=>r.buyer_uuid='invalid',r=>r.snapshot_json='{"name":"bad","quality":"legendary","equipment":{}}']){const f=fixture();change(f.row);assert.throws(()=>validateQueuedKit(f.row));assert.equal((await syncKitDeliveries(f.mysql,f.postgres)).retained,1);assert.equal(f.outbox.size,0);assert.equal(f.acks(),0);} +}); diff --git a/website/tests/kit-design-model.test.mjs b/website/tests/kit-design-model.test.mjs new file mode 100644 index 00000000..85c83686 --- /dev/null +++ b/website/tests/kit-design-model.test.mjs @@ -0,0 +1,22 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {defaultKitEquipment,remakeKitEquipment,validateKitEquipment,loreLine,KIT_SLOTS} from '../control-panel/public/kit-design-model.mjs'; + +test('remade kits have distinct rarity heraldry while preserving custom names and lore',()=>{ + const patterns=new Set();for(const quality of ['common','uncommon','rare','very_rare','legendary']){ + const value=remakeKitEquipment({quality,name:'Desert Watch',itemNames:{helmet:'My hood'},lore:['My story','','Last line']}); + patterns.add(value.armor.helmet.trim.pattern);assert.equal(value.armor.helmet.name,'My hood');assert.deepEqual(value.armor.boots.lore.map(l=>l.text),['My story','','Last line']);assert.equal(value.banner.enabled,true);assert.equal(value.banner.patterns.length,2); + }assert.equal(patterns.size,5); + const imperial=remakeKitEquipment({quality:'common',office:'emperor'});assert.equal(imperial.armor.helmet.trim.material,'gold');assert.equal(imperial.banner.base,'purple'); +}); +test('legacy kit migration preserves names and blank lore lines independently for every piece',()=>{ + const old={name:'Desert watch',itemNames:{helmet:'Sentinel hood'},lore:['First line','','Third line']},kit=defaultKitEquipment(old); + assert.equal(kit.armor.helmet.name,'Sentinel hood');assert.equal(kit.armor.helmet.material,'netherite');assert.equal(kit.armor.boots.lore[1].text,'');kit.armor.helmet.lore[0].text='Changed';assert.equal(kit.armor.boots.lore[0].text,'First line');assert.equal(old.lore[0],'First line');assert.deepEqual(validateKitEquipment(kit),kit); +}); +test('structured lore and banner layer order survive the shared game contract',()=>{ + const kit=defaultKitEquipment();kit.armor.chestplate.lore=[loreLine('Water is life.','#bca05b',true,false),loreLine('')];kit.banner={enabled:true,name:'The Golden Standard',base:'black',patterns:[{pattern:'border',color:'yellow'},{pattern:'rhombus',color:'red'}],lore:[loreLine('Carried in service.')]}; + const saved=validateKitEquipment(JSON.parse(JSON.stringify(kit)));assert.deepEqual(saved.banner.patterns,kit.banner.patterns);assert.equal(saved.armor.chestplate.lore[0].color,'#BCA05B');assert.equal(saved.armor.chestplate.lore[0].italic,false);assert.equal(saved.armor.chestplate.lore[1].text,''); +}); +test('kit format rejects commands, arbitrary components, oversized lore and invalid trim/banner entries',()=>{ + for(const mutate of [k=>k.armor.helmet.lore=[{...loreLine('x'),clickEvent:{action:'run_command',value:'/op me'}}],k=>k.armor.boots.name='