Add receipt-bound native kit delivery and Paper metadata verification
All checks were successful
DuneRealms Kit Delivery CI / kits (push) Successful in 58s
All checks were successful
DuneRealms Kit Delivery CI / kits (push) Successful in 58s
This commit is contained in:
parent
eccff352da
commit
99b4c89ee9
18 changed files with 909 additions and 1 deletions
41
.forgejo/workflows/kit-delivery.yml
Normal file
41
.forgejo/workflows/kit-delivery.yml
Normal file
|
|
@ -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
|
||||
2
DuneKits/.gitignore
vendored
Normal file
2
DuneKits/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
/.gradle/
|
||||
/build/
|
||||
14
DuneKits/build.gradle.kts
Normal file
14
DuneKits/build.gradle.kts
Normal file
|
|
@ -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<JavaCompile> { 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") }
|
||||
1
DuneKits/settings.gradle.kts
Normal file
1
DuneKits/settings.gradle.kts
Normal file
|
|
@ -0,0 +1 @@
|
|||
rootProject.name = "DuneKits"
|
||||
201
DuneKits/src/main/java/com/example/dunekits/DuneKits.java
Normal file
201
DuneKits/src/main/java/com/example/dunekits/DuneKits.java
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
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<UUID> inflight = new HashSet<>();
|
||||
private final Map<UUID, Long> 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);
|
||||
}
|
||||
|
||||
@Override public void onDisable() { inflight.clear(); notices.clear(); }
|
||||
|
||||
private Connection connect() throws Exception {
|
||||
String url = core.getConfig().getString("database.jdbc-url", "");
|
||||
if (!url.startsWith("jdbc:postgresql://")) 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("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<UUID> pending = new ArrayList<>();
|
||||
try (Connection connection = connect(); PreparedStatement q = connection.prepareStatement(
|
||||
"SELECT id FROM dune_kit_deliveries WHERE buyer_uuid=? AND delivered_at IS NULL ORDER BY created_at,id LIMIT 5")) {
|
||||
q.setObject(1, buyer);
|
||||
try (ResultSet rows = q.executeQuery()) { while (rows.next()) pending.add((UUID) rows.getObject(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>) 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<Connection> operation = connection -> {
|
||||
try (PreparedStatement q = connection.prepareStatement(
|
||||
"SELECT snapshot_json,snapshot_hash FROM dune_kit_deliveries WHERE id=? AND buyer_uuid=? AND delivered_at IS NULL FOR UPDATE")) {
|
||||
q.setObject(1, id); q.setObject(2, player.getUniqueId());
|
||||
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<String, ItemStack> base = factionBase(player);
|
||||
List<ItemStack> items = KitItemFactory.create(snapshot, base);
|
||||
if (!player.getInventory().addItem(items.toArray(ItemStack[]::new)).isEmpty())
|
||||
throw new NoRoom();
|
||||
try (PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE dune_kit_deliveries SET delivered_at=(EXTRACT(EPOCH FROM clock_timestamp())*1000)::bigint WHERE id=? AND buyer_uuid=? AND delivered_at IS NULL")) {
|
||||
update.setObject(1, id); update.setObject(2, player.getUniqueId());
|
||||
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<String, ItemStack> 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<String, ItemStack> 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); } }
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
100
DuneKits/src/main/java/com/example/dunekits/KitItemFactory.java
Normal file
100
DuneKits/src/main/java/com/example/dunekits/KitItemFactory.java
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
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<ItemStack> create(JsonObject snapshot, Map<String, ItemStack> base) {
|
||||
KitSpec kit = new KitSpec(snapshot);
|
||||
List<ItemStack> 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);
|
||||
}
|
||||
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<Pattern> 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);
|
||||
}
|
||||
}
|
||||
126
DuneKits/src/main/java/com/example/dunekits/KitSpec.java
Normal file
126
DuneKits/src/main/java/com/example/dunekits/KitSpec.java
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
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<String> SLOTS = List.of("helmet", "chestplate", "leggings", "boots");
|
||||
static final Set<String> QUALITIES = Set.of("common", "uncommon", "rare", "very_rare", "legendary");
|
||||
static final Set<String> 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> lore, Trim trim) {}
|
||||
record Layer(String pattern, String color) {}
|
||||
record Banner(boolean enabled, String name, String base, List<Layer> patterns, List<Lore> lore) {}
|
||||
final String name, quality, kind, legacyColor;
|
||||
final boolean modern;
|
||||
final Map<String, Piece> armor;
|
||||
final Banner banner;
|
||||
|
||||
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<String, Piece> 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<Layer> 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<Lore> 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);
|
||||
}
|
||||
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> lore(JsonElement value) {
|
||||
List<Lore> 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"); }
|
||||
}
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
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<ItemStack> 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++;
|
||||
}
|
||||
}
|
||||
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(); }
|
||||
}
|
||||
}
|
||||
17
DuneKits/src/main/resources/plugin.yml
Normal file
17
DuneKits/src/main/resources/plugin.yml
Normal file
|
|
@ -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
|
||||
37
DuneKits/src/test/java/com/example/dunekits/KitSpecTest.java
Normal file
37
DuneKits/src/test/java/com/example/dunekits/KitSpecTest.java
Normal file
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
79
network/server-control/install-kit-equipment.py
Normal file
79
network/server-control/install-kit-equipment.py
Normal file
|
|
@ -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)
|
||||
9
network/server-control/kit-delivery-schema.sql
Normal file
9
network/server-control/kit-delivery-schema.sql
Normal file
|
|
@ -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;
|
||||
|
|
@ -150,4 +150,3 @@ def save(connect, payload):
|
|||
con.rollback()
|
||||
raise
|
||||
return {'ok': True, 'uuid': data['uuid'], 'office': data['office'], 'term': data['term'], 'version': data['version'] + 1}
|
||||
|
||||
|
|
|
|||
58
website/node/kit-delivery-bridge.mjs
Normal file
58
website/node/kit-delivery-bridge.mjs
Normal file
|
|
@ -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;});
|
||||
40
website/scripts/install-kit-routines.mjs
Normal file
40
website/scripts/install-kit-routines.mjs
Normal file
|
|
@ -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;});
|
||||
27
website/tests/kit-delivery-bridge.test.mjs
Normal file
27
website/tests/kit-delivery-bridge.test.mjs
Normal file
|
|
@ -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);}
|
||||
});
|
||||
13
website/tests/kit-routine-equipment.test.mjs
Normal file
13
website/tests/kit-routine-equipment.test.mjs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {kitRoutineWithEquipment} from '../scripts/install-kit-routines.mjs';
|
||||
const routine="CREATE PROCEDURE dune_kit_catalogue() READS SQL DATA BEGIN SELECT b.lore_json AS kit_lore_json FROM website.site_kit_blueprints b JOIN website.site_accounts a ON a.id=b.owner_user_id WHERE b.active=1 FOR SHARE; END";
|
||||
test('kit routine update adds revision-bound cosmetics without changing authority filters or locks',()=>{
|
||||
const after=kitRoutineWithEquipment(routine);
|
||||
assert.ok(after.includes('ke.blueprint_version=b.version'));
|
||||
assert.ok(after.includes('WHERE b.active=1 FOR SHARE; END'));
|
||||
assert.equal(kitRoutineWithEquipment(after),after);
|
||||
assert.ok(!after.includes('UPDATE '));assert.ok(!after.includes('INSERT '));
|
||||
});
|
||||
test('unexpected native routine definitions are rejected before replacement',()=>{
|
||||
for(const source of ['',routine.replace('READS SQL DATA','MODIFIES SQL DATA'),routine.replace('b.lore_json','x.lore_json'),routine+routine])assert.throws(()=>kitRoutineWithEquipment(source));
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff