Checkpoint Alpha 1.0.0.3 graphical menus and moderation evidence
Preserve the current Alpha source and artwork snapshot. See handoff/alpha-1.0.0.3 for actual deployed hashes, checks, staged follow-ups and the production pause. This checkpoint does not claim every source feature is deployed.
This commit is contained in:
parent
6e0f02e19a
commit
77cdf19faa
862 changed files with 22092 additions and 584 deletions
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -14,3 +14,7 @@ __pycache__/
|
|||
# Private database credentials and manual profile recovery snapshots
|
||||
/network/database/.env
|
||||
**/inventory-recovery/
|
||||
|
||||
# Native LuckPermsWeb builds are reproducible from pinned upstream plus the theme.
|
||||
/website/control-panel/native-editor/
|
||||
|
||||
|
|
|
|||
18
DuneAtelier/build.gradle.kts
Normal file
18
DuneAtelier/build.gradle.kts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
plugins { java }
|
||||
version="1.0.2"
|
||||
repositories {mavenCentral();maven("https://repo.papermc.io/repository/maven-public/")}
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
|
||||
compileOnly(files("../../output/gui-performance-20261029/release/DuneCore-1.0.21-gui-performance.jar"))
|
||||
testImplementation("io.papermc.paper:paper-api:1.21.4-R0.1-SNAPSHOT")
|
||||
testImplementation(files("../../output/gui-performance-20261029/release/DuneCore-1.0.21-gui-performance.jar"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||
testImplementation("com.h2database:h2:2.3.232")
|
||||
testImplementation("org.mockito:mockito-core:5.15.2")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
}
|
||||
java {toolchain.languageVersion.set(JavaLanguageVersion.of(21))}
|
||||
tasks.withType<JavaCompile>{options.encoding="UTF-8";options.release.set(21)}
|
||||
tasks.test {useJUnitPlatform()}
|
||||
tasks.processResources {from("../website/content/kit-quest-arc-v1.json")}
|
||||
tasks.jar {isPreserveFileTimestamps=false;isReproducibleFileOrder=true}
|
||||
1
DuneAtelier/settings.gradle.kts
Normal file
1
DuneAtelier/settings.gradle.kts
Normal file
|
|
@ -0,0 +1 @@
|
|||
rootProject.name="DuneAtelier"
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
package com.dunerealms.atelier;
|
||||
import com.google.gson.*;import java.io.*;import java.nio.charset.StandardCharsets;
|
||||
final class ArcLore {
|
||||
private static final JsonArray CHAPTERS=load();
|
||||
private static JsonArray load(){try(InputStream in=ArcLore.class.getResourceAsStream("/kit-quest-arc-v1.json")){if(in==null)throw new IllegalStateException("Canonical quest story missing");JsonArray rows=JsonParser.parseReader(new InputStreamReader(in,StandardCharsets.UTF_8)).getAsJsonObject().getAsJsonArray("chapters");if(rows.size()!=5)throw new IllegalStateException("Invalid chapter count");for(int i=0;i<5;i++){JsonObject row=rows.get(i).getAsJsonObject();if(row.get("index").getAsInt()!=i||!row.get("quality").getAsString().equals(DeliveryStore.TIERS.get(i))||row.get("targetSales").getAsInt()!=ArcStore.TARGETS[i]||row.get("minimumPriceDunemarks").getAsLong()*100!=ArcStore.MINIMUM[i]||row.get("rewardDunemarks").getAsLong()*100!=ArcStore.REWARDS[i])throw new IllegalStateException("Canonical quest economy mismatch");}return rows;}catch(IOException e){throw new IllegalStateException("Canonical story unavailable",e);}}
|
||||
static String description(int index){return CHAPTERS.get(index).getAsJsonObject().get("description").getAsString();}
|
||||
static String templateName(int index){return CHAPTERS.get(index).getAsJsonObject().getAsJsonObject("kitTemplate").get("name").getAsString();}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package com.dunerealms.atelier;
|
||||
import java.sql.*;import java.math.BigDecimal;import java.util.*;
|
||||
/** Fixed sales chapters; rewards transfer existing treasury funds and never mint currency. */
|
||||
public final class ArcStore {
|
||||
static final int[] TARGETS={3,5,10,15,25};
|
||||
static final long[] MINIMUM={10000,20000,40000,80000,160000},REWARDS={1000,2500,5000,10000,20000};
|
||||
static final String[] TITLES={"A Stitch in the Sand","Colours of the Caravan","The Caravan’s Trust","Patterns of Influence","A Legacy in Gold"};
|
||||
public record Chapter(int index,String title,String quality,int sales,int target,BigDecimal reward,boolean claimed,boolean unlocked){public boolean canClaim(){return !claimed&&unlocked&&sales>=target;}public String description(){return ArcLore.description(index);}public String templateName(){return ArcLore.templateName(index);}}
|
||||
public enum Claim {credited,already_claimed,pending_funding}
|
||||
static int claims(Connection c,UUID player)throws SQLException{int n=0;try(PreparedStatement q=c.prepareStatement("SELECT stage_index FROM dune_kit_arc_claims WHERE player_uuid=? ORDER BY stage_index")){q.setString(1,player.toString());try(ResultSet r=q.executeQuery()){while(r.next()){if(r.getInt(1)!=n||n>=5)throw new SQLException("Invalid claim sequence");n++;}}}return n;}
|
||||
static int sales(Connection c,UUID player,int index)throws SQLException{try(PreparedStatement q=c.prepareStatement("SELECT COUNT(*) FROM (SELECT buyer_uuid,FLOOR(delivered_at/86400000) AS utc_day FROM dune_kit_sales WHERE seller_uuid=? AND rarity=? AND buyer_uuid<>seller_uuid AND commerce_kind='personal_sale' AND delivered_at IS NOT NULL AND quantity=1 AND gross_cents>=? GROUP BY buyer_uuid,FLOOR(delivered_at/86400000)) AS qualifying")){q.setString(1,player.toString());q.setString(2,DeliveryStore.TIERS.get(index));q.setLong(3,MINIMUM[index]);try(ResultSet r=q.executeQuery()){r.next();return r.getInt(1);}}}
|
||||
public List<Chapter> read(Connection c,UUID player)throws SQLException{int done=claims(c,player);List<Chapter> result=new ArrayList<>();for(int i=0;i<5;i++)result.add(new Chapter(i,TITLES[i],DeliveryStore.TIERS.get(i),sales(c,player,i),TARGETS[i],BigDecimal.valueOf(REWARDS[i],2),i<done,i<=done));return result;}
|
||||
public Claim claim(Connection c,UUID player,int index)throws SQLException{
|
||||
if(index<0||index>=5)throw new SQLException("Invalid chapter");if(c.getAutoCommit())throw new SQLException("Explicit transaction required");
|
||||
ArcLore.description(index);
|
||||
BigDecimal treasury=null;try(PreparedStatement q=c.prepareStatement("SELECT balance FROM dune_staff_bank_wallet WHERE account_key='network' FOR UPDATE");ResultSet r=q.executeQuery()){if(r.next())treasury=r.getBigDecimal(1);}
|
||||
int done=claims(c,player);if(index<done)return Claim.already_claimed;if(index!=done||sales(c,player,index)<TARGETS[index])throw new SQLException("Complete the current sales chapter first");
|
||||
BigDecimal reward=BigDecimal.valueOf(REWARDS[index],2);if(treasury==null||treasury.compareTo(reward)<0)return Claim.pending_funding;
|
||||
BigDecimal wallet;try(PreparedStatement q=c.prepareStatement("SELECT balance FROM dune_economy_balances WHERE uuid=? FOR UPDATE")){q.setString(1,player.toString());try(ResultSet r=q.executeQuery()){if(!r.next())throw new SQLException("Existing Minecraft wallet required");wallet=r.getBigDecimal(1).add(reward);}}
|
||||
if(wallet.compareTo(new BigDecimal("1000000000000"))>0)throw new SQLException("Wallet limit reached");long now=System.currentTimeMillis();
|
||||
try(PreparedStatement q=c.prepareStatement("INSERT INTO dune_kit_arc_claims(player_uuid,stage_index,reward_cents,claimed_at) VALUES(?,?,?,?)")){q.setString(1,player.toString());q.setInt(2,index);q.setLong(3,REWARDS[index]);q.setLong(4,now);q.executeUpdate();}
|
||||
try(PreparedStatement q=c.prepareStatement("UPDATE dune_staff_bank_wallet SET balance=?,updated_at=? WHERE account_key='network'")){q.setBigDecimal(1,treasury.subtract(reward));q.setLong(2,now);if(q.executeUpdate()!=1)throw new SQLException("Treasury changed");}
|
||||
try(PreparedStatement q=c.prepareStatement("UPDATE dune_economy_balances SET balance=? WHERE uuid=?")){q.setBigDecimal(1,wallet);q.setString(2,player.toString());if(q.executeUpdate()!=1)throw new SQLException("Wallet changed");}
|
||||
try(PreparedStatement q=c.prepareStatement("INSERT INTO dune_staff_bank_ledger(id,player_uuid,action,delta,balance_after,created_at,reference) VALUES(?,?,?,?,?,?,?)")){q.setString(1,UUID.randomUUID().toString());q.setString(2,player.toString());q.setString(3,"kit-arc-reward");q.setBigDecimal(4,reward.negate());q.setBigDecimal(5,treasury.subtract(reward));q.setLong(6,now);q.setString(7,"kit-arc:"+player+":"+index);q.executeUpdate();}
|
||||
return Claim.credited;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package com.dunerealms.atelier;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import com.google.gson.*;
|
||||
/** Paid receipts are immutable. Delivery consumption shares the inventory checkpoint transaction. */
|
||||
public final class DeliveryStore {
|
||||
public record Design(String id,String name,String color,List<String> lore,String quality){}
|
||||
public record Pending(String id,String name,String quality){}
|
||||
static final List<String> TIERS=List.of("common","uncommon","rare","very_rare","legendary");
|
||||
static String plain(JsonElement value,int limit){if(value==null||!value.isJsonPrimitive()||!value.getAsJsonPrimitive().isString())throw new IllegalArgumentException("Plain text required");String raw=value.getAsString();String s=raw.strip();if(s.isEmpty()||s.codePointCount(0,s.length())>limit||raw.chars().anyMatch(c->c<32||c==127||c=='<'||c=='>'||c==167))throw new IllegalArgumentException("Invalid design text");return s;}
|
||||
static Design parse(String json){if(json==null||json.length()>16384)throw new IllegalArgumentException("Invalid design");JsonObject o=JsonParser.parseString(json).getAsJsonObject();String id=plain(o.get("blueprintId"),36);UUID.fromString(id);String quality=plain(o.get("quality"),16);if(!TIERS.contains(quality))throw new IllegalArgumentException("Invalid quality");String color=plain(o.get("color"),7);if(!color.matches("#[0-9a-fA-F]{6}"))throw new IllegalArgumentException("Invalid color");JsonArray lines=o.getAsJsonArray("lore");if(lines==null||lines.size()>6)throw new IllegalArgumentException("Invalid lore");List<String> lore=new ArrayList<>();for(JsonElement line:lines)lore.add(plain(line,120));return new Design(id,plain(o.get("name"),64),color,List.copyOf(lore),quality);}
|
||||
public List<Pending> pending(Connection c,UUID player,boolean queuedOnly)throws SQLException{List<Pending> rows=new ArrayList<>();try(PreparedStatement q=c.prepareStatement("SELECT id,snapshot_json FROM dune_kit_sales WHERE buyer_uuid=? AND delivered_at IS NULL"+(queuedOnly?" AND redeem_requested_at IS NOT NULL":"")+" ORDER BY completed_at,id LIMIT 25")){q.setString(1,player.toString());try(ResultSet r=q.executeQuery()){while(r.next()){Design d=parse(r.getString(2));rows.add(new Pending(r.getString(1),d.name(),d.quality()));}}}return rows;}
|
||||
public Design lock(Connection c,UUID player,UUID order)throws SQLException{if(c.getAutoCommit())throw new SQLException("Fenced inventory transaction required");try(PreparedStatement q=c.prepareStatement("SELECT buyer_uuid,snapshot_json,delivered_at FROM dune_kit_sales WHERE id=? FOR UPDATE")){q.setString(1,order.toString());try(ResultSet r=q.executeQuery()){if(!r.next()||!player.toString().equals(r.getString(1))||r.getObject(3)!=null)throw new SQLException("Paid item receipt unavailable");return parse(r.getString(2));}}}
|
||||
public void delivered(Connection c,UUID player,UUID order,long now)throws SQLException{if(c.getAutoCommit())throw new SQLException("Fenced inventory transaction required");try(PreparedStatement q=c.prepareStatement("UPDATE dune_kit_sales SET delivered_at=?,redeem_requested_at=COALESCE(redeem_requested_at,?) WHERE id=? AND buyer_uuid=? AND delivered_at IS NULL")){q.setLong(1,now);q.setLong(2,now);q.setString(3,order.toString());q.setString(4,player.toString());if(q.executeUpdate()!=1)throw new SQLException("Item receipt already consumed");}}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
package com.dunerealms.atelier;
|
||||
import com.example.dunegui.NativeMenus;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.event.ClickEvent;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import org.bukkit.*;import org.bukkit.command.*;import org.bukkit.entity.Player;import org.bukkit.inventory.*;import org.bukkit.inventory.meta.LeatherArmorMeta;import org.bukkit.persistence.PersistentDataType;import org.bukkit.plugin.java.JavaPlugin;
|
||||
import java.sql.*;import java.util.*;import java.util.concurrent.*;import java.util.function.Consumer;
|
||||
/** Shared illustrated menu renderer; paid orders retain their authoritative inventory checkpoint. */
|
||||
public final class DuneAtelier extends JavaPlugin implements CommandExecutor {
|
||||
private JavaPlugin core;private Driver driver;private Properties auth;private String url;private volatile boolean ready;
|
||||
private final DeliveryStore store=new DeliveryStore();private final Set<UUID> busy=new HashSet<>();
|
||||
private final ExecutorService worker=Executors.newFixedThreadPool(2,r->{Thread t=new Thread(r,"DuneAtelier-reader");t.setDaemon(true);return t;});
|
||||
public void onEnable(){core=(JavaPlugin)getServer().getPluginManager().getPlugin("DuneCore");getCommand("duneatelier").setExecutor(this);try{url=core.getConfig().getString("database.jdbc-url","");if(!url.startsWith("jdbc:mysql:"))throw new IllegalStateException();auth=new Properties();auth.setProperty("user",core.getConfig().getString("database.username",""));auth.setProperty("password",core.getConfig().getString("database.password",""));auth.setProperty("connectTimeout","3000");auth.setProperty("socketTimeout","5000");auth.setProperty("allowPublicKeyRetrieval","true");driver=(Driver)Class.forName("com.mysql.cj.jdbc.Driver",true,core.getClass().getClassLoader()).getDeclaredConstructor().newInstance();verifyFactory();worker.execute(()->{try(Connection c=connect();Statement q=c.createStatement()){q.executeQuery("SELECT id FROM dune_kit_sales LIMIT 0").close();ready=true;getLogger().info("Paid kit deliveries ready; no starter items or funds generated.");}catch(Exception e){getLogger().severe("Commerce schema unavailable; item delivery disabled.");}});getServer().getScheduler().runTaskTimer(this,()->{for(Player p:getServer().getOnlinePlayers())queued(p);},200,300);}catch(Exception e){getLogger().severe("Private shared MySQL configuration required.");}}
|
||||
public void onDisable(){ready=false;worker.shutdownNow();}
|
||||
private Connection connect()throws SQLException{Connection c=driver.connect(url,auth);if(c==null)throw new SQLException("No SQL driver");return c;}
|
||||
private void main(Runnable r){if(isEnabled())getServer().getScheduler().runTask(this,r);}
|
||||
static boolean entryAllowed(Player p){return p.isOnline()&&p.hasPermission("dune.atelier.view");}
|
||||
private boolean allowed(Player p){return ready&&entryAllowed(p);}
|
||||
static Runnable guarded(Player p,Runnable action){return ()->{if(entryAllowed(p))action.run();else p.sendMessage("Atelier menu access changed. Reopen your account menu.");};}
|
||||
private NativeMenus.Choice choice(Player p,String title,String description,Runnable action){return new NativeMenus.Choice(title,description,guarded(p,action));}
|
||||
private NativeMenus.Choice choice(Player p,String title,String description,Runnable action,String image){return new NativeMenus.Choice(title,description,guarded(p,action),image);}
|
||||
private Inventory loading(Player p){Inventory model=Bukkit.createInventory(null,9,"Atelier - Loading");NativeMenus.inventory(this,p,"Atelier - Loading",model,Map.of(),()->allowed(p));return model;}
|
||||
boolean current(Player p,Inventory model){return allowed(p)&&NativeMenus.isCurrent(p,model);}
|
||||
public boolean onCommand(CommandSender sender,Command command,String label,String[] args){if(sender instanceof Player p&&allowed(p))menu(p);else sender.sendMessage("Kits Exchange requires an active shared profile and menu access.");return true;}
|
||||
private void website(Player p,String path){if(!allowed(p))return;p.sendMessage(Component.text("Open Kits Exchange",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl("https://cp.dunerealms.com/"+path)));}
|
||||
private void menu(Player p){if(!allowed(p)||!busy.add(p.getUniqueId()))return;Inventory loading=loading(p);worker.execute(()->{try(Connection c=connect()){List<DeliveryStore.Pending> pending=store.pending(c,p.getUniqueId(),false);main(()->{busy.remove(p.getUniqueId());if(!current(p,loading))return;List<NativeMenus.Choice> choices=new ArrayList<>();choices.add(choice(p,"Kits Exchange","Browse designs, prices and confirmed sales.",()->website(p,"#kits-exchange"),"https://www.dunerealms.com/assets/gui/imperial-portal.png"));choices.add(choice(p,"The Loom of the Desert","Review your five sales chapters and claim treasury-funded rewards.",()->arc(p)));for(var item:pending)choices.add(choice(p,"Receive "+item.name(),item.quality().replace('_',' ')+" - Four pieces - Already paid",()->deliver(p,UUID.fromString(item.id()))));choices.add(choice(p,"Refresh","Check confirmed purchases.",()->menu(p)));NativeMenus.show(this,p,"Imperial Atelier",pending.isEmpty()?"No unclaimed paid kit orders. Website purchases issue personal redeem codes.":"Only your paid orders appear here. Make four empty inventory slots before receiving a kit.",choices);});}catch(Exception e){main(()->{busy.remove(p.getUniqueId());if(current(p,loading))p.sendMessage("Kit receipts are unavailable; no items changed.");});}});}
|
||||
private void arc(Player p){if(!allowed(p)||!busy.add(p.getUniqueId()))return;Inventory loading=loading(p);worker.execute(()->{try(Connection c=connect()){List<ArcStore.Chapter> chapters=new ArcStore().read(c,p.getUniqueId());main(()->{busy.remove(p.getUniqueId());if(!current(p,loading))return;List<NativeMenus.Choice> choices=new ArrayList<>();StringBuilder text=new StringBuilder("Sell your own designs to other players. Only paid, delivered kits count; one buyer per tier per UTC day.\n\n");for(var chapter:chapters){text.append(chapter.title()).append("\n").append(chapter.description()).append("\nDesign: ").append(chapter.templateName()).append("\n").append(chapter.quality().replace('_',' ')).append(" · ").append(chapter.sales()).append('/').append(chapter.target()).append(" sales · ").append(chapter.reward().toPlainString()).append(" Dunemarks · ").append(chapter.claimed()?"Claimed":chapter.unlocked()?"In progress":"Locked").append("\n\n");if(chapter.canClaim())choices.add(choice(p,"Claim "+chapter.title(),chapter.reward().toPlainString()+" Dunemarks from the server treasury",()->claimReward(p,chapter.index())));}choices.add(choice(p,"Refresh","Read confirmed sales progress.",()->arc(p)));choices.add(choice(p,"Back","Return to paid kit deliveries.",()->menu(p)));NativeMenus.show(this,p,"The Loom of the Desert",text.toString(),choices);});}catch(Exception e){main(()->{busy.remove(p.getUniqueId());if(current(p,loading))p.sendMessage("Sales progress is unavailable. No reward changed.");});}});}
|
||||
private void claimReward(Player p,int index){if(!allowed(p)||!busy.add(p.getUniqueId()))return;UUID player=p.getUniqueId();Inventory loading=loading(p);worker.execute(()->{try(Connection c=connect()){c.setAutoCommit(false);try{ArcStore.Claim result=new ArcStore().claim(c,player,index);c.commit();main(()->{busy.remove(player);if(current(p,loading)){p.sendMessage(result==ArcStore.Claim.credited?"Chapter reward transferred from the server treasury.":result==ArcStore.Claim.already_claimed?"This chapter reward was already claimed.":"Your reward is pending server treasury funding. You can retry later.");arc(p);}});}catch(Exception e){c.rollback();throw e;}}catch(Exception e){main(()->{busy.remove(player);if(current(p,loading))p.sendMessage("Reward was not committed. No currency was created.");});}});}
|
||||
private void queued(Player p){if(!allowed(p)||!p.hasPermission("dune.atelier.redeem")||!busy.add(p.getUniqueId()))return;worker.execute(()->{try(Connection c=connect()){List<DeliveryStore.Pending> rows=store.pending(c,p.getUniqueId(),true);main(()->{busy.remove(p.getUniqueId());if(!rows.isEmpty()&&allowed(p)&&empty(p)>=4)deliver(p,UUID.fromString(rows.getFirst().id()));});}catch(Exception e){main(()->busy.remove(p.getUniqueId()));}});}
|
||||
static int empty(Player p){int n=0;for(ItemStack i:p.getInventory().getStorageContents())if(i==null||i.getType().isAir())n++;return n;}
|
||||
private void deliver(Player p,UUID order){if(!allowed(p)||!p.hasPermission("dune.atelier.redeem")||!busy.add(p.getUniqueId()))return;try{if(empty(p)<4){p.sendMessage("Make four empty inventory slots; your paid kit stays pending.");return;}Consumer<Connection> operation=c->{try{if(!allowed(p)||!p.hasPermission("dune.atelier.redeem"))throw new IllegalStateException("Delivery permission changed");DeliveryStore.Design design=store.lock(c,p.getUniqueId(),order);List<ItemStack> pieces=kit(p,design,order);for(ItemStack item:pieces)if(!p.getInventory().addItem(item).isEmpty())throw new IllegalStateException("Inventory capacity changed");store.delivered(c,p.getUniqueId(),order,System.currentTimeMillis());}catch(Exception e){throw new IllegalStateException("Paid kit delivery refused",e);}};core.getClass().getMethod("transactNetworkInventory",Player.class,Consumer.class).invoke(core,p,operation);p.sendMessage("Your paid kit has been delivered. Its item code is now used.");}catch(Exception e){p.sendMessage("Delivery was not committed. Your paid receipt stays available.");}finally{busy.remove(p.getUniqueId());}}
|
||||
private List<ItemStack> kit(Player p,DeliveryStore.Design d,UUID order)throws Exception{String faction=String.valueOf(core.getClass().getMethod("factionOf",Player.class).invoke(core,p));if(!Set.of("Fremen","Harkonnen","Corrino","Atreides","Ordos").contains(faction))throw new IllegalStateException("Select a playable faction first");Object raw=core.getClass().getMethod("createFactionKit",String.class).invoke(core,faction);if(!(raw instanceof List<?> base))throw new IllegalStateException("Faction factory unavailable");return KitFactory.decorate(base,d,order);}
|
||||
private void verifyFactory()throws Exception{for(String faction:List.of("Fremen","Harkonnen","Corrino","Atreides","Ordos")){Object raw=core.getClass().getMethod("createFactionKit",String.class).invoke(core,faction);if(!(raw instanceof List<?> base))throw new IllegalStateException("Faction factory unavailable");for(String quality:DeliveryStore.TIERS)KitFactory.verify(base,new DeliveryStore.Design(UUID.randomUUID().toString(),"Transient factory verification","#123456",List.of("Not issued to a player."),quality));}getLogger().info("25 faction/rarity factory cases passed; no inventory or balances touched.");}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package com.dunerealms.atelier;
|
||||
import java.util.*;
|
||||
/** Server-owned quality policy. Blueprint input never supplies enchantments. */
|
||||
final class KitEnchantments {
|
||||
static final String VERSION="pvp-v1";
|
||||
static Map<String,Integer> profile(String quality,String material){
|
||||
int tier=List.of("common","uncommon","rare","very_rare","legendary").indexOf(quality);
|
||||
if(tier<0)throw new IllegalArgumentException("Unknown kit quality");
|
||||
if(!Set.of("LEATHER_HELMET","LEATHER_CHESTPLATE","LEATHER_LEGGINGS","LEATHER_BOOTS").contains(material))throw new IllegalArgumentException("Expected stillsuit armour");
|
||||
Map<String,Integer> e=new LinkedHashMap<>();
|
||||
// Common is the unenchanted vanilla starter kit.
|
||||
if(tier==0)return Map.of();
|
||||
e.put("protection",tier);e.put("unbreaking",Math.min(tier,3));
|
||||
if(material.endsWith("BOOTS")){e.put("feather_falling",tier);if(tier>=2)e.put("depth_strider",tier-1);if(tier==4)e.put("soul_speed",3);}
|
||||
if(tier>=2&&material.endsWith("HELMET")){e.put("respiration",tier-1);e.put("aqua_affinity",1);}
|
||||
if(tier>=3){e.put("mending",1);if(material.endsWith("LEGGINGS"))e.put("swift_sneak",tier-1);}
|
||||
if(tier==4)e.put("thorns",3);
|
||||
return Collections.unmodifiableMap(e);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
package com.dunerealms.atelier;
|
||||
import org.bukkit.*;import org.bukkit.inventory.*;import org.bukkit.inventory.meta.LeatherArmorMeta;import org.bukkit.persistence.PersistentDataType;
|
||||
import net.kyori.adventure.text.Component;import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import java.util.*;
|
||||
final class KitFactory {
|
||||
static List<ItemStack> decorate(List<?> base,DeliveryStore.Design d,UUID order){
|
||||
if(!DeliveryStore.TIERS.contains(d.quality()))throw new IllegalArgumentException("Invalid kit rarity");List<ItemStack> pieces=new ArrayList<>();
|
||||
for(Object value:base)if(value instanceof ItemStack original&&original.getItemMeta() instanceof LeatherArmorMeta){
|
||||
ItemStack copy=original.clone();LeatherArmorMeta meta=(LeatherArmorMeta)copy.getItemMeta();meta.setColor(Color.fromRGB(Integer.parseInt(d.color().substring(1),16)));
|
||||
meta.displayName(Component.text(d.name()+" "+copy.getType().name().replace("LEATHER_","").toLowerCase(Locale.ROOT),NamedTextColor.GOLD));
|
||||
String label=Arrays.stream(d.quality().split("_")).map(s->Character.toUpperCase(s.charAt(0))+s.substring(1)).collect(java.util.stream.Collectors.joining(" "));
|
||||
List<Component> lore=new ArrayList<>();lore.add(Component.text("Quality: "+label,NamedTextColor.GREEN));for(String line:d.lore())lore.add(Component.text(line,NamedTextColor.GRAY));meta.lore(lore);
|
||||
applyEnchantments(meta,copy.getType(),d.quality());
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","quality"),PersistentDataType.STRING,d.quality());
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","kit_sale_id"),PersistentDataType.STRING,order.toString());
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","kit_design_id"),PersistentDataType.STRING,d.id());copy.setItemMeta(meta);pieces.add(copy);
|
||||
}
|
||||
if(pieces.size()!=4||pieces.stream().map(ItemStack::getType).distinct().count()!=4)throw new IllegalStateException("Incomplete faction kit");return pieces;
|
||||
}
|
||||
static void applyEnchantments(LeatherArmorMeta meta,Material material,String quality){
|
||||
for(var enchant:List.copyOf(meta.getEnchants().keySet()))meta.removeEnchant(enchant);
|
||||
for(var entry:KitEnchantments.profile(quality,material.name()).entrySet()){
|
||||
var enchant=org.bukkit.Registry.ENCHANTMENT.get(NamespacedKey.minecraft(entry.getKey()));
|
||||
if(enchant==null||entry.getValue()>enchant.getMaxLevel()||!meta.addEnchant(enchant,entry.getValue(),false))throw new IllegalStateException("Kit enchantment unavailable: "+entry.getKey());
|
||||
}
|
||||
}
|
||||
static boolean expectedEnchantments(LeatherArmorMeta meta,Material material,String quality){
|
||||
Map<String,Integer> actual=new HashMap<>();meta.getEnchants().forEach((key,value)->actual.put(key.getKey().getKey(),value));
|
||||
return actual.equals(KitEnchantments.profile(quality,material.name()));
|
||||
}
|
||||
static Object trim(org.bukkit.inventory.meta.ItemMeta meta){return meta instanceof org.bukkit.inventory.meta.ArmorMeta armor?armor.getTrim():null;}
|
||||
static void verify(List<?> base,DeliveryStore.Design d){
|
||||
List<ItemStack> originals=base.stream().filter(v->v instanceof ItemStack i&&i.getItemMeta() instanceof LeatherArmorMeta).map(v->(ItemStack)v).toList();
|
||||
List<byte[]> before=originals.stream().map(ItemStack::serializeAsBytes).toList();List<ItemStack> made=decorate(base,d,UUID.randomUUID());
|
||||
for(int i=0;i<4;i++){
|
||||
var original=originals.get(i);var originalMeta=(LeatherArmorMeta)original.getItemMeta();var result=made.get(i);var resultMeta=(LeatherArmorMeta)result.getItemMeta();
|
||||
if(!Arrays.equals(before.get(i),original.serializeAsBytes())||!Objects.equals(originalMeta.getAttributeModifiers(),resultMeta.getAttributeModifiers())||!expectedEnchantments(resultMeta,result.getType(),d.quality())||!Objects.equals(trim(originalMeta),trim(resultMeta)))throw new IllegalStateException("Kit decoration changed attributes, trim or quality enchantments");
|
||||
for(NamespacedKey tag:originalMeta.getPersistentDataContainer().getKeys()){if(tag.equals(new NamespacedKey("dunerealms","quality")))continue;String value=originalMeta.getPersistentDataContainer().get(tag,PersistentDataType.STRING);if(value!=null&&!value.equals(resultMeta.getPersistentDataContainer().get(tag,PersistentDataType.STRING)))throw new IllegalStateException("Faction authority changed");}
|
||||
if(!d.quality().equals(resultMeta.getPersistentDataContainer().get(new NamespacedKey("dunerealms","quality"),PersistentDataType.STRING)))throw new IllegalStateException("Quality label mismatch");
|
||||
}
|
||||
}
|
||||
}
|
||||
14
DuneAtelier/src/main/resources/plugin.yml
Normal file
14
DuneAtelier/src/main/resources/plugin.yml
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
name: DuneAtelier
|
||||
version: 1.0.2
|
||||
main: com.dunerealms.atelier.DuneAtelier
|
||||
api-version: '1.21.4'
|
||||
depend: [DuneCore, DuneMenus]
|
||||
commands:
|
||||
duneatelier:
|
||||
description: Kits Exchange, paid item deliveries and the Loom of the Desert
|
||||
aliases: [kitsexchange]
|
||||
permissions:
|
||||
dune.atelier.view:
|
||||
default: true
|
||||
dune.atelier.redeem:
|
||||
default: true
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
package com.dunerealms.atelier;
|
||||
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;import java.sql.*;import java.math.BigDecimal;import java.util.*;
|
||||
class ArcStoreTest {
|
||||
final UUID player=UUID.randomUUID();
|
||||
Connection database(String funding)throws Exception{Connection c=DriverManager.getConnection("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE");try(Statement s=c.createStatement()){s.execute("CREATE TABLE dune_kit_sales(buyer_uuid VARCHAR(36),seller_uuid VARCHAR(36),rarity VARCHAR(16),delivered_at BIGINT,quantity INT,gross_cents BIGINT,commerce_kind VARCHAR(16) NOT NULL DEFAULT 'personal_sale')");s.execute("CREATE TABLE dune_kit_arc_claims(player_uuid VARCHAR(36),stage_index INT,reward_cents BIGINT,claimed_at BIGINT,PRIMARY KEY(player_uuid,stage_index))");s.execute("CREATE TABLE dune_staff_bank_wallet(account_key VARCHAR(16) PRIMARY KEY,balance DECIMAL(20,2),updated_at BIGINT)");s.execute("CREATE TABLE dune_economy_balances(uuid VARCHAR(36) PRIMARY KEY,balance DECIMAL(20,2))");s.execute("CREATE TABLE dune_staff_bank_ledger(id VARCHAR(36) PRIMARY KEY,player_uuid VARCHAR(36),action VARCHAR(32),delta DECIMAL(20,2),balance_after DECIMAL(20,2),created_at BIGINT,reference VARCHAR(100) UNIQUE)");s.execute("INSERT INTO dune_staff_bank_wallet VALUES('network',"+funding+",0)");s.execute("INSERT INTO dune_economy_balances VALUES('"+player+"',0)");}return c;}
|
||||
void sale(Connection c,UUID buyer,Long delivered,String quality,long gross)throws Exception{try(PreparedStatement q=c.prepareStatement("INSERT INTO dune_kit_sales(buyer_uuid,seller_uuid,rarity,delivered_at,quantity,gross_cents) VALUES(?,?,?,?,1,?)")){q.setString(1,buyer.toString());q.setString(2,player.toString());q.setString(3,quality);if(delivered==null)q.setNull(4,Types.BIGINT);else q.setLong(4,delivered);q.setLong(5,gross);q.executeUpdate();}}
|
||||
void qualify(Connection c)throws Exception{for(int i=0;i<3;i++)sale(c,UUID.randomUUID(),1000L,"common",10000);}
|
||||
BigDecimal sum(Connection c)throws Exception{try(Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT (SELECT SUM(balance) FROM dune_staff_bank_wallet)+(SELECT SUM(balance) FROM dune_economy_balances)")){r.next();return r.getBigDecimal(1);}}
|
||||
@Test void paidDeliveredExternalUniqueBuyersOnly()throws Exception{try(Connection c=database("50")){UUID buyer=UUID.randomUUID();sale(c,buyer,1000L,"common",10000);sale(c,buyer,2000L,"common",10000);sale(c,player,1000L,"common",10000);sale(c,UUID.randomUUID(),null,"common",10000);sale(c,UUID.randomUUID(),1000L,"common",9999);assertEquals(1,ArcStore.sales(c,player,0));}}
|
||||
@Test void officialFactionAndServerSalesNeverAdvancePersonalDesignChapters()throws Exception{try(Connection c=database("50")){for(String kind:List.of("official_sale","faction_sale","server_sale")){UUID buyer=UUID.randomUUID();sale(c,buyer,1000L,"common",10000);try(PreparedStatement q=c.prepareStatement("UPDATE dune_kit_sales SET commerce_kind=? WHERE buyer_uuid=?")){q.setString(1,kind);q.setString(2,buyer.toString());q.executeUpdate();}}assertEquals(0,ArcStore.sales(c,player,0));sale(c,UUID.randomUUID(),1000L,"common",10000);assertEquals(1,ArcStore.sales(c,player,0));}}
|
||||
@Test void rewardsConserveExistingMoneyAndAreExactlyOnce()throws Exception{try(Connection c=database("50")){qualify(c);c.setAutoCommit(false);ArcStore store=new ArcStore();assertEquals(ArcStore.Claim.credited,store.claim(c,player,0));c.commit();assertEquals(ArcStore.Claim.already_claimed,store.claim(c,player,0));c.commit();assertEquals(new BigDecimal("50.00"),sum(c));try(Statement q=c.createStatement();ResultSet r=q.executeQuery("SELECT balance FROM dune_economy_balances")){r.next();assertEquals(new BigDecimal("10.00"),r.getBigDecimal(1));}}}
|
||||
@Test void unfundedRewardCreatesNoClaimOrMoney()throws Exception{try(Connection c=database("0")){qualify(c);c.setAutoCommit(false);assertEquals(ArcStore.Claim.pending_funding,new ArcStore().claim(c,player,0));c.commit();assertEquals(0,ArcStore.claims(c,player));assertEquals(new BigDecimal("0.00"),sum(c));}}
|
||||
@Test void transactionRollbackRestoresTreasuryWalletAndReceipt()throws Exception{try(Connection c=database("50")){qualify(c);c.setAutoCommit(false);new ArcStore().claim(c,player,0);c.rollback();assertEquals(0,ArcStore.claims(c,player));assertEquals(new BigDecimal("50.00"),sum(c));}}
|
||||
@Test void cannotSkipIncompleteChapter()throws Exception{try(Connection c=database("50")){qualify(c);c.setAutoCommit(false);assertThrows(SQLException.class,()->new ArcStore().claim(c,player,1));c.rollback();assertEquals(0,ArcStore.claims(c,player));}}
|
||||
@Test void canonicalStoryAndFiveCosmeticTemplatesMatchEconomy(){for(int i=0;i<5;i++){assertFalse(ArcLore.description(i).isBlank());assertFalse(ArcLore.templateName(i).isBlank());}assertEquals(38500,Arrays.stream(ArcStore.REWARDS).sum());}
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package com.dunerealms.atelier;
|
||||
import com.example.dunegui.NativeMenus;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class AtelierMenuAccessTest {
|
||||
@Test void aSavedDesignOrRewardButtonCannotRunAfterViewAccessRevocation(){
|
||||
Player p=mock(Player.class);when(p.isOnline()).thenReturn(true);when(p.hasPermission("dune.atelier.view")).thenReturn(true);
|
||||
AtomicInteger calls=new AtomicInteger();Runnable button=DuneAtelier.guarded(p,calls::incrementAndGet);
|
||||
when(p.hasPermission("dune.atelier.view")).thenReturn(false);button.run();assertEquals(0,calls.get());
|
||||
}
|
||||
@Test void disconnectedPlayersCannotRunStoredCallbacks(){
|
||||
Player p=mock(Player.class);when(p.hasPermission("dune.atelier.view")).thenReturn(true);
|
||||
AtomicInteger calls=new AtomicInteger();DuneAtelier.guarded(p,calls::incrementAndGet).run();assertEquals(0,calls.get());
|
||||
}
|
||||
@Test void anOldReceiptQueryCannotReopenAClosedOrReplacedScreen()throws Exception{
|
||||
DuneAtelier plugin=mock(DuneAtelier.class,CALLS_REAL_METHODS);Field ready=DuneAtelier.class.getDeclaredField("ready");ready.setAccessible(true);ready.set(plugin,true);
|
||||
Player p=mock(Player.class);Inventory old=mock(Inventory.class),fresh=mock(Inventory.class);
|
||||
when(p.isOnline()).thenReturn(true);when(p.hasPermission("dune.atelier.view")).thenReturn(true);
|
||||
try(var menus=mockStatic(NativeMenus.class)){
|
||||
menus.when(()->NativeMenus.isCurrent(p,fresh)).thenReturn(true);
|
||||
assertFalse(plugin.current(p,old));assertTrue(plugin.current(p,fresh));
|
||||
ready.set(plugin,false);assertFalse(plugin.current(p,fresh));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package com.dunerealms.atelier;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.sql.*;import java.util.*;
|
||||
class DeliveryStoreTest {
|
||||
final UUID owner=UUID.fromString("00000000-0000-0000-0009-000000000001"),other=UUID.fromString("00000000-0000-0000-0009-000000000002"),order=UUID.randomUUID();
|
||||
String design(){return "{\"blueprintId\":\""+UUID.randomUUID()+"\",\"name\":\"Desert Herald\",\"color\":\"#123456\",\"quality\":\"common\",\"lore\":[\"An original design.\"]}";}
|
||||
Connection database()throws Exception{Connection c=DriverManager.getConnection("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE");try(Statement s=c.createStatement()){s.execute("CREATE TABLE dune_kit_sales(id VARCHAR(36) PRIMARY KEY,buyer_uuid VARCHAR(36),snapshot_json TEXT,completed_at BIGINT,redeem_requested_at BIGINT,delivered_at BIGINT)");}try(PreparedStatement q=c.prepareStatement("INSERT INTO dune_kit_sales(id,buyer_uuid,snapshot_json,completed_at) VALUES(?,?,?,1)")){q.setString(1,order.toString());q.setString(2,owner.toString());q.setString(3,design());q.executeUpdate();}return c;}
|
||||
@Test void wrongPlayerCannotLockPaidReceipt()throws Exception{try(Connection c=database()){c.setAutoCommit(false);assertThrows(SQLException.class,()->new DeliveryStore().lock(c,other,order));}}
|
||||
@Test void unfencedConnectionCannotConsume()throws Exception{try(Connection c=database()){assertThrows(SQLException.class,()->new DeliveryStore().lock(c,owner,order));assertThrows(SQLException.class,()->new DeliveryStore().delivered(c,owner,order,2));}}
|
||||
@Test void rolledBackCheckpointLeavesReceiptAvailable()throws Exception{try(Connection c=database()){c.setAutoCommit(false);DeliveryStore store=new DeliveryStore();store.lock(c,owner,order);store.delivered(c,owner,order,2);c.rollback();assertNotNull(store.lock(c,owner,order));assertEquals(1,store.pending(c,owner,false).size());}}
|
||||
@Test void committedReceiptCannotBeConsumedTwice()throws Exception{try(Connection c=database()){c.setAutoCommit(false);DeliveryStore store=new DeliveryStore();assertNotNull(store.lock(c,owner,order));store.delivered(c,owner,order,2);c.commit();assertThrows(SQLException.class,()->store.lock(c,owner,order));assertThrows(SQLException.class,()->store.delivered(c,owner,order,3));assertTrue(store.pending(c,owner,false).isEmpty());}}
|
||||
@Test void onlyExplicitlyQueuedReceiptsAutoDeliver()throws Exception{try(Connection c=database()){DeliveryStore store=new DeliveryStore();assertEquals(1,store.pending(c,owner,false).size());assertTrue(store.pending(c,owner,true).isEmpty());try(Statement s=c.createStatement()){s.executeUpdate("UPDATE dune_kit_sales SET redeem_requested_at=2");}assertEquals(1,store.pending(c,owner,true).size());}}
|
||||
@Test void malformedCosmeticsCannotReachItemFactory(){for(String replacement:List.of("<script>","§kHidden","x\n"))assertThrows(Exception.class,()->DeliveryStore.parse(design().replace("Desert Herald",replacement)));assertThrows(Exception.class,()->DeliveryStore.parse(design().replace("common","admin")));assertThrows(Exception.class,()->DeliveryStore.parse(design().replace("#123456","red")));assertThrows(Exception.class,()->DeliveryStore.parse(design().replace("\"An original design.\"","{}")));}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package com.dunerealms.atelier;
|
||||
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;import java.util.*;
|
||||
class KitEnchantmentsTest {
|
||||
@Test void vanillaCommonHasNoEnchantments(){for(String piece:List.of("HELMET","CHESTPLATE","LEGGINGS","BOOTS"))assertTrue(KitEnchantments.profile("common","LEATHER_"+piece).isEmpty());}
|
||||
@Test void protectionProgressesByQuality(){int n=0;for(String q:List.of("uncommon","rare","very_rare","legendary"))assertEquals(++n,KitEnchantments.profile(q,"LEATHER_CHESTPLATE").get("protection"));}
|
||||
@Test void legendaryIsFullCompatibleArmour(){var b=KitEnchantments.profile("legendary","LEATHER_BOOTS");assertEquals(Map.of("protection",4,"unbreaking",3,"mending",1,"thorns",3,"feather_falling",4,"depth_strider",3,"soul_speed",3),b);var h=KitEnchantments.profile("legendary","LEATHER_HELMET");assertEquals(3,h.get("respiration"));assertEquals(1,h.get("aqua_affinity"));assertEquals(3,KitEnchantments.profile("legendary","LEATHER_LEGGINGS").get("swift_sneak"));assertFalse(b.containsKey("frost_walker"));assertFalse(b.containsKey("blast_protection"));}
|
||||
@Test void utilityAndDurabilityNeverDecrease(){for(String piece:List.of("HELMET","CHESTPLATE","LEGGINGS","BOOTS")){Map<String,Integer> before=Map.of();for(String q:List.of("common","uncommon","rare","very_rare","legendary")){var next=KitEnchantments.profile(q,"LEATHER_"+piece);for(var e:before.entrySet())assertTrue(next.getOrDefault(e.getKey(),0)>=e.getValue());before=next;}}}
|
||||
@Test void rejectsUnknownQualityAndNonArmour(){assertThrows(IllegalArgumentException.class,()->KitEnchantments.profile("admin","LEATHER_BOOTS"));assertThrows(IllegalArgumentException.class,()->KitEnchantments.profile("legendary","DIAMOND_SWORD"));}
|
||||
}
|
||||
36
DuneBan/MySqlStoreSmoke.java
Normal file
36
DuneBan/MySqlStoreSmoke.java
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package com.dunerealms.ban;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.*;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
/** Uses private connection-local TEMPORARY tables only; global guard cannot see test records. */
|
||||
public final class MySqlStoreSmoke {
|
||||
static int assertions;
|
||||
static void check(boolean value,String text){assertions++;if(!value)throw new AssertionError(text);}
|
||||
public static void main(String[] args)throws Exception {
|
||||
Properties p=new Properties();try(InputStream in=Files.newInputStream(Path.of(args[0]))){p.load(in);}Class.forName("com.mysql.cj.jdbc.Driver");
|
||||
Properties auth=new Properties();auth.setProperty("user",p.getProperty("username"));auth.setProperty("password",p.getProperty("password"));auth.setProperty("connectTimeout","3000");auth.setProperty("socketTimeout","5000");auth.setProperty("connectionTimeZone","UTC");
|
||||
try(Connection raw=DriverManager.getConnection(p.getProperty("jdbc-url"),auth)){
|
||||
String schema=Files.readString(Path.of(args[1])).replace("CREATE TABLE IF NOT EXISTS","CREATE TEMPORARY TABLE");
|
||||
try(Statement s=raw.createStatement()){for(String sql:schema.split(";"))if(!sql.isBlank())s.execute(sql);}
|
||||
Connection borrowed=(Connection)Proxy.newProxyInstance(Connection.class.getClassLoader(),new Class[]{Connection.class},(proxy,method,values)->{if(method.getName().equals("close"))return null;try{return method.invoke(raw,values);}catch(InvocationTargetException e){throw e.getCause();}});
|
||||
BanStore store=new BanStore(()->borrowed);UUID actor=UUID.fromString("00000000-0000-4000-8000-000000000001"),target=UUID.fromString("00000000-0000-4000-8000-000000000002");
|
||||
BanRecord initial=store.add(target,"Temporary Fixture",actor,"FixtureStaff","Private temporary SQL fixture",null,"arrakis");
|
||||
check(store.find(target).id().equals(initial.id()),"Inserted exact record must read back");
|
||||
check(store.online(List.of(target)).size()==1,"Active online lookup must enforce record");
|
||||
try{store.add(target,"Temporary Fixture",actor,"FixtureStaff","Duplicate temporary fixture",null,"kaitain");throw new AssertionError("Duplicate active ban allowed");}catch(SQLException expected){assertions++;}
|
||||
check(store.find(target).id().equals(initial.id()),"Duplicate must preserve original record");
|
||||
try{store.remove(target,initial.created()+1,"FixtureStaff","Stale snapshot fixture");throw new AssertionError("Stale removal allowed");}catch(SQLException expected){assertions++;}
|
||||
check(store.find(target)!=null,"Stale snapshot must keep current ban");
|
||||
check(store.remove(target,initial.created(),"FixtureStaff","Exact snapshot fixture"),"Exact removal must commit");check(store.find(target)==null,"Removed record must no longer enforce");
|
||||
check(!store.remove(target,initial.created(),"FixtureStaff","Duplicate removal fixture"),"Absent removal must report no match");
|
||||
BanRecord timed=store.add(target,"Temporary Fixture",actor,"FixtureStaff","Expiring temporary SQL fixture",1000L,"arrakis");
|
||||
try(PreparedStatement q=raw.prepareStatement("UPDATE dune_network_bans SET expires_at=1 WHERE id=?")){q.setString(1,timed.id().toString());q.executeUpdate();raw.commit();}
|
||||
check(store.find(target)==null,"Expired record must not enforce");
|
||||
BanRecord replacement=store.add(target,"Temporary Fixture",actor,"FixtureStaff","Replacement after expiry fixture",null,"giedi_prime");check(!replacement.id().equals(timed.id()),"Replacement needs distinct history record");
|
||||
check(store.active().size()==1,"Only current record enforces");
|
||||
}
|
||||
System.out.println("DuneBan MySQL store smoke PASS: "+assertions+" assertions; connection-local temporary tables only, no live player bans changed.");
|
||||
}
|
||||
}
|
||||
61
DuneBan/README.md
Normal file
61
DuneBan/README.md
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
# DuneBan: explicit local and network moderation
|
||||
|
||||
Paper 1.21.4 / Java 21 command plugin and a Velocity 4.3.1 / Java 25 network guard. This is a separate plugin; it does not replace Core, Essentials, inventories, wallets or worlds.
|
||||
|
||||
Commands from an authenticated in-game staff player:
|
||||
|
||||
```
|
||||
/duneban local <user> <reason>
|
||||
/duneban global <user> <reason>
|
||||
/duneunban local <user> <created-ISO> <reason>
|
||||
/duneunban global <user> <created-ISO> <reason>
|
||||
```
|
||||
|
||||
The new command name is deliberate: vanilla `/ban` is not silently redefined. Ban commands create permanent bans; the staff GUI can pass the existing 15-minute, one-hour, 24-hour, seven-day or permanent choices. Unban requires the reviewed original creation timestamp. Reasons must be single-line 5–500 characters, with no control characters or legacy formatting codes. Invalid or unavailable operations report no confirmed success.
|
||||
|
||||
Separate permissions `dune.ban.local`, `dune.ban.global`, `dune.unban.local`, `dune.unban.global` default to operators. A global grant does not implicitly confer local rights, or vice versa. Self, operator and protected targets are rejected. Protection recognizes `dune.ban.protected` and existing `dune.moderation.protected`. Online UUIDs are authoritative; offline Java names use the local verified name cache or the exact official Mojang name lookup. Offline target protection requires a successful LuckPerms user lookup. No offline-mode UUID is guessed. Select an online Bedrock player through the GUI rather than fabricating a Java identity.
|
||||
|
||||
Local bans use Paper's profile-ban API, verify the native ban before disconnecting, and remain local. Global bans are immutable historical records in central **MySQL** `dunegameplay`, with one active row per player. InnoDB player lock rows and a unique generated active-player index serialize changes. Global unban compares the exact original creation snapshot under the same row lock and retains the revoked row with actor/reason/time. Prepared statements bind all player and staff input. Shared database credentials are never embedded in JARs.
|
||||
|
||||
The backend and proxy check global bans on login. Velocity also checks each server transfer. Both check currently connected UUIDs at a bounded two-second interval, querying only the connected UUIDs; these checks do not poll ranks. Newly globally banned accounts disconnect without waiting for another login. A database/configuration failure rejects login/transfer or disconnects active sessions with a clear moderation-service-unavailable message, rather than inventing an account ban. Polling plus database timeout/scheduler delays bounds responsiveness; it is not a claim of instantaneous propagation.
|
||||
|
||||
## Private configuration and deployment
|
||||
|
||||
Install `DuneBan-Paper-1.0.0.jar` on the lobby and all planet backends. `plugins/DuneBan/config.yml` must set exact `server-id` (`lobby`, `arrakis`, `kaitain`, `giedi_prime`). Blank database settings inherit the existing DuneCore `database.jdbc-url`, `username`, `password`; the lobby, which does not run Core, needs those private settings explicitly.
|
||||
|
||||
Current topology uses an authenticated private SSH forward on **each game/proxy host**: `127.0.0.1:13307` → central website MySQL. Use a private JDBC URL such as `jdbc:mysql://127.0.0.1:13307/dunegameplay?allowPublicKeyRetrieval=true&connectionTimeZone=UTC` and the provisioned account. The public-key exchange remains inside the authenticated SSH transport; do not expose MySQL or downgrade its account authentication.
|
||||
|
||||
Apply `schema.sql` to the central gameplay schema before enabling the guard. The Paper writer also initializes missing tables, but the proxy guard intentionally does not need DDL rights. Its account can be SELECT-only on `dune_network_bans`. Paper needs read/write on the ban and lock tables plus initial schema setup if schema was not preprovisioned.
|
||||
|
||||
Install the network guard JAR in Velocity `plugins/`. Private `plugins/duneban-network/database.properties` contains:
|
||||
|
||||
```properties
|
||||
jdbc-url=jdbc:mysql://127.0.0.1:13307/dunegameplay?allowPublicKeyRetrieval=true&connectionTimeZone=UTC
|
||||
username=PRIVATE_ACCOUNT
|
||||
password=PRIVATE_VALUE
|
||||
```
|
||||
|
||||
Provision this file **before** loading the guard: missing credentials intentionally fail closed. Connector/J 26.10.0 and its protobuf runtime dependency are packaged. No Velocity server classes are packaged.
|
||||
|
||||
`output/network-ban-20261029/build-guard.sh /exact/velocity.jar [private/database.properties]` compiles the guard against the exact deployed Java-25 Velocity API using JDK25 and `--release 21`. It runs isolated real Velocity event API tests. The optional second argument runs the actual MySQL store smoke using **connection-local TEMPORARY tables only**; no record is visible to the live network guard, and no real player is punished. The test account needs CREATE TEMPORARY TABLES for this separate verification.
|
||||
|
||||
## Staff GUI API
|
||||
|
||||
Plugin name `DuneBan`; public asynchronous methods:
|
||||
|
||||
- `banScoped(Player, UUID, String reason, Duration durationOrNull, String scope)` → `CompletableFuture<Result>`.
|
||||
- `unbanScoped(Player, UUID, String expectedCreatedISO, String reason, String scope)` → `CompletableFuture<Result>`.
|
||||
- `listBans(Player, String scope)` → `CompletableFuture<List<BanView>>`.
|
||||
|
||||
Scope is exactly `local` or `global`. `Result.ok()`/`message()` carry confirmed outcome; `BanView` exposes `uuid`, `name`, `reason`, `created`, `expires`, `source`. Ban writes and view results recheck the authenticated current player/permission. Database and remote name operations run away from the Paper thread; Paper profile actions dispatch on its thread. Reflection adapters should keep loading-view UUID/permission/current-view checks and never turn an unavailable future into success.
|
||||
|
||||
## osTicket appeals and server-control integration
|
||||
|
||||
The old gateway agent reads global MySQL bans as `network:<player UUID>` with scope `network`, original UTC millisecond creation snapshot and expiry. Local planet sources remain independent. Private `/bans/action` accepts `remove` only, compares the exact snapshot under the same InnoDB lock, commits retained revocation metadata and verifies that no active replacement exists before returning matching-key `confirmed=true, absent=true`. A stale snapshot, outage or mismatched response keeps the appeal pending.
|
||||
|
||||
Private Python config `/etc/dunerealms-gameplay-mysql.json` uses host `127.0.0.1`, port `13307`, database `dunegameplay`, username and password. The agent uses PyMySQL; credentials and arbitrary hosts cannot arrive from a request. Global feed `recordId` is the same UUID shown in the login-ban reference and is preserved as the CP ban/appeal ID; it is not replaced with an unrelated ID. The CP feed validator permits only explicit `arrakis`, `lobby`, `kaitain`, `giedi_prime`, `network` scopes and verifies all rows before touching history.
|
||||
|
||||
## Verification limits
|
||||
|
||||
Eleven Java unit tests cover scoped policy, reason/username/duration bounds, target protection, current permissions, native ban confirmation before kick, local/global separation, exact unban snapshots and outage handling. Server-control tests cover transactional network removal, stale/replaced/absent records, parameter binding and matching feed timestamps. Velocity event smoke and live JDBC temporary-table smoke are separate deployment checks. None of these represent a real Minecraft client session, or permission to create a test punishment for a real player.
|
||||
|
||||
8
DuneBan/build.gradle.kts
Normal file
8
DuneBan/build.gradle.kts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
plugins { base }
|
||||
allprojects { group="com.dunerealms";version="1.0.0";repositories{mavenCentral();maven("https://repo.papermc.io/repository/maven-public/")} }
|
||||
subprojects {
|
||||
apply(plugin="java")
|
||||
extensions.configure<JavaPluginExtension>{toolchain.languageVersion.set(JavaLanguageVersion.of(21))}
|
||||
tasks.withType<JavaCompile>{options.encoding="UTF-8";options.release.set(21)}
|
||||
tasks.withType<Test>{useJUnitPlatform()}
|
||||
}
|
||||
4
DuneBan/common/build.gradle.kts
Normal file
4
DuneBan/common/build.gradle.kts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
plugins { java }
|
||||
dependencies { implementation("com.mysql:mysql-connector-j:26.10.0");testImplementation("org.junit.jupiter:junit-jupiter:5.11.4");testRuntimeOnly("org.junit.platform:junit-platform-launcher") }
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
package com.dunerealms.ban;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
public record BanRecord(UUID id,UUID player,String name,UUID actor,String actorName,String reason,long created,Long expires,String source) {
|
||||
public String createdText(){return Instant.ofEpochMilli(created).toString();}
|
||||
public String expiresText(){return expires==null?"forever":Instant.ofEpochMilli(expires).toString();}
|
||||
public String notice(){return "DuneRealms network ban\n"+reason+"\nReference: "+id+"\nExpires: "+expiresText()+"\nAppeal: https://support.dunerealms.com/appeal.php";}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package com.dunerealms.ban;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
public final class BanRules {
|
||||
private BanRules(){}
|
||||
public static String scope(String value){if(!"local".equals(value)&&!"global".equals(value))throw new IllegalArgumentException("Choose local or global scope.");return value;}
|
||||
public static String reason(String value){if(value==null||value.trim().length()<5||value.length()>500||value.codePoints().anyMatch(c->Character.isISOControl(c)||c==0x00a7))throw new IllegalArgumentException("Use a single-line reason of 5–500 characters.");return value.trim();}
|
||||
public static String username(String value){if(value==null||!value.matches("[A-Za-z0-9_]{3,16}"))throw new IllegalArgumentException("Use an exact Java username, or select an online Bedrock player in the GUI.");return value;}
|
||||
public static long created(String value){try{long epoch=Instant.parse(value).toEpochMilli();if(epoch<=0)throw new IllegalArgumentException();return epoch;}catch(Exception e){throw new IllegalArgumentException("Use the exact created timestamp from the ban list.");}}
|
||||
public static Long duration(Duration duration){if(duration==null)return null;long millis;try{millis=duration.toMillis();}catch(ArithmeticException e){throw new IllegalArgumentException("Invalid duration.");}if(millis<1000||millis>Duration.ofDays(3650).toMillis())throw new IllegalArgumentException("Duration must be one second to ten years, or permanent.");return millis;}
|
||||
public static void target(UUID actor,UUID target,boolean op,boolean protectedTarget){if(actor==null||target==null||actor.equals(target)||op||protectedTarget)throw new IllegalArgumentException("You cannot punish yourself, an operator or a protected account.");}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff