web/website/node/minecraft-item-payload.mjs
2026-11-27 23:43:05 +00:00

86 lines
7.1 KiB
JavaScript

import {gunzipSync} from 'node:zlib';
import {NATIVE_ITEM_GRADES} from '../control-panel/public/item-metadata-policy.mjs';
import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs';
/** Read Bukkit's compressed item NBT. Presentation only, never item authority. */
export function decodeMinecraftPayload(payload){
if(typeof payload!=='string'||payload.length<8||payload.length>65536||! /^[A-Za-z0-9+/]+={0,2}$/.test(payload))throw Error('Unsupported item payload');
const raw=Buffer.from(payload,'base64');if(raw[0]!==0x1f||raw[1]!==0x8b)throw Error('Unsupported item compression');
const bytes=gunzipSync(raw,{maxOutputLength:131072});let at=0,nodes=0;
function need(n){if(!Number.isSafeInteger(n)||n<0||at+n>bytes.length)throw Error('Truncated item');}
function num(n,method){need(n);const value=bytes[method](at);at+=n;return value;}
function string(){const n=num(2,'readUInt16BE');need(n);const value=bytes.toString('utf8',at,at+n);at+=n;return value;}
function count(){const n=num(4,'readInt32BE');if(n<0||n>65536)throw Error('Item array too large');return n;}
function tag(type,depth=0){
if(++nodes>20000||depth>32)throw Error('Item nesting too deep');
switch(type){
case 1:return num(1,'readInt8');case 2:return num(2,'readInt16BE');case 3:return num(4,'readInt32BE');
case 4:{need(8);const n=bytes.readBigInt64BE(at);at+=8;return n>=BigInt(Number.MIN_SAFE_INTEGER)&&n<=BigInt(Number.MAX_SAFE_INTEGER)?Number(n):n.toString();}
case 5:return num(4,'readFloatBE');case 6:return num(8,'readDoubleBE');
case 7:{const n=count();need(n);at+=n;return null;}
case 8:return string();
case 9:{const type=num(1,'readUInt8'),n=count();if(n>4096||type===0&&n)throw Error('Item list too large');return Array.from({length:n},()=>tag(type,depth+1));}
case 10:{const value=Object.create(null);while(true){const type=num(1,'readUInt8');if(type===0)return value;const key=string();if(Object.hasOwn(value,key))throw Error('Duplicate item field');value[key]=tag(type,depth+1);}}
case 11:{const n=count();if(n>4096)throw Error('Item array too large');return Array.from({length:n},()=>num(4,'readInt32BE'));}
case 12:{const n=count();if(n>4096)throw Error('Item array too large');return Array.from({length:n},()=>tag(4,depth+1));}
default:throw Error('Unknown NBT tag');
}
}
if(num(1,'readUInt8')!==10)throw Error('Item compound required');string();const item=tag(10);if(at!==bytes.length)throw Error('Trailing item data');return item;
}
export function minecraftText(value,depth=0){
if(depth>16)return '';
if(typeof value==='string'){
if(value.length>8192)return '';
if(/^[\[{]/.test(value.trim()))try{return minecraftText(JSON.parse(value),depth+1);}catch{}
return value.replace(/§[0-9a-fk-orx]/gi,'').replace(/[\uE000-\uF8FF]/g,'').replace(/[\x00-\x1f\x7f]/g,' ');
}
if(Array.isArray(value))return value.slice(0,64).map(v=>minecraftText(v,depth+1)).join('');
if(value&&typeof value==='object')return minecraftText(value.text||'',depth+1)+minecraftText(value.extra||[],depth+1);
return '';
}
const label=s=>String(s).replace(/^minecraft:/,'').replaceAll('_',' ').replace(/\b[a-z]/g,c=>c.toUpperCase());
// Only a trusted native payload's exact PDC field establishes creation origin.
// Never substitute the listing server, material type or visible lore.
export function minecraftItemOrigin(payload,expectedMaterial){
try{const item=decodeMinecraftPayload(payload);if(typeof item.id!=='string'||item.id.replace(/^minecraft:/,'')!==String(expectedMaterial).toLowerCase())return null;
return tradeWorld(item.components?.['minecraft:custom_data']?.PublicBukkitValues?.['dunerealms:origin_world']);
}catch{return null;}
}
export function minecraftItemMetadata(payload,expectedMaterial){
try{
const item=decodeMinecraftPayload(payload),material=String(item.id||'').replace(/^minecraft:/,'').toLowerCase();
if(!/^[a-z0-9_]{1,80}$/.test(material)||material!==String(expectedMaterial).toLowerCase())return {};
const c=item.components||{},pdc=c['minecraft:custom_data']?.PublicBukkitValues||{};
const result={nativeMetadata:true};let quality=pdc['dunerealms:quality'],mark=pdc['dunerealms:equipment_mark'];
if(!['common','uncommon','rare','very_rare','legendary','mythic','relic'].includes(quality)){
const native=NATIVE_ITEM_GRADES[String(c['minecraft:rarity']||'').toUpperCase()];if(native){quality=native.quality;mark=native.equipmentMark;}
}
if(quality&&((Number.isInteger(Number(mark))&&Number(mark)>=0&&Number(mark)<=14)||(quality==='relic'&&mark==='infinite'))){result.quality=quality;result.equipmentMark=mark==='infinite'?mark:Number(mark);}
if(typeof pdc['dunerealms:refit_organisation']==='string'&&pdc['dunerealms:refit_organisation'].length<=256)try{const org=JSON.parse(pdc['dunerealms:refit_organisation']);if(['clan','company','politics'].includes(org.kind)&&/^[a-f0-9-]{36}$/i.test(org.id)&&/^[A-Za-z0-9_-]{1,16}$/.test(org.tag))result.organisationGear={kind:org.kind,tag:org.tag};}catch{}
const name=minecraftText(c['minecraft:custom_name']||c['minecraft:item_name']);if(name.trim())result.displayName=name.trim().slice(0,96);
const enchantments=c['minecraft:enchantments']?.levels||c['minecraft:enchantments']||{},safe={};
if(enchantments&&typeof enchantments==='object'&&!Array.isArray(enchantments))for(const [key,n] of Object.entries(enchantments))if(/^(?:minecraft:)?[a-z_]{1,64}$/.test(key)&&Number.isInteger(n)&&n>0&&n<=255)safe[key]=n;
if(Object.keys(safe).length)result.enchantments=safe;
const lines=Array.isArray(c['minecraft:lore'])?c['minecraft:lore'].slice(0,128).map(v=>minecraftText(v).trim().slice(0,160)):[],story=[],stats=[];let section='story';
for(const line of lines){
if(/^ENCHANTMENTS$/i.test(line)){section='enchantments';continue;}
if(/^STATS$/i.test(line)){section='stats';continue;}
if(!line||/^(COMMON|UNCOMMON|RARE|VERY RARE|LEGENDARY|MYTHIC|RELIC)\s*\|\s*MK\b/i.test(line))continue;
if(/^S\d+\s*[|·]/.test(line)){result.season=line.split(/[|·]/)[0].trim();continue;}
if(/^Origin season: S\d{1,4}$/.test(line)){result.season=line.slice(15);continue;}
if(result.organisationGear&&line===result.organisationGear.tag+' | Organisation equipment')continue;
if(/^Made with ExecutableItems$/i.test(line))continue;
if(section==='stats'){const match=/^(.+?)\s+([+-][\d.,]+%?)$/.exec(line);if(match&&stats.length<12)stats.push({label:match[1].slice(0,48),value:match[2].slice(0,64)});}
else if(section==='story'&&story.length<8)story.push(line);
}
if(story.length)result.lore=story;if(stats.length)result.stats=stats;
if(typeof c['minecraft:item_model']==='string'){
const known={'dunerealms:spice_refined':'refined_spice','dunerealms:imperial_codex':'compass'};if(known[c['minecraft:item_model']])result.image='/assets/minecraft-items/'+known[c['minecraft:item_model']]+'.png';
for(const id of ['jerboa_raw_meat','jerboa_cooked_meat','jerboa_hide','jerboa_stew','jerboa_water_vial'])if(c['minecraft:item_model']==='dunerealms:ecology/'+id)result.image='/assets/minecraft-items/'+id+'.png';
}
return result;
}catch{return {};}
}
export function publicMinecraftListing(row){const {payload,...listing}=row;return {...listing,...minecraftItemMetadata(payload,row.material)};}