Restore CMS publication and seal official Exchange treasury routing #628
24 changed files with 632 additions and 29 deletions
|
|
@ -37,6 +37,7 @@
|
|||
- Preserve the accepted DuneRealms design and reuse existing navigation, services and domain permissions.
|
||||
- DuneForge is the existing `#forge/git-workspace` workspace; the root DuneGit register is `/git/`.
|
||||
- Item cards display authoritative metadata from native Bukkit items or a verified signed HQ design. Do not invent quality, marks, lore, enchantments or stats from material names.
|
||||
- Official CMS Exchange publications use the existing item-definition key and an immutable `cms.item` binding to the exact In-game Bank Treasury account. Player resales of custom items pay the player. Preserve the recovered HQ publisher, recipient-bound `/redeem` gift flow and atomic publication/payment/delivery receipts; do not replace them with placeholders or infer an official payee from an item's name or origin alone.
|
||||
- Preserve real voting, banking and item-issuance boundaries. Public presentation must not expose serialized items, signatures or service credentials.
|
||||
- Describe what is coded, tested, merged and deployed separately. Mark unavailable features honestly.
|
||||
- The owner requires one shared header and footer across portal, CP and other website surfaces. Use one canonical source and publication path; aligning labels on separate implementations is insufficient. Verify signed-in rendering as well as emitted HTML.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import {identity} from '../node/auth.mjs';
|
||||
import {can} from '../node/permissions.mjs';
|
||||
import {createItemDesigns} from '../node/item-designs.mjs';
|
||||
import {issueItemGift} from '../node/item-gifts.mjs';
|
||||
import {postHQOffer} from '../node/hq-exchange.mjs';
|
||||
import {createCMSItemPublications} from '../node/cms-item-publication.mjs';
|
||||
|
||||
export function createItemDesignAPI(db,keys,settings={},dependencies={}){
|
||||
const authenticate=dependencies.authenticate||(request=>identity(request,db));
|
||||
|
|
@ -9,6 +12,7 @@ export function createItemDesignAPI(db,keys,settings={},dependencies={}){
|
|||
return !!fresh&&await can(db,fresh,'web.items.manage');
|
||||
});
|
||||
const service=keys?createItemDesigns(db,keys,{authorize:allowed}):null;
|
||||
const publications=dependencies.publications||(keys&&settings.DUNE_INVENTORY_DATABASE_URL?.startsWith('mysql:')?createCMSItemPublications(db,keys,{secret:settings.GAME_LINK_SECRET,gameSchema:new URL(settings.DUNE_INVENTORY_DATABASE_URL).pathname.slice(1),centralSchema:settings.DB_NAME,bank:dependencies.bank||db,authorize:allowed}):null);
|
||||
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}});
|
||||
return async request=>{
|
||||
const url=new URL(request.url);if(url.pathname!=='/api/items/designs'||url.search)return reply({message:'Use the item definition register without identity overrides.'},400);
|
||||
|
|
@ -16,14 +20,28 @@ export function createItemDesignAPI(db,keys,settings={},dependencies={}){
|
|||
const actor=await authenticate(request);if(!actor)return reply({message:'Sign in first.'},401);
|
||||
if(!await allowed(actor,db))return reply({message:'Item definition management required.'},403);
|
||||
if(!service)return reply({message:'The item definition key service is unavailable.'},503);
|
||||
if(request.method==='GET')return reply({definitions:await service.list(actor)});
|
||||
if(request.method==='GET'){const definitions=await service.list(actor),candidates=publications?await publications.candidates(actor):[];return reply({definitions:definitions.map(row=>({...row,publication:candidates.find(p=>p.keyId===row.keyId)||row.publication||null}))});}
|
||||
if(request.headers.get('origin')!==new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin)return reply({message:'Origin rejected.'},403);
|
||||
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
|
||||
const reader=request.body?.getReader();if(!reader)return reply({message:'Item definition required.'},400);
|
||||
let input;try{const chunks=[];let length=0;while(true){const {value,done}=await reader.read();if(done)break;length+=value.byteLength;if(length>16384){await reader.cancel();return reply({message:'Item definition exceeds its bound.'},413);}chunks.push(value);}input=JSON.parse(Buffer.concat(chunks).toString('utf8'));}
|
||||
catch{return reply({message:'Invalid item definition.'},400);}finally{reader.releaseLock();}
|
||||
if(['seal-publication','withdraw-publication'].includes(input?.action)){
|
||||
if(Object.keys(input).sort().join(',')!=='action,confirmed,keyId,listingId'||input.confirmed!==true)return reply({message:'Confirm the existing item publication and key.'},400);
|
||||
if(!publications)return reply({message:'Official item publication is unavailable.'},503);
|
||||
if(!await (dependencies.canGift||((user)=>can(db,user,'dune.items.give')))(actor))return reply({message:'Item issuance permission required.'},403);
|
||||
try{return reply(await publications[input.action==='seal-publication'?'seal':'withdraw'](actor,input));}catch(error){return reply({message:error.status||error instanceof TypeError?error.message:'The publication was not confirmed.'},error.status||(error instanceof TypeError?400:503));}
|
||||
}
|
||||
if(input?.action==='gift'||input?.action==='publish'){
|
||||
const gift=input.action==='gift';
|
||||
const fields=gift?['action','id','revision','recipient','quantity']:['action','id','revision','requestId','quantity','priceMinor','confirmed'];
|
||||
if(Object.keys(input).length!==fields.length||!fields.every(key=>Object.hasOwn(input,key)))return reply({message:'Review the item revision and publication details.'},400);
|
||||
if(!await (dependencies.canGift||((user)=>can(db,user,'dune.items.give')))(actor))return reply({message:'Item issuance permission required.'},403);
|
||||
try{return reply(await (gift?issueItemGift(db,service,actor,input):postHQOffer(dependencies.bank,service,actor,input,settings,{sealPublication:(tx,fields)=>publications.seal(actor,fields,{transactionStore:tx})})),201);}
|
||||
catch(error){return reply({message:error instanceof TypeError?error.message:gift?'This gift could not be issued from the selected revision.':'Publication could not be confirmed. Retry the same request.'},error instanceof TypeError?400:409);}
|
||||
}
|
||||
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).length!==4||!['action','id','revision','design'].every(key=>Object.hasOwn(input,key))||input.action!=='save')return reply({message:'Use the selected item, current revision and complete design.'},400);
|
||||
try{const saved=await service.save(actor,input);return reply(saved,saved.revision===1&&!saved.replayed?201:200);}
|
||||
catch(error){if(error instanceof TypeError)return reply({message:error.message},400);if(error.message==='Item definition management required.')return reply({message:error.message},403);if(/^Item definition (?:changed|revision conflict)/.test(error.message))return reply({message:error.message},409);throw error;}
|
||||
catch(error){if(error instanceof TypeError)return reply({message:error.message},400);if(error.message==='Item definition management required.')return reply({message:error.message},403);if(/^Item definition (?:changed|revision conflict)/.test(error.message)||error.message.startsWith('Published item definition is sealed.'))return reply({message:error.message},409);throw error;}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import {readFile} from 'node:fs/promises';
|
||||
import {identity} from '../node/auth.mjs';
|
||||
import {can} from '../node/permissions.mjs';
|
||||
export function createItemRegister(db,{authenticate=request=>identity(request,db),allowed=user=>can(db,user,'web.menu.items'),readCatalogue=()=>readFile(new URL('../web/assets/items/catalogue-v1.json',import.meta.url),'utf8')}={}){
|
||||
export function createItemRegister(db,{authenticate=request=>identity(request,db),allowed=user=>can(db,user,'web.menu.items'),readCatalogue=()=>readFile(new URL('../web/assets/items/catalogue-v1.json',import.meta.url),'utf8'),publishedDesigns=async()=>[]}={}){
|
||||
return async request=>{
|
||||
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
|
||||
if(request.method!=='GET')return reply({message:'Method not allowed'},405);
|
||||
const user=await authenticate(request);if(!user)return reply({message:'Sign in first.'},401);if(!await allowed(user))return reply({message:'Item registry access required.'},403);
|
||||
try{const data=JSON.parse(await readCatalogue());if(data.schemaVersion!==1||!Array.isArray(data.items)||data.items.length>1000||!Array.isArray(data.qualityTiers))throw Error();return reply(data);}catch{return reply({message:'The published item catalogue is temporarily unavailable.'},503);}
|
||||
try{const data=JSON.parse(await readCatalogue());if(data.schemaVersion!==1||!Array.isArray(data.items)||data.items.length>1000||!Array.isArray(data.qualityTiers))throw Error();const hq=(await publishedDesigns()).map(({keyId,design,template})=>({id:keyId,name:design.name,quality:design.quality,equipmentMark:design.equipmentMark,baseMaterial:template.material.toUpperCase(),image:template.image,lore:design.lore.map(line=>line.text),enchantments:design.enchantments,kind:'hq'}));const items=new Map([...hq,...data.items].map(item=>[item.id,item]));for(const tier of [{key:'mythic',label:'Mythic',color:'#e69b70'},{key:'relic',label:'Relic',color:'#efb231'}])if(hq.some(item=>item.quality===tier.key)&&!data.qualityTiers.some(t=>t.key===tier.key))data.qualityTiers.push(tier);return reply({...data,items:[...items.values()].slice(0,1000)});}catch{return reply({message:'The published item catalogue is temporarily unavailable.'},503);}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ function select(values){const node=el('select');for(const [value,label]of values
|
|||
export function mountItemDesigner(host,{fetcher=fetch,initialDesign=null,onApply=null}={}){
|
||||
if(!document.querySelector('link[data-item-designer]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./cp-v2-item-designer.css',import.meta.url).href;css.dataset.itemDesigner='';document.head.append(css);}
|
||||
const embedded=typeof onApply==='function';
|
||||
let active=true,ready=embedded,pending=false,id=crypto.randomUUID(),revision=0,lastSaved='',definitions=[],loreRows=[],enchantmentInputs=new Map();const controller=new AbortController();
|
||||
let active=true,ready=embedded,pending=false,published=false,id=crypto.randomUUID(),revision=0,lastSaved='',definitions=[],loreRows=[],enchantmentInputs=new Map();const controller=new AbortController();
|
||||
const root=el('section',undefined,'item-designer'),status=el('p','Opening the item definition register…');status.setAttribute('role','status');
|
||||
const saved=select([['','Choose a saved draft']]),load=button('Load draft',()=>{const row=definitions.find(row=>row.id===saved.value);if(row){id=row.id;revision=row.revision;lastSaved=JSON.stringify(validateItemDesign(row.design));setDesign(row.design);status.textContent='Draft revision '+revision+' loaded.';}}),fresh=button('New item',()=>{id=crypto.randomUUID();revision=0;lastSaved="";setDesign(defaultItemDesign(template.value));status.textContent='New local draft. Save to record it in J.A.R.V.I.S.';}),refresh=button('Refresh drafts',()=>void readDefinitions());
|
||||
const saved=select([['','Choose a saved draft']]),load=button('Load draft',()=>{const row=definitions.find(row=>row.id===saved.value);if(row){id=row.id;revision=row.revision;published=row.state==='published';lastSaved=JSON.stringify(validateItemDesign(row.design));setDesign(row.design);status.textContent=published?'Published revision '+revision+' is sealed. Withdraw it before editing.':'Draft revision '+revision+' loaded.';}}),fresh=button('New item',()=>{id=crypto.randomUUID();revision=0;published=false;lastSaved="";setDesign(defaultItemDesign(template.value));status.textContent='New local draft. Save to record it in J.A.R.V.I.S.';}),refresh=button('Refresh drafts',()=>void readDefinitions());
|
||||
const tools=el('div',undefined,'item-designer-tools');tools.append(field('Saved definitions',saved),load,fresh,refresh);
|
||||
const form=el('form'),fields=el('fieldset'),layout=el('div',undefined,'item-designer-layout'),preview=el('div',undefined,'item-designer-preview');
|
||||
const copyPreview=button('Copy ingame preview command',async()=>{const command='/dm previewitem '+id+' '+revision;try{await navigator.clipboard.writeText(command);status.textContent='Preview command copied. Paste it in Minecraft: '+command;}catch{status.textContent='Paste this command in Minecraft: '+command;}});copyPreview.disabled=true;
|
||||
|
|
@ -27,13 +27,13 @@ export function mountItemDesigner(host,{fetcher=fetch,initialDesign=null,onApply
|
|||
const entry={row,text,color,bold,italic};row.append(field('Lore text',text),field('Colour',color),field('Bold',bold),field('Italic',italic),button('Remove',()=>{loreRows=loreRows.filter(value=>value!==entry);row.remove();paint();}));for(const input of [text,color,bold,italic])input.oninput=paint;loreRows.push(entry);lore.append(row);
|
||||
}
|
||||
function readDesign(){const base=defaultItemDesign(template.value);return validateItemDesign({...base,name:name.value,lore:loreRows.map(row=>({text:row.text.value,color:row.color.value,bold:row.bold.checked,italic:row.italic.checked})),enchantments:Object.fromEntries([...enchantmentInputs].map(([key,input])=>[key,Number(input.value)])),trim:trim.hidden||!trimPattern.value?null:{pattern:trimPattern.value,material:trimMaterial.value}});}
|
||||
function paint(){if(!active)return;let valid=true;try{const design=readDesign(),t=itemDesignTemplate(design.templateId);validation.textContent='';preview.replaceChildren(el('h4','Lore card preview'),itemLoreCard({...design,title:design.name,material:t.material,image:t.image,season:'S1'}));copyPreview.disabled=!ready||pending||revision<1||JSON.stringify(design)!==lastSaved;}catch(error){valid=false;copyPreview.disabled=true;validation.textContent=error.message;}save.disabled=!ready||pending||!valid;addLore.disabled=loreRows.length>=6;fields.disabled=!ready||pending;load.disabled=fresh.disabled=refresh.disabled=pending||!ready;}
|
||||
function paint(){if(!active)return;let valid=true;try{const design=readDesign(),t=itemDesignTemplate(design.templateId);validation.textContent='';preview.replaceChildren(el('h4','Lore card preview'),itemLoreCard({...design,title:design.name,material:t.material,image:t.image,season:'S1'}));copyPreview.disabled=!ready||pending||revision<1||JSON.stringify(design)!==lastSaved;}catch(error){valid=false;copyPreview.disabled=true;validation.textContent=error.message;}save.disabled=!ready||pending||published||!valid;addLore.disabled=loreRows.length>=6;fields.disabled=!ready||pending||published;load.disabled=fresh.disabled=refresh.disabled=pending||!ready;}
|
||||
function setDesign(design){template.value=design.templateId;name.value=design.name;const t=itemDesignTemplate(design.templateId);identity.textContent=itemWords(t.quality)+' · MK '+itemRoman(t.equipmentMark)+' · '+itemWords(t.itemClass);enchantmentInputs=new Map();enchants.replaceChildren();
|
||||
for(const [key,bounds]of Object.entries(t.enchantments)){const input=el('input');input.type='number';input.min=bounds.min;input.max=bounds.max;input.step=1;input.value=design.enchantments[key];input.oninput=paint;enchantmentInputs.set(key,input);enchants.append(field(itemWords(key)+' · '+bounds.min+'–'+bounds.max,input));}if(!enchantmentInputs.size)enchants.append(el('p','This template has no editable enchantments.'));
|
||||
trim.hidden=!t.armor;trimPattern.value=design.trim?.pattern||'';trimMaterial.value=design.trim?.material||'gold';loreRows=[];lore.replaceChildren();for(const line of design.lore)addLine(line);paint();
|
||||
}
|
||||
template.onchange=()=>setDesign(defaultItemDesign(template.value));name.oninput=trimPattern.onchange=trimMaterial.onchange=paint;
|
||||
async function readDefinitions(){refresh.disabled=true;try{const response=await fetcher('/api/items/designs',{credentials:'same-origin',cache:'no-store',signal:controller.signal}),data=await response.json();if(!response.ok)throw Error(data.message||'Item definitions unavailable.');if(!Array.isArray(data.definitions))throw Error('Invalid item definition register.');if(!active)return;definitions=data.definitions;saved.replaceChildren(el('option','Choose a saved draft'));saved.firstChild.value='';for(const row of definitions){const option=el('option',row.design.name+' · revision '+row.revision);option.value=row.id;saved.append(option);}ready=true;status.textContent=definitions.length+' saved definitions. Quality and MK follow the selected progression template.';}catch(error){if(active&&!controller.signal.aborted){ready=false;status.textContent=error.message;}}finally{paint();}}
|
||||
form.onsubmit=async event=>{event.preventDefault();if(pending||!ready)return;let design;try{design=readDesign();}catch(error){validation.textContent=error.message;return;}if(embedded){try{await onApply(design);}catch(error){validation.textContent=error.message;}return;}pending=true;paint();try{const response=await fetcher('/api/items/designs',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({action:'save',id,revision,design}),signal:controller.signal}),data=await response.json();if(!response.ok)throw Error(data.message||'Item definition was not saved.');if(!active)return;id=data.id;revision=data.revision;lastSaved=JSON.stringify(validateItemDesign(data.design));await readDefinitions();status.textContent='Draft revision '+revision+' saved. J.A.R.V.I.S. reference: '+data.keyId;}catch(error){if(active&&!controller.signal.aborted)status.textContent=error.message;}finally{pending=false;paint();}};
|
||||
form.onsubmit=async event=>{event.preventDefault();if(pending||!ready||published)return;let design;try{design=readDesign();}catch(error){validation.textContent=error.message;return;}if(embedded){try{await onApply(design);}catch(error){validation.textContent=error.message;}return;}pending=true;paint();try{const response=await fetcher('/api/items/designs',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({action:'save',id,revision,design}),signal:controller.signal}),data=await response.json();if(!response.ok)throw Error(data.message||'Item definition was not saved.');if(!active)return;id=data.id;revision=data.revision;lastSaved=JSON.stringify(validateItemDesign(data.design));await readDefinitions();status.textContent='Draft revision '+revision+' saved. J.A.R.V.I.S. reference: '+data.keyId;}catch(error){if(active&&!controller.signal.aborted)status.textContent=error.message;}finally{pending=false;paint();}};
|
||||
setDesign(initialDesign?validateItemDesign(initialDesign):defaultItemDesign('dr_s1_spice_shovel_mk1'));if(embedded)status.hidden=true;else void readDefinitions();return()=>{active=false;controller.abort();root.remove();};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,68 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
|
||||
export function mountItemPublication(host,{fetcher=fetch}={}){
|
||||
const controller=new AbortController();
|
||||
const form=el('form'),revision=el('select'),recipient=el('input'),quantity=el('input');
|
||||
const status=el('p','Loading saved item revisions…','cp-v2-news-status');
|
||||
status.setAttribute('role','status');
|
||||
recipient.required=true;recipient.maxLength=16;recipient.pattern='[A-Za-z0-9_]{1,16}';
|
||||
quantity.type='number';quantity.min=1;quantity.max=36;quantity.value=1;quantity.required=true;
|
||||
const label=(text,input)=>{const node=el('label');node.append(el('span',text),input);return node;};
|
||||
const gift=el('button','Create redeem key'),refresh=el('button','Refresh saved items'),command=el('input');
|
||||
const market=el('form'),marketQuantity=el('input'),price=el('input'),confirmation=el('input'),publish=el('button','Post to Exchange');
|
||||
marketQuantity.type='number';marketQuantity.min=1;marketQuantity.max=36;marketQuantity.value=1;marketQuantity.required=true;
|
||||
price.type='number';price.min='0.01';price.max='1000000';price.step='0.01';price.required=true;
|
||||
confirmation.type='checkbox';confirmation.required=true;publish.type='submit';publish.disabled=true;
|
||||
gift.type='submit';gift.disabled=true;refresh.type='button';
|
||||
command.readOnly=true;command.hidden=true;command.setAttribute('aria-label','Minecraft redemption command');
|
||||
const withdrawConfirm=el('input');withdrawConfirm.type='checkbox';const withdraw=el('button','Withdraw official listing');withdraw.type='button';const withdrawBox=el('div');withdrawBox.append(label('Withdraw this listing; existing paid deliveries remain owed.',withdrawConfirm),withdraw);
|
||||
const controls=el('div',undefined,'cp-v2-company-actions');
|
||||
controls.append(gift,refresh);
|
||||
form.append(label('Minecraft player',recipient),label('Quantity',quantity),controls);
|
||||
market.append(label('Stock',marketQuantity),label('Unit price in DM',price),label('Confirm that proceeds go to In-game Bank Treasury',confirmation),publish);
|
||||
host.append(el('h4','Item publication'),label('Saved item revision',revision),el('h5','Gift in Minecraft'),el('p','Give the redeem command to the named player.'),form,command,
|
||||
el('h5','Post to Exchange'),el('p','Origin world · J.A.R.V.I.S. HQ'),market,withdrawBox,status);
|
||||
let rows=[],busy=false,publication=null;
|
||||
function update(){gift.disabled=busy||!rows.length;const row=rows[Number(revision.value)],sealed=row?.state==='published',existing=row?.publication;withdrawBox.hidden=!sealed;withdraw.disabled=busy||!withdrawConfirm.checked;publish.textContent=existing?.state==='unsealed'?'Connect existing official listing':'Post to Exchange';if(existing?.state==='unsealed'){marketQuantity.value=existing.quantity;price.value=(existing.priceMinor/100).toFixed(2);}publish.disabled=busy||!rows.length||sealed;marketQuantity.disabled=price.disabled=busy||sealed||existing?.state==='unsealed';confirmation.disabled=busy||sealed;refresh.disabled=busy;}
|
||||
async function load(){
|
||||
busy=true;update();
|
||||
try{
|
||||
const response=await fetcher('/api/items/designs',{cache:'no-store',credentials:'same-origin',signal:controller.signal});
|
||||
const body=await response.json();if(!response.ok)throw Error(body.message||'Item revisions are unavailable.');
|
||||
rows=body.definitions;
|
||||
revision.replaceChildren(...rows.map((row,index)=>{const option=el('option',row.design.name+' · revision '+row.revision);option.value=String(index);return option;}));
|
||||
status.textContent=rows.length?'Select a saved revision.':'Save an item in the editor first.';
|
||||
}catch(error){if(!controller.signal.aborted)status.textContent=error.message;}
|
||||
finally{busy=false;update();}
|
||||
}
|
||||
withdrawConfirm.onchange=update;withdraw.onclick=async()=>{const row=rows[Number(revision.value)];if(busy||!withdrawConfirm.checked||!row?.publication)return;busy=true;update();try{const response=await fetcher('/api/items/designs',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},signal:controller.signal,body:JSON.stringify({action:'withdraw-publication',keyId:row.keyId,listingId:row.publication.listingId,confirmed:true})}),data=await response.json();if(!response.ok)throw Error(data.message||'Withdrawal was not confirmed.');withdrawConfirm.checked=false;await load();status.textContent='Official listing withdrawn. Save a new revision before publishing again.';}catch(error){if(!controller.signal.aborted)status.textContent=error.message;}finally{busy=false;update();}};revision.onchange=update;refresh.onclick=()=>void load();
|
||||
form.onsubmit=async event=>{
|
||||
event.preventDefault();const selected=rows[Number(revision.value)];if(!selected||busy)return;
|
||||
busy=true;update();command.hidden=true;command.value='';
|
||||
try{
|
||||
const response=await fetcher('/api/items/designs',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},signal:controller.signal,
|
||||
body:JSON.stringify({action:'gift',id:selected.id,revision:selected.revision,recipient:recipient.value.trim(),quantity:Number(quantity.value)})});
|
||||
const body=await response.json();if(!response.ok)throw Error(body.message||'Gift key was not created.');
|
||||
command.value=body.command;command.hidden=false;command.select();
|
||||
status.textContent='Key ready for '+body.recipient+'. It expires if unused after seven days.';
|
||||
}catch(error){if(!controller.signal.aborted)status.textContent=error.message;}
|
||||
finally{busy=false;update();}
|
||||
};
|
||||
market.onsubmit=async event=>{
|
||||
event.preventDefault();const selected=rows[Number(revision.value)];if(!selected||busy||selected.state==='published'||!confirmation.checked)return;
|
||||
const existing=selected.publication?.state==='unsealed';const input=existing?{action:'seal-publication',keyId:selected.keyId,listingId:selected.publication.listingId,confirmed:true}:{action:'publish',id:selected.id,revision:selected.revision,quantity:Number(marketQuantity.value),priceMinor:Math.round(Number(price.value)*100),confirmed:true};
|
||||
const signature=JSON.stringify(input);
|
||||
if(publication?.signature!==signature)publication={signature,requestId:crypto.randomUUID()};
|
||||
busy=true;update();
|
||||
try{
|
||||
const response=await fetcher('/api/items/designs',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},signal:controller.signal,
|
||||
body:JSON.stringify(existing?input:{...input,requestId:publication.requestId})});
|
||||
const body=await response.json();if(!response.ok)throw Error(body.message||'Exchange posting could not be confirmed.');
|
||||
status.textContent='Exchange listing '+body.listingId+' is published.';
|
||||
confirmation.checked=false;publication=null;await load();
|
||||
}catch(error){if(!controller.signal.aborted)status.textContent=error.message;}
|
||||
finally{busy=false;update();}
|
||||
};
|
||||
void load();
|
||||
return ()=>controller.abort();
|
||||
}
|
||||
|
|
@ -1,9 +1,10 @@
|
|||
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
|
||||
import {mountItemDesigner} from './cp-v2-item-designer.mjs';
|
||||
import {mountItemPublication} from './cp-v2-item-publication.mjs';
|
||||
export function itemCatalogue(data){
|
||||
if(data?.schemaVersion!==1||!Array.isArray(data.items)||data.items.length>1000||!Array.isArray(data.qualityTiers)||data.qualityTiers.length>20)throw Error('Invalid item catalogue.');
|
||||
const tiers=new Set(data.qualityTiers.map(t=>t.key));
|
||||
for(const item of data.items)if(typeof item.id!=='string'||typeof item.name!=='string'||!tiers.has(item.quality)||!Array.isArray(item.lore)||item.lore.some(line=>typeof line!=='string')||item.image&&!/^\/assets\/items\/[a-z0-9_-]+\.(png|webp)$/.test(item.image))throw Error('Invalid item record.');
|
||||
for(const item of data.items)if(typeof item.id!=='string'||typeof item.name!=='string'||!tiers.has(item.quality)||!Array.isArray(item.lore)||item.lore.some(line=>typeof line!=='string')||item.image&&!/^\/assets\/(?:items|minecraft-items)\/[a-z0-9_-]+\.(png|webp)$/.test(item.image))throw Error('Invalid item record.');
|
||||
return data;
|
||||
}
|
||||
export function mountItemRegister(host,{fetcher=fetch}={}){
|
||||
|
|
@ -12,9 +13,9 @@ export function mountItemRegister(host,{fetcher=fetch}={}){
|
|||
const search=el('input');search.type='search';search.placeholder='Search item, material or lore';search.setAttribute('aria-label',search.placeholder);const tier=el('select');tier.setAttribute('aria-label','Filter rarity');const all=el('option','All rarities');all.value='';tier.append(all);const refresh=el('button','Refresh catalogue');refresh.type='button';const tools=el('div',undefined,'cp-v2-company-actions');tools.append(search,tier,refresh);const status=el('p','Loading the published item register…','cp-v2-news-status');status.setAttribute('role','status');const tableHost=el('div');register.append(status,tools,tableHost);
|
||||
|
||||
const disposeDesigner=mountItemDesigner(definitions,{fetcher});
|
||||
publishing.append(el('h4','Item publication'),el('p','A staff item-publication queue and game-delivery approval API are not connected.'),el('p','PLANNED · No item is published or issued from this workspace.','cp-v2-bank-status'));
|
||||
const disposePublication=mountItemPublication(publishing,{fetcher});
|
||||
const {root,activate}=createCPV2Page({title:'Item Editor',description:'Published equipment, rarity and lore from the same catalogue used by the public armoury.',artwork:'nav-manual-v2.webp',tabs:[{id:'item-register',label:'Published items',content:register},{id:'item-definitions',label:'Item editor',content:definitions},{id:'item-publication',label:'Publication',content:publishing}]});host.replaceChildren(root);activate('item-definitions');
|
||||
function render(){if(!data)return;const q=search.value.trim().toLowerCase(),filtered=data.items.filter(item=>(!tier.value||item.quality===tier.value)&&[item.name,item.id,item.baseMaterial,...item.lore].join(' ').toLowerCase().includes(q)),pages=Math.max(1,Math.ceil(filtered.length/12));page=Math.min(page,pages);const table=el('table',undefined,'cp-v2-company-table'),head=el('thead'),hr=el('tr'),body=el('tbody');for(const label of ['Item','Rarity','Material','Stack','Details']){const th=el('th',label);th.scope='col';hr.append(th);}head.append(hr);for(const item of filtered.slice((page-1)*12,page*12)){const tr=el('tr'),details=el('details');details.append(el('summary','Details'));if(item.image){const image=el('img');image.src='https://www.dunerealms.com'+item.image;image.alt=item.name;image.width=image.height=96;image.loading='lazy';details.append(image);}details.append(el('p','Reference: '+item.id),el('p','Model: '+(item.model||'Not specified')));for(const line of item.lore)details.append(el('p',line));if(item.appearance)details.append(el('p',item.appearance));for(const value of [item.name,data.qualityTiers.find(t=>t.key===item.quality)?.label||item.quality,item.baseMaterial||'Not specified',item.maxStackSize||'Not specified',details]){const td=el('td');if(typeof value==='object')td.append(value);else td.textContent=String(value);tr.append(td);}body.append(tr);}if(!filtered.length){const tr=el('tr'),td=el('td','No registered items match this view.');td.colSpan=5;tr.append(td);body.append(tr);}table.append(head,body);const wrap=el('div',undefined,'cp-v2-company-table-wrap');wrap.append(table);const nav=el('div',undefined,'cp-v2-company-actions'),prev=el('button','Previous'),next=el('button','Next');prev.type=next.type='button';prev.disabled=page===1;next.disabled=page===pages;prev.onclick=()=>{page--;render();};next.onclick=()=>{page++;render();};nav.append(prev,el('span',filtered.length+' items · Page '+page+' of '+pages),next);tableHost.replaceChildren(wrap,nav);}
|
||||
async function load(){controller?.abort();controller=new AbortController();const c=controller,timer=setTimeout(()=>c.abort(),15000);data=null;search.disabled=tier.disabled=refresh.disabled=true;tableHost.replaceChildren();try{const r=await fetcher('/api/items/catalogue',{credentials:'same-origin',cache:'no-store',signal:c.signal}),d=await r.json();if(!r.ok)throw Error(d.message||'Item catalogue unavailable.');const confirmed=itemCatalogue(d);if(!active||c!==controller)return;data=confirmed;tier.replaceChildren(all);for(const t of data.qualityTiers){const option=el('option',t.label);option.value=t.key;tier.append(option);}page=1;render();status.textContent=data.items.length+' published item definitions loaded. This register is read-only.';}catch(error){if(active&&c===controller)status.textContent=c.signal.aborted?'Catalogue read timed out. Refresh to retry.':error.message;}finally{clearTimeout(timer);if(active&&c===controller){refresh.disabled=false;search.disabled=tier.disabled=!data;}}}
|
||||
search.oninput=tier.onchange=()=>{page=1;render();};refresh.onclick=()=>void load();void load();return()=>{active=false;controller?.abort();disposeDesigner();root.remove();};
|
||||
function render(){if(!data)return;const q=search.value.trim().toLowerCase(),filtered=data.items.filter(item=>(!tier.value||item.quality===tier.value)&&[item.name,item.id,item.baseMaterial,...item.lore].join(' ').toLowerCase().includes(q)),pages=Math.max(1,Math.ceil(filtered.length/12));page=Math.min(page,pages);const table=el('table',undefined,'cp-v2-company-table'),head=el('thead'),hr=el('tr'),body=el('tbody');for(const label of ['Item','Rarity','Material','Stack','Details']){const th=el('th',label);th.scope='col';hr.append(th);}head.append(hr);for(const item of filtered.slice((page-1)*12,page*12)){const tr=el('tr'),details=el('details');details.append(el('summary','Details'));if(item.image){const image=el('img');image.src='https://www.dunerealms.com'+item.image;image.alt=item.name;image.width=image.height=96;image.loading='lazy';details.append(image);}details.append(el('p','Reference: '+item.id));if(item.kind==='hq')details.append(el('p','Origin world · J.A.R.V.I.S. HQ'));if(item.equipmentMark!=null)details.append(el('p','Equipment mark · '+item.equipmentMark));if(item.model)details.append(el('p','Model · '+item.model));for(const line of item.lore)details.append(el('p',line));for(const [enchantment,level] of Object.entries(item.enchantments||{}))details.append(el('p',enchantment.replaceAll('_',' ')+' '+level));if(item.appearance)details.append(el('p',item.appearance));for(const value of [item.name,data.qualityTiers.find(t=>t.key===item.quality)?.label||item.quality,item.baseMaterial||'Not specified',item.maxStackSize||'Not specified',details]){const td=el('td');if(typeof value==='object')td.append(value);else td.textContent=String(value);tr.append(td);}body.append(tr);}if(!filtered.length){const tr=el('tr'),td=el('td','No registered items match this view.');td.colSpan=5;tr.append(td);body.append(tr);}table.append(head,body);const wrap=el('div',undefined,'cp-v2-company-table-wrap');wrap.append(table);const nav=el('div',undefined,'cp-v2-company-actions'),prev=el('button','Previous'),next=el('button','Next');prev.type=next.type='button';prev.disabled=page===1;next.disabled=page===pages;prev.onclick=()=>{page--;render();};next.onclick=()=>{page++;render();};nav.append(prev,el('span',filtered.length+' items · Page '+page+' of '+pages),next);tableHost.replaceChildren(wrap,nav);}
|
||||
async function load(){controller?.abort();controller=new AbortController();const c=controller,timer=setTimeout(()=>c.abort(),15000);data=null;search.disabled=tier.disabled=refresh.disabled=true;tableHost.replaceChildren();try{const r=await fetcher('/api/items/catalogue',{credentials:'same-origin',cache:'no-store',signal:c.signal}),d=await r.json();if(!r.ok)throw Error(d.message||'Item catalogue unavailable.');const confirmed=itemCatalogue(d);if(!active||c!==controller)return;data=confirmed;tier.replaceChildren(all);for(const t of data.qualityTiers){const option=el('option',t.label);option.value=t.key;tier.append(option);}page=1;render();status.textContent=data.items.length+' registered and published items. This register is read-only.';}catch(error){if(active&&c===controller)status.textContent=c.signal.aborted?'Catalogue read timed out. Refresh to retry.':error.message;}finally{clearTimeout(timer);if(active&&c===controller){refresh.disabled=false;search.disabled=tier.disabled=!data;}}}
|
||||
search.oninput=tier.onchange=()=>{page=1;render();};refresh.onclick=()=>void load();void load();return()=>{active=false;controller?.abort();disposeDesigner();disposePublication();root.remove();};
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
88
website/docs/CMS-ITEM-PUBLICATION-RECOVERY-20261129.md
Normal file
88
website/docs/CMS-ITEM-PUBLICATION-RECOVERY-20261129.md
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
# Restore official item publication and seal its payment destination
|
||||
|
||||
## Objective and bounded scope
|
||||
|
||||
Restore the existing staff publication and gift-key flow, then extend its
|
||||
item-definition key with immutable official-sale terms. Official `cms.item`
|
||||
listings pay the existing In-game Bank Treasury (`sys_game_treasury`); player
|
||||
resales, including custom items, continue paying the player. No backend JAR,
|
||||
account identity, permission rank, balance or earned progression is replaced.
|
||||
|
||||
## Recovered source
|
||||
|
||||
The source was found on the owner's PC in the project checkout
|
||||
`work/finished-site/website`, also present in other local saved checkouts.
|
||||
Original commits include `6aaa7eae` (signed HQ offers and redeemable gifts),
|
||||
`adbb1943` (publication receipt replay) and `e3a14460` (published catalogue).
|
||||
The GitHub fresh baseline had the same Publication placeholder as web/main;
|
||||
it did not contain this working publisher. The local reference checkout and
|
||||
its unrelated dirty work were left unchanged.
|
||||
|
||||
Restored components are the existing `hq-exchange.mjs`, `item-gifts.mjs`,
|
||||
Publication tab, `/internal/game/item-redeem` and `itemGifts` delivery adapter.
|
||||
The installed JARVIS already implements `/redeem ITM-…` and signed native
|
||||
gift receipt delivery; this restoration does not require rebuilding it.
|
||||
Staff gifts remain free grants to their named recipient. Priced Exchange
|
||||
sales use the existing atomic bank/stock/sales/delivery transaction.
|
||||
|
||||
## Publication and checkout
|
||||
|
||||
1. Staff save a versioned definition through the existing item editor.
|
||||
2. Publication verifies current item management and issuance permissions,
|
||||
saved revision, price, quantity and confirmation. The existing HQ publisher
|
||||
signs the definition and writes stock and its unique publication receipt.
|
||||
3. In that same transaction an extension record binds the existing key to
|
||||
`cms.item`, listing, seller, material, signed payload hash, unit price,
|
||||
initial quantity, and the exact active treasury account ID/number.
|
||||
4. The binding is signed server-side and has no editing endpoint. Checkout
|
||||
verifies it and the original unrevoked item-definition key/revision.
|
||||
Origin, name, category or an item model alone cannot establish a payee.
|
||||
5. Payment, stock reduction and native paid delivery still commit together.
|
||||
The original purchase reference and payload fingerprint provide replay
|
||||
protection. Ordinary resale listings use their linked personal seller.
|
||||
6. Published definitions cannot be edited. Withdrawal revokes the original
|
||||
publication key and removes unsold stock. A correction requires saving a
|
||||
new revision. Existing paid receipts replay and remain deliverable.
|
||||
|
||||
## Existing listing repair and deployment
|
||||
|
||||
Paul's Chopper is existing listing 9, saved definition
|
||||
`c4247cbd-ec62-4883-83b0-624b48ae1d7d` revision 3, key
|
||||
`7d249ee4-30ed-4002-a6b9-0e55422d22a3`. Read-only inspection verified its HQ
|
||||
seller identity, signed payload and existing key. Its seller is not a personal
|
||||
player account. No live purchase or cash test was executed for diagnosis.
|
||||
|
||||
After the exact reviewed build is live, run the built
|
||||
`ops/cms-publication-access.mjs` in plan mode, then `--apply` to restore only
|
||||
the scoped SQL privileges needed by the recovered publisher and new binding.
|
||||
It verifies both databases share one MySQL server and backs up current grants
|
||||
privately before applying them. It grants no global or delegation privileges.
|
||||
|
||||
Use built `ops/seal-cms-publication.mjs --key <key> --listing 9
|
||||
--actor <authorised-staff-name>` first as a read-only plan, then `--apply`.
|
||||
This verifies the exact signed existing listing and current staff authority,
|
||||
backs up its original classification privately, and seals metadata only.
|
||||
It invokes no schema initializer, item issuer or financial executor. Do not
|
||||
delete/recreate the owner's pending purchase reference or manufacture a bank
|
||||
payment. Existing publication can also be sealed by the authenticated API's
|
||||
`seal-publication` action.
|
||||
|
||||
## Acceptance and checks
|
||||
|
||||
- Staff can publish price/stock from the existing Publication tab and receive
|
||||
recipient-bound `/redeem` gift commands; ordinary users cannot issue them.
|
||||
- Published terms and treasury destination reject tampering; drafts remain
|
||||
editable. Player resale proceeds remain personal.
|
||||
- Publication faults roll back stock, key binding and receipt together.
|
||||
- Payment fixtures verify balanced entries, exactly-once treasury credit,
|
||||
stock consumption and paid delivery replay, including after withdrawal.
|
||||
- Named recipient, expiry and native receipt tests prevent gift replay.
|
||||
- Real client acceptance and actual paid delivery are separate from fixture
|
||||
success. Do not claim payment was tested live without its actual receipt.
|
||||
|
||||
Local website build passed. The full Windows suite reported 1,863 passed,
|
||||
6 skipped, zero failures; the two later publication UI tests also passed.
|
||||
Focused tests were rerun after sealing the exact destination account and
|
||||
restoring the publisher. Canonical CI, merge, scoped permission installation,
|
||||
existing-listing sealing and live acceptance remain pending. This document is
|
||||
not deployment evidence.
|
||||
6
website/integrations/game-item-publication-grants.sql
Normal file
6
website/integrations/game-item-publication-grants.sql
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
-- Apply to the existing Postbank application principal on the shared MySQL server.
|
||||
-- HQ publication inserts its stock and idempotency receipt in one transaction.
|
||||
GRANT INSERT (seller,seller_name,origin,category,material,quantity,price,payload,display_name)
|
||||
ON dunegameplay.dune_exchange_listings TO 'dune_postbank'@'127.0.0.1';
|
||||
GRANT INSERT (id,actor_uuid,kind,fingerprint,listing_id,created_at)
|
||||
ON dunegameplay.dune_exchange_inventory_ops TO 'dune_postbank'@'127.0.0.1';
|
||||
87
website/node/cms-item-publication.mjs
Normal file
87
website/node/cms-item-publication.mjs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
import {createHash,createHmac,timingSafeEqual} from 'node:crypto';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
||||
import {hqItemMetadata} from './minecraft-item-payload.mjs';
|
||||
import {BankError} from './postbank-service.mjs';
|
||||
|
||||
export const CMS_ITEM_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_item_publications(key_id CHAR(36) PRIMARY KEY,listing_id BIGINT NOT NULL UNIQUE,binding_json TEXT NOT NULL,binding_signature CHAR(64) NOT NULL,published_at BIGINT NOT NULL)`;
|
||||
const digest=value=>createHash('sha256').update(value).digest('hex');
|
||||
const schema=value=>{if(!/^[a-z][a-z0-9_]{2,63}$/.test(value||''))throw TypeError('Verified publication schema required');return '`'+value+'`';};
|
||||
const sign=(secret,raw)=>createHmac('sha256',secret).update('cms.item:'+raw).digest('hex');
|
||||
const unavailable=()=>new BankError('The official item publication requires review. No payment was taken.',409);
|
||||
function definition(row,secret){
|
||||
if(!hqItemMetadata(row.payload,row.material,secret).nativeMetadata)throw unavailable();
|
||||
return JSON.parse(Buffer.from(row.payload.split('.')[1],'base64').toString('utf8'));
|
||||
}
|
||||
function checkVersion(key,version,def){
|
||||
if(!key||!version||key.account_id!==STAFF_OFFICE_ACCOUNT_ID||key.key_type!=='item-definition'||key.revoked_at!==null||key.expires_at!=null||key.scope_id!==`item:${version.design_id}:v${version.revision}`||def.keyId!==key.id||digest(version.design_json)!==version.fingerprint||JSON.stringify(JSON.parse(version.design_json))!==JSON.stringify(def.design))throw unavailable();
|
||||
}
|
||||
// A listing publication extends its existing item-definition key. Item origin
|
||||
// alone never establishes a payee: a player's resale uses native item bytes.
|
||||
export function createCMSItemPublications(db,keys,{secret,gameSchema,centralSchema,bank=db,authorize,clock=Date.now}={}){
|
||||
const game=schema(gameSchema);if(typeof secret!=='string'||secret.length<32||typeof authorize!=='function')throw TypeError('Publication authority and signing secret required');
|
||||
return {
|
||||
async candidates(actor){
|
||||
if(!await authorize(actor,db))throw new BankError('Item publication management required.',403);
|
||||
const rows=await db.query("SELECT * FROM "+game+".dune_exchange_listings WHERE origin='jarvis-hq' ORDER BY id DESC LIMIT 1000"),out=[];
|
||||
for(const row of rows){try{
|
||||
const def=definition(row,secret),key=(await db.query('SELECT * FROM organisation_keys WHERE id=?',[def.keyId]))[0],version=(await db.query('SELECT * FROM jarvis_item_design_versions WHERE key_id=?',[def.keyId]))[0];checkVersion(key,version,def);
|
||||
const p=(await db.query('SELECT key_id FROM jarvis_item_publications WHERE key_id=?',[def.keyId]))[0];
|
||||
const priceMinor=Math.round(Number(row.price)*100);if(!Number.isSafeInteger(priceMinor)||priceMinor<1||priceMinor>100000000)continue;
|
||||
out.push({keyId:def.keyId,listingId:String(row.id),state:p?'published':'unsealed',quantity:Number(row.quantity),priceMinor,destination:'In-game Bank Treasury'});
|
||||
}catch(error){if(!(error instanceof BankError))throw error;}}
|
||||
return out;
|
||||
},
|
||||
async seal(actor,{keyId,listingId},{transactionStore=null}={}){
|
||||
if(!/^[a-f0-9-]{36}$/i.test(keyId||'')||! /^[1-9]\d{0,17}$/.test(String(listingId)))throw TypeError('Choose an existing official item publication');
|
||||
if(!await authorize(actor,db))throw new BankError('Item publication management required.',403);
|
||||
const version=(await db.query('SELECT * FROM jarvis_item_design_versions WHERE key_id=?',[keyId]))[0];if(!version)throw unavailable();
|
||||
const work=async tx=>{
|
||||
if(!await authorize(actor,tx))throw unavailable();
|
||||
const key=await tx.first('SELECT * FROM organisation_keys WHERE id=? FOR SHARE',[keyId]);
|
||||
const row=await tx.first('SELECT * FROM '+game+'.dune_exchange_listings WHERE id=? FOR UPDATE',[String(listingId)]);if(!row||row.origin!=='jarvis-hq')throw unavailable();
|
||||
const def=definition(row,secret);checkVersion(key,version,def);
|
||||
const recipient=transactionStore||bank,treasury=(await recipient.query("SELECT id,account_number,state FROM pb_accounts WHERE system_key='sys_game_treasury'"))[0];
|
||||
if(!treasury||treasury.state!=='active'||typeof treasury.account_number!=='string')throw unavailable();
|
||||
const prior=await tx.first('SELECT * FROM jarvis_item_publications WHERE key_id=?',[keyId]),initialQuantity=prior?JSON.parse(prior.binding_json).initialQuantity:Number(row.quantity);
|
||||
if(!Number.isInteger(initialQuantity)||initialQuantity<1||initialQuantity>36||Number(row.quantity)<1||Number(row.quantity)>initialQuantity)throw unavailable();
|
||||
const binding={type:'cms.item',keyId,listingId:String(row.id),sellerUuid:row.seller,origin:row.origin,material:row.material,payloadHash:digest(row.payload),price:String(row.price),initialQuantity,treasurySystemKey:'sys_game_treasury',treasuryAccountId:String(treasury.id),treasuryAccountNumber:treasury.account_number};
|
||||
const raw=JSON.stringify(binding);
|
||||
if(prior){if(prior.binding_json!==raw||prior.binding_signature!==sign(secret,raw))throw new BankError('Published item keys cannot be edited. Withdraw and publish a new revision.',409);}
|
||||
else await tx.query('INSERT INTO jarvis_item_publications(key_id,listing_id,binding_json,binding_signature,published_at) VALUES(?,?,?,?,?)',[keyId,String(row.id),raw,sign(secret,raw),clock()]);
|
||||
await tx.query("UPDATE "+game+".dune_exchange_listings SET category='cms.item' WHERE id=?",[String(row.id)]);
|
||||
};
|
||||
if(transactionStore){
|
||||
const prefix=schema(centralSchema)+'.',qualify=sql=>sql.replace(/\b(organisation_keys|jarvis_item_design_versions|jarvis_item_publications|site_accounts)\b/g,prefix+'`$1`');
|
||||
await work({query:(sql,args)=>transactionStore.query(qualify(sql),args),first:(sql,args)=>transactionStore.first(qualify(sql),args)});
|
||||
}else await db.transaction(work);
|
||||
return {keyId,listingId:String(listingId),state:'published',type:'cms.item',destination:'In-game Bank Treasury',editable:false};
|
||||
},
|
||||
async withdraw(actor,{keyId,listingId}){
|
||||
if(!/^[a-f0-9-]{36}$/i.test(keyId||'')||! /^[1-9]\d{0,17}$/.test(String(listingId)))throw TypeError('Choose an existing official publication');
|
||||
return keys.revoke({accountId:STAFF_OFFICE_ACCOUNT_ID,keyId,authorize:async(tx)=>{
|
||||
if(!await authorize(actor,tx))return false;
|
||||
const publication=await tx.first('SELECT * FROM jarvis_item_publications WHERE key_id=? FOR UPDATE',[keyId]);
|
||||
if(!publication||String(publication.listing_id)!==String(listingId))return false;
|
||||
// Existing paid delivery receipts remain untouched and payable.
|
||||
await tx.query('DELETE FROM '+game+'.dune_exchange_listings WHERE id=?',[String(listingId)]);return true;
|
||||
}});
|
||||
}
|
||||
};
|
||||
}
|
||||
export function createCMSItemResolver({centralSchema,secret}={}){
|
||||
const central=schema(centralSchema);if(typeof secret!=='string'||secret.length<32)throw TypeError('Publication signing secret required');
|
||||
return async(tx,row)=>{
|
||||
if(row.category!=='cms.item')return null;
|
||||
const def=definition(row,secret);
|
||||
const publication=await tx.first('SELECT * FROM '+central+'.jarvis_item_publications WHERE listing_id=? FOR SHARE',[String(row.id)]);
|
||||
if(!publication||publication.key_id!==def.keyId)throw unavailable();
|
||||
const raw=publication.binding_json,expected=sign(secret,raw);if(!/^[a-f0-9]{64}$/.test(publication.binding_signature)||!timingSafeEqual(Buffer.from(expected,'hex'),Buffer.from(publication.binding_signature,'hex')))throw unavailable();
|
||||
const b=JSON.parse(raw);
|
||||
if(!Number.isInteger(b.initialQuantity)||b.initialQuantity<1||b.initialQuantity>36||Number(row.quantity)<1||Number(row.quantity)>b.initialQuantity)throw unavailable();
|
||||
if(b.type!=='cms.item'||b.keyId!==def.keyId||b.listingId!==String(row.id)||b.sellerUuid!==row.seller||b.origin!==row.origin||b.material!==row.material||b.payloadHash!==digest(row.payload)||b.price!==String(row.price)||b.treasurySystemKey!=='sys_game_treasury')throw unavailable();
|
||||
const key=await tx.first('SELECT * FROM '+central+'.organisation_keys WHERE id=? FOR SHARE',[b.keyId]),version=await tx.first('SELECT * FROM '+central+'.jarvis_item_design_versions WHERE key_id=? FOR SHARE',[b.keyId]);
|
||||
checkVersion(key,version,def);
|
||||
if(!/^[1-9]\d{0,19}$/.test(b.treasuryAccountId)||typeof b.treasuryAccountNumber!=='string')throw unavailable();
|
||||
return {id:STAFF_OFFICE_ACCOUNT_ID,username:'Official CMS',treasurySystemKey:b.treasurySystemKey,treasuryAccountId:b.treasuryAccountId,treasuryAccountNumber:b.treasuryAccountNumber};
|
||||
};
|
||||
}
|
||||
|
|
@ -39,18 +39,23 @@ export function createGameExchangePayments(bank,authority,{clock=Date.now}={}){
|
|||
async post(tx,actor,seller,hold,tax=null,incentive=null){
|
||||
if(!payments)throw new BankError('The central bank is unavailable.',503);
|
||||
const amount=BigInt(hold.unit_minor)*BigInt(hold.quantity),fingerprint=exchangeFingerprint(hold);
|
||||
const candidates=await personal(tx,actor.id),recipients=await personal(tx,seller.id),taxMinor=tradeTaxMinor(amount,tax?.percent||0),houseId=taxMinor>0n?entityId('office','leader:'+tax.house):null;
|
||||
const official=seller.treasurySystemKey==='sys_game_treasury';
|
||||
if(seller.treasurySystemKey&&!official)throw new BankError('The official receiving account requires review.',409);
|
||||
const treasury=official?await tx.first("SELECT * FROM pb_accounts WHERE system_key='sys_game_treasury'"):null;
|
||||
if(official&&(!treasury||treasury.state!=='active'||String(treasury.id)!==seller.treasuryAccountId||treasury.account_number!==seller.treasuryAccountNumber))throw new BankError('The sealed In-game Bank Treasury destination requires review. No payment was taken.',503);
|
||||
const candidates=await personal(tx,actor.id),recipients=official?[treasury]:await personal(tx,seller.id),taxMinor=tradeTaxMinor(amount,tax?.percent||0),houseId=taxMinor>0n?entityId('office','leader:'+tax.house):null;
|
||||
const houseCandidates=houseId?(await tx.query(accounts+' WHERE e.id=? AND a.system_key IS NULL ORDER BY a.id',[houseId])).filter(ordinaryPaymentAccount):[];
|
||||
if(houseId&&!houseCandidates.length)throw new BankError('The House levy account is unavailable. No payment was taken.',503);
|
||||
for(const id of [...new Set([...candidates,...recipients,...houseCandidates].map(a=>a.entity_id))].sort())await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[id]);
|
||||
for(const id of [...new Set([...candidates,...recipients,...houseCandidates].map(a=>a.entity_id).filter(Boolean))].sort())await tx.first('SELECT id FROM pb_entities WHERE id=? FOR UPDATE',[id]);
|
||||
const previous=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[hold.id]);
|
||||
if(previous){if(previous.actor_id!==actor.id||previous.fingerprint!==fingerprint||previous.state!=='posted')throw new BankError('Exchange payment reference conflict.',409);return {replayed:true};}
|
||||
const ids=[...new Set([...candidates,...recipients,...houseCandidates].map(a=>String(a.id)))];
|
||||
if(!ids.length)throw new BankError('Active personal payment accounts are required.',409);
|
||||
const rows=await tx.query(accounts+' WHERE a.id IN ('+ids.map(()=>'?').join(',')+') ORDER BY a.id FOR UPDATE',ids);
|
||||
if(official){const locked=await tx.first('SELECT * FROM pb_accounts WHERE id=? FOR UPDATE',[treasury.id]);if(!locked||locked.system_key!=='sys_game_treasury'||locked.state!=='active')throw new BankError('The official receiving account changed. No payment was taken.',409);rows.push(locked);}
|
||||
const context=await authority(actor,{bank:tx});
|
||||
const source=rows.find(a=>a.external_key===actor.id&&ordinaryPaymentAccount(a)&&canDebitAccount(context,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=amount);
|
||||
const target=rows.find(a=>a.external_key===seller.id&&ordinaryPaymentAccount(a)&&BigInt(a.balance_minor)+amount<=9223372036854775807n);
|
||||
const target=rows.find(a=>(official?a.system_key==='sys_game_treasury'&&a.state==='active':a.external_key===seller.id&&ordinaryPaymentAccount(a))&&BigInt(a.balance_minor)+amount<=9223372036854775807n);
|
||||
if(!source||!target||String(source.id)===String(target.id))throw new BankError('Available funds or payment account authority changed.',409);
|
||||
const house=houseId?rows.find(a=>a.entity_id===houseId&&ordinaryPaymentAccount(a)&&BigInt(a.balance_minor)+taxMinor<=9223372036854775807n):null;
|
||||
if(houseId&&!house)throw new BankError('The House levy account changed. No payment was taken.',409);
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ export function exchangeListing(row){
|
|||
if(!/^[1-9]\d{0,17}$/.test(String(row.id))||!Number.isSafeInteger(Number(row.quantity))||Number(row.quantity)<1||!/^\w{1,80}$/.test(row.material)||row.payload!==null&&(typeof row.payload!=='string'||row.payload.length>65536))throw new BankError('This listing is not supported.',409);
|
||||
return {id:String(row.id),sellerUuid:row.seller,seller:String(row.seller_name||'Seller').slice(0,32),title:String(row.display_name||row.material).slice(0,120),material:row.material,payload:row.payload,quantity:Number(row.quantity),priceMinor:exchangeMinor(row.price),origin:String(row.origin).slice(0,48)};
|
||||
}
|
||||
export function createGameExchangeService(bank,{gameSchema,authority,resolveSeller,revalidate=async actor=>actor,clock=Date.now,tradePolicy=async()=>({}),incentives=null}={}){
|
||||
export function createGameExchangeService(bank,{gameSchema,authority,resolveSeller,resolvePublication=async()=>null,revalidate=async actor=>actor,clock=Date.now,tradePolicy=async()=>({}),incentives=null}={}){
|
||||
if(!/^[a-z][a-z0-9_]{2,63}$/.test(gameSchema||''))throw Error('A verified game schema is required.');
|
||||
const table=name=>'`'+gameSchema+'`.`'+name+'`',listings=table('dune_exchange_listings'),deliveries=table('dune_exchange_deliveries'),sales=table('dune_exchange_sales');
|
||||
const payments=createGameExchangePayments(bank,authority,{clock});
|
||||
|
|
@ -54,7 +54,7 @@ export function createGameExchangeService(bank,{gameSchema,authority,resolveSell
|
|||
if(offer.sellerUuid===player)throw new BankError('Use Sell to withdraw your own listing.',409);
|
||||
if(offer.priceMinor!==input.priceMinor||offer.quantity<input.amount)throw new BankError('The price or available quantity changed.',409);
|
||||
const current=await revalidate(actor,player);if(!current||current.id!==actor.id)throw new BankError('Your current Exchange authority is unavailable.',403);
|
||||
const seller=await resolveSeller(offer.sellerUuid);if(!seller||seller.id===actor.id)throw new BankError('The seller is not linked to an eligible personal account.',409);
|
||||
const seller=await resolvePublication(tx,row)||await resolveSeller(offer.sellerUuid);if(!seller||seller.id===actor.id)throw new BankError('The seller is not linked to an eligible personal account.',409);
|
||||
const order={id:input.requestId,buyer_uuid:player,buyer_account_id:actor.id,seller_uuid:offer.sellerUuid,listing_id:offer.id,quantity:input.amount,unit_minor:offer.priceMinor,payload_hash:createHash('sha256').update(row.material+'\n'+(row.payload||'')).digest('hex'),display_name:offer.title};
|
||||
const settlement=await payments.post(tx,current,seller,order,rule?{...rule,requestId:rule.taxRequestId}:null,incentives?{service:incentives,world}:null);
|
||||
if(offer.quantity===input.amount)await tx.query('DELETE FROM '+listings+' WHERE id=?',[offer.id]);
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import {createExchangeIncentives,verifyExchangeIncentive} from './exchange-incen
|
|||
import {createGameExchangeService} from './game-exchange-service.mjs';
|
||||
import {BankError} from './postbank-service.mjs';
|
||||
import {createBankTradePolicy} from './world-trade-governance.mjs';
|
||||
import {createCMSItemResolver} from './cms-item-publication.mjs';
|
||||
|
||||
const exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).length===keys.length&&keys.every(k=>Object.hasOwn(v,k));
|
||||
const price=v=>Number.isSafeInteger(v)&&v>=1&&v<=100000000;
|
||||
|
|
@ -27,7 +28,13 @@ export function createGameExchangeAPI(db,bank,pool,settings={},dependencies={}){
|
|||
const tables=['dune_exchange_listings','dune_exchange_sales','dune_exchange_deliveries'];
|
||||
const engines=await bank.query('SELECT TABLE_NAME AS name,ENGINE AS engine FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME IN (?,?,?)',[url.pathname.slice(1),...tables]);
|
||||
if(engines.length!==tables.length||engines.some(row=>row.engine!=='InnoDB'||!tables.includes(row.name)))throw Error('Transactional Exchange tables required');
|
||||
service=createGameExchangeService(bank,{gameSchema:url.pathname.slice(1),tradePolicy:db.worldTradeEnabled?createBankTradePolicy(db,bank):undefined,incentives:db.exchangeIncentiveEnabled?createExchangeIncentives(bank,{verify:(pool,now)=>verifyExchangeIncentive(db,pool,now)}):null,authority:createPostbankAuthority(db,{bank}),resolveSeller:actorFor,revalidate:async(actor,player)=>{const fresh=await actorFor(player);return fresh?.id===actor.id&&await allowed(fresh)?fresh:null;}});
|
||||
let publications;
|
||||
const resolvePublication=async(tx,row)=>{
|
||||
if(row.category!=='cms.item')return null;
|
||||
if(!publications){const central=(await db.query('SELECT DATABASE() AS name,@@hostname AS host,@@port AS port,@@server_id AS server_id'))[0];if(!central||['host','port','server_id'].some(k=>String(central[k])!==String(b[k])))throw new BankError('Official publication storage requires review.',503);publications=createCMSItemResolver({centralSchema:central.name,secret:settings.GAME_LINK_SECRET});}
|
||||
return publications(tx,row);
|
||||
};
|
||||
service=createGameExchangeService(bank,{gameSchema:url.pathname.slice(1),resolvePublication,tradePolicy:db.worldTradeEnabled?createBankTradePolicy(db,bank):undefined,incentives:db.exchangeIncentiveEnabled?createExchangeIncentives(bank,{verify:(pool,now)=>verifyExchangeIncentive(db,pool,now)}):null,authority:createPostbankAuthority(db,{bank}),resolveSeller:actorFor,revalidate:async(actor,player)=>{const fresh=await actorFor(player);return fresh?.id===actor.id&&await allowed(fresh)?fresh:null;}});
|
||||
})().catch(error=>{storage=null;throw error;});
|
||||
await storage;
|
||||
};
|
||||
|
|
@ -53,6 +60,6 @@ export function createGameExchangeAPI(db,bank,pool,settings={},dependencies={}){
|
|||
else if(input.action==='prepare_sale'){result=await service.prepareSale(actor);Object.assign(result,{requestId:input.requestId,amount:input.amount,priceMinor:input.priceMinor,expiresAt:Date.now()+30000});}
|
||||
else result={allowed:true,requestId:input.requestId,expiresAt:Date.now()+30000};
|
||||
return json({ok:true,schema:1,action:input.action,playerUuid:input.uuid,...result});
|
||||
}catch(error){return json({message:error instanceof BankError?error.message:'The Exchange is temporarily unavailable. Retry the same purchase reference; paid items remain queued.'},error instanceof BankError?error.status||409:503);}
|
||||
}catch(error){if(!(error instanceof BankError)){const safe=value=>typeof value==='string'&&/^[A-Za-z0-9_]{1,64}$/.test(value)?value:'unknown';(dependencies.reportError||((details)=>console.error('Game Exchange failure',JSON.stringify(details))))({action:input.action,requestId:validUuid(input.requestId)?input.requestId:null,code:safe(error.code),name:safe(error.name)});}return json({message:error instanceof BankError?error.message:'The Exchange is temporarily unavailable. Retry the same purchase reference; paid items remain queued.'},error instanceof BankError?error.status||409:503);}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,16 @@
|
|||
import {gameAuthorized,validUuid,json} from './game-link.mjs';
|
||||
import {pendingKitsetGrants} from './kitset-grants.mjs';
|
||||
import {pendingItemGifts} from './item-gifts.mjs';
|
||||
export function createGameKitGrantsAPI(db,settings,dependencies={}){return async request=>{
|
||||
if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401);
|
||||
const url=new URL(request.url);if(url.pathname!=='/internal/game/kit-grants'||url.search||request.method!=='POST')return json({message:'Not found'},404);
|
||||
try{
|
||||
const reader=request.body?.getReader();if(!reader)return json({message:'Game identity required.'},400);let raw='';
|
||||
try{let bytes=0;const parts=[];while(true){const {value,done}=await reader.read();if(done)break;bytes+=value.length;if(bytes>1024){await reader.cancel();return json({message:'Request too large'},413);}parts.push(value);}raw=Buffer.concat(parts).toString('utf8');}finally{reader.releaseLock();}
|
||||
const input=JSON.parse(raw);if(!input||Object.keys(input).length!==2||!validUuid(input.uuid)||typeof input.serverKey!=='string'||!/^[-a-z0-9_]{1,48}$/.test(input.serverKey))return json({message:'Current game identity required.'},400);
|
||||
const input=JSON.parse(raw);if(!input||Object.keys(input).some(k=>!['uuid','serverKey','itemGifts'].includes(k))||Object.hasOwn(input,'itemGifts')&&input.itemGifts!==true||!validUuid(input.uuid)||typeof input.serverKey!=='string'||!/^[-a-z0-9_]{1,48}$/.test(input.serverKey))return json({message:'Current game identity required.'},400);
|
||||
let grants=await (dependencies.pending||pendingKitsetGrants)(db,input.uuid,input.serverKey,settings);
|
||||
if(dependencies.starter)grants.push(...await dependencies.starter.pendingRepairs(input.uuid,input.serverKey));
|
||||
if(dependencies.pool&&input.itemGifts===true)grants.push(...await pendingItemGifts(db,input.uuid,input.serverKey,settings,dependencies.pool));
|
||||
if(dependencies.commerce){const actors=await db.query("SELECT a.id FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[input.uuid]);if(actors.length!==1)throw Error('Current linked buyer required');grants.push(...await dependencies.commerce.pending(actors[0].id,input.uuid,input.serverKey));}
|
||||
if(dependencies.pool&&grants.length){
|
||||
const ids=grants.map(g=>JSON.parse(Buffer.from(g.payload,'base64')).recipients[0].receiptId),args=[input.uuid,...ids];
|
||||
|
|
|
|||
73
website/node/hq-exchange.mjs
Normal file
73
website/node/hq-exchange.mjs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import {createHash,createHmac,timingSafeEqual} from 'node:crypto';
|
||||
import {validUuid} from './game-link.mjs';
|
||||
import {kitsetDeliveryItems} from './kitset-grants.mjs';
|
||||
|
||||
export const HQ_ORIGIN='jarvis-hq';
|
||||
export const HQ_LABEL='J.A.R.V.I.S. HQ';
|
||||
const seller='b17d80bc-1f96-4e02-bc5d-ffb9fa51b366';
|
||||
const prefix='HQ1.';
|
||||
const mac=(secret,body)=>createHmac('sha256',secret).update(prefix+body).digest('hex');
|
||||
function signedHQDefinition(row,secret){
|
||||
if((row?.sellerUuid??row?.seller)!==seller||row?.origin!==HQ_ORIGIN||typeof secret!=='string'||secret.length<32||typeof row.payload!=='string'||!row.payload.startsWith(prefix))return null;
|
||||
const [format,body,signature,...extra]=row.payload.split('.');
|
||||
if(format!=='HQ1'||extra.length||!body||!/^[a-f0-9]{64}$/.test(signature||'')||!timingSafeEqual(Buffer.from(signature),Buffer.from(mac(secret,body))))return null;
|
||||
try{const data=JSON.parse(Buffer.from(body,'base64').toString('utf8'));return data.template.material.toUpperCase()===row.material?data:null;}
|
||||
catch{return null;}
|
||||
}
|
||||
export const signedHQDesign=(row,secret)=>signedHQDefinition(row,secret)?.design||null;
|
||||
export const isHQOffer=(row,secret)=>!!signedHQDesign(row,secret);
|
||||
|
||||
export async function publishedHQDesigns(bank,settings){
|
||||
if(!bank||!settings.DUNE_INVENTORY_DATABASE_URL)return [];
|
||||
const url=new URL(settings.DUNE_INVENTORY_DATABASE_URL),schema=url.pathname.slice(1);
|
||||
if(url.protocol!=='mysql:'||!/^[a-z][a-z0-9_]{2,63}$/.test(schema))return [];
|
||||
const stock='`'+schema+'`.dune_exchange_listings',deliveries='`'+schema+'`.dune_exchange_deliveries';
|
||||
const rows=await bank.query('SELECT seller,origin,material,payload,id AS listing_id FROM '+stock+' WHERE seller=? AND origin=? UNION ALL SELECT seller_uuid AS seller,origin,material,payload,listing_id FROM '+deliveries+' WHERE seller_uuid=? AND origin=? ORDER BY listing_id DESC LIMIT 500',[seller,HQ_ORIGIN,seller,HQ_ORIGIN]);
|
||||
const definitions=new Map();
|
||||
for(const row of rows){
|
||||
const definition=signedHQDefinition(row,settings.GAME_LINK_SECRET);
|
||||
if(definition&&validUuid(definition.keyId)&&!definitions.has(definition.keyId))definitions.set(definition.keyId,definition);
|
||||
}
|
||||
return [...definitions.values()];
|
||||
}
|
||||
|
||||
export async function postHQOffer(bank,service,actor,input,settings,{clock=Date.now,sealPublication}={}){
|
||||
const {id,revision,requestId,quantity,priceMinor}=input;
|
||||
if(!validUuid(id)||!validUuid(requestId)||!Number.isInteger(revision)||revision<1||!Number.isInteger(quantity)||quantity<1||quantity>36||!Number.isSafeInteger(priceMinor)||priceMinor<1||priceMinor>100000000||input.confirmed!==true)throw new TypeError('Choose a saved revision, quantity, price and confirm the listing.');
|
||||
const secret=settings.GAME_LINK_SECRET;
|
||||
let schema;try{const url=new URL(settings.DUNE_INVENTORY_DATABASE_URL);if(url.protocol==='mysql:')schema=url.pathname.slice(1);}catch{}
|
||||
if(!bank||!/^[a-z][a-z0-9_]{2,63}$/.test(schema||'')||typeof secret!=='string'||secret.length<32)throw Error('The shared Exchange is unavailable.');
|
||||
const saved=await service.version(actor,{id,revision});
|
||||
const [item]=kitsetDeliveryItems({items:[{design:saved.design,quantity}]});
|
||||
const material=item.template.material.toUpperCase();
|
||||
const body=Buffer.from(JSON.stringify({design:item.design,template:item.template,keyId:saved.keyId})).toString('base64');
|
||||
const payload=prefix+body+'.'+mac(secret,body);
|
||||
if(payload.length>65536)throw new TypeError('This item definition exceeds the Exchange limit.');
|
||||
const fingerprint=createHash('sha256').update(JSON.stringify([actor.id,saved.keyId,quantity,priceMinor])).digest('hex');
|
||||
const stock='`'+schema+'`.dune_exchange_listings',receipts='`'+schema+'`.dune_exchange_inventory_ops';
|
||||
const replay=async store=>{
|
||||
const prior=await store.first('SELECT actor_uuid,kind,fingerprint,listing_id FROM '+receipts+' WHERE id=?',[requestId]);
|
||||
if(prior){
|
||||
if(prior.kind!=='hq-publish'||prior.actor_uuid!==seller||prior.fingerprint!==fingerprint)throw Error('Publication reference already used.');
|
||||
return {listingId:String(prior.listing_id),replayed:true};
|
||||
}
|
||||
};
|
||||
try{
|
||||
return await bank.transaction(async tx=>{
|
||||
const prior=await replay(tx);if(prior)return prior;
|
||||
if(!await tx.first("SELECT id FROM pb_accounts WHERE system_key='sys_game_treasury' AND state='active' FOR SHARE"))throw Error('The In-game Bank Treasury is unavailable.');
|
||||
const inserted=await tx.query('INSERT INTO '+stock+'(seller,seller_name,origin,category,material,quantity,price,payload,display_name) VALUES(?,?,?,?,?,?,?,?,?)',[seller,HQ_LABEL,HQ_ORIGIN,'misc',material,quantity,(priceMinor/100).toFixed(2),payload,saved.design.name]);
|
||||
const listingId=String(inserted.insertId);
|
||||
if(!/^[1-9]\d*$/.test(listingId))throw Error('Exchange listing receipt unavailable.');
|
||||
if(typeof sealPublication!=='function')throw Error('Official publication sealing is unavailable.');
|
||||
await sealPublication(tx,{keyId:saved.keyId,listingId});
|
||||
// The unique receipt wins concurrent retries. A duplicate rolls back this
|
||||
// transaction’s stock insert before the committed receipt is reread.
|
||||
await tx.query("INSERT INTO "+receipts+"(id,actor_uuid,kind,fingerprint,listing_id,created_at) VALUES(?,?,'hq-publish',?,?,?)",[requestId,seller,fingerprint,listingId,clock()]);
|
||||
return {listingId,replayed:false};
|
||||
});
|
||||
}catch(error){
|
||||
if(error.code==='ER_DUP_ENTRY'){const prior=await replay(bank);if(prior)return prior;}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
|
||||
import {validateItemDesign} from '../control-panel/public/item-design-model.mjs';
|
||||
import {CMS_ITEM_SCHEMA} from './cms-item-publication.mjs';
|
||||
|
||||
export const ITEM_DESIGN_SCHEMA=[
|
||||
export const ITEM_DESIGN_SCHEMA=[CMS_ITEM_SCHEMA,
|
||||
'CREATE TABLE IF NOT EXISTS jarvis_item_designs(id CHAR(36) PRIMARY KEY,revision INT NOT NULL,key_id CHAR(36) NOT NULL,author_id CHAR(36) NOT NULL,design_json TEXT NOT NULL,fingerprint CHAR(64) NOT NULL,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL)',
|
||||
'CREATE TABLE IF NOT EXISTS jarvis_item_design_versions(key_id CHAR(36) PRIMARY KEY,design_id CHAR(36) NOT NULL,revision INT NOT NULL,author_id CHAR(36) NOT NULL,design_json TEXT NOT NULL,fingerprint CHAR(64) NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY item_design_revision(design_id,revision))'
|
||||
];
|
||||
|
|
@ -10,7 +11,7 @@ export async function initializeItemDesigns(db){for(const sql of ITEM_DESIGN_SCH
|
|||
const uuid=value=>typeof value==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
|
||||
const first=async(store,sql,args=[])=>(await store.query(sql,args))[0]||null;
|
||||
const hash=raw=>createHash('sha256').update(raw).digest('hex');
|
||||
function record(row){if(!row)return null;if(hash(row.design_json)!==row.fingerprint)throw Error('Item definition requires review.');return {id:row.design_id||row.id,revision:Number(row.revision),keyId:row.key_id,authorId:row.author_id,design:JSON.parse(row.design_json),state:'draft'};}
|
||||
function record(row){if(!row)return null;if(hash(row.design_json)!==row.fingerprint)throw Error('Item definition requires review.');return {id:row.design_id||row.id,revision:Number(row.revision),keyId:row.key_id,authorId:row.author_id,design:JSON.parse(row.design_json),state:row.published_key_id&&row.publication_revoked_at==null?'published':'draft',...(row.published_listing_id&&row.publication_revoked_at==null?{publication:{listingId:String(row.published_listing_id),state:'published',type:'cms.item',destination:'In-game Bank Treasury'}}:{})};}
|
||||
|
||||
// Drafts and their immutable versions reuse the system-key transaction. They do
|
||||
// not publish a native file, issue inventory, charge money or unlock a rarity.
|
||||
|
|
@ -18,7 +19,7 @@ export function createItemDesigns(db,keys,{authorize,clock=Date.now}={}){
|
|||
if(typeof authorize!=='function'||!keys)throw TypeError('A current item-editor authority adapter is required.');
|
||||
const allowed=async(actor,store)=>{if(!uuid(actor?.id)||await authorize(actor,store)!==true)throw Error('Item definition management required.');};
|
||||
return Object.freeze({
|
||||
async list(actor){await allowed(actor,db);return (await db.query('SELECT * FROM jarvis_item_designs ORDER BY updated_at DESC,id LIMIT 1000')).map(record);},
|
||||
async list(actor){await allowed(actor,db);return (await db.query('SELECT d.*,p.key_id published_key_id,p.listing_id published_listing_id,k.revoked_at publication_revoked_at FROM jarvis_item_designs d LEFT JOIN jarvis_item_publications p ON p.key_id=d.key_id LEFT JOIN organisation_keys k ON k.id=p.key_id ORDER BY d.updated_at DESC,d.id LIMIT 1000')).map(record);},
|
||||
async version(actor,{id,revision}){
|
||||
await allowed(actor,db);if(!uuid(id)||!Number.isSafeInteger(revision)||revision<1||revision>999999)throw TypeError('Choose a saved item definition revision.');
|
||||
const row=await first(db,'SELECT v.*,k.account_id issuer,k.key_type,k.scope_id,k.revoked_at FROM jarvis_item_design_versions v JOIN organisation_keys k ON k.id=v.key_id WHERE v.design_id=? AND v.revision=?',[id.toLowerCase(),revision]);
|
||||
|
|
@ -33,6 +34,7 @@ export function createItemDesigns(db,keys,{authorize,clock=Date.now}={}){
|
|||
const prior=await first(tx,'SELECT * FROM jarvis_item_design_versions WHERE design_id=? AND revision=?',[id,next]);
|
||||
if(prior){if(prior.fingerprint!==fingerprint||prior.author_id!==actor.id)throw Error('Item definition revision conflict. Refresh before saving.');return;}
|
||||
const current=await first(tx,'SELECT * FROM jarvis_item_designs WHERE id=? FOR UPDATE',[id]);
|
||||
if(current){const published=await first(tx,'SELECT p.key_id FROM jarvis_item_publications p JOIN organisation_keys k ON k.id=p.key_id WHERE p.key_id=? AND k.revoked_at IS NULL',[current.key_id]);if(published)throw Error('Published item definition is sealed. Withdraw before saving a new revision.');}
|
||||
if(Number(current?.revision||0)!==revision)throw Error('Item definition changed. Refresh before saving.');
|
||||
await tx.query('INSERT INTO jarvis_item_design_versions(key_id,design_id,revision,author_id,design_json,fingerprint,created_at) VALUES(?,?,?,?,?,?,?)',[keyId,id,next,actor.id,raw,fingerprint,now]);
|
||||
if(current)await tx.query('UPDATE jarvis_item_designs SET revision=?,key_id=?,author_id=?,design_json=?,fingerprint=?,updated_at=? WHERE id=?',[next,keyId,actor.id,raw,fingerprint,now,id]);
|
||||
|
|
|
|||
75
website/node/item-gifts.mjs
Normal file
75
website/node/item-gifts.mjs
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import {createHash,randomBytes,randomUUID} from 'node:crypto';
|
||||
import {gameAuthorized,json,validUuid} from './game-link.mjs';
|
||||
import {kitGrantReceipt,kitsetDeliveryItems,signKitsetDelivery} from './kitset-grants.mjs';
|
||||
import {validateItemDesign} from '../control-panel/public/item-design-model.mjs';
|
||||
|
||||
const hash=value=>createHash('sha256').update(value).digest('hex');
|
||||
const activePerson="a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')";
|
||||
|
||||
export const ITEM_GIFT_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_item_gifts(
|
||||
id CHAR(36) PRIMARY KEY,token_hash CHAR(64) NOT NULL UNIQUE,design_key CHAR(36) NOT NULL,
|
||||
issuer_id CHAR(36) NOT NULL,recipient_id CHAR(36) NOT NULL,recipient_uuid CHAR(36) NOT NULL,
|
||||
quantity INT NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,redeemed_at BIGINT NULL,delivered_at BIGINT NULL,
|
||||
INDEX item_gift_delivery(recipient_id,recipient_uuid,redeemed_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
|
||||
|
||||
export async function issueItemGift(db,service,actor,input,{clock=Date.now}={}){
|
||||
const {id,revision,recipient,quantity}=input;
|
||||
if(!validUuid(id)||!Number.isInteger(revision)||revision<1||typeof recipient!=='string'||!/^[A-Za-z0-9_]{1,16}$/.test(recipient)||!Number.isInteger(quantity)||quantity<1||quantity>36)throw new TypeError('Choose a saved revision, a linked Minecraft player and a quantity from 1 to 36.');
|
||||
const saved=await service.version(actor,{id,revision});
|
||||
kitsetDeliveryItems({items:[{design:saved.design,quantity}]});
|
||||
const recipients=await db.query(`SELECT a.id,l.minecraft_uuid,l.minecraft_name FROM site_game_links l JOIN site_accounts a ON a.id=l.user_id WHERE LOWER(l.minecraft_name)=LOWER(?) AND ${activePerson} LIMIT 2`,[recipient]);
|
||||
if(recipients.length!==1||!validUuid(recipients[0].minecraft_uuid))throw new TypeError('Choose one linked Minecraft player.');
|
||||
const target=recipients[0],token='ITM-'+randomBytes(16).toString('hex'),now=clock(),giftId=randomUUID(),expiresAt=now+7*86400000;
|
||||
await db.query('INSERT INTO jarvis_item_gifts(id,token_hash,design_key,issuer_id,recipient_id,recipient_uuid,quantity,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?)',[giftId,hash(token),saved.keyId,actor.id,target.id,target.minecraft_uuid,quantity,now,expiresAt]);
|
||||
return {giftId,recipient:target.minecraft_name,expiresAt,command:'/redeem '+token,origin:'J.A.R.V.I.S. HQ'};
|
||||
}
|
||||
|
||||
export function createGameItemRedeem(db,settings,{clock=Date.now}={}){
|
||||
return async request=>{
|
||||
if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401);
|
||||
if(request.method!=='POST')return json({message:'Method not allowed'},405);
|
||||
let input;try{input=await request.json();}catch{return json({message:'Invalid redemption request.'},400);}
|
||||
const {uuid,key}=input||{};
|
||||
if(!validUuid(uuid)||typeof key!=='string'||!/^ITM-[a-f0-9]{32}$/.test(key))return json({message:'Use /dune redeem <key>.'},400);
|
||||
const now=clock();
|
||||
const result=await db.transaction(async tx=>{
|
||||
const gift=await tx.first(`SELECT g.id,g.expires_at,g.redeemed_at FROM jarvis_item_gifts g
|
||||
JOIN site_game_links l ON l.user_id=g.recipient_id AND l.minecraft_uuid=g.recipient_uuid
|
||||
JOIN site_accounts a ON a.id=l.user_id JOIN organisation_keys k ON k.id=g.design_key
|
||||
WHERE g.token_hash=? AND g.recipient_uuid=? AND ${activePerson} AND k.revoked_at IS NULL FOR UPDATE`,[hash(key),uuid]);
|
||||
if(!gift||gift.redeemed_at==null&&Number(gift.expires_at)<=now)return false;
|
||||
if(gift.redeemed_at==null)await tx.query('UPDATE jarvis_item_gifts SET redeemed_at=? WHERE id=?',[now,gift.id]);
|
||||
return true;
|
||||
});
|
||||
return result?json({ok:true,message:'J.A.R.V.I.S. HQ accepted the gift. Keep room in your inventory for delivery.'}):json({message:'This key is invalid, expired or issued to a different player.'},409);
|
||||
};
|
||||
}
|
||||
|
||||
export async function pendingItemGifts(db,uuid,serverKey,settings,pool,{clock=Date.now}={}){
|
||||
const rows=await db.query(`SELECT g.*,v.design_id,v.revision,v.design_json,v.fingerprint FROM jarvis_item_gifts g
|
||||
JOIN jarvis_item_design_versions v ON v.key_id=g.design_key
|
||||
JOIN site_game_links l ON l.user_id=g.recipient_id AND l.minecraft_uuid=g.recipient_uuid
|
||||
JOIN site_accounts a ON a.id=l.user_id
|
||||
WHERE g.recipient_uuid=? AND ${activePerson} AND g.redeemed_at IS NOT NULL AND g.delivered_at IS NULL ORDER BY g.redeemed_at,g.id LIMIT 64`,[uuid]);
|
||||
if(!rows.length||!pool)return [];
|
||||
const ids=rows.map(row=>kitGrantReceipt(row.id,uuid));
|
||||
const result=await pool.query({text:"SELECT id FROM dune_exchange_inventory_ops WHERE actor_uuid=$1 AND kind='kit-grant' AND id IN ("+ids.map((_,i)=>'$'+(i+2)).join(',')+')', values:[uuid,...ids],query_timeout:5000});
|
||||
const completed=new Set(result.rows.map(row=>row.id));
|
||||
const envelopes=[];
|
||||
for(const [i,row] of rows.entries()){
|
||||
if(completed.has(ids[i])){
|
||||
await db.query('UPDATE jarvis_item_gifts SET delivered_at=? WHERE id=? AND delivered_at IS NULL',[clock(),row.id]);
|
||||
continue;
|
||||
}
|
||||
if(hash(row.design_json)!==row.fingerprint)continue;
|
||||
const design=validateItemDesign(JSON.parse(row.design_json));
|
||||
const definition={key_id:row.design_key,revision:row.revision,fingerprint:row.fingerprint};
|
||||
envelopes.push(signKitsetDelivery(definition,{name:design.name,items:[{design,quantity:Number(row.quantity)}]},{
|
||||
actorId:row.issuer_id,kitsetId:row.design_id,requestId:row.id,serverKey,action:'items.design-gift',
|
||||
linked:[{uuid,accountId:row.recipient_id,receiptId:ids[i]}]
|
||||
},settings,clock()).envelope);
|
||||
if(envelopes.length===16)break;
|
||||
}
|
||||
return envelopes;
|
||||
}
|
||||
|
|
@ -24,7 +24,7 @@ export async function prepareKitsetGrant(db,{actorId,kitsetId,requestId,recipien
|
|||
return signKitsetDelivery(row,kit,{actorId:actors[0].id,kitsetId,requestId,serverKey,linked},settings,now);
|
||||
}
|
||||
export function signKitsetDelivery(row,kit,{actorId,kitsetId,requestId,serverKey,linked,action="items.kitset-grant"},settings,now){
|
||||
if(!["items.kitset-grant","items.kitset-purchase"].includes(action))throw Error("Unsupported delivery action");
|
||||
if(!["items.kitset-grant","items.kitset-purchase","items.design-gift"].includes(action))throw Error("Unsupported delivery action");
|
||||
const items=kitsetDeliveryItems(kit);
|
||||
const grantFingerprint=hash(JSON.stringify({requestId,keyId:row.key_id,definitionHash:row.fingerprint,recipients:linked.map(r=>r.uuid)}));
|
||||
const data={action,requestId,serverKey,actorId,kitsetId,kitKeyId:row.key_id,kitRevision:Number(row.revision),kitName:kit.name,definitionHash:row.fingerprint,grantFingerprint,issuedAt:now,expiresAt:now+900000,recipients:linked,items};
|
||||
|
|
|
|||
37
website/ops/cms-publication-access.mjs
Normal file
37
website/ops/cms-publication-access.mjs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import {readFile,writeFile,mkdir} from 'node:fs/promises';
|
||||
import {execFileSync} from 'node:child_process';
|
||||
import {pathToFileURL} from 'node:url';
|
||||
import {resolve} from 'node:path';
|
||||
import mysql from 'mysql2/promise';
|
||||
|
||||
export function publicationAccessPlan({centralSchema,gameSchema,centralIdentity,bankIdentity}){
|
||||
const db=value=>{if(!/^[a-z][a-z0-9_]{2,63}$/.test(value||''))throw TypeError('Verified schema required');return '`'+value+'`';};
|
||||
const principal=value=>{const parts=String(value).split('@');if(parts.length!==2||parts.some(p=>! /^[a-zA-Z0-9_.%:-]+$/.test(p)))throw TypeError('Verified application identity required');return parts.map(p=>"'"+p+"'").join('@');};
|
||||
const central=db(centralSchema),game=db(gameSchema),site=principal(centralIdentity),bank=principal(bankIdentity);
|
||||
return [
|
||||
`GRANT SELECT,INSERT ON ${central}.jarvis_item_publications TO ${bank}`,
|
||||
...['organisation_keys','jarvis_item_design_versions','site_accounts'].map(t=>`GRANT SELECT ON ${central}.${t} TO ${bank}`),
|
||||
`GRANT SELECT ON ${game}.dune_exchange_listings TO ${site}`,
|
||||
`GRANT UPDATE(category),DELETE ON ${game}.dune_exchange_listings TO ${site}`,
|
||||
`GRANT SELECT ON ${game}.dune_exchange_deliveries TO ${site}`,
|
||||
`GRANT INSERT(seller,seller_name,origin,category,material,quantity,price,payload,display_name) ON ${game}.dune_exchange_listings TO ${bank}`,
|
||||
`GRANT SELECT,INSERT(id,actor_uuid,kind,fingerprint,listing_id,created_at) ON ${game}.dune_exchange_inventory_ops TO ${bank}`
|
||||
];
|
||||
}
|
||||
async function main(){
|
||||
process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');const e=process.env,raw=JSON.parse(await readFile(e.POSTBANK_DB_CONFIG,'utf8'));
|
||||
const site=await mysql.createConnection({host:e.DB_HOST||'127.0.0.1',port:Number(e.DB_PORT||3306),user:e.DB_USER,password:e.DB_PASSWORD,database:e.DB_NAME}),bank=await mysql.createConnection(raw);
|
||||
try{
|
||||
const [a]=await site.query('SELECT CURRENT_USER() identity,DATABASE() name,@@hostname host,@@port port,@@server_id server_id'),[b]=await bank.query('SELECT CURRENT_USER() identity,@@hostname host,@@port port,@@server_id server_id');
|
||||
if(['host','port','server_id'].some(k=>String(a[0][k])!==String(b[0][k])))throw Error('Publication records must share the bank transaction server');
|
||||
const plan=publicationAccessPlan({centralSchema:a[0].name,gameSchema:new URL(e.DUNE_INVENTORY_DATABASE_URL).pathname.slice(1),centralIdentity:a[0].identity,bankIdentity:b[0].identity});
|
||||
if(!process.argv.includes('--apply')){console.log(JSON.stringify({applied:false,statements:plan},null,2));return;}
|
||||
const backup=resolve('/root/dunerealms-cms-access-backups',new Date().toISOString().replace(/[:.]/g,'-'));await mkdir(backup,{recursive:true,mode:0o700});
|
||||
// Root's existing local MySQL administration connection; no app password is
|
||||
// interpolated into a shell or an argument. Application secrets stay private.
|
||||
const identities=[a[0].identity,b[0].identity];for(let i=0;i<identities.length;i++){const user=identities[i].split('@').map(p=>"'"+p+"'").join('@');const grants=execFileSync('mysql',['--batch','--raw','--skip-column-names','--execute','SHOW GRANTS FOR '+user],{encoding:'utf8'});await writeFile(resolve(backup,'principal-'+i+'.sql'),grants,{mode:0o600,flag:'wx'});}
|
||||
for(const sql of plan)execFileSync('mysql',['--execute',sql],{stdio:['ignore','pipe','pipe']});
|
||||
console.log(JSON.stringify({applied:true,statements:plan.length,backup}));
|
||||
}finally{await site.end();await bank.end();}
|
||||
}
|
||||
if(process.argv[1]&&import.meta.url===pathToFileURL(resolve(process.argv[1])).href)await main();
|
||||
34
website/ops/seal-cms-publication.mjs
Normal file
34
website/ops/seal-cms-publication.mjs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import {readFile,mkdir,writeFile} from 'node:fs/promises';
|
||||
import {resolve} from 'node:path';
|
||||
import {createHash} from 'node:crypto';
|
||||
import mysql from 'mysql2/promise';
|
||||
import {mysqlSql} from '../node/mysql.mjs';
|
||||
import {can} from '../node/permissions.mjs';
|
||||
import {createCMSItemPublications} from '../node/cms-item-publication.mjs';
|
||||
|
||||
// Explicit repair of an already published signed HQ listing. No schema
|
||||
// initializer, key generation, inventory issuance or financial executor runs.
|
||||
process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');
|
||||
const e=process.env,args=process.argv.slice(2),arg=name=>args[args.indexOf(name)+1];
|
||||
const keyId=arg('--key'),listingId=arg('--listing'),username=arg('--actor'),apply=args.includes('--apply');
|
||||
if(!/^[a-f0-9-]{36}$/i.test(keyId||'')||! /^[1-9]\d{0,17}$/.test(listingId||'')||! /^[A-Za-z0-9_]{1,32}$/.test(username||''))throw TypeError('Explicit --key, --listing and --actor required');
|
||||
const game=new URL(e.DUNE_INVENTORY_DATABASE_URL).pathname.slice(1);if(!/^[a-z][a-z0-9_]{2,63}$/.test(game))throw TypeError('Verified game schema required');
|
||||
const pool=mysql.createPool({host:e.DB_HOST||'127.0.0.1',port:Number(e.DB_PORT||3306),user:e.DB_USER,password:e.DB_PASSWORD,database:e.DB_NAME,connectionLimit:4,supportBigNumbers:true}),api=c=>{
|
||||
const store={async query(sql,values=[]){if(!apply&&!/^\s*SELECT\b/i.test(sql))throw Error('Plan is read-only');return(await c.execute(mysqlSql(sql),values))[0]},async first(sql,values=[]){return(await store.query(sql,values))[0]||null},prepare(sql){let values=[];return{bind(...args){values=args;return this},first:()=>store.first(sql,values),all:async()=>({results:await store.query(sql,values)})}}};return store;
|
||||
};
|
||||
const db={...api(pool),organisationAccessEnabled:e.ORGANISATION_ACCESS_ENABLED==='true',async transaction(work){const c=await pool.getConnection();try{await c.beginTransaction();const result=await work(api(c));await c.commit();return result;}catch(error){await c.rollback();throw error;}finally{c.release()}},async readSnapshot(work){const c=await pool.getConnection();try{await c.query('START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY');const result=await work({...db,...api(c)});await c.commit();return result;}catch(error){await c.rollback();throw error;}finally{c.release()}}};
|
||||
const bankPool=mysql.createPool(JSON.parse(await readFile(e.POSTBANK_DB_CONFIG,'utf8'))),bank=api(bankPool);
|
||||
try{
|
||||
const info='SELECT @@hostname host,@@port port,@@server_id server_id';const [centralInfo,bankInfo]=await Promise.all([db.first(info),bank.first(info)]);if(['host','port','server_id'].some(k=>String(centralInfo[k])!==String(bankInfo[k])))throw Error('Publication and bank must share the transaction server');
|
||||
const actor=await db.first("SELECT id,username,role FROM site_accounts WHERE LOWER(username)=LOWER(?) AND password_hash NOT LIKE '!%'",[username]);
|
||||
const authorize=async a=>!!a&&await can(db,a,'web.items.manage')&&await can(db,a,'dune.items.give');if(!await authorize(actor))throw Error('Current staff publication authority required');
|
||||
const publications=createCMSItemPublications(db,null,{secret:e.GAME_LINK_SECRET,gameSchema:game,bank,authorize});
|
||||
const candidate=(await publications.candidates(actor)).find(p=>p.keyId===keyId&&p.listingId===listingId);if(!candidate)throw Error('Exact signed official publication not found');
|
||||
if(!apply){console.log(JSON.stringify({applied:false,...candidate,financialWrites:false}));}
|
||||
else{
|
||||
const row=await db.first('SELECT id,seller,origin,category,material,quantity,price,payload FROM `'+game+'`.dune_exchange_listings WHERE id=?',[listingId]);const {payload,...metadata}=row;
|
||||
const backup=resolve('/root/dunerealms-cms-publication-backups',new Date().toISOString().replace(/[:.]/g,'-'));await mkdir(backup,{recursive:true,mode:0o700});
|
||||
const prior=await db.first('SELECT * FROM jarvis_item_publications WHERE key_id=?',[keyId]);await writeFile(resolve(backup,'before.json'),JSON.stringify({keyId,listing:metadata,payloadHash:createHash('sha256').update(payload).digest('hex'),publication:prior},null,2),{mode:0o600,flag:'wx'});
|
||||
const result=await publications.seal(actor,{keyId,listingId});console.log(JSON.stringify({applied:true,...result,backup,financialWrites:false}));
|
||||
}
|
||||
}finally{await pool.end();await bankPool.end()}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff