diff --git a/.forgejo/tests/web-deploy.test.mjs b/.forgejo/tests/web-deploy.test.mjs index 2874e598..472e930c 100644 --- a/.forgejo/tests/web-deploy.test.mjs +++ b/.forgejo/tests/web-deploy.test.mjs @@ -44,3 +44,11 @@ test('publication comparison, artifact upload and deployment require canonical m if (name !== 'Trigger deployment after successful CI') assert.doesNotMatch(body, /DUNEREALMS_DEPLOY_KEY|ssh .*dunedeploy@/); } }); + + +test('deployment uses the verified dedicated host and its pinned SSH key', () => { + const deploy = step('Trigger deployment after successful CI'); + assert.ok(deploy.includes('95.216.100.187 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICdHgR/5lVFKbOpAYR2+/Bi5LSg+8nDCSm77mJOmJKRg')); + assert.ok(deploy.includes('dunedeploy@95.216.100.187')); + assert.ok(!deploy.includes('91.107.196.242')); +}); diff --git a/.forgejo/workflows/web-deploy.yml b/.forgejo/workflows/web-deploy.yml index cd75e390..ea4a8b42 100644 --- a/.forgejo/workflows/web-deploy.yml +++ b/.forgejo/workflows/web-deploy.yml @@ -87,7 +87,7 @@ jobs: printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/deploy_key chmod 600 ~/.ssh/deploy_key trap 'rm -f ~/.ssh/deploy_key' EXIT - printf '%s\n' '91.107.196.242 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC8x/XocsIz41fWHGty0DbZhSvafSQFt9jaHHgzdr55W root@ubuntu-4gb-fsn1-1' >> ~/.ssh/known_hosts - ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes dunedeploy@91.107.196.242 "$GITHUB_SHA" + printf '%s\n' '95.216.100.187 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICdHgR/5lVFKbOpAYR2+/Bi5LSg+8nDCSm77mJOmJKRg' >> ~/.ssh/known_hosts + ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes dunedeploy@95.216.100.187 "$GITHUB_SHA" rm -f ~/.ssh/deploy_key diff --git a/website/.env.example b/website/.env.example index ba192071..8eaaa4ff 100644 --- a/website/.env.example +++ b/website/.env.example @@ -18,3 +18,6 @@ EXCHANGE_READ_TOKEN= # Optional private read-only PostgreSQL role for CP inventory/sales. # Never use the game writer role or publish this URL to browser code. DUNE_INVENTORY_DATABASE_URL= + +# Enable only after the paired native Guild travel release is installed. +GUILD_OPEN_TRAVEL=false diff --git a/website/control-panel/public/cp-v2/art/quests/armoury-banner.png b/website/control-panel/public/cp-v2/art/quests/armoury-banner.png new file mode 100644 index 00000000..e2371a76 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/armoury-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/armoury-icon.png b/website/control-panel/public/cp-v2/art/quests/armoury-icon.png new file mode 100644 index 00000000..c2459950 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/armoury-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/arrival-banner.png b/website/control-panel/public/cp-v2/art/quests/arrival-banner.png new file mode 100644 index 00000000..5a11d94d Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/arrival-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/arrival-icon.png b/website/control-panel/public/cp-v2/art/quests/arrival-icon.png new file mode 100644 index 00000000..30959ce3 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/arrival-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/campaign-banner.png b/website/control-panel/public/cp-v2/art/quests/campaign-banner.png new file mode 100644 index 00000000..9e0931cb Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/campaign-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/campaign-icon.png b/website/control-panel/public/cp-v2/art/quests/campaign-icon.png new file mode 100644 index 00000000..9393b1af Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/campaign-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/coin-banner.png b/website/control-panel/public/cp-v2/art/quests/coin-banner.png new file mode 100644 index 00000000..4eeb36de Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/coin-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/coin-icon.png b/website/control-panel/public/cp-v2/art/quests/coin-icon.png new file mode 100644 index 00000000..2153df3a Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/coin-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/contracts-banner.png b/website/control-panel/public/cp-v2/art/quests/contracts-banner.png new file mode 100644 index 00000000..be61740b Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/contracts-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/contracts-icon.png b/website/control-panel/public/cp-v2/art/quests/contracts-icon.png new file mode 100644 index 00000000..ebd6e3c1 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/contracts-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/deep-desert-banner.png b/website/control-panel/public/cp-v2/art/quests/deep-desert-banner.png new file mode 100644 index 00000000..6d41364f Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/deep-desert-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/deep-desert-icon.png b/website/control-panel/public/cp-v2/art/quests/deep-desert-icon.png new file mode 100644 index 00000000..eadf0ae4 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/deep-desert-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/landsraad-banner.png b/website/control-panel/public/cp-v2/art/quests/landsraad-banner.png new file mode 100644 index 00000000..083a47bf Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/landsraad-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/landsraad-icon.png b/website/control-panel/public/cp-v2/art/quests/landsraad-icon.png new file mode 100644 index 00000000..1de6c56e Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/landsraad-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/lanes-banner.png b/website/control-panel/public/cp-v2/art/quests/lanes-banner.png new file mode 100644 index 00000000..7c5c485d Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/lanes-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/lanes-icon.png b/website/control-panel/public/cp-v2/art/quests/lanes-icon.png new file mode 100644 index 00000000..12129dc3 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/lanes-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/melange-banner.png b/website/control-panel/public/cp-v2/art/quests/melange-banner.png new file mode 100644 index 00000000..65d0d293 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/melange-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/melange-icon.png b/website/control-panel/public/cp-v2/art/quests/melange-icon.png new file mode 100644 index 00000000..c844df32 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/melange-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/other-banner.png b/website/control-panel/public/cp-v2/art/quests/other-banner.png new file mode 100644 index 00000000..b6806442 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/other-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/other-icon.png b/website/control-panel/public/cp-v2/art/quests/other-icon.png new file mode 100644 index 00000000..ebd6e3c1 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/other-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/place-banner.png b/website/control-panel/public/cp-v2/art/quests/place-banner.png new file mode 100644 index 00000000..806ba961 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/place-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/place-icon.png b/website/control-panel/public/cp-v2/art/quests/place-icon.png new file mode 100644 index 00000000..53952c3e Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/place-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/prophecy-banner.png b/website/control-panel/public/cp-v2/art/quests/prophecy-banner.png new file mode 100644 index 00000000..90d73c05 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/prophecy-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/prophecy-icon.png b/website/control-panel/public/cp-v2/art/quests/prophecy-icon.png new file mode 100644 index 00000000..8787f24a Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/prophecy-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/sons-banner.png b/website/control-panel/public/cp-v2/art/quests/sons-banner.png new file mode 100644 index 00000000..1a499ca4 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/sons-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/sons-icon.png b/website/control-panel/public/cp-v2/art/quests/sons-icon.png new file mode 100644 index 00000000..067d5014 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/sons-icon.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/wings-banner.png b/website/control-panel/public/cp-v2/art/quests/wings-banner.png new file mode 100644 index 00000000..731e003f Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/wings-banner.png differ diff --git a/website/control-panel/public/cp-v2/art/quests/wings-icon.png b/website/control-panel/public/cp-v2/art/quests/wings-icon.png new file mode 100644 index 00000000..f737ee40 Binary files /dev/null and b/website/control-panel/public/cp-v2/art/quests/wings-icon.png differ diff --git a/website/control-panel/public/cp-v2/cp-v2-elytra-quests.mjs b/website/control-panel/public/cp-v2/cp-v2-elytra-quests.mjs index 1fba8e86..f02471f6 100644 --- a/website/control-panel/public/cp-v2/cp-v2-elytra-quests.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-elytra-quests.mjs @@ -10,7 +10,8 @@ const rows=[ ['IRON','Imperial Iron','On Kaitain, smelt raw iron and take at least 2 iron ingots from a furnace or blast furnace.','flight-iron',2,50,[]], ['DIAMOND','Under the Ice','Obtain a diamond on Ordos.','flight-diamond',1,100,[]], ['CRAFT','Wings over the Desert','Return to Arrakis. Complete the preparation quests to reveal the elytra recipe. Craft the elytra there.','flight-crafted',1,250,['NETHERITE','CONTAMINATE','MEMBRANES','IRON','DIAMOND']], - ['ACQUIRE','Another Way to Fly','Alternatively, buy and receive an elytra through the Exchange, or obtain an elytra from an End ship. This completes this entire branch and grants every unclaimed branch reward once.','flight-elytra-acquired',1,0,[]] + ['ACQUIRE','Another Way to Fly','Alternatively, buy and receive an elytra through the Exchange, or obtain an elytra from an End ship. This completes the elytra preparation and acquisition quests and grants their unclaimed rewards once. The armour merge still requires a real physical merge.','flight-elytra-acquired',1,0,[]] ]; +rows.push(['MERGE','Wings and Armour','Merge one elytra with a chestplate at an anvil. Keep the chestplate’s existing protection, enchantments, durability, grade and Origin World; one elytra is consumed. No additional currency fee.','flight-merged',1,0,[]]); export const ELYTRA_QUESTS=Object.freeze(rows.map(([suffix,title,objective,metric,target,xp,requires])=>Object.freeze({id:'POL-ELYTRA-'+suffix,title,objective,metric,target,xp,requires:requires.map(v=>'POL-ELYTRA-'+v),requiresAny:[],branch:'elytra',season:'S01',revision:1,optional:true,verifiedOnly:true,xpType:'pol'}))); export const ELYTRA_BRANCH=Object.freeze({id:'elytra',office:null,title:'Wings across the Realms',issuer:'esmar_tuek',issuerName:'Esmar Tuek',theme:'Five worlds, two material chains, one elytra · Reputation XP',xpType:'pol',quests:ELYTRA_QUESTS,decisions:[]}); diff --git a/website/control-panel/public/cp-v2/cp-v2-mission-journal-model.mjs b/website/control-panel/public/cp-v2/cp-v2-mission-journal-model.mjs new file mode 100644 index 00000000..efbf043f --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-mission-journal-model.mjs @@ -0,0 +1,87 @@ +// Pure view-model for the mission journal: story arcs on the left, one mission on the right. +// The server decides state, eligibility and rewards; nothing here grants anything. +export const STATUS_LABEL=Object.freeze({done:'Done',ready:'Ready to claim',active:'Active',available:'Available',locked:'Locked'}); + +export function questStatus(q){ + if(q.state==='claimed')return 'done'; + if(q.canClaim&&q.progress>=q.target)return 'ready'; + if(q.state==='completed')return 'ready'; + if(q.state==='active')return 'active'; + return q.canStart?'available':'locked'; +} +const money=(q,v)=>q.metric?.endsWith('-minor')?(v/100).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2})+' DM':Number(v).toLocaleString('en-US'); + +/** Orders an arc so a quest never appears before the quests it requires; ties keep catalogue order. */ +export function orderArc(quests){ + const byId=new Map(quests.map(q=>[q.id,q])),placed=new Set(),out=[]; + const place=q=>{if(placed.has(q.id))return;placed.add(q.id);for(const id of [...(q.requires||[]),...(q.requiresAny||[])]){const parent=byId.get(id);if(parent)place(parent);}out.push(q);}; + quests.forEach(place);return out; +} + +export function buildJournal(data,{arcTitles={}}={}){ + const quests=Array.isArray(data?.quests)?data.quests:[],order=[],groups=new Map(); + for(const q of quests){if(!groups.has(q.branch)){groups.set(q.branch,[]);order.push(q.branch);}groups.get(q.branch).push(q);} + const titles=new Map([...(data?.branches||[]).map(b=>[b.id,b.title]),...Object.entries(arcTitles)]); + const names=new Map(quests.map(q=>[q.id,q.title])); + const arcs=order.map(id=>{ + const list=orderArc(groups.get(id)).map(q=>{ + const status=questStatus(q),missing=(q.requires||[]).filter(r=>names.has(r)&&quests.find(x=>x.id===r)?.state!=='claimed'); + return {...q,status,statusLabel:STATUS_LABEL[status],lockedBy:status==='locked'&&missing.length?'Complete '+names.get(missing[0])+' first.':null}; + }); + const done=list.filter(q=>q.status==='done').length; + return {id,title:titles.get(id)||String(id).toUpperCase(),quests:list,done,total:list.length,complete:done===list.length}; + }); + return {arcs,all:arcs.flatMap(a=>a.quests)}; +} + +/** Chosen mission: the player's pick, else the tracked one, else whatever needs attention first. */ +export function pickSelection(journal,{preferred=null,tracked=null}={}){ + const has=id=>id&&journal.all.some(q=>q.id===id); + if(has(preferred))return preferred;if(has(tracked))return tracked; + for(const status of ['ready','active','available'])for(const q of journal.all)if(q.status===status)return q.id; + return journal.all[0]?.id||null; +} +/** The next unfinished mission in the same arc after the given one. */ +export function nextInArc(journal,id){ + const arc=journal.arcs.find(a=>a.quests.some(q=>q.id===id));if(!arc)return null; + const index=arc.quests.findIndex(q=>q.id===id); + return arc.quests.slice(index+1).find(q=>q.status!=='done')?.id||arc.quests.find(q=>q.status!=='done'&&q.id!==id)?.id||null; +} +export function advanceTracked(journal,id){ + return journal.all.find(q=>q.id===id)?.status==='done'?nextInArc(journal,id):id; +} +export function briefing(q,limit=220){ + const text=String(q.objective||'').replace(/\s+/g,' ').trim();if(!text)return 'Follow your objective below.'; + const sentence=text.match(/^.*?[.!?](?:\s|$)/)?.[0].trim()||text; + return sentence.length>limit?sentence.slice(0,limit-1).trimEnd()+'…':sentence; +} +export function objectives(q){ + const target=Math.max(1,Number(q.target)||1),progress=Math.min(Number(q.progress)||0,target); + return [{label:q.objective?briefing(q,120):q.title,progress,target,percent:Math.floor(progress*100/target),done:progress>=target,text:money(q,progress)+' / '+money(q,target)}]; +} +export function rewards(q,{xpType='personal'}={}){ + const rows=[]; + if(Number.isSafeInteger(q.xp))rows.push({label:xpType==='pol'?'Reputation':'Experience',value:q.xp.toLocaleString('en-US')+' XP'}); + if(Number.isSafeInteger(q.personalXP))rows.push({label:'Personal experience',value:q.personalXP.toLocaleString('en-US')+' XP'}); + if(Number.isSafeInteger(q.baseDMMinor))rows.push({label:'Base funded reward',value:(q.baseDMMinor/100).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2})+' DM'}); + if(!q.rewardConfigured)rows.push({label:'Reward',value:'Not configured yet'}); + return rows; +} +/** Which single button the selected mission offers: Track always, Claim only when something is unpaid, Start when it can begin. */ +export function actions(q,{tracked=null}={}){ + const list=[{kind:'track',label:tracked===q.id?'Tracking':'Track',disabled:q.status==='done'||q.status==='locked'}]; + if(q.status==='ready'&&q.canClaim)list.push({kind:'claim',label:'Claim reward'}); + else if(q.status==='available'&&q.canStart)list.push({kind:'start',label:'Start mission'}); + return list; +} +/** The sidebar shows the tracked mission's current objective, or the first active one when nothing is tracked. */ +export function currentObjective(journal,tracked){ + const q=journal.all.find(x=>x.id===tracked&&x.status!=='done')||journal.all.find(x=>x.status==='active')||journal.all.find(x=>x.status==='ready')||null; + if(!q)return null;const o=objectives(q)[0];return {id:q.id,title:q.title,objective:o.label,text:o.text,percent:o.percent,ready:q.status==='ready'}; +} +/** Missions that moved forward between two loads, for the objective-complete banner. */ +export function completions(previous,journal){ + if(!previous)return [];const before=new Map(previous.all.map(q=>[q.id,q.status])),out=[]; + for(const q of journal.all){const was=before.get(q.id);if(was&&was!=='ready'&&was!=='done'&&(q.status==='ready'||q.status==='done'))out.push({id:q.id,title:q.title,claimed:q.status==='done'});} + return out; +} diff --git a/website/control-panel/public/cp-v2/cp-v2-mission-journal.css b/website/control-panel/public/cp-v2/cp-v2-mission-journal.css new file mode 100644 index 00000000..d3b8a256 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-mission-journal.css @@ -0,0 +1,25 @@ +.mj{display:grid;gap:.9rem} +.mj-banner{display:flex;gap:.8rem;align-items:center;justify-content:space-between;padding:.7rem 1rem;border:1px solid var(--accent,#d7a548);border-radius:.5rem;background:rgba(215,165,72,.12)} +.mj-current{display:grid;gap:.25rem;padding:.7rem 1rem;border-left:4px solid var(--accent,#d7a548);background:rgba(255,255,255,.04);border-radius:.4rem} +.mj-current progress,.mj-objectives progress{width:100%;height:.6rem} +.mj-layout{display:grid;grid-template-columns:minmax(14rem,22rem) 1fr;gap:1rem;align-items:start} +@media(max-width:46rem){.mj-layout{grid-template-columns:1fr}} +.mj-arcs{display:grid;gap:.5rem} +.mj-arc{border:1px solid rgba(255,255,255,.14);border-radius:.5rem;padding:.25rem .5rem} +.mj-arc summary{display:flex;justify-content:space-between;gap:.5rem;cursor:pointer;padding:.4rem .2rem;font-weight:600} +.mj-arc ol{list-style:none;margin:0;padding:0 0 .3rem;display:grid;gap:.2rem} +.mj-mission{display:flex;flex-wrap:wrap;justify-content:space-between;gap:.2rem .6rem;width:100%;text-align:left;padding:.45rem .6rem;border-radius:.35rem;border:1px solid transparent;background:transparent;color:inherit;cursor:pointer} +.mj-mission[aria-pressed=true]{border-color:var(--accent,#d7a548);background:rgba(215,165,72,.1)} +.mj-mission[data-status=done]{opacity:.65}.mj-mission[data-status=done] span::before{content:"\2713\00a0"} +.mj-mission[data-status=locked]{opacity:.5}.mj-mission[data-status=locked] span::before{content:"\1F512\00a0"} +.mj-mission[data-status=ready] small:first-of-type,.mj-mission[data-status=active] small:first-of-type{color:var(--accent,#d7a548);font-weight:600} +.mj-tracked{width:100%;font-style:italic} +.mj-detail{display:grid;gap:.5rem;padding:1rem;border:1px solid rgba(255,255,255,.14);border-radius:.5rem} +.mj-detail h3,.mj-detail h4{margin:.2rem 0} +.mj-status{justify-self:start;padding:.1rem .6rem;border-radius:1rem;border:1px solid currentColor;font-size:.8rem} +.mj-briefing{font-size:1.02rem;line-height:1.45} +.mj-objectives{list-style:none;margin:0;padding:0;display:grid;gap:.6rem} +.mj-objectives li{display:grid;gap:.2rem} +.mj-objectives li[data-done=true] span::before{content:"\2713\00a0"} +.mj-rewards{display:grid;grid-template-columns:auto 1fr;gap:.2rem 1rem;margin:0}.mj-rewards dd{margin:0;font-weight:600} +.mj-actions{display:flex;gap:.6rem;flex-wrap:wrap;margin-top:.4rem} diff --git a/website/control-panel/public/cp-v2/cp-v2-mission-journal.mjs b/website/control-panel/public/cp-v2/cp-v2-mission-journal.mjs new file mode 100644 index 00000000..c9fd812b --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-mission-journal.mjs @@ -0,0 +1,65 @@ +import {element as el} from './cp-v2-page-template.mjs'; +import {actions,briefing,currentObjective,nextInArc,objectives,rewards,pickSelection} from './cp-v2-mission-journal-model.mjs'; + +import {categoryFor,categoryHero,groupJournalArcs,bannerUrl,iconUrl,ensureStyles} from './cp-v2-quest-categories.mjs'; + +const bar=(percent,label)=>{const p=el('progress');p.max=100;p.value=percent;p.setAttribute('aria-label',label);return p;}; +const button=(text,fn,disabled=false)=>{const b=el('button',text);b.type='button';b.disabled=disabled;b.onclick=fn;return b;}; + +/** Draws the journal. Pure presentation: every action goes back through the handlers to the server. */ +export function renderMissionJournal(body,{journal,selected,tracked,banners=[],busy=false,xpType='personal',notice=''},{onSelect,onAct,onTrack,onSteps}){ + const root=el('div',undefined,'mj'); + for(const banner of banners){ + const note=el('div',undefined,'mj-banner');note.setAttribute('role','status'); + note.append(el('strong',(banner.claimed?'Mission complete: ':'Objective complete: ')+banner.title)); + const next=nextInArc(journal,banner.id);if(next)note.append(button('Next mission',()=>onSelect(next))); + root.append(note); + } + if(notice){const n=el('p',notice,'progression-notice');n.setAttribute('role','alert');root.append(n);} + const current=currentObjective(journal,tracked); + const strip=el('div',undefined,'mj-current'); + if(current){strip.append(el('small','Current objective'),el('strong',current.title),el('span',current.objective+' — '+current.text),bar(current.percent,'Current objective progress'));if(current.ready)strip.append(el('em','Ready to claim'));} + else strip.append(el('small','Current objective'),el('span','No active mission. Pick one from the list.')); + root.append(strip); + + const layout=el('div',undefined,'mj-layout'),nav=el('nav',undefined,'mj-arcs');nav.setAttribute('aria-label','Story arcs'); + ensureStyles(); + for(const arc of groupJournalArcs(journal.arcs)){ + const group=el('details',undefined,'mj-arc');group.dataset.categoryId=arc.category.id;group.open=arc.quests.some(q=>q.id===selected)||(!arc.complete&&arc.quests.some(q=>q.status==='active'||q.status==='ready')); + const head=el('summary',undefined,'quest-category-heading');head.style.backgroundImage='linear-gradient(90deg,rgba(24,34,25,.75),rgba(24,34,25,.15)),url("'+bannerUrl(arc.category)+'")'; + const icon=el('img');icon.src=iconUrl(arc.category);icon.alt='';icon.width=icon.height=24; + head.append(icon,el('span',arc.category.title),el('small',arc.done+' / '+arc.total)); + head.onclick=event=>{if(!arc.quests.some(q=>q.id===selected)){event.preventDefault();onSelect(pickSelection({all:arc.quests},{tracked}));}}; + group.append(head,el('p',arc.category.tagline,'mj-arc-tagline'),bar(arc.total?arc.done/arc.total*100:0,arc.category.title+' progress')); + if(arc.ready)group.append(el('small',arc.ready+' reward'+(arc.ready===1?'':'s')+' ready','mj-arc-ready')); + const list=el('ol'); + for(const q of arc.quests){ + const item=el('li'),pick=button('',()=>onSelect(q.id));pick.className='mj-mission';pick.dataset.status=q.status;pick.setAttribute('aria-pressed',String(q.id===selected)); + pick.append(el('span',q.title),el('small',q.statusLabel));if(q.id===tracked&&q.status!=='done')pick.append(el('small','Tracked','mj-tracked')); + item.append(pick);list.append(item); + } + group.append(list);nav.append(group); + } + layout.append(nav); + + const q=journal.all.find(x=>x.id===selected),pane=el('section',undefined,'mj-detail');pane.setAttribute('aria-label','Selected mission'); + if(!q)pane.append(el('p','No missions are available yet.')); + else{ + pane.append(categoryHero(categoryFor(q.branch),el)); + pane.append(el('h3',q.title),el('span',q.statusLabel,'mj-status'),el('p',briefing(q),'mj-briefing')); + if(q.lockedBy)pane.append(el('p',q.lockedBy,'progression-notice')); + if(q.cooldownUntil>Date.now())pane.append(el('p','Next available: '+new Date(q.cooldownUntil).toLocaleString(),'progression-notice')); + pane.append(el('h4','Objectives'));const goals=el('ul',undefined,'mj-objectives'); + for(const o of objectives(q)){const row=el('li');row.dataset.done=String(o.done);row.append(el('span',o.label),el('small',o.text),bar(o.percent,o.label));goals.append(row);} + pane.append(goals,el('h4','Rewards'));const prizes=el('dl',undefined,'mj-rewards'); + for(const r of rewards(q,{xpType})){prizes.append(el('dt',r.label),el('dd',r.value));} + pane.append(prizes); + const row=el('div',undefined,'mj-actions'); + for(const a of actions(q,{tracked})){ + row.append(button(a.label,a.kind==='track'?()=>onTrack(q.id):()=>onAct(q),a.disabled||busy||(a.kind==='track'&&q.id===tracked))); + } + if(onSteps)row.append(button("Mission steps",()=>onSteps(q),busy)); + pane.append(row); + } + layout.append(pane);root.append(layout);body.append(root); +} diff --git a/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs b/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs index 34711d83..a23df64a 100644 --- a/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-personal-progression.mjs @@ -5,6 +5,9 @@ import {questArtwork,questChannel} from './cp-v2-quest-channels.mjs'; import {renderProgressionHistory} from './cp-v2-progression-history.mjs'; import {element as el} from './cp-v2-page-template.mjs'; import {MISSION_BRANCHES} from './cp-v2-progression-catalogue.mjs'; +import {categoryFor,categoryHero,groupBranches,orderChapters} from './cp-v2-quest-categories.mjs'; +import {advanceTracked,buildJournal,completions,nextInArc,pickSelection} from './cp-v2-mission-journal-model.mjs'; +import {renderMissionJournal} from './cp-v2-mission-journal.mjs'; const art='https://www.dunerealms.com/assets/'; const labels={claimed:'Reward claimed',completed:'Ready to claim',active:'In progress','not-started':'Not started'}; @@ -15,11 +18,17 @@ const date=n=>new Date(n).toLocaleString(undefined,{dateStyle:'medium',timeStyle // The server supplies all state, eligibility and rewards. The browser sends only // the selected definition and its displayed revision, never XP or counters. -export function mountPersonalProgression(host,{view='missions',fetcher=fetch,apiBase='/api/progression',onData=()=>{},onBranches=()=>{},externalBranches=false,onCareerNavigate=null,initialBranch='a',allowedBranches=null,artwork=null}={}){ +export function mountPersonalProgression(host,{view='missions',fetcher=fetch,apiBase='/api/progression',onData=()=>{},onBranches=()=>{},externalBranches=false,onCareerNavigate=null,initialBranch='a',allowedBranches=null,artwork=null,journal=true}={}){ const controller=new AbortController(),status=el('p','Opening your mission journal…','progression-notice'),body=el('div'); status.setAttribute('role','status');host.replaceChildren(status,body); let active=true,data=null,branch=initialBranch,selected=null,busy=false,uncertain=false,page=1,loadSequence=0,connectorObserver=null; - let detailOpen=false;const dossier=createProgressionDialog(host,{onClose:()=>{detailOpen=false;}}); + let requestedArc=typeof initialBranch==='string'&&initialBranch!=='a'?initialBranch:null; + const journalMode=journal!==false&&view==='missions'; + if(journalMode&&!document.querySelector('link[data-mission-journal]')){const link=el('link');link.rel='stylesheet';link.href=new URL('./cp-v2-mission-journal.css',import.meta.url).href;link.dataset.missionJournal='true';document.head.append(link);} + const trackKey=()=>'dunerealms.tracked-mission:'+(data?.xpType==='pol'?'pol':'personal');let tracked=null,trackedLoaded=false,lastJournal=null,lastData=null,banners=[]; + const rememberTrack=id=>{tracked=id;try{if(id)localStorage.setItem(trackKey(),id);else localStorage.removeItem(trackKey());}catch{}try{window.dispatchEvent(new CustomEvent('dunerealms:tracked-mission'));}catch{}}; + const track=id=>{rememberTrack(id);render();}; + let detailOpen=false;const dossier=createProgressionDialog(host,{onClose:()=>{detailOpen=false;if(journalMode&&active)render();}}); const requestIds=new Map(); async function api(path,options={}){ const response=await fetcher(apiBase+path,{credentials:'same-origin',cache:'no-store',signal:controller.signal,...options}); @@ -45,19 +54,33 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api } function render(){ connectorObserver?.disconnect(); + const arcScroll=body.querySelector?.('.mj-arcs')?.scrollTop??0; body.replaceChildren();if(!data)return; - const reload=button('Reload journal',load);reload.className='progression-reload';reload.disabled=busy;body.append(reload); + if(!journalMode){const reload=button('Reload journal',load);reload.className='progression-reload';reload.disabled=busy;body.append(reload);} if(view==='history'){renderProgressionHistory(body,data,{page,busy,onPrevious:()=>{page--;load();},onNext:()=>{page++;load();}});return;} if(data.state!=='active')return; + if(journalMode&&!detailOpen){ + if(!trackedLoaded){trackedLoaded=true;try{tracked=localStorage.getItem(trackKey());}catch{tracked=null;}} + const model=buildJournal(data); + if(requestedArc!==null){const scope=requestedArc;requestedArc=null;const choices=model.all.filter(q=>scope.startsWith('category:')?categoryFor(q.branch).id===scope.slice(9):q.branch===scope);if(choices.length)selected=pickSelection({all:choices},{tracked});} + if(data!==lastData){banners=completions(lastJournal,model);lastData=data;lastJournal=model;const next=advanceTracked(model,tracked);if(next!==tracked)rememberTrack(next);} + selected=pickSelection(model,{preferred:selected,tracked}); + branch=model.all.find(q=>q.id===selected)?.branch||branch; + const stats=el('div',undefined,'progression-stats');stats.append(el('strong',(data.xpType==='pol'?'Reputation level ':'Personal level ')+data.profile.level+(data.season.levelCap===null?' · uncapped':' / '+data.season.levelCap)));body.append(stats); + onBranches(model.arcs.map(a=>({id:a.id,title:a.title})),branch); + renderMissionJournal(body,{journal:model,selected,tracked,banners,busy,xpType:data.xpType,notice:uncertain?status.textContent:''},{onSelect:id=>{selected=id;banners=[];render();},onTrack:track,onSteps:row=>{branch=row.branch;selected=row.id;detailOpen=true;render();},onAct:row=>{const arcNext=()=>nextInArc(buildJournal(data),row.id);act(row).then(()=>{if(!selected||selected===row.id)selected=arcNext()||selected;if(active)render();});}}); + const arcNav=body.querySelector?.('.mj-arcs');if(arcNav)arcNav.scrollTop=arcScroll; + return; + } const stats=el('div',undefined,'progression-stats');stats.append(el('strong',(data.xpType==='pol'?'Reputation level ':'Personal level ')+data.profile.level+(data.season.levelCap===null?' · uncapped':' / '+data.season.levelCap)),el('span',data.profile.effectiveXP.toLocaleString()+(data.xpType==='pol'?' reputation':' seasonal XP')),el('span','Season ends '+date(data.season.endsAt))); const progress=el('progress');progress.max=data.season.levelCap;progress.value=data.profile.level;progress.setAttribute('aria-label','Season level');if(data.season.levelCap!==null)stats.append(progress);body.append(stats); if(data.affiliations?.length){const affiliation=el('aside',undefined,'progression-intro');affiliation.append(el('strong','The Unmarked Caravan'),el('p','Your smuggler clan and company affiliations are secondary. Your ordinary affiliations stay in place.'));body.append(affiliation);} const select=el('select');select.setAttribute('aria-label','Mission branch'); - const availableBranches=data.branches||branches;for(const b of availableBranches){if(!data.quests.some(q=>q.branch===b.id))continue;const option=el('option',b.title);option.value=b.id;select.append(option);} + const availableBranches=data.branches||branches;for(const group of groupBranches(availableBranches.filter(b=>data.quests.some(q=>q.branch===b.id)))){const option=el('option',group.category.title);option.value=group.category.id;select.append(option);} if(!data.quests.some(q=>q.branch===branch))branch=data.quests[0]?.branch; - select.value=branch;select.onchange=()=>{branch=select.value;selected=null;render();};onBranches(availableBranches.filter(b=>data.quests.some(q=>q.branch===b.id)),branch);if(!externalBranches)body.append(select); + select.value=categoryFor(branch).id;select.onchange=()=>{branch=data.quests.find(q=>categoryFor(q.branch).id===select.value)?.branch||branch;selected=null;render();};onBranches(availableBranches.filter(b=>data.quests.some(q=>q.branch===b.id)),branch);body.append(categoryHero(categoryFor(branch),el));if(!externalBranches)body.append(select); if(branch==='e'&&typeof onCareerNavigate==='function'){const careers=el('section',undefined,'progression-toolbar');careers.append(el('h3','Reputation careers'),button('Official Spice Harvesting',()=>onCareerNavigate('spice-harvesting')),button('Smuggling Jobs',()=>onCareerNavigate('smugglers')),button('Bounty Jobs',()=>onCareerNavigate('bounty-jobs')));body.append(careers);} - const rows=data.quests.filter(q=>q.branch===branch).map(q=>({...q,channel:questChannel(q.executionRequirements)}));selected=rows.find(q=>q.id===selected)?.id||null; + const rows=orderChapters(data.quests.filter(q=>categoryFor(q.branch).id===categoryFor(branch).id)).map(q=>({...q,channel:questChannel(q.executionRequirements)}));selected=rows.find(q=>q.id===selected)?.id||null; const layout=el('div',undefined,'progression-layout'),tree=el('div',undefined,'progression-tree');tree.setAttribute('aria-label','Mission tree'); for(const row of rows){const card=button('',()=>{selected=row.id;detailOpen=true;render();});card.className='progression-mission';card.dataset.missionId=row.id;card.dataset.channel=row.channel==='website'?'website':'shared';card.setAttribute('aria-pressed',String(row.id===selected));card.setAttribute('aria-haspopup','dialog');card.append(image(artwork||questArtwork(row.channel)),el('strong',row.title),el('span',labels[row.state]||'Awaiting verification','progression-badge'));tree.append(card);} layout.append(tree);const row=rows.find(q=>q.id===selected); @@ -75,5 +98,5 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api const connect=()=>{if(!active||!tree.isConnected)return;const box=tree.getBoundingClientRect();svg.setAttribute('viewBox','0 0 '+box.width+' '+box.height);svg.replaceChildren();const cards=new Map([...tree.querySelectorAll('[data-mission-id]')].map(n=>[n.dataset.missionId,n]));for(const row of rows)for(const dependency of row.requires||[]){if(!cards.has(dependency))continue;const a=cards.get(dependency).getBoundingClientRect(),b=cards.get(row.id).getBoundingClientRect(),line=document.createElementNS(svg.namespaceURI,'path'),sameRow=Math.abs(a.top-b.top)<5,x1=(sameRow?a.right:a.left+a.width/2)-box.left,y1=(sameRow?a.top+a.height/2:a.bottom)-box.top,x2=(sameRow?b.left:b.left+b.width/2)-box.left,y2=(sameRow?b.top+b.height/2:b.top)-box.top;line.setAttribute('d',sameRow?`M ${x1} ${y1} H ${x2}`:`M ${x1} ${y1} V ${y1+14} H ${x2} V ${y2}`);svg.append(line);}}; connectorObserver=new ResizeObserver(connect);connectorObserver.observe(tree);requestAnimationFrame(connect); } - load();const dispose=()=>{active=false;dossier.dispose();connectorObserver?.disconnect();controller.abort();};dispose.selectBranch=id=>{if(active&&data?.quests?.some(q=>q.branch===id)){branch=id;selected=null;render();}};return dispose; + load();const poll=journalMode?setInterval(()=>{if(active&&!busy&&!document.hidden)load();},30000):null;const dispose=()=>{active=false;if(poll)clearInterval(poll);dossier.dispose();connectorObserver?.disconnect();controller.abort();};dispose.selectBranch=id=>{if(!active||typeof id!=='string')return;requestedArc=id;if(data?.quests){selected=null;render();}};return dispose; } diff --git a/website/control-panel/public/cp-v2/cp-v2-progression-sidebar.mjs b/website/control-panel/public/cp-v2/cp-v2-progression-sidebar.mjs index 2724afa8..382564ed 100644 --- a/website/control-panel/public/cp-v2/cp-v2-progression-sidebar.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-progression-sidebar.mjs @@ -1,7 +1,8 @@ import {MISSION_BRANCHES} from './cp-v2-progression-catalogue.mjs'; +import {groupBranches,bannerUrl,iconUrl,ensureStyles} from './cp-v2-quest-categories.mjs'; import {element as el} from './cp-v2-page-template.mjs'; import {mentatFromDeeds,mentatFromCharacterChoice,systemPortrait,MENTAT_NAMES} from './cp-v2-mentat-portraits.mjs'; -export function xpReport(data){ +export function xpReport(data,{tracked=null}={}){ if(data?.state!=='active'||!data.profile||!data.season)return null; const p=data.profile,s=data.season,level=p.level,xp=p.effectiveXP,base=s.curveBase; if(!Number.isSafeInteger(level)||level<1||!Number.isSafeInteger(xp)||xp<0)return null; @@ -10,7 +11,7 @@ export function xpReport(data){ const next=capped?null:start===null?null:base*level*(level+1)/2; const percent=capped?100:Number.isSafeInteger(start)&&Number.isSafeInteger(next)&&next>start?Math.max(0,Math.min(100,(xp-start)/(next-start)*100)):null; const quests=(data.quests||[]).filter(q=>q.keyId&&['active','completed'].includes(q.state)); - return {level,cap:s.levelCap,xp,totalXP:p.totalXP,reserveXP:p.reserveXP,nextXP:Number.isSafeInteger(next)?next:null,percent,capped,quest:quests[0]||null,activeCount:quests.length,season:s.id}; + return {level,cap:s.levelCap,xp,totalXP:p.totalXP,reserveXP:p.reserveXP,nextXP:Number.isSafeInteger(next)?next:null,percent,capped,quest:quests.find(q=>q.id===tracked)||quests[0]||null,activeCount:quests.length,season:s.id}; } export function createProgressionSidebar(host,{fetcher=fetch,onBranch=()=>{},onNavigate=()=>{}}={}){ const right=host.closest('#content')?.parentElement?.querySelector('#sidebar-right'); @@ -25,7 +26,7 @@ export function createProgressionSidebar(host,{fetcher=fetch,onBranch=()=>{},onN const adviser=el('div',undefined,'mentat-adviser'),name=mentat?MENTAT_NAMES[mentat.username]:'House adviser';adviser.append(portrait(mentat?.portrait||systemPortrait(''),'Portrait of '+name)); const caption=el('div');if(mentat){const link=el('a',name);link.href='https://www.dunerealms.com/people/'+mentat.username;link.target='_top';caption.append(link,el('small',mentat.house));}else caption.append(el('strong',name),el('small',houseState==='loading'?'Opening House deed…':'House deed pending'));adviser.append(caption);summary.append(adviser); const citizen=el('div',undefined,'mentat-citizen');if(player?.username){const avatar=el('img');avatar.src='https://cp.dunerealms.com/api/avatars/face/member/'+encodeURIComponent(player.username);avatar.alt=player.username+' avatar';avatar.width=avatar.height=36;avatar.loading='lazy';avatar.onerror=()=>{avatar.replaceWith(portrait(systemPortrait(''),'Player portrait placeholder'));};citizen.append(avatar,el('span',player.name||player.username));}else citizen.append(portrait(systemPortrait(''),'Player portrait placeholder'),el('span','Your account'));summary.append(citizen); - for(const [kind,label]of [['personal','Personal level'],['pol','Reputation level']]){const block=el('section',undefined,'mentat-xp mentat-xp-'+kind),data=journals.get(kind),report=xpReport(data);const title=el('h4'),link=el('a',label);link.href=href(kind,'missions');link.setAttribute('aria-current',currentKind===kind?'page':'false');link.onclick=event=>open(event,kind,'missions');title.append(link);block.append(title); + for(const [kind,label]of [['personal','Personal level'],['pol','Reputation level']]){const block=el('section',undefined,'mentat-xp mentat-xp-'+kind),data=journals.get(kind),report=xpReport(data,{tracked:(()=>{try{return localStorage.getItem('dunerealms.tracked-mission:'+kind);}catch{return null;}})()});const title=el('h4'),link=el('a',label);link.href=href(kind,'missions');link.setAttribute('aria-current',currentKind===kind?'page':'false');link.onclick=event=>open(event,kind,'missions');title.append(link);block.append(title); const level=el('strong',report?String(report.level)+(report.cap===null?' · uncapped':' / '+report.cap):'—','mentat-level');block.append(level); const progress=el('progress');progress.max=100;progress.value=report?.percent??0;progress.setAttribute('aria-label',label+' progress towards next level');if(report?.percent===null||!report)progress.className='mentat-placeholder';block.append(progress); block.append(el('p',report?format(report.xp)+(report.nextXP!==null?' / '+format(report.nextXP):'')+(kind==='pol'?' reputation':' XP')+(report.capped?' · season cap reached':''):(kind==='pol'?'Reputation —':'XP —'),'mentat-xp-value')); @@ -39,7 +40,8 @@ export function createProgressionSidebar(host,{fetcher=fetch,onBranch=()=>{},onN function menuIcon(key){const img=el('img');img.src=typeof globalThis.uniqueMenuIcon==='function'?globalThis.uniqueMenuIcon('quests/'+key):'https://www.dunerealms.com/assets/nav-account-v2.webp';img.alt='';img.width=img.height=24;return img;} function menuHeading(label,count){const title=el('div',undefined,'category-heading');title.setAttribute('role','heading');title.setAttribute('aria-level','2');title.append(menuIcon('category/'+label),el('span',label,'category-name'),el('span',String(count),'category-count'));return title;} function renderViews(){journalMenu.replaceChildren(menuHeading('Journal views',3));const links=el('div',undefined,'category-links');for(const [view,label]of [['missions','Missions'],['decisions','Decisions'],['history','History']]){const link=el('a',undefined,'navitem');link.append(menuIcon('view/'+view),el('span',label));link.href=href(currentKind,view);link.setAttribute('aria-current',view===currentView?'page':'false');link.onclick=event=>open(event,currentKind,view);links.append(link);}journalMenu.append(links);} - function renderBranches(){directory.replaceChildren(menuHeading('Mission branches',branchRows.length));const links=el('div',undefined,'category-links');for(const row of branchRows){const button=el('button',undefined,'navitem');button.type='button';button.setAttribute('aria-current',row.id===branchId?'page':'false');button.append(menuIcon('branch/'+row.id),el('span',row.title));button.onclick=()=>{onBranch(row.id);closeMenus();};links.append(button);}directory.append(links);directory.hidden=!branchRows.length;} + function renderBranches(){const groups=groupBranches(branchRows);directory.replaceChildren(menuHeading('Story arcs',groups.length));ensureStyles();const links=el('div',undefined,'category-links');for(const group of groups){const button=el('button',undefined,'navitem quest-arc-link');button.type='button';button.setAttribute('aria-current',group.rows.some(row=>row.id===branchId)?'page':'false');button.style.backgroundImage='linear-gradient(90deg,rgba(24,34,25,.75),rgba(24,34,25,.2)),url("'+bannerUrl(group.category)+'")';const icon=el('img');icon.src=iconUrl(group.category);icon.alt='';icon.width=icon.height=28;button.append(icon,el('span',group.category.title));button.onclick=()=>{onBranch('category:'+group.category.id);closeMenus();};links.append(button);}directory.append(links);directory.hidden=!groups.length;} + async function read(path){const r=await fetcher(path,{credentials:'same-origin',cache:'no-store',signal:controller.signal});if(!r.ok)throw Error('Report unavailable');return r.json();} function updateBranches(){const data=journals.get(currentKind);const rows=data?.branches||[...MISSION_BRANCHES.filter(b=>b.id!=='discoveries'),{id:'acquisitions',title:'Acquisitions'}];branchRows=data?.quests?rows.filter(b=>data.quests.some(q=>q.branch===b.id)):[];if(!branchRows.some(b=>b.id===branchId))branchId=branchRows[0]?.id;renderBranches();} function ensureJournal(kind){if(journals.has(kind)||pending.has(kind))return;pending.add(kind);void read(kind==='pol'?'/api/progression/pol':'/api/progression').then(data=>setJournal(kind,data)).catch(()=>{if(alive){failures.add(kind);render();}}).finally(()=>pending.delete(kind));} @@ -47,5 +49,6 @@ export function createProgressionSidebar(host,{fetcher=fetch,onBranch=()=>{},onN render();renderViews();directory.hidden=true; ensureJournal('pol'); void (async()=>{try{let choice=null;try{choice=await read('/api/account/character');}catch{}if(!alive)return;mentat=mentatFromCharacterChoice(choice);if(!mentat){const deeds=await read('/api/politics/workspace');if(!alive)return;mentat=mentatFromDeeds(deeds.organisations);}houseState='loaded';render();}catch{if(alive){houseState='unavailable';render();}}})(); - return {available:true,setJournal,setBranches(rows,id){branchRows=rows;branchId=id;renderBranches();},showBranches(show){directory.hidden=!show||!branchRows.length;if(directoryBanner)directoryBanner.hidden=!show;},setNavigation(kind,view){currentKind=kind;currentView=view;updateBranches();if(view!=='missions')ensureJournal(kind);render();renderViews();},dispose(){alive=false;controller.abort();summary.remove();journalMenu.remove();directory.remove();if(directoryBanner&&left&&right.isConnected){directoryBanner.hidden=false;right.insertBefore(directoryBanner,bannerNext?.parentNode===right?bannerNext:null);}}}; + const onTracked=()=>render();if(typeof window!=='undefined')window.addEventListener('dunerealms:tracked-mission',onTracked); + return {available:true,setJournal,setBranches(rows,id){branchRows=rows;branchId=id;renderBranches();},showBranches(show){directory.hidden=!show||!branchRows.length;if(directoryBanner)directoryBanner.hidden=!show;},setNavigation(kind,view){currentKind=kind;currentView=view;updateBranches();if(view!=='missions')ensureJournal(kind);render();renderViews();},dispose(){alive=false;if(typeof window!=='undefined')window.removeEventListener('dunerealms:tracked-mission',onTracked);controller.abort();summary.remove();journalMenu.remove();directory.remove();if(directoryBanner&&left&&right.isConnected){directoryBanner.hidden=false;right.insertBefore(directoryBanner,bannerNext?.parentNode===right?bannerNext:null);}}}; } diff --git a/website/control-panel/public/cp-v2/cp-v2-quest-categories.css b/website/control-panel/public/cp-v2/cp-v2-quest-categories.css new file mode 100644 index 00000000..50df102b --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-quest-categories.css @@ -0,0 +1,17 @@ +.quest-category-hero{position:relative;min-height:88px;margin:0 0 .8rem;border:1px solid #46322a;border-radius:6px;background-size:cover;background-position:center;display:flex;align-items:center;padding:.6rem 9rem .6rem 1rem;overflow:hidden} +.quest-category-hero h3{margin:0;font-size:1.15rem;color:#fff7e6;text-shadow:0 1px 3px rgba(40,26,18,.85)} +.quest-category-hero p{margin:.15rem 0 0;color:#f6e7c6;text-shadow:0 1px 3px rgba(40,26,18,.85);font-size:.9rem} +.quest-category-heading{display:flex;align-items:center;gap:.5rem;margin:.6rem 0 .25rem;padding:.35rem .5rem;border-radius:4px;background-size:cover;background-position:right center;color:#fff7e6;font-weight:600;text-shadow:0 1px 2px rgba(40,26,18,.9)} +.quest-category-heading img{width:20px;height:20px;image-rendering:pixelated} + +.mj .mj-arcs{max-height:calc(100vh - 16rem);min-height:15rem;overflow-y:auto;overscroll-behavior:contain;padding-right:.35rem} +@media(max-width:46rem){.mj .mj-arcs{max-height:42vh;min-height:10rem}.quest-category-hero{padding-right:5rem}} + +.mj .mj-arc>summary.quest-category-heading{display:grid;grid-template-columns:24px minmax(0,1fr) auto;gap:.6rem;min-height:44px;padding:.55rem .65rem;margin:0;border-radius:.35rem} +.mj .mj-arc[open]>summary{box-shadow:inset 0 0 0 1px #b6995c} +.mj .mj-arc>progress{width:calc(100% - 1rem);height:.45rem;margin:.25rem .5rem} +.mj-arc-tagline{font-size:.82rem;line-height:1.4;margin:.45rem .5rem;color:#c9b991} +.mj-arc-ready{display:block;margin:.2rem .5rem;color:#e5c27b} +.quest-arc-link{display:flex;align-items:center;gap:.65rem;min-height:52px;background-size:cover;background-position:right center;text-shadow:0 1px 3px #10231e;color:#fff4d8} +.quest-arc-link img{width:28px;height:28px;image-rendering:pixelated} +.quest-arc-link[aria-current=page]{outline:1px solid #d5b36c;outline-offset:-1px} diff --git a/website/control-panel/public/cp-v2/cp-v2-quest-categories.mjs b/website/control-panel/public/cp-v2/cp-v2-quest-categories.mjs new file mode 100644 index 00000000..b33a1759 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-quest-categories.mjs @@ -0,0 +1,192 @@ +// Themed story-arc categories over the quest branches. Presentation only: quest ids, rewards, +// prerequisites and progress are never changed. Mirrors DuneRealmsGUI/src/main/resources/quest-categories.json. +export const QUEST_CATEGORIES=Object.freeze([ + { + "id": "arrival", + "title": "Arrival", + "tagline": "First steps beneath a foreign sun.", + "accent": "#d9b66a", + "icon": "quests/arrival", + "branches": [ + "a" + ] + }, + { + "id": "coin", + "title": "Coin of the Realm", + "tagline": "Solari, ledgers and honest weights.", + "accent": "#cfa24a", + "icon": "quests/coin", + "branches": [ + "b" + ] + }, + { + "id": "melange", + "title": "The Melange Path", + "tagline": "From raw sand to refined spice.", + "accent": "#e29a3f", + "icon": "quests/melange", + "branches": [ + "c", + "spice-harvesting", + "spice-upgrading" + ] + }, + { + "id": "deep-desert", + "title": "Deep Desert", + "tagline": "Walk where the worms walk.", + "accent": "#c98b54", + "icon": "quests/deep-desert", + "branches": [ + "d", + "discoveries" + ] + }, + { + "id": "place", + "title": "A Place in the Realm", + "tagline": "Earn a name, a trade and a seat at the table.", + "accent": "#bfa77a", + "icon": "quests/place", + "branches": [ + "e", + "f", + "g" + ] + }, + { + "id": "armoury", + "title": "The Armoury", + "tagline": "Stillsuits, steel and good design.", + "accent": "#a89572", + "icon": "quests/armoury", + "branches": [ + "h", + "i", + "acquisitions" + ] + }, + { + "id": "landsraad", + "title": "The Landsraad Game", + "tagline": "Four Houses. One game. No mercy.", + "accent": "#b9863f", + "icon": "quests/landsraad", + "branches": [ + "atreides", + "harkonnen", + "corrino", + "ordos" + ] + }, + { + "id": "sons", + "title": "Sons of the Sand", + "tagline": "Water discipline, worm-sign and tribe.", + "accent": "#d28b3c", + "icon": "quests/sons", + "branches": [ + "fremen", + "fremen-husbandry" + ] + }, + { + "id": "prophecy", + "title": "The Prophecy", + "tagline": "Faith, fear and the long game.", + "accent": "#d8c79a", + "icon": "quests/prophecy", + "branches": [ + "faith-sisterhood", + "faith-church", + "bene" + ] + }, + { + "id": "lanes", + "title": "Lanes and Shadows", + "tagline": "Guild lanes, smugglers' routes and hunted bounties.", + "accent": "#b07a4a", + "icon": "quests/lanes", + "branches": [ + "guild", + "smugglers", + "bounty-jobs" + ] + }, + { + "id": "contracts", + "title": "Contracts of the Realm", + "tagline": "Work for clan and company.", + "accent": "#c3a060", + "icon": "quests/contracts", + "branches": [ + "clan", + "company" + ] + }, + { + "id": "wings", + "title": "Wings across the Realms", + "tagline": "Five worlds. One elytra.", + "accent": "#e0c27c", + "icon": "quests/wings", + "branches": [ + "elytra" + ] + }, + { + "id": "campaign", + "title": "Campaign Banners", + "tagline": "Banners raised, ground held.", + "accent": "#b5653f", + "icon": "quests/campaign", + "branches": [ + "war-service" + ] + } +].map(c=>Object.freeze({...c,branches:Object.freeze([...c.branches])}))); +export const OTHER_CATEGORY=Object.freeze({id:'other',title:'Other Work',tagline:'Quests outside the main story arcs.',accent:'#8f7a5a',icon:'quests/other',branches:Object.freeze([])}); +const byBranch=new Map(QUEST_CATEGORIES.flatMap(c=>c.branches.map(b=>[b,c]))); +export const categoryFor=branchId=>byBranch.get(branchId)||OTHER_CATEGORY; +export const bannerUrl=category=>new URL('./art/quests/'+category.id+'-banner.png',import.meta.url).href; +export const iconUrl=category=>new URL('./art/quests/'+category.id+'-icon.png',import.meta.url).href; +/** Branch rows [{id,title}] regrouped by category in catalogue order; unmapped branches land in "Other Work" last. */ +export function groupBranches(rows){ + const groups=[]; + for(const category of [...QUEST_CATEGORIES,OTHER_CATEGORY]){ + const members=category===OTHER_CATEGORY?rows.filter(r=>categoryFor(r.id)===OTHER_CATEGORY):category.branches.map(id=>rows.find(r=>r.id===id)).filter(Boolean); + if(members.length)groups.push({category,rows:members}); + } + return groups; +} +/** A themed arc can contain several legacy branches. Keep their IDs internal. */ +export function groupJournalArcs(arcs){ + return groupBranches(arcs).map(({category,rows})=>{ + const quests=orderChapters(rows.flatMap(row=>row.quests)); + const done=quests.filter(quest=>quest.status==='done').length; + return {category,quests,done,total:quests.length,ready:quests.filter(quest=>quest.status==='ready'&&quest.canClaim).length,complete:done===quests.length}; + }); +} +/** Chapter order: prerequisites first, otherwise the server's own order. Stable and cycle-safe. */ +export function orderChapters(rows){ + const byId=new Map(rows.map(r=>[r.id,r])),placed=new Set(),out=[]; + const place=(row,trail=new Set())=>{ + if(placed.has(row.id)||trail.has(row.id))return;trail.add(row.id); + for(const parent of [...(row.requires||[]),...(row.requiresAny||[])]){const p=byId.get(parent);if(p)place(p,trail);} + trail.delete(row.id);if(!placed.has(row.id)){placed.add(row.id);out.push(row);} + }; + for(const row of rows)place(row);return out; +} +export function ensureStyles(){ + if(typeof document==='undefined'||document.querySelector('link[data-quest-categories]'))return; + const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('./cp-v2-quest-categories.css',import.meta.url).href;css.setAttribute?.('data-quest-categories','');document.head?.append(css); +} +/** Banner header for a category: sandy gradient art, title and tagline. */ +export function categoryHero(category,el){ + ensureStyles(); + const hero=el('header',undefined,'quest-category-hero');hero.style.backgroundImage='url("'+bannerUrl(category)+'")'; + const text=el('div');text.append(el('h3',category.title),el('p',category.tagline));hero.append(text);return hero; +} diff --git a/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs b/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs index 1cc03227..c157e442 100644 --- a/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs @@ -15,7 +15,7 @@ export const QUEST_GUIDANCE=Object.freeze({ 'guild-travel':live('Book Spacing Guild passage in the lobby, remain online and arrive on your House world. The 100 DM fare is taken from your central personal bank account on arrival.','Lobby → Spacing Guild NPC / Imperial Codex → Spacing Guild','Confirmed destination arrival and settled passage payment'), 'citizen-introduction':live('Start this quest, then read the Imperial Citizen briefing and press I understand in your ingame mission journal. Refresh this quest after confirmation, then claim the reward. This is separate from choosing a House or completing your profile.','Imperial Codex → Mission journal → Personal Experience → Onboarding → Complete Imperial Citizen introduction → Read citizen briefing','Confirmed ingame Citizen briefing acknowledgement'), 'earned-minor':live('Receive the stated cumulative amount in DM from posted incoming bank transfers, quest rewards, wages, P&O spice payouts and Exchange sales during this season. Spending it later does not reduce your earned total. Transfers between your own accounts, refunds and pending payments do not count.','Central bank → Transactions; receive transfers, complete reward quests, earn wages or sell goods on the Exchange','Settled central-bank income, not your current balance'), - 'bank-deposit':pending('Deposit physical cash into your personal central-bank account through the ingame ATM. A transfer between your own accounts is not a cash deposit.','Rihla / ATM ingame menu'), + 'bank-deposit':live('Deposit physical cash at an ATM to get a RIA ID, then redeem that ID to your personal bank account. Cash pickup and bank transfers do not count.','Ingame Rihla / ATM → redeem to bank','Settled ATM voucher redemption to your bank account'), 'bank-transfer':live('Send a payment from an authorised personal bank account to another customer. Wait until it is posted; a queued payment or transfer between your own accounts does not count.','Website bank → Transfers','Posted standard or instant payment to another customer'), 'shop-purchase':live('Buy and pay for goods listed by another player on the Exchange. Browsing, publishing your own listing or withdrawing an unsold item does not count.','Ingame /exchange → Buy','Settled central-bank Exchange purchase'), 'spice-harvest':live('Personally harvest genuine raw spice from deposits on Arrakis. Buying, trading or selling spice does not count; selling your own harvest does not count it a second time.','Arrakis → Natural spice deposits','Verified native harvest receipt'), diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index 493984ed..d9295792 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -62,7 +62,8 @@ export const MASTER_KEY_TEMPLATES=[ action('progression.mentor-policy','Scoped Mentat reward bonus','progression-policy',[field('season','Season'),field('policyVersion','Policy version','number',{min:3})],{webIssue:false,recordOnly:true,domainAdapter:'ensurePOLMentorPolicy',executionStatus:'recorded-system-policy',effect:'Record the bounded 10% eligible Mentat bonus through the existing POL award engine. Preserve Personal XP and earlier claims; no default DM reward.'}), action('progression.pol-funded-rewards','Funded Reputation reward delivery','quest',[],{webIssue:false,recordOnly:true,domainAdapter:'createPOLFundedRewards',executionStatus:'consumed-quest-outbox-only',effect:'Pay only explicitly configured and verified claim rewards from existing website treasury funds to the bound ordinary player bank account. Original QST identity prevents duplicate ledger entries; unfunded or invalid rewards remain queued.'}), action('progression.flight-policy','Elytra Reputation quest policy','progression-policy',[],{version:4,webIssue:false,recordOnly:true,domainAdapter:'ensureElytraQuestPolicy',executionStatus:'recorded-system-policy',effect:'Install the twelve Elytra quest reward configurations through their own policy:POL:S01:v4 instrument. Preserve existing quest settings, season dates and the separate v3 Mentat bonus instrument.'}), - action('progression.game-observation','Native quest observation','quest-milestone',[field('eventId','Original native event UUID'),field('uuid','Linked Minecraft UUID'),field('kind','Fixed observation kind'),field('server','Native server'),field('occurredAt','Original event time','number',{min:1}),field('quantity','Native produced quantity','number',{min:1,max:64,required:false}),field('dimension','Native dimension','text',{required:false}),field('source','Fixed Elytra acquisition source','text',{required:false})],{version:4,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestEventsAPI',executionStatus:'authenticated-game-service',effect:'Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Fixed world/dimension flight observations feed the Reputation Elytra branch. A committed paid delivery or natural End-ship acquisition completes only this branch, awarding its remaining rewards once. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.'}), + action('progression.flight-merge-policy','Armoured flight quest policy','progression-policy',[],{version:10,webIssue:false,recordOnly:true,domainAdapter:'ensureElytraMergePolicy/createGameQuestEventsAPI',executionStatus:'authenticated-native-physical-merge-consumer',effect:'Add POL-ELYTRA-MERGE through policy:POL:S01:v10 without changing existing rewards or season dates. A physical native chestplate-and-elytra merge consumes one elytra, preserves armour properties and records one receipt-bound flight_merged observation on a shared-profile planet. No currency charge or XP award. Acquiring an ordinary elytra cannot complete this separate step; web/menu clicks never assert physical completion.'}), + action('progression.game-observation','Native quest observation','quest-milestone',[field('eventId','Original native event UUID'),field('uuid','Linked Minecraft UUID'),field('kind','Fixed observation kind'),field('server','Native server'),field('occurredAt','Original event time','number',{min:1}),field('quantity','Native produced quantity','number',{min:1,max:64,required:false}),field('dimension','Native dimension','text',{required:false}),field('source','Fixed Elytra acquisition source','text',{required:false})],{version:4,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestEventsAPI',executionStatus:'authenticated-game-service',effect:'Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Fixed world/dimension flight observations feed the Reputation Elytra branch. A committed paid delivery or natural End-ship acquisition completes only the flight preparation/acquisition quests, awarding their remaining rewards once. Armour merging needs its separate physical receipt. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.'}), action('commerce.spice-sale','Arrakis spice sale','entity-state',[field('uuid','Linked Minecraft UUID'),field('requestId','Original sale UUID'),field('channel','Buyer','select',{options:['guild','smuggler']}),field('amount','Surrendered spice','number',{min:1,max:21312})],{version:3,webIssue:false,recordOnly:true,domainAdapter:'createGameSpiceAPI + ExchangeInventory.sellSpice + createSpiceQuestReceipts',executionStatus:'authenticated-arrakis-inventory-receipt',effect:'Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice and compressed blocks (nine raw units each), retaining Guild versus contraband identity before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. Paid Guild sales supply Personal harvest and Reputation spice evidence; paid contraband sales supply separate Reputation smuggling evidence through existing ordinary quest-milestone keys. Pending quest reporting retries from the same stored sale without taking items or paying again. No Vault wallet or Exchange listing.'}), action('progression.spice-refining','NPC spice refinement','quest-milestone',[field('uuid','Linked player UUID'),field('requestId','Original turn-in UUID'),field('definitionId','Fixed refining quest'),field('npcUuid','Nearby Arrakis Smuggler UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestsAPI.prepare_refine + SpiceRefiner + ExchangeInventory.refine',executionStatus:'authenticated-native-npc-turn-in',effect:'Revalidate the current player and quest prerequisites, then require the physical Arrakis NPC again before consuming two real raw spice, or two refined spice and two scraps. Core checkpoints inputs, two EI outputs and a recoverable receipt atomically. Existing QSM observations award no reward until verified by the Reputation quest engine.'}), action('progression.earned-dm','Verified earned DM','quest-milestone',[],{version:2,webIssue:false,recordOnly:true,domainAdapter:'bankQuestIncome + progressionRuntime.collect',executionStatus:'committed-central-bank-source',effect:'Count posted wages, fixed-P&O spice-sale payouts, Exchange sale income, incoming bank transfers and verified quest treasury credits across the player’s personal central-bank accounts during the active season. Count each bank order once and preserve cumulative earnings after spending. Exclude own-account transfers, refunds, pending payments, unrelated system grants and organisation income; never use a legacy game wallet or current balance as an earnings counter.'}), diff --git a/website/control-panel/quest-category-art.mjs b/website/control-panel/quest-category-art.mjs new file mode 100644 index 00000000..b60eeb32 --- /dev/null +++ b/website/control-panel/quest-category-art.mjs @@ -0,0 +1,15 @@ +import {readFile} from 'node:fs/promises'; +import {QUEST_CATEGORIES,OTHER_CATEGORY} from './public/cp-v2/cp-v2-quest-categories.mjs'; + +const categories=new Set([...QUEST_CATEGORIES,OTHER_CATEGORY].map(category=>category.id)); + +// Only the authored category PNGs are public; this is not a directory server. +export async function questCategoryArt(request){ + const match=/^\/(?:v2|cp-v2)\/art\/quests\/([a-z0-9-]+)-(icon|banner)\.png$/.exec(new URL(request.url).pathname); + if(!match||!categories.has(match[1]))return null; + if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405,headers:{Allow:'GET, HEAD'}}); + try{ + const bytes=await readFile(new URL('./public/cp-v2/art/quests/'+match[1]+'-'+match[2]+'.png',import.meta.url)); + return new Response(request.method==='HEAD'?null:bytes,{headers:{'Content-Type':'image/png','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); + }catch(error){if(error.code==='ENOENT')return new Response('Not found',{status:404});throw error;} +} diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 090acb86..6700cae4 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,5 @@ +import {provisionLobbyStartingBank} from '../node/lobby-starting-budget.mjs'; +import {LOBBY_ACCOUNT_SCHEMA,createLobbyAccountAPI} from '../node/lobby-account.mjs'; import {initializeImperialRaids} from '../node/imperial-raid-orders.mjs'; import {createImperialRaidRuntime} from '../node/imperial-raid-runtime.mjs'; import {createGameImperialRaidsAPI} from '../node/game-imperial-raids.mjs'; @@ -5,7 +7,7 @@ import {imperialRaidHomeReservations,imperialRaidCalendarAvailable} from '../nod import {initializeHousePrologue,HOUSE_PROLOGUE_IDS} from '../node/house-prologue.mjs'; import {QUEST_DEFINITIONS,XP_POLICY} from '../node/progression-definitions.mjs'; import {createOrganisationFundedRewards} from '../node/organisation-quest-rewards.mjs'; -import {ensureFaithQuestPolicy,ensureFaunaQuestPolicy,ensureBountyQuestPolicy,ensureSpiceUpgradeQuestPolicy} from '../node/progression-pol.mjs'; +import {ensureFaithQuestPolicy,ensureFaunaQuestPolicy,ensureBountyQuestPolicy,ensureSpiceUpgradeQuestPolicy,ensureElytraMergePolicy} from '../node/progression-pol.mjs'; import {initializeClanFaith,createClanFaithAPI,createClanFaith} from '../node/clan-faith.mjs'; import {initializeHouseFaith,createHouseFaithAPI,createHouseFaithLaws,missionaryFaithOutlawed} from '../node/house-faith-laws.mjs'; import {createPoliticalMarketReports} from '../node/political-market-reports.mjs'; @@ -46,6 +48,7 @@ import {POL_COOP_CARGO_SCHEMA} from '../node/pol-coop-cargo.mjs'; import {createPOLCargoService} from '../node/pol-cargo-service.mjs'; import {createGameRefits} from '../node/organisation-refits.mjs'; import {createGameQuestEventsAPI} from '../node/game-quest-events.mjs'; +import {questCategoryArt} from './quest-category-art.mjs'; import {createGameItemDesignAPI} from '../node/game-item-designs.mjs'; import {createPOLFundedRewards} from '../node/pol-funded-rewards.mjs'; import {ensurePOLMentorPolicy} from '../node/pol-mentor-rewards.mjs'; @@ -304,6 +307,7 @@ export function createPanel(db,settings={},dependencies={}){ const progressionRuntime=dependencies.progressionRuntime||(dependencies.organisationKeys?createProgressionRuntime(db,dependencies.bankDatabase||null,dependencies.organisationKeys):null); const progression=createProgressionAPI(db,{...progressionRuntime,origin}); const polRuntime=dependencies.polProgressionRuntime||(dependencies.organisationKeys?createPOLProgressionRuntime(db,dependencies.organisationKeys,{bank:dependencies.bankDatabase||null}):null); + const lobbyAccount=createLobbyAccountAPI(db,settings,{onProvisioned:async user=>{if(!dependencies.bankDatabase)throw Error('The basic bank account service is unavailable');await provisionLobbyStartingBank(dependencies.bankDatabase,user);await ensureRihlaAccount(dependencies.bankDatabase,user.id);if(dependencies.organisationKeys)await ensureOriginalKeys(dependencies.organisationKeys,user.id);}}); const gameHouseSelection=createHouseSelectionAPI(db,dependencies.organisationKeys,settings,{readBriefing:createGameBriefing({personal:progressionRuntime,pol:polRuntime,bank:dependencies.bankDatabase||null,authority:createPostbankAuthority(db,{bank:dependencies.bankDatabase||null}),organisations:actor=>readGameMemberships(db,actor),identity:actor=>readGamePublicIdentity(db,actor),wars:actor=>readWarStatistics(db,dependencies.bankDatabase||null,actor)})}); const gameStarter=dependencies.organisationKeys?createGameStarterKit(db,dependencies.organisationKeys,settings):null; const gameResearch=dependencies.organisationKeys?createGameResearch(db,dependencies.organisationKeys):null; @@ -418,6 +422,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/politics/directory'){const response=await electionDirectory(request);if(request.method==='GET'&&response.ok&&progressionRuntime){try{const visitor=await identity(request,db);if(visitor)await progressionRuntime.recordPoliticalVisit(visitor);}catch{}}return response;} if(['/api/politics/ballot/house','/api/politics/ballot/imperial','/api/politics/ballot/bene','/api/politics/ballot/church','/api/politics/ballot/guild','/api/politics/ballot/clan_delegate','/api/politics/ballot/naib_chair'].includes(path))return electionVoting(request); if(path==='/api/account/character')return characterChoice(request); + if(path==='/internal/game/lobby-account')return lobbyAccount(request); if(path==='/internal/game/house')return gameHouseSelection(request); if(path==='/internal/game/native-state')return gameNativeState(request); if(path==='/internal/game/imperial-raids')return gameImperialRaids(request); @@ -602,6 +607,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/politics-cp')return new Response(request.method==='HEAD'?null:politicsCPDocument(await readFile(new URL('./public/cp-v2/index.html',import.meta.url),'utf8')),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); const calendarVendorFiles=new Set(['fullcalendar.global.min.js','monarch.global.min.js','skeleton.css','monarch.css','palette.css','LICENSE.md','SOURCE.json']); if(path.startsWith('/v2/vendor/fullcalendar/')&&['GET','HEAD'].includes(request.method)){const file=path.slice('/v2/vendor/fullcalendar/'.length);if(!calendarVendorFiles.has(file))return new Response('Not found',{status:404});const type=file.endsWith('.js')?'text/javascript':file.endsWith('.css')?'text/css':file.endsWith('.json')?'application/json':'text/plain';return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/vendor/fullcalendar/'+file,import.meta.url)),{headers:{'Content-Type':type+'; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});} + const categoryArtwork=await questCategoryArt(request);if(categoryArtwork)return categoryArtwork; // All authored cp-v2 browser modules share this bounded public directory. // New components must not require a second, manually maintained route list. if(path==='/mentat-report')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/cp-v2-mentat-embed.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff','Content-Security-Policy':PANEL_CSP.replace("img-src 'self' data:;","img-src 'self' data: https://www.dunerealms.com;")}}); @@ -629,7 +635,7 @@ export async function startPanel(settings=process.env){ inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); } const bankDatabase=await openPostbankDatabase(settings); - const db=await openDatabase(settings);await db.query(WAR_MEDAL_SCHEMA);await initializeItemDesigns(db);await db.query(ITEM_GIFT_SCHEMA);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await db.query(POLITICAL_REVIEW_PUBLICATION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);await db.query(POLITICAL_COMPANY_REPLY_SCHEMA);await db.query(POLITICAL_PERSON_REPLY_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await db.query(sql);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeElectionRallies(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;db.paxEnabled=true;db.guildSubsidyEnabled=true;db.exchangeIncentiveEnabled=true;await initializeProgression(db);db.questAchievementsEnabled=true;await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureProgressionPolicy(db,organisationKeys,{policy:{...XP_POLICY,version:2},definitions:QUEST_DEFINITIONS.filter(d=>HOUSE_PROLOGUE_IDS.includes(d.id))});await initializeHousePrologue(db);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);await db.query(POL_DOSSIER_SCHEMA);await db.query(POL_CARGO_SCHEMA);await db.query(POL_COOP_CARGO_SCHEMA);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensureFaunaQuestPolicy(db,organisationKeys);db.faunaQuestsEnabled=true;db.smugglerContractsEnabled=true;db.polSupplyEnabled=true;db.polContractMissionsEnabled=true;await ensureBountyQuestPolicy(db,organisationKeys);db.bountyQuestsEnabled=true;await ensureSpiceUpgradeQuestPolicy(db,organisationKeys);db.spiceUpgradeEnabled=true;await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);let rihla; + const db=await openDatabase(settings);await db.query(WAR_MEDAL_SCHEMA);await initializeItemDesigns(db);await db.query(ITEM_GIFT_SCHEMA);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await db.query(POLITICAL_REVIEW_PUBLICATION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);await db.query(POLITICAL_COMPANY_REPLY_SCHEMA);await db.query(POLITICAL_PERSON_REPLY_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await db.query(sql);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);if(settings.LOBBY_ACCOUNT_ENABLED==='true')await db.query(LOBBY_ACCOUNT_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeElectionRallies(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;db.paxEnabled=true;db.guildSubsidyEnabled=true;db.exchangeIncentiveEnabled=true;await initializeProgression(db);db.questAchievementsEnabled=true;await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureProgressionPolicy(db,organisationKeys,{policy:{...XP_POLICY,version:2},definitions:QUEST_DEFINITIONS.filter(d=>HOUSE_PROLOGUE_IDS.includes(d.id))});await initializeHousePrologue(db);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);await db.query(POL_DOSSIER_SCHEMA);await db.query(POL_CARGO_SCHEMA);await db.query(POL_COOP_CARGO_SCHEMA);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensureFaunaQuestPolicy(db,organisationKeys);db.faunaQuestsEnabled=true;db.smugglerContractsEnabled=true;db.polSupplyEnabled=true;db.polContractMissionsEnabled=true;await ensureBountyQuestPolicy(db,organisationKeys);db.bountyQuestsEnabled=true;await ensureSpiceUpgradeQuestPolicy(db,organisationKeys);await ensureElytraMergePolicy(db,organisationKeys);db.spiceUpgradeEnabled=true;await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);let rihla; db.imperialRaidsEnabled=settings.IMPERIAL_RAIDS_ENABLED==='true'&&settings.WAR_BRIDGE_ENABLED==='true'&&settings.POSTBANK_ENABLED==='true'; if(db.imperialRaidsEnabled){if(!bankDatabase)throw Error('Imperial raids require the existing bank and war services');await initializeImperialRaids(db);} const imperialRaidRuntime=db.imperialRaidsEnabled?createImperialRaidRuntime(db,bankDatabase,organisationKeys):null; diff --git a/website/data/cookbook/dunechest-recipes.json b/website/data/cookbook/dunechest-recipes.json new file mode 100644 index 00000000..207470f4 --- /dev/null +++ b/website/data/cookbook/dunechest-recipes.json @@ -0,0 +1,147 @@ +{ + "items": { + "ender_chest": { + "id": "dunechest_ender_chest", + "name": "Ender Chest", + "material": "ender_chest", + "custom": true, + "icon": "/recipe-icons/dunechest_ender_chest.png", + "summary": "A custom chest with three colour pads. Matching frequencies share storage on the same planet; diamond toggles the supplied private mode." + }, + "speed_hopper_1": { + "id": "dunechest_speed_hopper_1", + "name": "Ixian sorting devices MK 1", + "material": "hopper", + "custom": true, + "icon": "/recipe-icons/dunechest_speed_hopper_1.png", + "summary": "A faster hopper with an item filter. Open its settings with a Wrench or sneak-click with an empty hand." + }, + "speed_hopper_2": { + "id": "dunechest_speed_hopper_2", + "name": "Ixian sorting devices MK 2", + "material": "hopper", + "custom": true, + "icon": "/recipe-icons/dunechest_speed_hopper_2.png", + "summary": "The second Ixian sorting device tier. Craft it with a genuine MK 1; an ordinary hopper does not satisfy the upgrade recipe." + }, + "speed_hopper_3": { + "id": "dunechest_speed_hopper_3", + "name": "Ixian sorting devices MK 3", + "material": "hopper", + "custom": true, + "icon": "/recipe-icons/dunechest_speed_hopper_3.png", + "summary": "The third Ixian sorting device tier. Craft it with a genuine MK 2 and netherite ingots." + }, + "auto_crafter": { + "id": "dunechest_auto_crafter", + "name": "Ixian Replicator MK XIV", + "material": "crafting_table", + "custom": true, + "summary": "A custom crafting block that takes ingredients from the container above and sends its result to the container below. Right-click to set its recipe." + }, + "wrench": { + "id": "dunechest_wrench", + "name": "Wrench", + "material": "knowledge_book", + "custom": true, + "icon": "/recipe-icons/dunechest_wrench.png", + "summary": "Left-click a DuneChest, Ixian sorting device or Ixian Replicator to open its settings. Works on Java and Bedrock." + }, + "dune_beacon": { + "id": "dunechest_dune_beacon", + "name": "Ixian Powercore MK XIV", + "material": "sea_lantern", + "custom": true, + "icon": "/recipe-icons/dunechest_dune_beacon.png", + "summary": "A beamless powercore with beacon effects. Build a beacon pyramid beneath it, then choose effects in its settings. It works indoors without open sky." + } + }, + "recipes": [ + { + "id": "ender_chest", + "pattern": [ + "OEO", + "OBO", + "OOO" + ], + "ingredients": { + "O": "minecraft:obsidian", + "E": "minecraft:ender_eye", + "B": "minecraft:barrel" + } + }, + { + "id": "speed_hopper_1", + "pattern": [ + "GRG", + "RHR", + "GRG" + ], + "ingredients": { + "G": "minecraft:gold_ingot", + "R": "minecraft:redstone", + "H": "minecraft:hopper" + } + }, + { + "id": "speed_hopper_2", + "pattern": [ + "DRD", + "RIR", + "DRD" + ], + "ingredients": { + "D": "minecraft:diamond", + "R": "minecraft:redstone_block", + "I": "speed_hopper_1" + } + }, + { + "id": "speed_hopper_3", + "pattern": [ + "NRN", + "RIR", + "NRN" + ], + "ingredients": { + "N": "minecraft:netherite_ingot", + "R": "minecraft:redstone_block", + "I": "speed_hopper_2" + } + }, + { + "id": "auto_crafter", + "pattern": [ + "IRI", + "RTR", + "IDI" + ], + "ingredients": { + "I": "minecraft:iron_ingot", + "R": "minecraft:redstone", + "T": "minecraft:crafting_table", + "D": "minecraft:dropper" + } + }, + { + "id": "wrench", + "pattern": [ + "I I", + " I ", + " S " + ], + "ingredients": { + "I": "minecraft:iron_ingot", + "S": "minecraft:stick" + } + }, + { + "id": "dune_beacon", + "shapeless": [ + "minecraft:beacon", + "minecraft:ender_eye" + ], + "notes": "Available on all six servers, including Lobby. This recipe uses a vanilla beacon; it does not replace the vanilla beacon recipe." + } + ] +} diff --git a/website/data/cookbook/dunechest-source.json b/website/data/cookbook/dunechest-source.json new file mode 100644 index 00000000..fc21a269 --- /dev/null +++ b/website/data/cookbook/dunechest-source.json @@ -0,0 +1,65 @@ +{ + "sourceRepository": "unimatrix/plugins", + "sourceCommit": "56346a273d1b014fa256d26d34b4a4e33cc1d6b5", + "purpose": "Original six recipe registrations and their supplied artwork remain pinned here. Beacon additions and Owner-requested display names have separate source pins below.", + "files": { + "DuneChest/src/main/java/com/example/dunechest/StorageItems.java": "41c4a853c08877ce369cb4e203332a213ccf377f982181b832c87e1993a69c79", + "DuneChest/src/main/java/com/example/dunechest/StorageRules.java": "d7e273e01e59f297d0670e8ab7410a600e63bd4753be3dadec99f0e965666fd5" + }, + "icons": { + "icons/dunechest_ender_chest.png": { + "source": "network/resource-pack/central/overlay/assets/dunerealms/textures/block/ender_chest_front.png", + "sha256": "bb70bff5e49f84aec457110069dbc4279c159eeb264703f70b15c6ebcf1a7e6c", + "sourceCommit": "2faba139906da15741db2702b3bed3e92ad7ee26" + }, + "icons/dunechest_speed_hopper_1.png": { + "source": "network/resource-pack/central/overlay/assets/dunerealms/textures/block/speed_hopper_1.png", + "sha256": "f41ca0dfe2fe591df724c7a25b67338405e1dab6fbf1e978cf7f14b76cd73378", + "sourceCommit": "2faba139906da15741db2702b3bed3e92ad7ee26" + }, + "icons/dunechest_speed_hopper_2.png": { + "source": "network/resource-pack/central/overlay/assets/dunerealms/textures/block/speed_hopper_2.png", + "sha256": "c6b25e755fb66984cd6d1de254c9b299a9e0279e4637bbae5491bb69be150185", + "sourceCommit": "2faba139906da15741db2702b3bed3e92ad7ee26" + }, + "icons/dunechest_speed_hopper_3.png": { + "source": "network/resource-pack/central/overlay/assets/dunerealms/textures/block/speed_hopper_3.png", + "sha256": "fae56fa0f0f2724c0184b703b24b2787b17c63837d8d978815beb7f9f265144b", + "sourceCommit": "2faba139906da15741db2702b3bed3e92ad7ee26" + }, + "icons/dunechest_wrench.png": { + "source": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/wrench.png", + "sha256": "e9d730f7d79114a0dd4699a3b2048ba234ae2589f5eda3f217dad8a02606be7a", + "sourceCommit": "2faba139906da15741db2702b3bed3e92ad7ee26" + } + }, + "recipeCount": 7, + "iconSource": "Exact supplied wrench sprite and custom block face textures; no rarity or equipment metadata inferred.", + "beacon": { + "sourceCommit": "7d53eaf8f51b9100ecc10ea47cc21a3207f260d2", + "recipe": "One vanilla beacon and one eye of ender; shapeless.", + "files": { + "DuneChest/src/main/java/com/example/dunechest/StorageItems.java": "ea42754c0d50520a7fea158e5802d763f5d13cedf8b46779bd2e4f0875f009c0" + }, + "icon": { + "path": "icons/dunechest_dune_beacon.png", + "source": "network/resource-pack/central/overlay/assets/dunerealms/textures/block/dune_beacon_crystal.png", + "sha256": "8365dcadc2f5c1c1f86c99f06fb2c9a60ff91882401c65693dac71d6cd829a2b", + "presentation": "Exact crystal texture as a flat preview, not a rendered 3D item." + } + }, + "displayNames": { + "authority": "Owner request, 30 November 2026", + "items": { + "speed_hopper_1": "Ixian sorting devices MK 1", + "speed_hopper_2": "Ixian sorting devices MK 2", + "speed_hopper_3": "Ixian sorting devices MK 3", + "auto_crafter": "Ixian Replicator MK XIV", + "dune_beacon": "Ixian Powercore MK XIV" + }, + "sourceCommit": "2faba139906da15741db2702b3bed3e92ad7ee26", + "files": { + "DuneChest/src/main/java/com/example/dunechest/StorageItems.java": "1fe4be5e924ab2b2281839f567182c0baed43c83fccfb87baeb72cf78569cde7" + } + } +} diff --git a/website/data/cookbook/icons/dunechest_dune_beacon.png b/website/data/cookbook/icons/dunechest_dune_beacon.png new file mode 100644 index 00000000..328f3f32 Binary files /dev/null and b/website/data/cookbook/icons/dunechest_dune_beacon.png differ diff --git a/website/data/cookbook/icons/dunechest_ender_chest.png b/website/data/cookbook/icons/dunechest_ender_chest.png new file mode 100644 index 00000000..62bfb5bc Binary files /dev/null and b/website/data/cookbook/icons/dunechest_ender_chest.png differ diff --git a/website/data/cookbook/icons/dunechest_speed_hopper_1.png b/website/data/cookbook/icons/dunechest_speed_hopper_1.png new file mode 100644 index 00000000..0fe23dbc Binary files /dev/null and b/website/data/cookbook/icons/dunechest_speed_hopper_1.png differ diff --git a/website/data/cookbook/icons/dunechest_speed_hopper_2.png b/website/data/cookbook/icons/dunechest_speed_hopper_2.png new file mode 100644 index 00000000..0228fe43 Binary files /dev/null and b/website/data/cookbook/icons/dunechest_speed_hopper_2.png differ diff --git a/website/data/cookbook/icons/dunechest_speed_hopper_3.png b/website/data/cookbook/icons/dunechest_speed_hopper_3.png new file mode 100644 index 00000000..366bcd7c Binary files /dev/null and b/website/data/cookbook/icons/dunechest_speed_hopper_3.png differ diff --git a/website/data/cookbook/icons/dunechest_wrench.png b/website/data/cookbook/icons/dunechest_wrench.png new file mode 100644 index 00000000..f66cfedb Binary files /dev/null and b/website/data/cookbook/icons/dunechest_wrench.png differ diff --git a/website/data/cookbook/icons/spice_blast_furnace.png b/website/data/cookbook/icons/spice_blast_furnace.png new file mode 100644 index 00000000..f9d87058 Binary files /dev/null and b/website/data/cookbook/icons/spice_blast_furnace.png differ diff --git a/website/data/cookbook/icons/spice_campfire.png b/website/data/cookbook/icons/spice_campfire.png new file mode 100644 index 00000000..492efca6 Binary files /dev/null and b/website/data/cookbook/icons/spice_campfire.png differ diff --git a/website/data/cookbook/icons/spice_coal.png b/website/data/cookbook/icons/spice_coal.png new file mode 100644 index 00000000..751e68d4 Binary files /dev/null and b/website/data/cookbook/icons/spice_coal.png differ diff --git a/website/data/cookbook/icons/spice_furnace.png b/website/data/cookbook/icons/spice_furnace.png new file mode 100644 index 00000000..b73aea76 Binary files /dev/null and b/website/data/cookbook/icons/spice_furnace.png differ diff --git a/website/data/cookbook/icons/spice_smoker.png b/website/data/cookbook/icons/spice_smoker.png new file mode 100644 index 00000000..f22ea5a8 Binary files /dev/null and b/website/data/cookbook/icons/spice_smoker.png differ diff --git a/website/data/cookbook/icons/spice_soul_campfire.png b/website/data/cookbook/icons/spice_soul_campfire.png new file mode 100644 index 00000000..8567baaa Binary files /dev/null and b/website/data/cookbook/icons/spice_soul_campfire.png differ diff --git a/website/data/cookbook/icons/spice_tender.png b/website/data/cookbook/icons/spice_tender.png new file mode 100644 index 00000000..38437f42 Binary files /dev/null and b/website/data/cookbook/icons/spice_tender.png differ diff --git a/website/data/cookbook/item-grades.json b/website/data/cookbook/item-grades.json new file mode 100644 index 00000000..bfad7126 --- /dev/null +++ b/website/data/cookbook/item-grades.json @@ -0,0 +1,320 @@ +{ + "schema": 1, + "policy": "s1-item-metadata-v1", + "sourceRepository": "unimatrix/plugins", + "sourceCommit": "c7c390972d74557347503b98aaf5400e21d0069c", + "files": { + "JarvisConnector/src/main/resources/item-templates.json": "2c0512376fe8036d03baeb7f240a4d411d4e77cf87001261d943fc1d730fff73", + "JarvisConnector/src/main/java/com/dunerealms/jarvis/ItemMetadataPolicy.java": "48694030cf6fa42ce277b11f56c43f47811e06ac97008b2e553c374e93c3a6fe", + "JarvisConnector/src/main/java/com/dunerealms/jarvis/ItemMetadataOverlay.java": "0d559ca87139659acdceaa615650be4eb3982c14079fe5e1439b9a786c1153f4", + "JarvisConnector/src/main/java/com/dunerealms/jarvis/CraftingGrades.java": "e0ff3547e747f150a760a6a98ade395744a1ba949b7d2b776de4d9a4729c5e56", + "JarvisConnector/src/main/java/com/dunerealms/jarvis/StarterKitFlow.java": "0488703761f22a84557289edfe3b95ceaf7e4f421dce15ef2cd811117f8f60ca", + "JarvisConnector/src/main/java/com/dunerealms/jarvis/CraftedFlight.java": "10d400400ba1c3aeba5f047df7ec94780758b9b5a1521952b6b9789cc6317ce2", + "JarvisConnector/src/main/java/com/dunerealms/jarvis/ArrakisBrewing.java": "454c9931b0c649e50d60dce8953053c2220edab785e234251da4edfcb6feab54", + "JarvisConnector/src/main/java/com/dunerealms/jarvis/SpiceBlocks.java": "5abae8692ae52e3f2bf928a2266c38b847ed2d696c21b38b604045fe69cda90f", + "DuneChest/src/main/java/com/example/dunechest/StorageItems.java": "3027dbad35245027f924db0307c35d280afcb613a1bb8259c19fec1de7c9620d" + }, + "nativeBaseline": { + "version": "26.2", + "clientSha256": "40896ee9f1e2bec3c934daac7e93d41e9e3d9c2f8ae0ca366d52ffbfd1afa290", + "files": { + "data/minecraft/recipe/crafting_table.json": "a400eb22cbca14596197f27a537392103857edd3271bd21771f78c416abc18b9", + "data/minecraft/recipe/ender_chest.json": "6d113f9e8381f20c30477d3a460aeb58d98845e180ab4abc5421663f63f0ca85", + "data/minecraft/tags/item/planks.json": "41c794fb511416dcd3ab6a4da76921b1c9a29e644fd846be92387fa840ea8848", + "net/minecraft/world/item/Items.class": "85e6a9852ce230b7d593ac1ce194b5229b4b60cc2ac53935834eb053649b85aa" + }, + "knowledgeBookRarity": "EPIC" + }, + "scope": "Default issued item grades from JARVIS, independent of the MK device tier in display names. Input-dependent brewing retains the input item metadata. No gameplay grading policy changes.", + "items": { + "bio_paste": { + "material": "magma_cream", + "quality": "very_rare", + "equipmentMark": 8, + "source": "item template:bio_paste" + }, + "chukka_cooked_meat": { + "material": "cooked_chicken", + "quality": "common", + "equipmentMark": 2, + "source": "item template:chukka_cooked_meat" + }, + "contaminated_spice_block": { + "material": "dried_kelp_block", + "quality": "rare", + "equipmentMark": 4, + "source": "item template:contaminated_spice_block" + }, + "dunesponge": { + "material": "sponge", + "quality": "common", + "equipmentMark": 2, + "source": "item template:dunesponge" + }, + "jerboa_cooked_meat": { + "material": "cooked_rabbit", + "quality": "rare", + "equipmentMark": 6, + "source": "item template:jerboa_cooked_meat" + }, + "jerboa_hide_paste": { + "material": "clay_ball", + "quality": "common", + "equipmentMark": 2, + "source": "item template:jerboa_hide_paste" + }, + "jerboa_stew": { + "material": "rabbit_stew", + "quality": "very_rare", + "equipmentMark": 9, + "source": "item template:jerboa_stew" + }, + "farmers_bucket": { + "material": "water_bucket", + "quality": "rare", + "equipmentMark": 7, + "source": "item template:farmers_bucket" + }, + "rehydrated_steak": { + "material": "beef", + "quality": "rare", + "equipmentMark": 7, + "source": "item template:rehydrated_steak" + }, + "spice_cake": { + "material": "pumpkin_pie", + "quality": "rare", + "equipmentMark": 7, + "source": "item template:spice_cake" + }, + "spice_dough": { + "material": "wheat", + "quality": "common", + "equipmentMark": 2, + "source": "item template:spice_dough" + }, + "spice_paste": { + "material": "slime_ball", + "quality": "common", + "equipmentMark": 2, + "source": "item template:spice_paste" + }, + "jerboa_egg": { + "material": "egg", + "quality": "uncommon", + "equipmentMark": 3, + "source": "item template:jerboa_egg" + }, + "jerboa_leather": { + "material": "leather", + "quality": "uncommon", + "equipmentMark": 3, + "source": "item template:jerboa_leather" + }, + "spice_bread": { + "material": "enchanted_golden_apple", + "quality": "very_rare", + "equipmentMark": 9, + "source": "item template:spice_bread" + }, + "starter-repair-plate-v1": { + "material": "iron_ingot", + "quality": "uncommon", + "equipmentMark": 1, + "source": "StarterKitFlow.part factory" + }, + "starter-binding-patch-v1": { + "material": "leather", + "quality": "uncommon", + "equipmentMark": 1, + "source": "StarterKitFlow.part factory" + }, + "starter-tool-fitting-v1": { + "material": "copper_ingot", + "quality": "uncommon", + "equipmentMark": 1, + "source": "StarterKitFlow.part factory" + }, + "starter-calibration-piece-v1": { + "material": "quartz", + "quality": "uncommon", + "equipmentMark": 1, + "source": "StarterKitFlow.part factory" + }, + "spice_block": { + "material": "dried_kelp_block", + "quality": "uncommon", + "equipmentMark": 2, + "source": "item template:spice_block" + }, + "smuggled_spice_block": { + "material": "dried_kelp_block", + "quality": "uncommon", + "equipmentMark": 3, + "source": "item template:smuggled_spice_block" + }, + "crafted_elytra": { + "material": "elytra", + "quality": "very_rare", + "equipmentMark": 11, + "source": "item template:dr_s1_elytra_crafted_v2" + }, + "jerboa_water_vial": { + "material": "potion", + "quality": "rare", + "equipmentMark": 6, + "source": "item template:jerboa_water_vial" + }, + "water_of_life": { + "material": "potion", + "quality": "very_rare", + "equipmentMark": 7, + "source": "item template:water_of_life" + }, + "spice_boosted_potion": { + "material": "potion", + "mode": "input", + "source": "ArrakisBrewing.boost clones the imported potion and preserves its item metadata" + }, + "dunechest_ender_chest": { + "material": "ender_chest", + "quality": "very_rare", + "equipmentMark": 9, + "source": "vanilla recipe:ender_chest; fixed ender_eye MK8 +1" + }, + "dunechest_speed_hopper_1": { + "material": "hopper", + "quality": "uncommon", + "equipmentMark": 3, + "source": "material grade:HOPPER" + }, + "dunechest_speed_hopper_2": { + "material": "hopper", + "quality": "uncommon", + "equipmentMark": 3, + "source": "material grade:HOPPER" + }, + "dunechest_speed_hopper_3": { + "material": "hopper", + "quality": "uncommon", + "equipmentMark": 3, + "source": "material grade:HOPPER" + }, + "dunechest_auto_crafter": { + "material": "crafting_table", + "quality": "uncommon", + "equipmentMark": 3, + "source": "vanilla recipe:crafting_table; minimum planks MK2 +1" + }, + "dunechest_wrench": { + "material": "knowledge_book", + "quality": "very_rare", + "equipmentMark": 10, + "source": "native rarity:EPIC" + }, + "dunechest_dune_beacon": { + "material": "sea_lantern", + "quality": "rare", + "equipmentMark": 8, + "source": "material grade:SEA_LANTERN" + }, + "spice_furnace": { + "material": "furnace", + "quality": "common", + "equipmentMark": 2, + "baseEquipmentMark": 1, + "source": "spiceCookersAndRails" + }, + "spice_smoker": { + "material": "smoker", + "quality": "uncommon", + "equipmentMark": 3, + "baseEquipmentMark": 2, + "source": "spiceCookersAndRails" + }, + "spice_blast_furnace": { + "material": "blast_furnace", + "quality": "uncommon", + "equipmentMark": 3, + "baseEquipmentMark": 2, + "source": "spiceCookersAndRails" + }, + "spice_campfire": { + "material": "campfire", + "quality": "uncommon", + "equipmentMark": 5, + "baseEquipmentMark": 4, + "source": "spiceCookersAndRails" + }, + "spice_soul_campfire": { + "material": "soul_campfire", + "quality": "uncommon", + "equipmentMark": 4, + "baseEquipmentMark": 3, + "source": "spiceCookersAndRails" + }, + "spice_coal": { + "material": "coal", + "quality": "uncommon", + "equipmentMark": 4, + "baseEquipmentMark": 3, + "source": "spiceCookersAndRails" + }, + "spice_tender": { + "material": "chest_minecart", + "quality": "uncommon", + "equipmentMark": 5, + "baseEquipmentMark": 4, + "source": "spiceCookersAndRails" + } + }, + "additionalSources": { + "spiceCookersAndRails": { + "sourceRepository": "unimatrix/plugins", + "sourceCommit": "13a8f23247497ac5cd9d59b6869e19097ee307be", + "files": { + "network/content-assets/cookbook/spice-crafting.json": "9e5f7bf35f3886dd4e8a78d313075ce4ab8193d2e05546c4bc2028929c2e6c91", + "JarvisConnector/src/main/java/com/dunerealms/jarvis/SpiceFurnaces.java": "d30ea6b51e5f3b17db8f847d9325042ae2b495356ed4214ef4799891063c9fea", + "JarvisConnector/src/main/resources/item-templates.json": "0eeda8b713de1912cd1dbd2d1c5d93cda2ecdf69a45f5c54974269971a464b5d", + "vendor/minecart-trains/spice-coal.patch": "a71e6a7c0c1f565006e0a23d4e71365785aa3d52fd2ded00d83b827a1763775b" + }, + "icons": { + "spice_furnace": { + "path": "icons/spice_furnace.png", + "sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_furnace.png", + "sha256": "695e2828feecd30e5bfdd7b5910d548069f3686d4814a7ef619e83fbf21d43b0" + }, + "spice_smoker": { + "path": "icons/spice_smoker.png", + "sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_smoker.png", + "sha256": "cda6b0f98a364a7d601037858107fbd37d67cce35f9e41b6c0f16d88eed8e4c0" + }, + "spice_blast_furnace": { + "path": "icons/spice_blast_furnace.png", + "sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_blast_furnace.png", + "sha256": "007b5adba64020e4381b39e1c5251b7b0a8c6d4dabd18fb94a6947b15615634d" + }, + "spice_campfire": { + "path": "icons/spice_campfire.png", + "sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_campfire.png", + "sha256": "3c1cbe1b7714ff8d310c146fcf24deb6400e93fe4757d0d044eb6f034118641f" + }, + "spice_soul_campfire": { + "path": "icons/spice_soul_campfire.png", + "sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_soul_campfire.png", + "sha256": "9fdb25e9035314bd95326aec07dc044acba1de416e211ed837077930487035a5" + }, + "spice_coal": { + "path": "icons/spice_coal.png", + "sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_coal.png", + "sha256": "228ead2784f3b7b0179b2daf0329e69683805d96c7e50182e3d61fe36b323d70" + }, + "spice_tender": { + "path": "icons/spice_tender.png", + "sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_tender.png", + "sha256": "3c573a0831320ca23172f31dc4ee43656af4abab25dc50bf1e6915cf90423310" + } + } + } + } +} diff --git a/website/data/cookbook/spice-crafting.json b/website/data/cookbook/spice-crafting.json new file mode 100644 index 00000000..ff314ff9 --- /dev/null +++ b/website/data/cookbook/spice-crafting.json @@ -0,0 +1,72 @@ +[ + { + "id": "spice_furnace", + "name": "Spice-Infused Furnace", + "material": "FURNACE", + "baseMark": 1, + "mark": 2, + "quality": "common", + "ingredients": "4 Iron Ingots · 4 raw Melange Spice · 1 Furnace", + "details": "Put the vanilla cooker in the centre, spice on the four sides, and iron in the corners. Cooks twice as fast." + }, + { + "id": "spice_smoker", + "name": "Spice-Infused Smoker", + "material": "SMOKER", + "baseMark": 2, + "mark": 3, + "quality": "uncommon", + "ingredients": "4 Iron Ingots · 4 raw Melange Spice · 1 Smoker", + "details": "Put the vanilla cooker in the centre, spice on the four sides, and iron in the corners. Cooks twice as fast." + }, + { + "id": "spice_blast_furnace", + "name": "Spice-Infused Blast Furnace", + "material": "BLAST_FURNACE", + "baseMark": 2, + "mark": 3, + "quality": "uncommon", + "ingredients": "4 Iron Ingots · 4 raw Melange Spice · 1 Blast Furnace", + "details": "Put the vanilla cooker in the centre, spice on the four sides, and iron in the corners. Cooks twice as fast." + }, + { + "id": "spice_campfire", + "name": "Spice-Infused Campfire", + "material": "CAMPFIRE", + "baseMark": 4, + "mark": 5, + "quality": "uncommon", + "ingredients": "4 Iron Ingots · 4 raw Melange Spice · 1 Campfire", + "details": "Put the vanilla cooker in the centre, spice on the four sides, and iron in the corners. Cooks twice as fast." + }, + { + "id": "spice_soul_campfire", + "name": "Spice-Infused Soul Campfire", + "material": "SOUL_CAMPFIRE", + "baseMark": 3, + "mark": 4, + "quality": "uncommon", + "ingredients": "4 Iron Ingots · 4 raw Melange Spice · 1 Soul Campfire", + "details": "Put the vanilla cooker in the centre, spice on the four sides, and iron in the corners. Cooks twice as fast." + }, + { + "id": "spice_coal", + "name": "Spice Coal", + "material": "COAL", + "baseMark": 3, + "mark": 4, + "quality": "uncommon", + "ingredients": "1 raw Melange Spice · 1 Coal or Charcoal", + "details": "Shapeless recipe. Fuels cookers and furnace minecarts." + }, + { + "id": "spice_tender", + "name": "Spice Fuel Cart", + "material": "CHEST_MINECART", + "baseMark": 4, + "mark": 5, + "quality": "uncommon", + "ingredients": "1 Minecart · 1 Spice Coal", + "details": "Shapeless recipe. A fuel cart for Spice Coal." + } +] diff --git a/website/integrations/osticket/dev-jarvis-catalogue.json b/website/integrations/osticket/dev-jarvis-catalogue.json index e13138c2..bb2b2345 100644 --- a/website/integrations/osticket/dev-jarvis-catalogue.json +++ b/website/integrations/osticket/dev-jarvis-catalogue.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "sourceHash": "e5c15002efdf1a533fc3ac3c0f9d13019d751c3149792d1e848b4282bf05efde", + "sourceHash": "e3bd4f927cac88e1ba94681857c6e26ba0f36cef960099f01f21c4b2263316f2", "actions": [ { "id": "war.coalition-consent", @@ -2911,6 +2911,25 @@ "webIssue": false, "recordOnly": true }, + { + "id": "progression.flight-merge-policy", + "label": "Progression & XP · Armoured flight quest policy", + "version": 10, + "keyType": "progression-policy", + "fields": [ + { + "name": "ticketId", + "label": "Ban / support ticket ID", + "type": "text", + "required": true, + "maxLength": 80 + } + ], + "effect": "Add POL-ELYTRA-MERGE through policy:POL:S01:v10 without changing existing rewards or season dates. A physical native chestplate-and-elytra merge consumes one elytra, preserves armour properties and records one receipt-bound flight_merged observation on a shared-profile planet. No currency charge or XP award. Acquiring an ordinary elytra cannot complete this separate step; web/menu clicks never assert physical completion.", + "fixedTargets": [], + "webIssue": false, + "recordOnly": true + }, { "id": "progression.game-observation", "label": "Progression & XP · Native quest observation", @@ -2976,7 +2995,7 @@ "required": false } ], - "effect": "Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Fixed world/dimension flight observations feed the Reputation Elytra branch. A committed paid delivery or natural End-ship acquisition completes only this branch, awarding its remaining rewards once. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.", + "effect": "Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Fixed world/dimension flight observations feed the Reputation Elytra branch. A committed paid delivery or natural End-ship acquisition completes only the flight preparation/acquisition quests, awarding their remaining rewards once. Armour merging needs its separate physical receipt. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.", "fixedTargets": [], "webIssue": false, "recordOnly": true diff --git a/website/node/bank-quest-activities.mjs b/website/node/bank-quest-activities.mjs index 4e037070..d6767646 100644 --- a/website/node/bank-quest-activities.mjs +++ b/website/node/bank-quest-activities.mjs @@ -33,3 +33,28 @@ export function createBankQuestActivities(central,bank,keys,{clock=Date.now}={}) return {pendingMetrics:rows.length?[]:['shop-purchase']}; }; } + +const verifiedBankDeposits = `SELECT id,created_at FROM ria_cash_redemptions + WHERE owner_id=? AND player_uuid=? AND mode='bank' AND state='redeemed' + AND CAST(amount_minor AS DECIMAL(20,0))>0 AND created_at>=? AND created_at{ + if(actor!==producer||p.metric!=='bank-deposit'||p.quantity!==1||p.reference!=='bank-deposit:'+p.eventId)return false; + const rows=await bank.query(verifiedBankDeposits+' AND id=?',[p.accountId,p.minecraftUuid,p.occurredAt,p.occurredAt+1,p.eventId]); + return rows.length===1; + }}); + return async function collect(actor,season){ + const links=await central.query('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[actor.id]); + if(links.length!==1)return {pendingMetrics:['bank-deposit']}; + const minecraftUuid=links[0].minecraft_uuid.toLowerCase(); + // This receipt and its Postbank credit are committed in the same transaction. + const rows=await bank.query(verifiedBankDeposits+' ORDER BY created_at,id LIMIT 1',[actor.id,minecraftUuid,Number(season.starts_at),clock()+1]); + const receipt=rows[0]; + if(!receipt)return {pendingMetrics:['bank-deposit']}; + await events.record(producer,{eventId:receipt.id,accountId:actor.id,minecraftUuid,seasonId:season.season_id, + metric:'bank-deposit',quantity:1,occurredAt:Number(receipt.created_at),reference:'bank-deposit:'+receipt.id}); + return {pendingMetrics:[]}; + }; +} diff --git a/website/node/elytra-quest-policy.mjs b/website/node/elytra-quest-policy.mjs index 3d778ea6..9aea8ac7 100644 --- a/website/node/elytra-quest-policy.mjs +++ b/website/node/elytra-quest-policy.mjs @@ -1,5 +1,5 @@ import {ELYTRA_QUESTS} from '../control-panel/public/cp-v2/cp-v2-elytra-quests.mjs'; export const ELYTRA_RECIPE=Object.freeze({world:'Arrakis',quality:'very_rare',equipmentMark:11,result:'Elytra',grid:[['Netherite ingot','Phantom membrane','Netherite ingot'],['Iron ingot','Diamond','Iron ingot'],['Contaminated spice','Phantom membrane','Contaminated spice']]}); -export const FLIGHT_METRICS=Object.freeze(Object.fromEntries(ELYTRA_QUESTS.map(d=>[d.metric,d.target]))); +export const FLIGHT_METRICS=Object.freeze(Object.fromEntries(ELYTRA_QUESTS.filter(d=>d.id!=='POL-ELYTRA-MERGE').map(d=>[d.metric,d.target]))); export function applyElytraAlternative(totals){if((totals.get('flight-elytra-acquired')||0)>0)for(const [metric,target]of Object.entries(FLIGHT_METRICS))totals.set(metric,Math.max(target,totals.get(metric)||0));return totals;} export function flightDossier(quest){if(quest.id!=='POL-ELYTRA-CRAFT')return quest;if(!quest.canStart&&!['active','completed','claimed'].includes(quest.state))return {...quest,objective:'Complete the preparation quests to reveal the elytra recipe.'};return {...quest,objective:'Craft this elytra on Arrakis using the revealed recipe.',recipe:ELYTRA_RECIPE};} diff --git a/website/node/game-guild.mjs b/website/node/game-guild.mjs index 4c10e5d7..33fc7a83 100644 --- a/website/node/game-guild.mjs +++ b/website/node/game-guild.mjs @@ -1,14 +1,20 @@ import {createBankTradePolicy} from './world-trade-governance.mjs'; -import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs'; +import {tradeWorld,TRADE_WORLDS} from '../control-panel/public/world-trade-policy.mjs'; import {createGuildSubsidies,verifyGuildSubsidy} from './guild-subsidy.mjs'; import {currentGuildSurcharge,currentGuildDiscount,standardGuildFare} from './guild-tariff-policy.mjs'; import {createHash} from 'node:crypto'; import {gameAuthorized,validUuid,json} from './game-link.mjs'; import {boardingOpen} from './game-organisation-policy.mjs'; import {createPostbankAuthority} from './postbank-authority.mjs'; -import {canDebitAccount} from './postbank-authorisations.mjs'; -import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs'; -import {PostbankPayments} from './postbank-payments.mjs'; +import {createGuildPassageLedger} from './guild-passage-ledger.mjs'; +import {paidTariff,effectiveTrips,classifyRoute,BOUNTY_MULTIPLIER} from './travel-tariff.mjs'; +import {createNativeHoldingCheck} from './travel-holdings.mjs'; +import {createTravelBountyClaims,TRAVEL_BOUNTY_CLAIM_SCHEMA} from './travel-bounty-claims.mjs'; +export {TRAVEL_BOUNTY_CLAIM_SCHEMA}; +export const TRAVEL_OPEN_PASSAGE_SCHEMA="CREATE TABLE IF NOT EXISTS pb_guild_open_passages(id CHAR(36) PRIMARY KEY,source_world VARCHAR(32) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; +import {createOwnedSmugglerRoutes} from './owned-smuggler-routes.mjs'; +import {createOwnedSmugglerPassages} from './owned-smuggler-passages.mjs'; +import {validOwnedSmugglerRequest} from './owned-smuggler-request.mjs'; import {BankError} from './postbank-service.mjs'; import {createPOLActivityEvents} from './pol-activity-events.mjs'; import {createPersonalActivityEvents} from './personal-activity-events.mjs'; @@ -20,58 +26,99 @@ import {housePrologueState} from './house-prologue.mjs'; export const GUILD_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_guild_passages(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,house_key CHAR(36) NOT NULL,house_version INT NOT NULL,destination VARCHAR(32) NOT NULL,fare_minor BIGINT NOT NULL,source_id BIGINT UNSIGNED NOT NULL,target_id BIGINT UNSIGNED NOT NULL,fingerprint CHAR(64) NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,arrived_at BIGINT NULL,reported_at BIGINT NULL,INDEX guild_pending(minecraft_uuid,state,expires_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; export const SMUGGLER_PASSAGE_SCHEMA="CREATE TABLE IF NOT EXISTS pb_smuggler_passages(id CHAR(36) PRIMARY KEY,permit_key CHAR(36) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; const routes={atreides:'caladan',harkonnen:'giedi_prime',corrino:'kaitain',ordos:'sigma_draconis_iv',fremen:'arrakis'}; -const accountSQL=`SELECT a.*,c.entity_id,e.external_key,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id`; const fail=(message,status=409)=>{throw new BankError(message,status);}; -export function createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true,subsidies=null}={}){ +export const TRAVEL_LADDER_SCHEMA="CREATE TABLE IF NOT EXISTS pb_travel_ladder(actor_id CHAR(36) PRIMARY KEY,trips INT NOT NULL,last_paid_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; +export const TRAVEL_BOUNTY_SCHEMA="CREATE TABLE IF NOT EXISTS pb_travel_bounties(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,traveller VARCHAR(64) NOT NULL,world VARCHAR(32) NOT NULL,fare_minor BIGINT NOT NULL,amount_minor BIGINT NOT NULL,state VARCHAR(12) NOT NULL,created_at BIGINT NOT NULL,claimed_by CHAR(36) NULL,claimed_at BIGINT NULL,claim_request CHAR(36) NULL UNIQUE,INDEX travel_bounty_open(minecraft_uuid,state,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; +export function createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,openTravel=false,holdingOnWorld=async()=>false,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true,subsidies=null,routeBindings=false,homeRoutes=null,authorityForStore=null}={}){ if(!Number.isSafeInteger(fareMinor)||fareMinor<1||fareMinor>100000000||!Number.isSafeInteger(smugglerFareMinor)||smugglerFareMinor<1||smugglerFareMinor>100000000)throw Error('Invalid Guild fare'); - const payments=new PostbankPayments(bank,authority,{clock}); + const ledger=createGuildPassageLedger(bank,{authority,clock,subsidies}),{funds,release,reserve,settle,payout}=ledger; async function quotedFare(user,store=bank,lock=false){const percent=await surcharge(clock()),reduction=await discount(user.faction,clock());const normal=standardGuildFare(fareMinor,percent,reduction);if(normal===null)fail('The Guild tariff requires review.',503);const offer=subsidies?await subsidies.quote(store,normal,reduction,lock):null;return {price:offer?.price??normal,offer};} const view=r=>({requestId:r.id,destination:r.destination,state:r.state,fareMinor:Number(r.fare_minor),expiresAt:Number(r.expires_at)}); const readyForTravel=async(user,uuid,store=bank)=>await prologueReady(user,uuid)||!!await store.first("SELECT id FROM pb_guild_passages WHERE actor_id=? AND minecraft_uuid=? AND state='arrived' LIMIT 1",[user.id,uuid]); - const allowed=async(user,destination)=>!!routes[user?.faction]&&(destination===routes[user.faction]||destination==='arrakis'&&await allowArrakis(user.faction,user)); - async function funds(tx,user,amount,lock=false){const context=await authority(user,{bank:tx});return(await tx.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.system_key IS NULL ORDER BY a.id"+(lock?' FOR UPDATE':''),[user.id])).find(a=>ordinaryPaymentAccount(a)&&canDebitAccount(context,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(amount));} - async function release(tx,r){if(r.state!=='pending')return;const a=await tx.first('SELECT id,reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[r.source_id]);if(!a||BigInt(a.reserved_minor)!!routes[user?.faction]&&(openTravel?Object.values(routes).includes(destination):destination===routes[user.faction]||destination==='arrakis'&&await allowArrakis(user.faction,user)); async function expire(){const expired=await bank.transaction(async tx=>{const rows=await tx.query("SELECT * FROM pb_guild_passages WHERE state='pending' AND expires_at<=? ORDER BY id LIMIT 25 FOR UPDATE",[clock()]);for(const r of rows)await release(tx,r);return rows.length;});if(subsidies)await subsidies.expire();return expired;} - async function quote(uuid,sourceWorld='lobby'){await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403);const ready=await readyForTravel(user,uuid);if(!ready)return {ok:true,destination:routes[user.faction],destinations:[],fareMinor:(await quotedFare(user)).price,affordable:false,account:null,prologueRequired:true};const {price,offer}=await quotedFare(user),source=await funds(bank,user,price),destinations=[routes[user.faction]];if(!destinations.includes('arrakis')&&await allowArrakis(user.faction,user))destinations.push('arrakis');const open=[];for(const destination of destinations)if(await allowJourney(sourceWorld,destination,bank,false))open.push(destination);return{ok:true,destination:routes[user.faction],destinations:open,fareMinor:price,...(offer?{subsidyMinor:offer.amount}:{}),affordable:!!source,account:source?.account_number||null};} - async function smugglerPermit(user,uuid,source,tx,lock=false){if(!allowSmuggling||source!=='lobby'||!routes[user?.faction]||!await readyForTravel(user,uuid))return null;if(await allowed(user,'arrakis')&&await allowJourney(source,'arrakis',tx,lock))return null;return allowSmuggling(user,uuid,clock());} - async function quoteSmuggler(uuid,sourceWorld='lobby'){await expire();const user=await resolve(uuid);if(!user)fail('Link your active website account and choose your House first.',403);const eligible=!!allowSmuggling&&sourceWorld==='lobby'&&!!routes[user.faction]&&await readyForTravel(user,uuid)&&(!await allowed(user,'arrakis')||!await allowJourney(sourceWorld,'arrakis',bank,false)),permit=eligible?await allowSmuggling(user,uuid,clock()):null;return{ok:true,eligible,allowed:!!permit,permitExpiresAt:permit?.expiresAt||null,fareMinor:smugglerFareMinor,affordable:!!permit&&!!await funds(bank,user,smugglerFareMinor),keyId:user.keyId,version:user.version};} + + // ---- Open travel: race world and Lobby are free, every other world is paid and carries a bounty ---- + async function tariff(user,uuid,destination,store,lock=false){ + const decree=destination==='arrakis'&&await allowArrakis(user.faction,user),route=classifyRoute({destination,raceWorld:routes[user.faction],decree}); + if(route.free)return{free:true,reason:route.reason,fareMinor:0,bountyMinor:0}; + const row=await store.first('SELECT trips,last_paid_at FROM pb_travel_ladder WHERE actor_id=?'+(lock?' FOR UPDATE':''),[user.id]); + const trips=effectiveTrips(row?.trips??0,row?.last_paid_at??null,clock()); + return{free:false,reason:'paid',...paidTariff({trips,reduced:await holdingOnWorld(user,uuid,destination,{fresh:lock})})}; + } + async function recordTrip(tx,r,user){ + const fare=Number(r.fare_minor);if(fare<1)return; // a free passage carries no bounty and does not move the ladder + const now=clock(),row=await tx.first('SELECT trips,last_paid_at FROM pb_travel_ladder WHERE actor_id=? FOR UPDATE',[user.id]),trips=effectiveTrips(row?.trips??0,row?.last_paid_at??null,now)+1; + if(row)await tx.query('UPDATE pb_travel_ladder SET trips=?,last_paid_at=? WHERE actor_id=?',[trips,now,user.id]);else await tx.query('INSERT INTO pb_travel_ladder(actor_id,trips,last_paid_at) VALUES(?,?,?)',[user.id,trips,now]); + await tx.query("INSERT INTO pb_travel_bounties(id,actor_id,minecraft_uuid,traveller,world,fare_minor,amount_minor,state,created_at) VALUES(?,?,?,?,?,?,?,'open',?)",[r.id,user.id,r.minecraft_uuid,String(user.username).slice(0,64),r.destination,fare,fare*BOUNTY_MULTIPLIER,now]); + } + async function quoteOpen(uuid,sourceWorld){ + await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403); + const ready=await readyForTravel(user,uuid),open=[],catalog=[]; + for(const world of TRADE_WORLDS){ + const t=await tariff(user,uuid,world.id,bank),journey=await allowJourney(sourceWorld,world.id,bank,false),source=ready&&journey&&t.fareMinor>0?await funds(bank,user,t.fareMinor):null; + const reason=!ready?'Complete your House Prologue first.':world.id===tradeWorld(sourceWorld)?'Already on this world.':tradeWorld(sourceWorld)!=='lobby'?'Board ordinary passages from the Guild Lobby.':!journey?'The Spacing Guild has embargoed this route.':t.fareMinor>0&&!source?'Not enough available Dunemarks.':''; + if(!reason)open.push(world.id); + catalog.push({server:world.id,name:world.name,available:!reason,reason,fareMinor:t.fareMinor,free:t.free,...(t.free?{freeReason:t.reason}:{bountyMinor:t.bountyMinor,reduced:t.reduced,trip:t.trip})}); + } + const home=catalog.find(r=>r.server===routes[user.faction]); + return{ok:true,openTravel:true,destination:routes[user.faction],destinations:open,routes:catalog,fareMinor:home?.fareMinor??0,affordable:open.length>0,...(!ready?{prologueRequired:true}:{})}; + } + const bountyClaim=createTravelBountyClaims(bank,{resolve,clock,payout,enabled:()=>openTravel}); + async function quote(uuid,sourceWorld='lobby'){ + if(openTravel)return quoteOpen(uuid,sourceWorld); + await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403); + const ready=await readyForTravel(user,uuid),{price,offer}=await quotedFare(user),source=ready?await funds(bank,user,price):null,open=[],catalog=[]; + for(const world of TRADE_WORLDS){const lawful=await allowed(user,world.id),journey=lawful&&await allowJourney(sourceWorld,world.id,bank,false);if(ready&&journey)open.push(world.id); + const reason=!ready?'Complete your House Prologue first.':world.id===tradeWorld(sourceWorld)?'Already on this world.':!lawful?'Your House has no Imperial passage for this destination.':!journey?'The Spacing Guild has embargoed this route.':!source?'Not enough available Dunemarks.':''; + catalog.push({server:world.id,name:world.name,available:!reason,reason,fareMinor:price}); + } + return {ok:true,destination:routes[user.faction],destinations:[...new Set([routes[user.faction],...open])].filter(w=>open.includes(w)),routes:catalog,fareMinor:price,...(offer?{subsidyMinor:offer.amount}:{}),affordable:!!source,account:source?.account_number||null,...(!ready?{prologueRequired:true}:{})}; + } + async function smugglerPermit(user,uuid,source,tx,lock=false,destination='arrakis'){ + if(!allowSmuggling||!tradeWorld(source)||(!routeBindings&&(source!=='lobby'||destination!=='arrakis'))||source===destination||!routes[user?.faction]||!await readyForTravel(user,uuid))return null; + if(await allowed(user,destination)&&await allowJourney(source,destination,tx,lock))return null;return allowSmuggling(user,uuid,clock()); + } + async function quoteSmuggler(uuid,sourceWorld='lobby'){ + await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403); + const ready=await readyForTravel(user,uuid),currentPermit=allowSmuggling&&ready?await allowSmuggling(user,uuid,clock()):null,source=ready?await funds(bank,user,smugglerFareMinor):null,catalog=[]; + for(const world of TRADE_WORLDS){const lawful=await allowed(user,world.id)&&await allowJourney(sourceWorld,world.id,bank,false),eligible=!!allowSmuggling&&!!tradeWorld(sourceWorld)&&ready&&world.id!==tradeWorld(sourceWorld)&&!lawful&&(routeBindings||sourceWorld==='lobby'&&world.id==='arrakis'),permit=eligible?currentPermit:null; + const reason=!ready?'Complete your House Prologue first.':world.id===tradeWorld(sourceWorld)?'Already on this world.':lawful?'Use ordinary Guild passage for this lawful route.':!eligible?'This smuggler route is unavailable.':!permit?'Meet Esmar for a current personal smuggler permission.':!source?'Not enough available Dunemarks.':''; + catalog.push({server:world.id,name:world.name,available:!reason,reason,fareMinor:smugglerFareMinor,eligible,allowed:!!permit,affordable:!!permit&&!!source,permitExpiresAt:permit?.expiresAt||null}); + } + const legacy=catalog.find(r=>r.server==='arrakis');return {ok:true,eligible:legacy.eligible,allowed:legacy.allowed,permitExpiresAt:legacy.permitExpiresAt,fareMinor:smugglerFareMinor,affordable:legacy.affordable,keyId:user.keyId,version:user.version,routes:catalog}; + } async function board(input,smuggler=false){await expire();const user=await resolve(input.uuid);if(!user||!routes[user.faction]||user.keyId!==input.keyId||user.version!==input.version)fail('Your House key changed. Reopen the Guild menu.',403); - if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);if(!Number.isSafeInteger(input.fareMinor)||input.fareMinor<1||input.fareMinor>100000000)fail('Invalid Guild fare.',400);const destination=input.destination??routes[user.faction];if(smuggler?destination!=='arrakis'||input.sourceWorld!=='lobby':!await allowed(user,destination))fail(smuggler?'A current smuggler passage is required.':'Your House has no Imperial passage for this destination.',403);const fingerprint=createHash('sha256').update(JSON.stringify([input.uuid,user.id,input.keyId,input.version,destination,input.fareMinor,...(smuggler?["smuggler"]:[])])).digest('hex'); + if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);if(!Number.isSafeInteger(input.fareMinor)||input.fareMinor<(openTravel&&!smuggler?0:1)||input.fareMinor>100000000)fail('Invalid Guild fare.',400);const destination=input.destination??routes[user.faction];if(smuggler?!Object.values(routes).includes(destination)||!tradeWorld(input.sourceWorld)||destination===tradeWorld(input.sourceWorld)||!routeBindings&&(destination!=='arrakis'||input.sourceWorld!=='lobby'):!await allowed(user,destination))fail(smuggler?'A current smuggler passage is required.':'Your House has no Imperial passage for this destination.',403);const legacyFingerprint=createHash('sha256').update(JSON.stringify([input.uuid,user.id,input.keyId,input.version,destination,input.fareMinor,...(smuggler?["smuggler"]:[])])).digest('hex'),fingerprint=smuggler&&routeBindings?createHash('sha256').update(JSON.stringify([legacyFingerprint,input.sourceWorld])).digest('hex'):legacyFingerprint; + if(openTravel&&!smuggler&&tradeWorld(input.sourceWorld||'lobby')!=='lobby')fail('Board ordinary Guild passages from the Guild Lobby.',403); return bank.transaction(async tx=>{ - const prior=await tx.first('SELECT * FROM pb_guild_passages WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.fingerprint!==fingerprint)fail('This passage reference was already used.');return{ok:true,...view(prior),...(smuggler?{smuggler:true}:{}),replayed:true};} - const {price,offer}=smuggler?{price:smugglerFareMinor,offer:null}:await quotedFare(user,tx,true);if(input.fareMinor!==price)fail('The Guild fare changed. Reopen the passage menu.'); + const prior=await tx.first('SELECT * FROM pb_guild_passages WHERE id=? FOR UPDATE',[input.requestId]);if(prior){const legacy=smuggler&&routeBindings&&destination==='arrakis'&&input.sourceWorld==='lobby'&&prior.fingerprint===legacyFingerprint&&!await tx.first('SELECT id FROM pb_guild_route_bindings WHERE id=?',[prior.id]);if(prior.actor_id!==user.id||prior.fingerprint!==fingerprint&&!legacy)fail('This passage reference was already used.');return{ok:true,...view(prior),...(smuggler?{smuggler:true}:{}),replayed:true};} + const openRoute=openTravel&&!smuggler?await tariff(user,input.uuid,destination,tx,true):null,{price,offer}=smuggler?{price:smugglerFareMinor,offer:null}:openRoute?{price:openRoute.fareMinor,offer:null}:await quotedFare(user,tx,true);if(input.fareMinor!==price)fail('The Guild fare changed. Reopen the passage menu.'); if(!smuggler&&!await allowJourney(input.sourceWorld||'lobby',destination,tx,true))fail('The Spacing Guild has embargoed this world. Smuggler routes remain available.',403); if(!smuggler&&!boardingOpen(clock()))fail('Boarding opens at :00, :20 and :40 for five minutes.'); const fresh=await resolve(input.uuid);if(!fresh||fresh.id!==user.id||fresh.keyId!==input.keyId||fresh.version!==input.version||!await readyForTravel(fresh,input.uuid,tx)||!smuggler&&!await allowed(fresh,destination))fail('Your House key or Imperial passage changed.',403); - const permit=smuggler?await smugglerPermit(fresh,input.uuid,input.sourceWorld,tx,true):null;if(smuggler&&!permit)fail("Meet Esmar Tuek for a current personal smuggler permission.",403); + const permit=smuggler?await smugglerPermit(fresh,input.uuid,input.sourceWorld,tx,true,destination):null;if(smuggler&&!permit)fail("Meet Esmar Tuek for a current personal smuggler permission.",403); // Lock this customer's accounts before checking their other in-flight passage. - const source=await funds(tx,user,price,true);if(!source)fail('Not enough available Dunemarks in your central personal bank account.'); - const other=await tx.first("SELECT id FROM pb_guild_passages WHERE minecraft_uuid=? AND state='pending' FOR UPDATE",[input.uuid]);if(other)fail('Your previous passage is still awaiting arrival.'); - const target=await tx.first("SELECT * FROM pb_accounts WHERE system_key='sys_game_treasury' FOR UPDATE");if(!target||target.state!=='active')fail('The Guild receiving account is unavailable.',503); - const now=clock(),r={id:input.requestId,actor_id:user.id,minecraft_uuid:input.uuid,house_key:input.keyId,house_version:input.version,destination,fare_minor:price,source_id:source.id,target_id:target.id,fingerprint,state:'pending',created_at:now,expires_at:smuggler?Math.min(now+120000,permit.expiresAt):now+120000}; - await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[price,source.id]); - await tx.query('INSERT INTO pb_guild_passages(id,actor_id,minecraft_uuid,house_key,house_version,destination,fare_minor,source_id,target_id,fingerprint,state,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',Object.values(r));if(smuggler)await tx.query("INSERT INTO pb_smuggler_passages(id,permit_key) VALUES(?,?)",[r.id,permit.keyId]);if(offer)await subsidies.reserve(tx,r.id,offer);return{ok:true,...view(r),...(smuggler?{smuggler:true}:{})}; + const now=clock(),r=await reserve(tx,input,user,{price,fingerprint,destination,expiresAt:smuggler?Math.min(now+120000,permit.expiresAt):now+120000,permitKey:permit?.keyId||null,offer}); + if(openRoute)await tx.query('INSERT INTO pb_guild_open_passages(id,source_world,created_at) VALUES(?,?,?)',[r.id,'lobby',now]); + if(smuggler&&routeBindings)await tx.query("INSERT INTO pb_guild_route_bindings(id,route_kind,source_world,created_at) VALUES(?,'esmar',?,?)",[r.id,input.sourceWorld,now]);return{ok:true,...view(r),...(smuggler?{smuggler:true}:{})}; }); } async function arrive(uuid,server){ await expire();const user=await resolve(uuid);if(!user)fail('A current linked personal account is required.',403); const row=await bank.transaction(async tx=>{ - const r=await tx.first("SELECT * FROM pb_guild_passages WHERE minecraft_uuid=? AND actor_id=? AND destination=? AND (state='pending' OR state='arrived' AND reported_at IS NULL) ORDER BY created_at DESC LIMIT 1 FOR UPDATE",[uuid,user.id,server]);if(!r)return null; + const r=await tx.first("SELECT * FROM pb_guild_passages WHERE minecraft_uuid=? AND actor_id=? AND destination=? AND (state='pending' OR state='arrived' AND reported_at IS NULL)"+(routeBindings?" AND NOT EXISTS(SELECT 1 FROM pb_guild_route_bindings b WHERE b.id=pb_guild_passages.id AND b.route_kind='owned-home')":"")+" ORDER BY created_at DESC LIMIT 1 FOR UPDATE",[uuid,user.id,server]);if(!r)return null; const marker=allowSmuggling?await tx.first('SELECT permit_key FROM pb_smuggler_passages WHERE id=? FOR UPDATE',[r.id]):null;r.smuggler=!!marker;if(r.state==='arrived')return r; if(Number(r.expires_at)<=clock()){await release(tx,r);return null;} if(user.keyId!==r.house_key||user.version!==Number(r.house_version)||!await readyForTravel(user,uuid,tx)||(marker?(await allowSmuggling(user,uuid,clock()))?.keyId!==marker.permit_key:!await allowed(user,r.destination)||!await allowJourney('lobby',r.destination,tx,true))){await release(tx,r);return null;} - const accounts=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[r.source_id,r.target_id]),source=accounts.find(a=>String(a.id)===String(r.source_id)),target=accounts.find(a=>String(a.id)===String(r.target_id)); - if(!ordinaryPaymentAccount(source)||!target||target.system_key!=='sys_game_treasury'||target.state!=='active'||BigInt(source.reserved_minor)0){const b=await bank.first('SELECT * FROM pb_travel_bounties WHERE id=?',[row.id]);if(b)bounty={requestId:b.id,traveller:b.traveller,world:b.world,amountMinor:Number(b.amount_minor),state:b.state};}return{ok:true,passage:row?{...view(row),...(row.smuggler?{smuggler:true}:{})}:null,...(bounty?{bounty}:{})}; } async function checkTravel(uuid,source,destination){if(!await resolve(uuid))fail('A linked account is required.',403);return bank.transaction(async tx=>{if(!await allowJourney(source,destination,tx,true))fail('The Spacing Guild has embargoed journeys to and from this world. Smuggler routes remain available.',403);return{ok:true,source,destination,expiresAt:clock()+5000};});} - async function smugglerReturn(uuid,source){const user=await resolve(uuid);if(!user||source!=='arrakis'||!allowSmuggling)fail('Meet Esmar Tuek on Arrakis.',403);const r=await bank.first("SELECT p.id,s.permit_key FROM pb_guild_passages p LEFT JOIN pb_smuggler_passages s ON s.id=p.id WHERE p.actor_id=? AND p.minecraft_uuid=? AND p.destination='arrakis' AND p.state='arrived' ORDER BY p.arrived_at DESC,p.id DESC LIMIT 1",[user.id,uuid]);if(!r?.permit_key)fail('No confirmed personal smuggler arrival is available for return.',403);return{ok:true,source,destination:'lobby',expiresAt:clock()+5000,smuggler:true};} - return{quote,quoteSmuggler,board,arrive,expire,checkTravel,smugglerReturn}; + async function smugglerReturn(uuid,source){const user=await resolve(uuid);if(!user||!Object.values(routes).includes(source)||!routeBindings&&source!=='arrakis'||!allowSmuggling)fail('Meet Esmar Tuek on the arrival world.',403);const r=await bank.first("SELECT p.id,s.permit_key"+(routeBindings?',b.source_world,b.route_kind':'')+" FROM pb_guild_passages p LEFT JOIN pb_smuggler_passages s ON s.id=p.id"+(routeBindings?' LEFT JOIN pb_guild_route_bindings b ON b.id=p.id':'')+" WHERE p.actor_id=? AND p.minecraft_uuid=? AND p.destination=? AND p.state='arrived'"+" ORDER BY p.arrived_at DESC,p.id DESC LIMIT 1",[user.id,uuid,source]);if(!r?.permit_key||r.route_kind==='owned-home')fail('No confirmed personal smuggler arrival is available for return.',403);const destination=tradeWorld(r.source_world||'lobby');if(!destination||destination===source)fail('The recorded return route requires review.');return{ok:true,source,destination,expiresAt:clock()+5000,smuggler:true};} + const owned=routeBindings&&homeRoutes?createOwnedSmugglerPassages(bank,homeRoutes,{resolve,clock,price:smugglerFareMinor,ledger,expire,readyForTravel,authorityForStore}):{}; + return{quote,quoteSmuggler,board,arrive,expire,checkTravel,smugglerReturn,bountyClaim,openTravel,...owned}; } export function createGuildQuestReceipts(db,bank,keys,{clock=Date.now}={}){ const authorize=metric=>async(_actor,p)=>{const row=await bank.first("SELECT * FROM pb_guild_passages WHERE id=? AND state='arrived' AND NOT EXISTS(SELECT 1 FROM pb_smuggler_passages s WHERE s.id=pb_guild_passages.id)",[p.eventId]);return !!row&&row.actor_id===p.accountId&&row.minecraft_uuid===p.minecraftUuid&&p.metric===metric&&p.quantity===1&&p.occurredAt===Number(row.arrived_at)&&p.reference===(metric==='guild-travel'?'guild:':'guild-route:')+row.id;}; @@ -79,17 +126,22 @@ export function createGuildQuestReceipts(db,bank,keys,{clock=Date.now}={}){ return async(user,row)=>{for(const [service,metric,prefix]of [[personal,'guild-travel','guild:'],[pol,'pol-verified-route','guild-route:']])if(service)await service.record(user,{eventId:row.id,accountId:user.id,minecraftUuid:row.minecraft_uuid,seasonId:'S01',metric,quantity:1,occurredAt:Number(row.arrived_at),reference:prefix+row.id});}; } export function createGameGuildAPI(db,bank,keys,settings={},dependencies={}){ - const resolve=dependencies.resolve||(async(uuid)=>{const rows=await db.query("SELECT a.id,a.username,a.role,c.faction,c.version,h.key_id keyId FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id JOIN site_character_choices c ON c.user_id=a.id AND c.minecraft_uuid=l.minecraft_uuid JOIN jarvis_house_selections h ON h.account_id=a.id AND h.minecraft_uuid=l.minecraft_uuid AND h.version=c.version AND h.faction=c.faction JOIN organisation_keys k ON k.id=h.key_id AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000) WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[uuid]);return rows.length===1?{...rows[0],version:Number(rows[0].version)}:null;}); + const resolve=dependencies.resolve||(async(uuid,store=db)=>{const rows=await store.query("SELECT a.id,a.username,a.role,c.faction,c.version,h.key_id keyId FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id JOIN site_character_choices c ON c.user_id=a.id AND c.minecraft_uuid=l.minecraft_uuid JOIN jarvis_house_selections h ON h.account_id=a.id AND h.minecraft_uuid=l.minecraft_uuid AND h.version=c.version AND h.faction=c.faction JOIN organisation_keys k ON k.id=h.key_id AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000) WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[uuid]);return rows.length===1?{...rows[0],version:Number(rows[0].version)}:null;}); const tradePolicy=db?.worldTradeEnabled&&bank?createBankTradePolicy(db,bank):null; const allowJourney=async(source,destination,tx,lock)=>{if(!tradePolicy)return true;const policy=await tradePolicy(tx,Date.now(),lock);return ![source,destination].some(w=>policy[tradeWorld(w)]?.embargoUntil>Date.now());}; - const service=dependencies.service||(bank?createGuildService(bank,{resolve,allowJourney,surcharge:now=>currentGuildSurcharge(db,now),discount:(house,now)=>currentGuildDiscount(db,house,now),allowArrakis:async(house,user)=>await hasImperialPassage(db,house)||await hasOrganisationPassage(db,user),authority:createPostbankAuthority(db,{bank}),fareMinor:Number(settings.GUILD_FARE_MINOR||10000),recordArrival:createGuildQuestReceipts(db,bank,keys),allowSmuggling:(user,uuid,now)=>activeSmugglerPermit(db,keys,user,uuid,now),smugglerFareMinor:Number(settings.SMUGGLER_FARE_MINOR||settings.GUILD_FARE_MINOR||10000),prologueReady:async(user,uuid)=>(await housePrologueState(db,keys,user,uuid)).ready,subsidies:db?.guildSubsidyEnabled?createGuildSubsidies(bank,{verify:(pool,now)=>verifyGuildSubsidy(db,pool,now)}):null}):null); + const service=dependencies.service||(bank?createGuildService(bank,{resolve,allowJourney,clock:dependencies.clock||Date.now,routeBindings:bank.guildRouteBindingsEnabled===true,authorityForStore:reader=>createPostbankAuthority(reader,{bank}),homeRoutes:db?.transaction?createOwnedSmugglerRoutes(db,{resolve,clock:dependencies.clock||Date.now}):null,surcharge:now=>currentGuildSurcharge(db,now),discount:(house,now)=>currentGuildDiscount(db,house,now),allowArrakis:async(house,user)=>await hasImperialPassage(db,house)||await hasOrganisationPassage(db,user),authority:createPostbankAuthority(db,{bank}),fareMinor:Number(settings.GUILD_FARE_MINOR||10000),openTravel:settings.GUILD_OPEN_TRAVEL==='true',holdingOnWorld:createNativeHoldingCheck(db),recordArrival:createGuildQuestReceipts(db,bank,keys),allowSmuggling:(user,uuid,now)=>activeSmugglerPermit(db,keys,user,uuid,now),smugglerFareMinor:Number(settings.SMUGGLER_FARE_MINOR||settings.GUILD_FARE_MINOR||10000),prologueReady:async(user,uuid)=>(await housePrologueState(db,keys,user,uuid)).ready,subsidies:db?.guildSubsidyEnabled?createGuildSubsidies(bank,{verify:(pool,now)=>verifyGuildSubsidy(db,pool,now)}):null}):null); return async request=>{ if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401); if(request.method!=='POST'||new URL(request.url).search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return json({message:'A JSON Guild action is required.'},400); let b;const reader=request.body?.getReader();if(!reader)return json({message:'Guild action required'},400);try{let bytes=0;const chunks=[];while(true){const {done,value}=await reader.read();if(done)break;bytes+=value.byteLength;if(bytes>2048){await reader.cancel();return json({message:'Request too large'},413);}chunks.push(value);}b=JSON.parse(Buffer.concat(chunks).toString());}catch{return json({message:'Invalid Guild action'},400);}finally{reader.releaseLock();} - const fields={smuggler_return:['action','uuid','sourceWorld'],smuggler_quote:['action','uuid','sourceWorld'],smuggler_board:['action','uuid','requestId','keyId','version','fareMinor','sourceWorld','destination'],travel_check:['action','uuid','sourceWorld','destination'],quote:['action','uuid',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[])],board:['action','uuid','requestId','keyId','version','fareMinor',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[]),...(Object.hasOwn(b||{},'destination')?['destination']:[])],arrive:['action','uuid','server'],expire:['action']}[b?.action]; - if((Object.hasOwn(b||{},'sourceWorld')&&!tradeWorld(b.sourceWorld))||b?.action==='travel_check'&&b.destination!=='lobby'||!fields||Object.keys(b).length!==fields.length||fields.some(f=>!Object.hasOwn(b,f))||b.action!=='expire'&&!validUuid(b.uuid)||['board','smuggler_board'].includes(b.action)&&(!validUuid(b.requestId)||!validUuid(b.keyId)||!Number.isSafeInteger(b.version)||b.version<1||!Number.isSafeInteger(b.fareMinor)||b.fareMinor<1||Object.hasOwn(b,'destination')&&!Object.values(routes).includes(b.destination))||b.action==='arrive'&&!Object.values(routes).includes(b.server))return json({message:'Invalid Guild fields'},400); + if(typeof b?.action==='string'&&b.action.startsWith('home_')){ + if(!validOwnedSmugglerRequest(b))return json({message:'Invalid Home Block passage fields'},400); + if(!service||typeof service[b.action]!=='function')return json({message:'Home Block navigation is unavailable.'},503); + try{const result=await service[b.action](b);return json(result,result.needsReview?409:200);}catch(error){return json({message:error instanceof BankError?error.message:'The passage could not be confirmed. Retry the original reference.'},error instanceof BankError?error.status||409:503);} + } + const fields={smuggler_return:['action','uuid','sourceWorld'],smuggler_quote:['action','uuid','sourceWorld'],smuggler_board:['action','uuid','requestId','keyId','version','fareMinor','sourceWorld','destination'],travel_check:['action','uuid','sourceWorld','destination'],quote:['action','uuid',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[])],board:['action','uuid','requestId','keyId','version','fareMinor',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[]),...(Object.hasOwn(b||{},'destination')?['destination']:[])],arrive:['action','uuid','server'],bounty_claim:['action','uuid','victim','requestId','server'],expire:['action']}[b?.action]; + if((Object.hasOwn(b||{},'sourceWorld')&&!tradeWorld(b.sourceWorld))||b?.action==='travel_check'&&b.destination!=='lobby'||!fields||Object.keys(b).length!==fields.length||fields.some(f=>!Object.hasOwn(b,f))||b.action!=='expire'&&!validUuid(b.uuid)||['board','smuggler_board'].includes(b.action)&&(!validUuid(b.requestId)||!validUuid(b.keyId)||!Number.isSafeInteger(b.version)||b.version<1||!Number.isSafeInteger(b.fareMinor)||b.fareMinor<(b.action==='board'&&service?.openTravel?0:1)||Object.hasOwn(b,'destination')&&!Object.values(routes).includes(b.destination))||b.action==='arrive'&&!Object.values(routes).includes(b.server)||b.action==='bounty_claim'&&(!validUuid(b.victim)||!validUuid(b.requestId)||b.victim===b.uuid||!Object.values(routes).includes(b.server)))return json({message:'Invalid Guild fields'},400); if(!service)return json({message:'The central bank is unavailable.'},503); - try{return json(b.action==='smuggler_return'?await service.smugglerReturn(b.uuid,b.sourceWorld):b.action==='smuggler_quote'?await service.quoteSmuggler(b.uuid,b.sourceWorld):b.action==='smuggler_board'?await service.board(b,true):b.action==='quote'?await service.quote(b.uuid,b.sourceWorld):b.action==='travel_check'?await service.checkTravel(b.uuid,b.sourceWorld,b.destination):b.action==='board'?await service.board(b):b.action==='arrive'?await service.arrive(b.uuid,b.server):{ok:true,expired:await service.expire()});}catch(e){return json({message:e instanceof BankError?e.message:'The Guild could not confirm this passage. Retry the same reference.'},e instanceof BankError?e.status||409:503);} + try{return json(b.action==='smuggler_return'?await service.smugglerReturn(b.uuid,b.sourceWorld):b.action==='smuggler_quote'?await service.quoteSmuggler(b.uuid,b.sourceWorld):b.action==='smuggler_board'?await service.board(b,true):b.action==='quote'?await service.quote(b.uuid,b.sourceWorld):b.action==='travel_check'?await service.checkTravel(b.uuid,b.sourceWorld,b.destination):b.action==='board'?await service.board(b):b.action==='arrive'?await service.arrive(b.uuid,b.server):b.action==='bounty_claim'?await service.bountyClaim({killer:b.uuid,victim:b.victim,requestId:b.requestId,server:b.server}):{ok:true,expired:await service.expire()});}catch(e){return json({message:e instanceof BankError?e.message:'The Guild could not confirm this passage. Retry the same reference.'},e instanceof BankError?e.status||409:503);} }; } diff --git a/website/node/game-quest-events.mjs b/website/node/game-quest-events.mjs index 85cf8f4a..89378847 100644 --- a/website/node/game-quest-events.mjs +++ b/website/node/game-quest-events.mjs @@ -20,7 +20,7 @@ const husbandry=Object.freeze(Object.fromEntries([...FREMEN_HUSBANDRY_TASKS,...F metrics.smuggler_delivery=SMUGGLER_DELIVERY_METRIC; for(const task of POL_SUPPLY_TASKS)metrics[task.kind]=task.metric; metrics.bounty_accept='pol-bounty-accepted';metrics.bounty_complete='pol-bounty-completed'; -const flight={flight_spice:['arrakis','NORMAL'],flight_refined:['arrakis','NORMAL'],flight_contaminated:['arrakis','NORMAL'],flight_debris:['giedi-prime','NETHER'],flight_scrap:['giedi-prime','NETHER'],flight_gold:['giedi-prime','NETHER'],flight_netherite:['giedi-prime','NETHER'],flight_membrane:['caladan','NORMAL'],flight_iron:['kaitain','NORMAL'],flight_diamond:['sigma-draconis-iv','NORMAL'],flight_crafted:['arrakis','NORMAL'],flight_elytra_acquired:null}; +const flight={flight_spice:['arrakis','NORMAL'],flight_refined:['arrakis','NORMAL'],flight_contaminated:['arrakis','NORMAL'],flight_debris:['giedi-prime','NETHER'],flight_scrap:['giedi-prime','NETHER'],flight_gold:['giedi-prime','NETHER'],flight_netherite:['giedi-prime','NETHER'],flight_membrane:['caladan','NORMAL'],flight_iron:['kaitain','NORMAL'],flight_diamond:['sigma-draconis-iv','NORMAL'],flight_crafted:['arrakis','NORMAL'],flight_elytra_acquired:null,flight_merged:null}; for(const kind of Object.keys(flight))metrics[kind]=kind.replaceAll('_','-'); export function createGameQuestEventsAPI(db,keys,settings,{clock=Date.now,events:provided=null,starter=null,research=null,cargo=null}={}){ const producer=Object.freeze({source:'native-quest-observation'}); @@ -45,6 +45,7 @@ export function createGameQuestEventsAPI(db,keys,settings,{clock=Date.now,events if(!input||Array.isArray(input)||Object.keys(input).length!==fields.length||fields.some(f=>!Object.hasOwn(input,f))||!validUuid(input.eventId)||!validUuid(input.uuid)||!Object.hasOwn(metrics,input.kind)||!servers.has(input.server)||!isFlight&&!supply&&input.kind!=='citizen_introduction'&&input.kind!=='house_mentor_intro'&&!(input.kind==='smuggler_introduction'&&input.server==='lobby')&&(input.server==='lobby'||input.kind!=='equipment_use'&&input.server!=='arrakis')||!Number.isSafeInteger(input.occurredAt)||input.occurredAt<=0||input.occurredAt>clock()+30000)return json({message:'Invalid observation fields'},400); if(input.kind==='house_mentor_intro'&&(input.server!=='lobby'||!Object.values(HOUSE_MENTOR_CONTACTS).includes(input.npcRole)))return json({message:'Meet your matching House Mentat in the Guild lobby.'},400); if(isFlight&&(!Number.isSafeInteger(input.quantity)||input.quantity<1||input.quantity>64||!['NORMAL','NETHER','THE_END'].includes(input.dimension)||flight[input.kind]&&(flight[input.kind][0]!==input.server||flight[input.kind][1]!==input.dimension)||input.kind==='flight_elytra_acquired'&&(!['end','exchange'].includes(input.source)||input.source==='end'&&input.dimension!=='THE_END')))return json({message:'Invalid flight objective location'},400); + if(input.kind==='flight_merged'&&(input.quantity!==1||input.dimension!=='NORMAL'||input.server==='lobby'))return json({message:'A single completed physical armour merge on a shared-profile planet is required.'},400); if(input.kind==='spice_harvest'&&(!Number.isSafeInteger(input.quantity)||input.quantity<1||input.quantity>64))return json({message:'Invalid harvest quantity'},400); const turnin=FREMEN_TURNIN_TRACKS.find(t=>t.kind===input.kind); if(isHusbandry&&(!Number.isSafeInteger(input.quantity)||input.quantity<1||(turnin?input.quantity!==turnin.units:input.quantity>(['husbandry_leather','husbandry_collect_egg','husbandry_collect_hide','husbandry_hide_paste','husbandry_spice_paste','husbandry_spice_bread','husbandry_spice_cake'].includes(input.kind)?64:1))))return json({message:'Invalid husbandry observation quantity'},400); diff --git a/website/node/game-quests.mjs b/website/node/game-quests.mjs index f7b7fb96..caa0d382 100644 --- a/website/node/game-quests.mjs +++ b/website/node/game-quests.mjs @@ -27,6 +27,18 @@ export function createGameQuestsAPI(db,settings,{personal=null,pol=null,starter= let input; try{const chunks=[];let size=0;while(true){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4096){await reader.cancel();return json({message:'Quest request too large.'},413);}chunks.push(value);}input=JSON.parse(Buffer.concat(chunks).toString('utf8'));} catch{return json({message:'Invalid quest action.'},400);}finally{reader.releaseLock();} + if(input?.action==='login_settle'){ + if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!['action','uuid'].includes(k))||!validUuid(input.uuid))return json({message:'A player UUID is required.'},400); + try{ + const user=await resolve(input.uuid);if(!user)return json({message:'Link an active personal Minecraft account first.'},403); + const actor={...user,revalidate:()=>resolve(input.uuid)},settled=[];let failed=0; + for(const [kind,runtime] of [['personal',personal],['pol',pol]]){ + if(!runtime?.quests?.settleCompleted)continue; + try{await runtime.collect?.(actor);const result=await runtime.quests.settleCompleted(actor);for(const row of result.settled)settled.push({...row,kind});failed+=result.failed;if(result.settled.length)await runtime.quests.processCompletions?.({accountId:actor.id});}catch{failed++;} + } + return json({ok:true,settled,failed}); + }catch{return json({message:'The quest payout was not confirmed. It will be retried on your next login.'},503);} + } const refine=input?.action==='prepare_refine'; const equipment=input?.action==='prepare_starter'; const meatTurnin=input?.action==='prepare_husbandry_turnin',supply=input?.action==='prepare_pol_supply',dossier=input?.action==='dossier_step',cargoAction=input?.action==='prepare_pol_cargo',cargoPartner=input?.action==='cargo_partner'; diff --git a/website/node/guild-passage-ledger.mjs b/website/node/guild-passage-ledger.mjs new file mode 100644 index 00000000..5a59dfa0 --- /dev/null +++ b/website/node/guild-passage-ledger.mjs @@ -0,0 +1,43 @@ +import {PostbankPayments} from './postbank-payments.mjs'; +import {BankError} from './postbank-service.mjs'; +import {canDebitAccount} from './postbank-authorisations.mjs'; +import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs'; +import {creditID} from './postbank-credit-ledger.mjs'; +import {postPayrollIssue} from './postbank-payroll-issuer.mjs'; +const accountSQL=`SELECT a.*,c.entity_id,e.external_key,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id`; +const fail=(message,status=409)=>{throw new BankError(message,status);}; +// Shared by ordinary Guild, Esmar and owned-home routes. One reservation and ledger. +export function createGuildPassageLedger(bank,{authority,clock=Date.now,subsidies=null}){ + const payments=new PostbankPayments(bank,authority,{clock}); + async function funds(tx,user,amount,lock=false,authorise=authority){const context=await authorise(user,{bank:tx});return(await tx.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.system_key IS NULL ORDER BY a.id"+(lock?' FOR UPDATE':''),[user.id])).find(a=>ordinaryPaymentAccount(a)&&canDebitAccount(context,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(amount));} + async function release(tx,r){if(r.state!=='pending')return;const a=await tx.first('SELECT id,reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[r.source_id]);if(!a||BigInt(a.reserved_minor)String(a.id)===String(r.source_id)),target=accounts.find(a=>String(a.id)===String(r.target_id)); + if(!ordinaryPaymentAccount(source)||!target||target.system_key!=='sys_game_treasury'||target.state!=='active'||BigInt(source.reserved_minor)2500000n)fail('Invalid bounty amount.',400); + const source=(await tx.query(accountSQL+" WHERE a.system_key='sys_payroll_po' FOR UPDATE"))[0];if(!source||source.type_code!=='979'||source.state!=='active')fail('The P&O issuer is unavailable.',503); + const target=(await tx.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.system_key IS NULL ORDER BY a.id FOR UPDATE",[hunter.id])).find(ordinaryPaymentAccount);if(!target)fail('The hunter needs an active central bank account to receive a bounty.'); + const orderId=creditID('travel-bounty:'+id),fingerprint=(await import('node:crypto')).createHash('sha256').update(JSON.stringify(['travel-bounty',id,hunter.id,String(amount),String(target.id)])).digest('hex'); + await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'guild','queued',?)",[orderId,hunter.id,source.id,target.id,fingerprint,String(amount),memo.slice(0,140),clock()]); + await postPayrollIssue(tx,{id:orderId,actor_id:hunter.id,amount_minor:String(amount)},source,target,{now:clock()}); + } + return {funds,release,reserve,settle,payout}; +} diff --git a/website/node/guild-route-bindings.mjs b/website/node/guild-route-bindings.mjs new file mode 100644 index 00000000..b0380bd4 --- /dev/null +++ b/website/node/guild-route-bindings.mjs @@ -0,0 +1,3 @@ +// Route receipt metadata only; organisation ownership stays in original deeds. +export const GUILD_ROUTE_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_guild_route_bindings(id CHAR(36) PRIMARY KEY,route_kind VARCHAR(16) NOT NULL,source_world VARCHAR(32) NOT NULL,binding_json TEXT NULL,delivered_at BIGINT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; +export const passageView=r=>({requestId:r.id,destination:r.destination,state:r.state,fareMinor:Number(r.fare_minor),expiresAt:Number(r.expires_at)}); diff --git a/website/node/lobby-account.mjs b/website/node/lobby-account.mjs new file mode 100644 index 00000000..af846a22 --- /dev/null +++ b/website/node/lobby-account.mjs @@ -0,0 +1,99 @@ +import {randomBytes,randomUUID,createHash,createCipheriv,createDecipheriv,scrypt as rawScrypt,timingSafeEqual} from 'node:crypto'; +import {promisify} from 'node:util'; +import {validUuid} from './game-link.mjs'; +import {nativeSyncMutation} from './native-sync-outbox.mjs'; +const scrypt=promisify(rawScrypt),digest=v=>createHash('sha256').update(v).digest('hex'); +const fault=(message,status=409)=>Object.assign(Error(message),{status}); +export const LOBBY_ACCOUNT_SCHEMA=`CREATE TABLE IF NOT EXISTS site_lobby_account_provisions ( + minecraft_uuid CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,minecraft_name VARCHAR(32) NOT NULL, + account_id CHAR(36) NOT NULL,credential_hash CHAR(64) NOT NULL,ciphertext TEXT, + created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,delivered_at BIGINT, + FOREIGN KEY(account_id) REFERENCES site_accounts(id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; +export const LOBBY_PLACEHOLDER_EMAIL='no_reply@dunerealms.com'; +const ttl=7*86400000; +function seal(password,key,binding){ + const iv=randomBytes(12),cipher=createCipheriv('aes-256-gcm',key,iv);cipher.setAAD(Buffer.from(binding)); + const data=Buffer.concat([cipher.update(password,'utf8'),cipher.final()]); + return [iv,cipher.getAuthTag(),data].map(x=>x.toString('base64url')).join('.'); +} +function unseal(value,key,binding){ + const [iv,tag,data]=value.split('.').map(x=>Buffer.from(x,'base64url')); + const cipher=createDecipheriv('aes-256-gcm',key,iv);cipher.setAAD(Buffer.from(binding));cipher.setAuthTag(tag); + return Buffer.concat([cipher.update(data),cipher.final()]).toString('utf8'); +} +export function createLobbyAccountService(db,{encryptionKey,clock=Date.now,onProvisioned=async()=>{}}={}){ + if(!/^[a-f0-9]{64}$/.test(encryptionKey||''))throw Error('Lobby account encryption key is unavailable'); + const key=Buffer.from(encryptionKey,'hex'); + async function execute(input){ + if(input.schema!==1||!validUuid(input.uuid)||!validUuid(input.requestId)||!['provision','ack'].includes(input.action)||input.action==='provision'&&!/^[A-Za-z0-9_.-]{1,32}$/.test(input.name||''))throw fault('Invalid lobby account request',400); + const {uuid,requestId,action}=input,now=clock(),binding=uuid+':'+requestId; + const base={ok:true,schema:1,action,requestId,uuid}; + // Hash before entering the transaction; no password is logged or put in audit details. + const password=action==='provision'?randomBytes(24).toString('base64url'):null; + const salt=password?randomBytes(16).toString('hex'):null; + const hash=password?(await scrypt(password,salt,64)).toString('hex'):null; + let readyId; + const result=await db.transaction(async tx=>{ + const prior=await tx.first('SELECT * FROM site_lobby_account_provisions WHERE minecraft_uuid=? FOR UPDATE',[uuid]); + if(prior){ + if(prior.request_id!==requestId||action==='provision'&&prior.minecraft_name!==input.name)throw fault('The original provisioning reference is required'); + const account=await tx.first('SELECT a.id,a.username,a.password_hash,l.minecraft_uuid FROM site_accounts a LEFT JOIN site_game_links l ON l.user_id=a.id WHERE a.id=? FOR UPDATE',[prior.account_id]); + if(!account||account.minecraft_uuid!==uuid)throw fault('The account link needs manual review'); + if(action==='ack'){ + await tx.query('UPDATE site_lobby_account_provisions SET ciphertext=NULL,delivered_at=COALESCE(delivered_at,?) WHERE minecraft_uuid=? AND request_id=?',[now,uuid,requestId]); + return {...base,state:'delivered'}; + } + if(prior.delivered_at!==null)return {...base,state:'delivered',username:account.username}; + if(digest(account.password_hash)!==prior.credential_hash||now>=Number(prior.expires_at)||!prior.ciphertext){ + await tx.query('UPDATE site_lobby_account_provisions SET ciphertext=NULL WHERE minecraft_uuid=?',[uuid]); + return {...base,state:'recovery_required',username:account.username}; + } + readyId=account.id; + return {...base,state:'created',username:account.username,password:unseal(prior.ciphertext,key,binding)}; + } + if(action==='ack')throw fault('No matching provisioning reference'); + const reused=await tx.first('SELECT minecraft_uuid FROM site_lobby_account_provisions WHERE request_id=? FOR UPDATE',[requestId]); + if(reused)throw fault('Provisioning reference conflict'); + const linked=await tx.first('SELECT a.id,a.username,a.password_hash,a.role FROM site_game_links l JOIN site_accounts a ON a.id=l.user_id WHERE l.minecraft_uuid=? FOR UPDATE',[uuid]); + if(linked)return {...base,state:'existing',username:linked.username}; + if(await tx.first('SELECT minecraft_uuid FROM site_game_identities WHERE minecraft_uuid=? FOR UPDATE',[uuid]))return {...base,state:'manual_link_required',username:''}; + let username=input.name.toLowerCase().replace(/[^a-z0-9_]/g,'_');if(username.length<3)username='mc_'+username; + if(await tx.first('SELECT id FROM site_accounts WHERE username=? FOR UPDATE',[username]))username=username.slice(0,15)+'_'+uuid.replaceAll('-','').slice(0,16); + if(await tx.first('SELECT id FROM site_accounts WHERE username=? FOR UPDATE',[username]))throw fault('Website username needs manual review'); + const id=randomUUID(); + await tx.query('INSERT INTO site_accounts(id,username,display_name,password_salt,password_hash,role,created_at) VALUES(?,?,?,?,?,?,?)',[id,username,input.name,salt,hash,'user',now]); + await tx.query('INSERT INTO player_profiles(user_id,display_name,minecraft_name,discord_name,created_at,updated_at) VALUES(?,?,?,?,?,?)',[id,input.name,input.name,'',now,now]); + await tx.query('INSERT INTO site_profiles(user_id,bio,public_info,socials_json,updated_at) VALUES(?,?,?,?,?)',[id,'DuneRealms player '+input.name+'.','','{}',now]); + await tx.query('INSERT INTO site_game_links(user_id,minecraft_uuid,minecraft_name,linked_at) VALUES(?,?,?,?)',[id,uuid,input.name,now]); + await tx.query('INSERT INTO site_game_identities(minecraft_uuid,first_linked_at,last_name) VALUES(?,?,?)',[uuid,now,input.name]); + const sync=nativeSyncMutation(now);await tx.query(sync.sql,sync.values); + await tx.query('INSERT INTO site_contact_emails(user_id,address,verified_at) VALUES(?,?,NULL)',[id,LOBBY_PLACEHOLDER_EMAIL]); + await tx.query('INSERT INTO site_first_login(user_id,password_changed,created_at) VALUES(?,0,?)',[id,now]); + await tx.query('INSERT INTO site_lobby_account_provisions(minecraft_uuid,request_id,minecraft_name,account_id,credential_hash,ciphertext,created_at,expires_at,delivered_at) VALUES(?,?,?,?,?,?,?,?,NULL)',[uuid,requestId,input.name,id,digest(hash),seal(password,key,binding),now,now+ttl]); + await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),id,'lobby-account-provisioned',JSON.stringify({requestId,uuid,source:'lobby',ageDeclared:false,placeholderEmail:true}),now]); + readyId=id; + return {...base,state:'created',username,password}; + }); + // The existing bank has its own transaction. An outage retains this exact + // provisioning reference and encrypted password; retry never creates a user + // twice or sends credentials before the zero-balance account is ready. + if(readyId)await onProvisioned({id:readyId,username:result.username,uuid}); + return result; + } + return {execute}; +} +export function createLobbyAccountAPI(db,settings={},deps={}){ + const enabled=settings.LOBBY_ACCOUNT_ENABLED==='true'; + const token=settings.LOBBY_ACCOUNT_TOKEN||'',validToken=/^[A-Za-z0-9_-]{43,128}$/.test(token); + const service=enabled&&validToken?deps.service||createLobbyAccountService(db,{encryptionKey:settings.LOBBY_ACCOUNT_ENCRYPTION_KEY,onProvisioned:deps.onProvisioned}):null; + const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store','Pragma':'no-cache'}}); + return async request=>{ + const auth=request.headers.get('authorization')||''; + if(!service||!timingSafeEqual(Buffer.from(digest(auth)),Buffer.from(digest('Bearer '+token))))return reply({message:'Unauthorized'},401); + if(request.method!=='POST'||new URL(request.url).search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'Invalid lobby account request'},400); + let b;try{const reader=request.body.getReader(),parts=[];let bytes=0;try{while(true){const {done,value}=await reader.read();if(done)break;bytes+=value.length;if(bytes>1024){await reader.cancel();return reply({message:'Request too large'},413);}parts.push(value);}}finally{reader.releaseLock();}b=JSON.parse(Buffer.concat(parts).toString());}catch{return reply({message:'Invalid lobby account request'},400);} + if(!b||Array.isArray(b)||Object.keys(b).sort().join(',')!==(b.action==='ack'?'action,requestId,schema,uuid':'action,name,requestId,schema,uuid'))return reply({message:'Invalid lobby account fields'},400); + try{return reply(await service.execute(b));}catch(e){return reply({message:e.status?e.message:'Account setup is temporarily unavailable. Retry the original reference.'},e.status||503);} + }; +} diff --git a/website/node/lobby-starting-budget.mjs b/website/node/lobby-starting-budget.mjs new file mode 100644 index 00000000..492a9cb3 --- /dev/null +++ b/website/node/lobby-starting-budget.mjs @@ -0,0 +1,43 @@ +import {createHash,randomUUID} from 'node:crypto'; +import {validUuid} from './game-link.mjs'; +import {ensureBasicCurrentAccount} from './postbank-payroll-accounts.mjs'; +import {REGISTRY_ACTOR} from './postbank-registry.mjs'; + +export const LOBBY_STARTING_MINOR=100000n; +export function lobbyBudgetId(uuid){ + if(!validUuid(uuid))throw Error('A verified Minecraft identity is required'); + const h=createHash('sha256').update('lobby-starting-budget-v1:'+uuid).digest('hex'); + return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32); +} +// Only the first-join provisioning callback calls this policy. No caller-chosen +// amount, source account or recipient account is admitted by the game endpoint. +export async function provisionLobbyStartingBank(bank,recipient,{clock=Date.now}={}){ + if(!validUuid(recipient?.id)||!validUuid(recipient?.uuid)||!recipient.username)throw Error('Verified first-join account required'); + return bank.transaction(async tx=>{ + const ready=await ensureBasicCurrentAccount(tx,recipient,{source:'lobby',now:clock()}); + const issuer=await tx.first("SELECT id FROM pb_accounts WHERE system_key='sys_bank_capital_issuer'"); + if(!issuer)throw Error('The starting-budget reserve is unavailable'); + const rows=await tx.query('SELECT a.*,c.entity_id,e.external_key,e.kind,e.active AS entity_active,p.state AS package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[issuer.id,ready.accountId]); + const source=rows.find(a=>String(a.id)===String(issuer.id)),target=rows.find(a=>String(a.id)===ready.accountId); + if(!source||source.system_key!=='sys_bank_capital_issuer'||source.state!=='active'||source.type_code!=='979'||!target||target.system_key||target.state!=='active'||target.package_state!=='active'||target.kind!=='person'||target.external_key!==recipient.id||Number(target.entity_active)!==1||!['102','108'].includes(target.type_code))throw Error('The starting-budget account requires review'); + const id=lobbyBudgetId(recipient.uuid),fingerprint=createHash('sha256').update(JSON.stringify(['lobby-starting-budget-v1',recipient.uuid,recipient.id,String(source.id),String(target.id),String(LOBBY_STARTING_MINOR)])).digest('hex'); + const prior=await tx.first('SELECT * FROM pb_orders WHERE id=? FOR UPDATE',[id]); + if(prior){ + if(prior.fingerprint!==fingerprint||prior.state!=='posted'||prior.mode!=='grant'||String(prior.amount_minor)!==String(LOBBY_STARTING_MINOR)||String(prior.source_id)!==String(source.id)||String(prior.target_id)!==String(target.id))throw Error('The original starting-budget receipt requires review'); + const entries=await tx.query('SELECT account_id,amount_minor FROM pb_entries WHERE order_id=? ORDER BY account_id',[id]); + if(entries.length!==2||!entries.some(e=>String(e.account_id)===String(source.id)&&BigInt(e.amount_minor)===-LOBBY_STARTING_MINOR)||!entries.some(e=>String(e.account_id)===String(target.id)&&BigInt(e.amount_minor)===LOBBY_STARTING_MINOR))throw Error('The starting-budget ledger requires review'); + return {accountId:ready.accountId,paymentId:id,replayed:true}; + } + const debit=BigInt(source.balance_minor)-LOBBY_STARTING_MINOR,credit=BigInt(target.balance_minor)+LOBBY_STARTING_MINOR; + // The existing capital issuer is the bank's issuance account. It may have a + // negative reserve balance, using the same balanced grant policy as bank grants. + if(debit< -9223372036854775808n||credit>9223372036854775807n)throw Error('Starting-budget balance limit reached'); + const now=clock(); + await tx.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at,posted_at) VALUES(?,?,?,?,?,?,?,'grant','posted',?,?)",[id,REGISTRY_ACTOR,source.id,target.id,fingerprint,String(LOBBY_STARTING_MINOR),'Lobby starting budget · 1000 DM',now,now]); + await tx.query('UPDATE pb_accounts SET balance_minor=? WHERE id=?',[String(debit),source.id]); + await tx.query('UPDATE pb_accounts SET balance_minor=? WHERE id=?',[String(credit),target.id]); + for(const [a,amount,balance] of [[source,-LOBBY_STARTING_MINOR,debit],[target,LOBBY_STARTING_MINOR,credit]])await tx.query('INSERT INTO pb_entries(order_id,account_id,amount_minor,balance_after_minor,created_at) VALUES(?,?,?,?,?)',[id,a.id,String(amount),String(balance),now]); + await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),REGISTRY_ACTOR,'lobby_starting_budget',ready.entityId,JSON.stringify({paymentId:id,uuid:recipient.uuid,accountId:recipient.id,amountDM:'1000.00',policy:'lobby-starting-budget-v1'}),now]); + return {accountId:ready.accountId,paymentId:id,replayed:false}; + }); +} diff --git a/website/node/managed-game-permissions.json b/website/node/managed-game-permissions.json index 119e46b3..a7ab3a91 100644 --- a/website/node/managed-game-permissions.json +++ b/website/node/managed-game-permissions.json @@ -330,6 +330,42 @@ "label": "Visit lobby", "source": "DuneRealms central registered permission catalogue", "highRisk": false + }, + { + "node": "voicechat.listen", + "label": "Listen to nearby voice chat", + "source": "Simple Voice Chat 2.6.25 plugin.yml", + "highRisk": false + }, + { + "node": "voicechat.speak", + "label": "Speak in voice chat", + "source": "Simple Voice Chat 2.6.25 plugin.yml", + "highRisk": false + }, + { + "node": "voicechat.groups", + "label": "Use voice chat groups", + "source": "Simple Voice Chat 2.6.25 plugin.yml", + "highRisk": false + }, + { + "node": "dunestaff.fly", + "label": "Staff self flight", + "source": "DuneStaff explicit command or visibility check", + "highRisk": true + }, + { + "node": "dunestaff.vanish", + "label": "Staff self vanish", + "source": "DuneStaff explicit command or visibility check", + "highRisk": true + }, + { + "node": "dunestaff.vanish.see", + "label": "See vanished staff", + "source": "DuneStaff explicit command or visibility check", + "highRisk": true } ], "networkAdministratorRoles": [ @@ -350,7 +386,10 @@ "duneess.chat.faction": true, "duneess.chat.nearby": true, "duneess.chat.network": true, - "duneess.chat.team": true + "duneess.chat.team": true, + "voicechat.listen": true, + "voicechat.speak": true, + "voicechat.groups": true }, "scope": "network-global; local-only moderation requires a separate server-context design, not this global snapshot" }, diff --git a/website/node/organisation-default-policies.mjs b/website/node/organisation-default-policies.mjs index eccab264..2bd4b044 100644 --- a/website/node/organisation-default-policies.mjs +++ b/website/node/organisation-default-policies.mjs @@ -1,7 +1,7 @@ import {NODES} from './permissions.mjs'; import {ORGANISATION} from './organisation-model.mjs'; import {validatePolicyNodes} from './organisation-management.mjs'; -const staff=['web.menu.staffmanual','web.mail.internal.view']; +const staff=['web.menu.staffmanual','web.mail.internal.view','dunestaff.fly','dunestaff.vanish','dunestaff.vanish.see']; const branchNodes={ customer_support:['web.tickets.support','web.tickets.staff','web.menu.tickets','web.accounts.view','dune.tickets.staff','dune.staff.open','dune.staff.history'], sales_accounts:['web.tickets.sales','web.tickets.staff','web.menu.tickets','web.shop.support','web.accounts.view','web.bank.staff.view','web.bank.staff.clients'], diff --git a/website/node/organisation-runtime.mjs b/website/node/organisation-runtime.mjs index b844bfae..8d5a4061 100644 --- a/website/node/organisation-runtime.mjs +++ b/website/node/organisation-runtime.mjs @@ -7,7 +7,7 @@ const privileged=value=>{ const node=value.startsWith('cp.')?'web.'+value.slice(3):value; return /^web\.(accounts\.|ranks\.|servers\.|luckperms\.|tickets\.|bank\.staff\.|payroll\.|posts\.(edit|publish)|items\.manage|bans\.|forum\.(moderate|admin)|git\.admin|community\.manage|quests\.manage)/.test(node) ||/^dune\.(admin|staff\.|moderation\.|ban\.|unban\.|items\.give|tickets\.staff)/.test(node) - ||node.startsWith('duneprotect.')||/^dunelobby\.(admin|build)$/.test(node) + ||node.startsWith('dunestaff.')||node.startsWith('duneprotect.')||/^dunelobby\.(admin|build)$/.test(node) ||/^web\.menu\.(?:administration|staffmanual|permissions|servers|luckperms|bans|forum|items|posts|tickets)$/.test(node) ||/^web\.(?:shop\.support|bank\.projects\.approve|mail\.staff\.)/.test(node); }; diff --git a/website/node/owned-smuggler-passages.mjs b/website/node/owned-smuggler-passages.mjs new file mode 100644 index 00000000..7e5e4d29 --- /dev/null +++ b/website/node/owned-smuggler-passages.mjs @@ -0,0 +1,62 @@ +import {createHash} from 'node:crypto'; +import {BankError} from './postbank-service.mjs'; +import {passageView} from './guild-route-bindings.mjs'; +import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs'; +const fail=(message,status=409)=>{throw new BankError(message,status);}; +const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex'); +export function createOwnedSmugglerPassages(bank,routes,{resolve,clock,price,ledger,expire,readyForTravel,authorityForStore=null}){ + const reference=h=>({kind:h.kind,id:h.id,homeBlockId:h.homeBlockId,claimRevision:h.claimRevision}); + const home=h=>({kind:h.kind,id:h.id,homeBlockId:h.homeBlockId,revision:h.claimRevision,worldUuid:h.home.worldUuid,worldName:h.home.worldName,position:h.home.position}); + const ticket=(r,b)=>({ok:true,schema:1,...passageView(r),smuggler:true,paid:r.state==='arrived',...(r.state==='expired'?{cancelled:true}:{}),home:b.home}); + const identity=async uuid=>{const u=await resolve(uuid);if(!u)fail('Link an active character first.',403);return u;}; + const binding=input=>[input.uuid,input.sourceWorld,input.origin,input.target,input.originHomeBlockId,input.originRevision,input.targetHomeBlockId,input.targetRevision,input.keyId,input.version,input.fareMinor]; + async function lookup(tx,id,user,server=null,lock=false){ + const r=await tx.first('SELECT * FROM pb_guild_passages WHERE id=?'+(lock?' FOR UPDATE':''),[id]); + const marker=await tx.first("SELECT * FROM pb_guild_route_bindings WHERE id=? AND route_kind='owned-home'"+(lock?' FOR UPDATE':''),[id]); + if(!r||!marker||r.actor_id!==user.id||(user.uuid&&r.minecraft_uuid!==user.uuid)||(server&&r.destination!==tradeWorld(server)))fail('This Home Block passage is unavailable.',404); + return {r,marker,b:JSON.parse(marker.binding_json)}; + } + async function list(input){await expire();const user=await identity(input.uuid),result=await routes.list(user,input),ready=await readyForTravel(user,input.uuid);return {ok:true,schema:1,destinations:result.destinations.map(({home,...h})=>({...h,fareMinor:price,available:h.available&&ready,reason:!ready?'Complete your House Prologue first.':h.reason}))};} + async function quote(input){await expire();const user=await identity(input.uuid),ctx=await routes.quote(user,input);if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);return {ok:true,schema:1,origin:reference(ctx.origin),target:reference(ctx.target),keyId:user.keyId,version:user.version,fareMinor:price,affordable:!!await ledger.funds(bank,user,price),expiresAt:clock()+60000};} + async function board(input){ + await expire();const user=await identity(input.uuid),fingerprint=hash([user.id,...binding(input)]); + const prior=await bank.first('SELECT * FROM pb_guild_passages WHERE id=?',[input.requestId]); + if(prior){const saved=await lookup(bank,input.requestId,{...user,uuid:input.uuid});if(prior.fingerprint!==fingerprint)fail('This passage reference was already used.');return {...ticket(saved.r,saved.b),replayed:true};} + if(user.keyId!==input.keyId||user.version!==input.version||input.fareMinor!==price||input.confirmed!==true)fail('Your House key or smuggler fare changed. Reopen the Navigator.'); + if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403); + return routes.withLock(user,input,'board',async(ctx,fresh,reader)=>bank.transaction(async tx=>{ + const previous=await tx.first('SELECT * FROM pb_guild_passages WHERE id=? FOR UPDATE',[input.requestId]); + if(previous){const saved=await lookup(tx,input.requestId,{...fresh,uuid:input.uuid});if(previous.fingerprint!==fingerprint)fail('This passage reference was already used.');return {...ticket(saved.r,saved.b),replayed:true};} + if(fresh.keyId!==input.keyId||fresh.version!==input.version)fail('Your House key changed.',403); + const r=await ledger.reserve(tx,input,fresh,{price,fingerprint,destination:ctx.target.server,expiresAt:clock()+120000,permitKey:fresh.keyId,...(authorityForStore?{authorise:authorityForStore(reader)}:{})}); + const b={origin:reference(ctx.origin),target:reference(ctx.target),home:home(ctx.target)}; + await tx.query("INSERT INTO pb_guild_route_bindings(id,route_kind,source_world,binding_json,created_at) VALUES(?,'owned-home',?,?,?)",[r.id,input.sourceWorld,JSON.stringify(b),clock()]);return ticket(r,b); + })); + } + async function arrive(input){await expire();const user=await identity(input.uuid);const rows=await bank.query("SELECT p.* FROM pb_guild_passages p JOIN pb_guild_route_bindings b ON b.id=p.id AND b.route_kind='owned-home' WHERE p.actor_id=? AND p.minecraft_uuid=? AND p.destination=? AND (p.state='pending' OR p.state='arrived') AND b.delivered_at IS NULL ORDER BY p.created_at,p.id LIMIT 1",[user.id,input.uuid,tradeWorld(input.server)]);if(!rows.length)return {ok:true,schema:1,ticket:null};const saved=await lookup(bank,rows[0].id,{...user,uuid:input.uuid},input.server);return {ok:true,schema:1,ticket:ticket(saved.r,saved.b)};} + async function ready(input){ + await expire();const user=await identity(input.uuid),saved=await lookup(bank,input.requestId,{...user,uuid:input.uuid},input.server); + if(saved.r.state==='expired')return {ok:true,schema:1,requestId:input.requestId,state:'expired',paid:false,cancelled:true}; + if(saved.r.state==='pending'&&!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403); + const proof={uuid:input.uuid,target:saved.b.target,targetHomeBlockId:saved.b.home.homeBlockId,targetRevision:saved.b.home.revision}; + try{return await routes.withLock(user,proof,'ready',async(ctx,fresh,reader)=>bank.transaction(async tx=>{ + const current=await lookup(tx,input.requestId,{...fresh,uuid:input.uuid},input.server,true),r=current.r; + if(hash(home(ctx.target))!==hash(current.b.home))fail('The registered destination changed.'); + if(r.state==='arrived')return {...ticket(r,current.b),replayed:true}; + if(r.state!=='pending')return {ok:true,schema:1,requestId:r.id,state:r.state,cancelled:r.state==='expired',paid:false}; + if(Number(r.expires_at)<=clock()){await ledger.release(tx,r);return {ok:true,schema:1,requestId:r.id,state:'expired',paid:false,cancelled:true};} + if(fresh.keyId!==r.house_key||fresh.version!==Number(r.house_version))fail('Your House key changed.',403); + await ledger.settle(tx,r,fresh,true,authorityForStore?authorityForStore(reader):undefined);return ticket(r,current.b); + }));}catch(error){if(saved.r.state==='arrived'&&error instanceof BankError)return {ok:false,schema:1,requestId:input.requestId,state:'review',paid:true,needsReview:true,message:'Your paid passage needs destination review. Keep the original reference.'};throw error;} + } + async function delivered(input){ + const user=await identity(input.uuid);return bank.transaction(async tx=>{ + const {r,marker,b}=await lookup(tx,input.requestId,{...user,uuid:input.uuid},input.server,true),receipt=hash([input.requestId,input.arrivedAt,input.arrival]); + if(marker.delivered_at!=null){if(b.deliveryReceipt!==receipt)fail('Arrival receipt reference conflict.');return {ok:true,schema:1,requestId:r.id,delivered:true,replayed:true};} + const at=input.arrival?.position; + if(r.state!=='arrived'||input.arrival?.worldUuid!==b.home.worldUuid||!Number.isSafeInteger(input.arrivedAt)||input.arrivedAtclock()+10000||!at||!['x','y','z'].every(k=>Number.isFinite(at[k]))||['x','y','z'].reduce((n,k)=>n+(at[k]-b.home.position[k])**2,0)>9)fail('A matching native Home Block arrival is required.'); + b.deliveryReceipt=receipt;await tx.query('UPDATE pb_guild_route_bindings SET delivered_at=?,binding_json=? WHERE id=? AND delivered_at IS NULL',[input.arrivedAt,JSON.stringify(b),r.id]);await tx.query("UPDATE pb_guild_passages SET reported_at=? WHERE id=? AND state='arrived'",[clock(),r.id]);return {ok:true,schema:1,requestId:r.id,delivered:true}; + }); + } + return {home_list:list,home_quote:quote,home_board:board,home_arrive:arrive,home_ready:ready,home_delivered:delivered}; +} diff --git a/website/node/owned-smuggler-request.mjs b/website/node/owned-smuggler-request.mjs new file mode 100644 index 00000000..2e73145f --- /dev/null +++ b/website/node/owned-smuggler-request.mjs @@ -0,0 +1,14 @@ +import {validUuid} from './game-link.mjs'; +import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs'; +const exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join(',')===[...keys].sort().join(','); +const ref=v=>exact(v,['kind','id'])&&['clan','company'].includes(v.kind)&&validUuid(v.id); +const position=v=>exact(v,['x','y','z'])&&Object.values(v).every(Number.isFinite)&&Math.abs(v.x)<=29999980&&Math.abs(v.z)<=29999980&&v.y>=-64&&v.y<=320; +export function validOwnedSmugglerRequest(b){ + const fields={home_list:['origin','sourceWorld','sourceLocation'],home_quote:['origin','sourceWorld','sourceLocation','target'],home_board:['origin','sourceWorld','sourceLocation','target','requestId','keyId','version','fareMinor','confirmed','originHomeBlockId','originRevision','targetHomeBlockId','targetRevision'],home_arrive:['server'],home_ready:['server','requestId'],home_delivered:['server','requestId','arrivedAt','arrival']}[b?.action]; + if(!fields||!exact(b,['action','uuid',...fields])||!validUuid(b.uuid))return false; + if(fields.includes('origin')&&(!ref(b.origin)||tradeWorld(b.sourceWorld)!==b.sourceWorld||!exact(b.sourceLocation,['worldUuid','position','observedAt'])||!validUuid(b.sourceLocation.worldUuid)||!position(b.sourceLocation.position)||!Number.isSafeInteger(b.sourceLocation.observedAt)))return false; + if(fields.includes('target')&&!ref(b.target)||fields.includes('server')&&(!tradeWorld(b.server)||tradeWorld(b.server)!==b.server||b.server==='lobby')||fields.includes('requestId')&&!validUuid(b.requestId))return false; + if(b.action==='home_board'&&(!validUuid(b.keyId)||!validUuid(b.originHomeBlockId)||!validUuid(b.targetHomeBlockId)||![b.version,b.originRevision,b.targetRevision,b.fareMinor].every(n=>Number.isSafeInteger(n)&&n>0)||b.fareMinor>100000000||b.confirmed!==true))return false; + if(b.action==='home_delivered'&&(!Number.isSafeInteger(b.arrivedAt)||!exact(b.arrival,['worldUuid','position'])||!validUuid(b.arrival.worldUuid)||!position(b.arrival.position)))return false; + return true; +} diff --git a/website/node/owned-smuggler-routes.mjs b/website/node/owned-smuggler-routes.mjs new file mode 100644 index 00000000..ee826c62 --- /dev/null +++ b/website/node/owned-smuggler-routes.mjs @@ -0,0 +1,63 @@ +import {boardReadStore} from './board-deed-source.mjs'; +import {clanDeedAuthority} from './clan-deeds.mjs'; +import {readCompanyDeed} from './company-deeds.mjs'; +import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs'; +import {BankError} from './postbank-service.mjs'; +const fail=(message,status=409)=>{throw new BankError(message,status);}; +const ref=value=>value&&['clan','company'].includes(value.kind)&&typeof value.id==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value.id); +export function createOwnedSmugglerRoutes(db,{resolve,clock=Date.now}){ + async function home(store,user,item){ + if(!ref(item))fail('Choose a registered clan or company.',400); + let name; + if(item.kind==='clan'){const p=await clanDeedAuthority(store,user.id,item.id);if(!p.isOwner||!p.canManage)fail('Only your own active clan Home Blocks are available.',403);name=p.deed.clan.name;} + else{let d;try{d=await readCompanyDeed(store,item.id);}catch(error){if([403,404,409].includes(error.status))fail('The current company deed requires review.',error.status);throw error;}if(d.company.status!=='active'||d.company.owner_account_id!==user.id)fail('Only your own active company Home Blocks are available.',403);name=d.company.name;} + const row=await store.first('SELECT revision,snapshot_json FROM site_claim_registry WHERE organisation_kind=? AND organisation_id=?',[item.kind,item.id]); + const snapshot=row?JSON.parse(row.snapshot_json):null,h=snapshot?.source==='minecraft'?snapshot.homeBlock:null; + return {...item,name,homeBlockId:h?.id||null,claimRevision:Number(row?.revision||0),server:tradeWorld(h?.worldName),home:h}; + } + function sourceProof(origin,input){ + const p=input.sourceLocation,h=origin.home,at=p?.position; + if(!h||origin.server!==tradeWorld(input.sourceWorld))fail('Meet this organisation’s registered Home Block NPC on its own world.',403); + if(p?.worldUuid!==h.worldUuid||!at||Object.keys(at).sort().join(',')!=='x,y,z'||!Object.values(at).every(Number.isFinite)||!Number.isSafeInteger(p.observedAt)||Math.abs(clock()-p.observedAt)>30000||['x','y','z'].reduce((n,k)=>n+(at[k]-h.position[k])**2,0)>100)fail('Reopen the Navigator beside the registered Home Block NPC.',403); + } + async function context(store,user,input,stage){ + let origin=null;if(stage!=='ready'){origin=await home(store,user,input.origin);sourceProof(origin,input);} + const target=await home(store,user,input.target); + if(!target.home||!target.server)fail('The destination has no registered game Home Block.'); + if(stage!=='ready'&&target.server===origin.server)fail('This Home Block is on your current world.'); + if(stage!=='quote'&&(target.homeBlockId!==input.targetHomeBlockId||target.claimRevision!==input.targetRevision||stage==='board'&&(origin.homeBlockId!==input.originHomeBlockId||origin.claimRevision!==input.originRevision)))fail('A Home Block changed. Reopen the Navigator.'); + return {origin,target}; + } + async function list(user,input){ + const reader=boardReadStore(db,db),origin=await home(reader,user,input.origin);sourceProof(origin,input); + const clans=await db.query('SELECT id FROM site_clans WHERE active=1 AND owner_id=? ORDER BY id',[user.id]),companies=await db.query("SELECT c.id FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id WHERE c.status='active' AND d.owner_account_id=? ORDER BY c.id",[user.id]); + if(clans.length+companies.length>500)fail('Your owned organisation registry requires review.'); + const destinations=[]; + for(const item of [...clans.map(c=>({kind:'clan',id:c.id})),...companies.map(c=>({kind:'company',id:c.id}))]){try{const h=await home(reader,user,item),available=!!h.home&&!!h.server&&h.server!==origin.server;destinations.push({...h,available,reason:!h.home?'No registered Home Block.':h.server===origin.server?'Already on this world.':!h.server?'Unregistered destination world.':''});}catch(error){if(error.status!==403&&error.status!==404)throw error;}} + return {origin,destinations}; + } + async function withLock(user,input,stage,work){ + // Central changes nothing. Its deed/read locks remain held through the one + // atomic bank reservation/posting transaction, avoiding distributed writes. + return db.transaction(async tx=>{ + const reader=boardReadStore(tx,db); + // Permission resolvers use readSnapshot; stay on this already held reader + // instead of inheriting the pool method and opening another connection. + reader.readSnapshot=async read=>read(reader); + await tx.query('SELECT id FROM site_accounts WHERE id=? FOR SHARE',[user.id]);await tx.query('SELECT minecraft_uuid FROM site_game_links WHERE user_id=? FOR SHARE',[user.id]); + await tx.query('SELECT version FROM site_character_choices WHERE user_id=? FOR SHARE',[user.id]); + const selections=await tx.query('SELECT key_id FROM jarvis_house_selections WHERE account_id=? FOR SHARE',[user.id]); + for(const id of [...new Set([user.keyId,...selections.map(r=>r.key_id)])].filter(Boolean).sort())await tx.query('SELECT id FROM organisation_keys WHERE id=? FOR SHARE',[id]); + if([input.origin,input.target].some(r=>r?.kind==='clan')){await tx.query('SELECT id FROM site_clans WHERE active=1 ORDER BY id LIMIT 501 FOR SHARE');await tx.query('SELECT clan_id FROM site_clan_deeds ORDER BY clan_id LIMIT 501 FOR SHARE');await tx.query('SELECT user_id FROM site_clan_members WHERE user_id=? FOR SHARE',[user.id]);} + for(const item of [input.origin,input.target].filter(ref).sort((a,b)=>(a.kind+a.id).localeCompare(b.kind+b.id))){ + if(item.kind==='company'){await tx.query('SELECT id FROM corrino_companies WHERE id=? FOR SHARE',[item.id]);await tx.query('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR SHARE',[item.id]);await tx.query('SELECT user_id FROM site_company_members WHERE company_id=? AND user_id=? FOR SHARE',[item.id,user.id]);} + await tx.query('SELECT revision FROM site_claim_registry WHERE organisation_kind=? AND organisation_id=? FOR SHARE',[item.kind,item.id]); + } + // Start no consistent read until every relevant row is locked. Under MySQL + // REPEATABLE READ, resolving first would freeze a pre-lock deed/key snapshot. + const fresh=await resolve(input.uuid,reader);if(!fresh||fresh.id!==user.id)fail('Your linked character changed.',403); + return work(await context(reader,fresh,input,stage),fresh,reader); + }); + } + return {list,quote:(user,input)=>context(boardReadStore(db,db),user,input,'quote'),withLock}; +} diff --git a/website/node/owner-homeblock-release.mjs b/website/node/owner-homeblock-release.mjs index 57ec09d7..00d8f373 100644 --- a/website/node/owner-homeblock-release.mjs +++ b/website/node/owner-homeblock-release.mjs @@ -3,33 +3,36 @@ import {OFFICIAL_ACCOUNT} from './official-account.mjs'; import {createStaffHomeBlockKeys} from './staff-homeblock-keys.mjs'; const first=async(db,sql,args=[])=>db.first?db.first(sql,args):(await db.query(sql,args))[0]||null; const digest=value=>createHash('sha256').update(value).digest('hex'); -export async function ownerHomeBlockAuthority(db,clanId=null){ +export async function ownerHomeBlockAuthority(db,clanId=null,kind='clan'){ + if(!['clan','company'].includes(kind))throw Error('Choose a clan or company Home Block'); const actor=await first(db,"SELECT a.id,a.username FROM site_accounts a JOIN org_control_principals p ON p.user_id=a.id WHERE a.id=? AND a.username='unimatrix999' AND a.password_hash NOT LIKE '!%' AND p.principal_kind='owner'",[OFFICIAL_ACCOUNT.ownerId]); if(!actor)throw Error('Existing protected Owner authority required'); - const clans=await db.query('SELECT id,name FROM site_clans WHERE owner_id=? AND active=1',[actor.id]); - if(clans.length!==1||clanId&&clans[0].id!==clanId)throw Error('Exactly one matching active owned clan required'); + const clans=kind==='clan'?await db.query('SELECT id,name FROM site_clans WHERE owner_id=? AND active=1',[actor.id]):await db.query("SELECT c.id,c.name FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id WHERE d.owner_account_id=? AND c.status='active' AND EXISTS(SELECT 1 FROM site_company_members m WHERE m.company_id=c.id AND m.user_id=d.owner_account_id)",[actor.id]); + if(clans.length!==1||clanId&&clans[0].id!==clanId)throw Error('Exactly one matching active owned '+kind+' required'); return {actor,clan:clans[0]}; } -export async function ownerHomeBlockPlan(db){ - const {actor,clan}=await ownerHomeBlockAuthority(db); - const row=await first(db,"SELECT snapshot_json,revision FROM site_claim_registry WHERE organisation_kind='clan' AND organisation_id=?",[clan.id]); - if(!row||!JSON.parse(row.snapshot_json).homeBlock)throw Error('The clan has no Home Block to release'); - return {actorId:actor.id,clanId:clan.id,clanName:clan.name,revision:Number(row.revision),snapshotHash:digest(row.snapshot_json),homeBlockId:JSON.parse(row.snapshot_json).homeBlock.id}; +export async function ownerHomeBlockPlan(db,kind='clan'){ + const {actor,clan}=await ownerHomeBlockAuthority(db,null,kind); + const row=kind==='clan'?await first(db,"SELECT snapshot_json,revision FROM site_claim_registry WHERE organisation_kind='clan' AND organisation_id=?",[clan.id]):await first(db,"SELECT snapshot_json,revision FROM site_claim_registry WHERE organisation_kind='company' AND organisation_id=?",[clan.id]); + if(!row||!JSON.parse(row.snapshot_json).homeBlock)throw Error('The '+kind+' has no Home Block to release'); + return {actorId:actor.id,...(kind==='clan'?{clanId:clan.id,clanName:clan.name}:{kind,companyId:clan.id,companyName:clan.name}),revision:Number(row.revision),snapshotHash:digest(row.snapshot_json),homeBlockId:JSON.parse(row.snapshot_json).homeBlock.id}; } export async function applyOwnerHomeBlockRelease(db,keys,plan,{requestId}={}){ - const {actor}=await ownerHomeBlockAuthority(db,plan.clanId); + const kind=plan.kind||'clan',id=kind==='company'?plan.companyId:plan.clanId; + const {actor}=await ownerHomeBlockAuthority(db,id,kind); if(plan.actorId!==actor.id)throw Error('Owner release plan identity mismatch'); const prior=await first(db,"SELECT fields_json,manifest_json,state FROM jarvis_generated_instructions WHERE request_id=? AND action_id='claims.remove-homeblock'",[requestId]); - if(prior){const fields=JSON.parse(prior.fields_json),manifest=JSON.parse(prior.manifest_json);if(fields.kind!=='clan'||fields.id!==plan.clanId||fields.expectedRevision!==plan.revision||manifest.actorId!==actor.id||manifest.snapshotHash!==plan.snapshotHash)throw Error('Release reference belongs to another instruction');} - else{const current=await ownerHomeBlockPlan(db);if(JSON.stringify(current)!==JSON.stringify(plan))throw Error('Home Block changed; review a fresh release plan');} + if(prior){const fields=JSON.parse(prior.fields_json),manifest=JSON.parse(prior.manifest_json);if(fields.kind!==kind||fields.id!==id||fields.expectedRevision!==plan.revision||manifest.actorId!==actor.id||manifest.snapshotHash!==plan.snapshotHash)throw Error('Release reference belongs to another instruction');} + else{const current=await ownerHomeBlockPlan(db,kind);if(JSON.stringify(current)!==JSON.stringify(plan))throw Error('Home Block changed; review a fresh release plan');} const service=createStaffHomeBlockKeys(db,keys,{authorizeStaff:async(user,tx)=>{ await tx.query('SELECT id FROM site_accounts WHERE id=? FOR UPDATE',[actor.id]); await tx.query('SELECT user_id FROM org_control_principals WHERE user_id=? FOR SHARE',[actor.id]); - await tx.query('SELECT id FROM site_clans WHERE id=? FOR UPDATE',[plan.clanId]); - if(!prior){const current=await first(tx,"SELECT snapshot_json,revision FROM site_claim_registry WHERE organisation_kind='clan' AND organisation_id=?",[plan.clanId]);if(!current||Number(current.revision)!==plan.revision||digest(current.snapshot_json)!==plan.snapshotHash)throw Error('Home Block changed; review a fresh release plan');} - return user.id===(await ownerHomeBlockAuthority(tx,plan.clanId)).actor.id; + if(kind==='clan')await tx.query('SELECT id FROM site_clans WHERE id=? FOR UPDATE',[id]); + else{await tx.query('SELECT id FROM corrino_companies WHERE id=? FOR UPDATE',[id]);await tx.query('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE',[id]);await tx.query('SELECT user_id FROM site_company_members WHERE company_id=? AND user_id=? FOR SHARE',[id,actor.id]);} + if(!prior){const current=await first(tx,'SELECT snapshot_json,revision FROM site_claim_registry WHERE organisation_kind=? AND organisation_id=?',[kind,id]);if(!current||Number(current.revision)!==plan.revision||digest(current.snapshot_json)!==plan.snapshotHash)throw Error('Home Block changed; review a fresh release plan');} + return user.id===(await ownerHomeBlockAuthority(tx,id,kind)).actor.id; }}); - const key=await service.issue(actor,{kind:'clan',id:plan.clanId,expectedRevision:plan.revision,ticketId:'owner-home-reset',reason:'Owner requested a free Home Block reset',requestId}); + const key=await service.issue(actor,{kind,id,expectedRevision:plan.revision,ticketId:'owner-home-reset',reason:'Owner requested a free Home Block reset',requestId}); await service.apply(actor,{keyId:key.keyId,requestId}); const saved=await first(db,'SELECT manifest_json FROM jarvis_generated_instructions WHERE key_id=?',[key.keyId]); return {released:true,...JSON.parse(saved.manifest_json).receipt}; diff --git a/website/node/permissions.mjs b/website/node/permissions.mjs index 9251e730..e3507923 100644 --- a/website/node/permissions.mjs +++ b/website/node/permissions.mjs @@ -1,6 +1,9 @@ import {JARVIS_IDENTITY,isJarvisIdentity} from './jarvis-identity.mjs'; import {organisationRuntimeAccess} from './organisation-runtime.mjs'; export const NODES={ + 'dunestaff.fly':'Toggle your own staff flight', + 'dunestaff.vanish':'Toggle your own staff vanish', + 'dunestaff.vanish.see':'See vanished staff', 'web.jarvis.clans.reset':'Issue and redeem fixed protected-clan roster reset keys', 'web.jarvis.keys.view':'Browse JARVIS masterkey templates', 'web.jarvis.accounts.test-identity':'Issue and redeem synthetic test identities for unlinked accounts', diff --git a/website/node/postbank-db.mjs b/website/node/postbank-db.mjs index b34125ee..c23c88b0 100644 --- a/website/node/postbank-db.mjs +++ b/website/node/postbank-db.mjs @@ -5,7 +5,8 @@ import {WAR_MUSTER_SCHEMA} from './war-muster.mjs'; import {WAR_EXCHANGE_SCHEMA} from './war-exchange.mjs'; import {EXCHANGE_INCENTIVE_SCHEMA} from './exchange-incentive.mjs'; import {GUILD_SUBSIDY_SCHEMA} from './guild-subsidy.mjs'; -import {GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA} from './game-guild.mjs'; +import {GUILD_ROUTE_SCHEMA} from './guild-route-bindings.mjs'; +import {GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA,TRAVEL_LADDER_SCHEMA,TRAVEL_BOUNTY_SCHEMA,TRAVEL_BOUNTY_CLAIM_SCHEMA,TRAVEL_OPEN_PASSAGE_SCHEMA} from './game-guild.mjs'; import {HOME_SCHEMA} from './game-home.mjs'; import {DEED_PURCHASE_SCHEMA} from './deed-purchases.mjs'; import {ESTATE_SCHEMA} from './postbank-estates.mjs'; @@ -30,7 +31,7 @@ export async function openPostbankDatabase(settings){ const pool=mysql.createPool({host:settings.BANK_DB_HOST||'127.0.0.1',port:Number(settings.BANK_DB_PORT||3306),database:name,user:settings.BANK_DB_USER,password:settings.BANK_DB_PASSWORD,connectionLimit:4,supportBigNumbers:true,bigNumberStrings:true,charset:'utf8mb4',connectTimeout:8000}); const api=c=>({async query(sql,args=[]){return(await c.execute(sql,args))[0];},async first(sql,args=[]){return(await c.execute(sql,args))[0][0]||null;}}); const db={async query(sql,args=[]){return(await pool.execute(sql,args))[0];},async first(sql,args=[]){return(await pool.execute(sql,args))[0][0]||null;},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 close(){await pool.end();}}; - try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...RIHLA_CASH_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,...WAR_MUSTER_SCHEMA,WAR_CAMPAIGN_SCHEMA,WAR_SETTLEMENT_JOB_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);for(const sql of [...GUILD_SUBSIDY_SCHEMA,...EXCHANGE_INCENTIVE_SCHEMA])await db.query(sql);await db.query(SMUGGLER_PASSAGE_SCHEMA);await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);await db.query(ECONOMY_OPERATION_SCHEMA);}catch(error){await pool.end();throw error;} + try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...RIHLA_CASH_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,...WAR_MUSTER_SCHEMA,WAR_CAMPAIGN_SCHEMA,WAR_SETTLEMENT_JOB_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);for(const sql of [...GUILD_SUBSIDY_SCHEMA,...EXCHANGE_INCENTIVE_SCHEMA])await db.query(sql);await db.query(SMUGGLER_PASSAGE_SCHEMA);await db.query(TRAVEL_LADDER_SCHEMA);await db.query(TRAVEL_BOUNTY_SCHEMA);await db.query(TRAVEL_BOUNTY_CLAIM_SCHEMA);await db.query(TRAVEL_OPEN_PASSAGE_SCHEMA);await db.query(GUILD_ROUTE_SCHEMA);db.guildRouteBindingsEnabled=true;await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);await db.query(ECONOMY_OPERATION_SCHEMA);}catch(error){await pool.end();throw error;} return db; } diff --git a/website/node/postbank-payroll-accounts.mjs b/website/node/postbank-payroll-accounts.mjs index e95e0713..dd8b11ad 100644 --- a/website/node/postbank-payroll-accounts.mjs +++ b/website/node/postbank-payroll-accounts.mjs @@ -6,6 +6,12 @@ import {REGISTRY_ACTOR} from './postbank-registry.mjs'; // Internal payroll operation. The caller supplies a freshly verified staff // recipient and runs this inside the payroll transaction, never a public route. export async function ensurePayrollCurrentAccount(tx,recipient,{now=Date.now(),makeId=randomUUID}={}){ + return ensureBasicCurrentAccount(tx,recipient,{now,makeId,source:'payroll'}); +} +// First-join provisioning shares the same zero-balance basic product. It never +// bypasses an existing blocked current account or records player acceptance. +export async function ensureBasicCurrentAccount(tx,recipient,{now=Date.now(),makeId=randomUUID,source}={}){ + if(!['payroll','lobby'].includes(source))throw Error('A reviewed basic-account source is required.'); if(!recipient?.id||!recipient.username)throw Error('A verified payroll recipient is required.'); const id=entityId('person',recipient.id); await tx.query("INSERT INTO pb_entities(id,kind,external_key,display_name,active,created_at) VALUES(?,'person',?,?,1,?) ON DUPLICATE KEY UPDATE id=id",[id,recipient.id,recipient.username,now]); @@ -27,11 +33,11 @@ export async function ensurePayrollCurrentAccount(tx,recipient,{now=Date.now(),m if(!client)throw Error('Personal client number could not be allocated.'); } const packageId=makeId(); - await tx.query("INSERT INTO pb_packages(id,client_number,package_key,monthly_minor,terms_version,accepted_by,accepted_at,state) VALUES(?,?,'pb_start',0,'payroll-provisioned-basic-v1',?,?,'active')",[packageId,client.client_number,REGISTRY_ACTOR,now]); + await tx.query(`INSERT INTO pb_packages(id,client_number,package_key,monthly_minor,terms_version,accepted_by,accepted_at,state) VALUES(?,?,'pb_start',0,'${source}-provisioned-basic-v1',?,?,'active')`,[packageId,client.client_number,REGISTRY_ACTOR,now]); const result=await tx.query("INSERT INTO pb_accounts(client_number,package_id,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES(?,?,'108',?,0,0,'active',?)",[client.client_number,packageId,recipient.username+' · Current',now]); const accountId=String(result.insertId); await tx.query('UPDATE pb_accounts SET account_number=? WHERE id=?',[bankNumber('108',Number(accountId)),accountId]); await tx.query('INSERT INTO pb_activations(entity_id,package_id) VALUES(?,?) ON DUPLICATE KEY UPDATE entity_id=entity_id',[id,packageId]); - await tx.query("INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,'payroll_account_provisioned',?,?,?)",[makeId(),REGISTRY_ACTOR,id,JSON.stringify({recipientId:recipient.id,accountId,packageKey:'pb_start',typeCode:'108',openingBalanceMinor:0}),now]); + await tx.query(`INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,'${source}_account_provisioned',?,?,?)`,[makeId(),REGISTRY_ACTOR,id,JSON.stringify({recipientId:recipient.id,accountId,packageKey:'pb_start',typeCode:'108',openingBalanceMinor:0}),now]); return {accountId,created:true,entityId:id}; } diff --git a/website/node/progression-api.mjs b/website/node/progression-api.mjs index 6e7e021c..f41d913f 100644 --- a/website/node/progression-api.mjs +++ b/website/node/progression-api.mjs @@ -9,7 +9,7 @@ export function createProgressionAPI(db,{quests,xp,collect=async()=>{},authentic if(!quests)return reply({message:'The quest service is not available.'},503); try{ if(request.method==='GET'){ - if(path==='/api/progression'&&!url.search){const sources=await collect(actor);return reply({...await quests.list(actor),player:{username:user.username,name:user.display_name||user.username},sources});} + if(path==='/api/progression'&&!url.search){const sources=await collect(actor);let settled={settled:[],failed:0};try{settled=await quests.settleCompleted?.(actor)||settled;}catch{settled={settled:[],failed:1};}return reply({...await quests.list(actor),player:{username:user.username,name:user.display_name||user.username},sources,settled:settled.settled});} if(path==='/api/progression/history'){ if([...url.searchParams.keys()].some(k=>k!=='page')||url.searchParams.getAll('page').length>1||!/^\d{1,4}$/.test(url.searchParams.get('page')||'1'))return reply({message:'Choose a valid history page.'},400); const page=Number(url.searchParams.get('page')||1);if(page<1)return reply({message:'Choose a valid history page.'},400); diff --git a/website/node/progression-definitions.mjs b/website/node/progression-definitions.mjs index 7770f93d..02132bf7 100644 --- a/website/node/progression-definitions.mjs +++ b/website/node/progression-definitions.mjs @@ -26,7 +26,7 @@ export const QUEST_DEFINITIONS=Object.freeze([...MISSION_BRANCHES.filter(b=>b.id requiresAny:[],season:'S01',xp:defaultQuestXP({branch:'acquisitions',metric:`acquired-${kind}`},index),reward:null,revision:1 })))]); export const QUEST_METRICS=Object.freeze([...new Set(QUEST_DEFINITIONS.map(d=>d.metric))]); -export const XP_POLICY=Object.freeze({version:1,base:25,seasonCap:70,season:'S01',months:6}); +export const XP_POLICY=Object.freeze({version:1,base:25,seasonCap:100,season:'S01',months:6}); export function xpAtLevel(level,base=XP_POLICY.base){if(!Number.isSafeInteger(level)||level<1||level>1000||!Number.isSafeInteger(base)||base<1||base>100000)throw TypeError('Invalid XP curve');return base*level*(level-1)/2;} export function levelForXP(xp,{base=XP_POLICY.base,cap=XP_POLICY.seasonCap}={}){if(cap===null)return unlimitedLevelForXP(xp,base);if(!Number.isSafeInteger(xp)||xp<0||!Number.isSafeInteger(cap)||cap<1||cap>1000)throw TypeError('Invalid XP state');let level=1;while(level=xpAtLevel(level+1,base))level++;return level;} export function questPrerequisites(definition,claimed){return definition.requires.every(id=>claimed.has(id))&&(!definition.requiresAny.length||definition.requiresAny.some(id=>claimed.has(id)));} diff --git a/website/node/progression-pol-runtime.mjs b/website/node/progression-pol-runtime.mjs index 6bd1bc07..a3a2e205 100644 --- a/website/node/progression-pol-runtime.mjs +++ b/website/node/progression-pol-runtime.mjs @@ -94,7 +94,7 @@ export function createPOLProgressionRuntime(central,keys,{clock=Date.now,verifyO if(!await authorizePlayer(actor,central))throw Error('Current player identity required');if(raidQuests)await raidQuests.collect(actor);let acquisitionAvailable=true;if(bank)try{await collectPOLAcquisition(central,bank,keys,actor,{clock});}catch{acquisitionAvailable=false;}const proof=await evidence(actor);if(!proof)return {state:'verified-key-sources',sources:[{source:'pol-activity-keys',available:false,reason:'pending-verified-producer'}]}; const digest=createHash('sha256').update(JSON.stringify(proof.proofIds)).digest('hex'); const current=await engineFor(actor),metrics=new Set(current.definitions.map(d=>d.metric));for(const [metric,value]of proof.totals)if(metrics.has(metric))await current.engine.observe(observer,{accountId:actor.id,seasonId:proof.season.season_id,metric,value,eventId:'pol-activity:'+actor.id+':'+metric+':'+digest.slice(0,32),source:'verified-activity-key'}); - if((proof.totals.get('flight-elytra-acquired')||0)>0)await current.engine.completeVerifiedBranch(actor,'elytra'); + if((proof.totals.get('flight-elytra-acquired')||0)>0)await current.engine.completeVerifiedBranch(actor,'elytra',{exclude:['POL-ELYTRA-MERGE']}); return {state:'verified-key-sources',sources:[{source:'pol-activity-keys',available:true,verifiedEvents:proof.proofIds.length},...(bank?[{source:'posted-exchange-mission',available:acquisitionAvailable}]:[])]}; } return Object.freeze({quests,collect}); diff --git a/website/node/progression-pol.mjs b/website/node/progression-pol.mjs index 41a8a18f..746fc7dd 100644 --- a/website/node/progression-pol.mjs +++ b/website/node/progression-pol.mjs @@ -50,7 +50,7 @@ export const ensurePOLProgressionPolicy=(db,keys,options={})=>ensureProgressionP export const ensurePOLRepeatablePolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:2},definitions:repeatablePolicyDefinitions()}); -export const ensureElytraQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:4},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='elytra')}); +export const ensureElytraQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:4},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='elytra'&&d.id!=='POL-ELYTRA-MERGE')}); export const ensureWarQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:5},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='war-service')}); @@ -59,3 +59,6 @@ export const ensureFaithQuestPolicy=(db,keys,options={})=>ensureProgressionPolic export const ensureFaunaQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:7},definitions:[...POL_QUEST_DEFINITIONS.filter(d=>d.faction==='fremen'),...repeatablePolicyDefinitions({faction:'fremen'})],rewardForDefinition:fremenInitialReward}); export const ensureBountyQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:8},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='bounty-jobs')}); export const ensureSpiceUpgradeQuestPolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:9},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.branch==='spice-upgrading')}); + +// Add the physical merge without replaying v4 or overwriting existing flight rewards. +export const ensureElytraMergePolicy=(db,keys,options={})=>ensureProgressionPolicy(polProgressionStore(db),polPolicyKeys(keys),{...options,policy:{...POL_XP_POLICY,version:10},definitions:POL_QUEST_DEFINITIONS.filter(d=>d.id==='POL-ELYTRA-MERGE')}); diff --git a/website/node/progression-quests.mjs b/website/node/progression-quests.mjs index 67051b0c..1ced52bb 100644 --- a/website/node/progression-quests.mjs +++ b/website/node/progression-quests.mjs @@ -147,14 +147,32 @@ export function createQuestProgression(db,keys,{definitions=QUEST_DEFINITIONS,au } return {completed}; }, - async completeVerifiedBranch(actor,branch){ + async completeVerifiedBranch(actor,branch,{exclude=[]}={}){ + if(!Array.isArray(exclude)||exclude.some(id=>typeof id!=='string'||!definitions.some(d=>d.id===id&&d.branch===branch)))throw TypeError('Registered branch exclusions required'); await player(actor);let completed=0; - for(const d of definitions.filter(d=>d.branch===branch&&!d.repeatable)){ + for(const d of definitions.filter(d=>d.branch===branch&&!d.repeatable&&!exclude.includes(d.id))){ const view=await service.list(actor),q=view.quests.find(q=>q.id===d.id);if(!q||q.state==='claimed')continue; if(!q.canClaim||!q.rewardConfigured)throw Error('Verified branch completion is not ready'); await service.claim(actor,{definitionId:q.id,revision:q.revision,requestId:deterministicId('branch:'+actor.id+':'+view.season.id+':'+q.id)});completed++; }return {completed}; }, + /** Pays every quest whose verified objective is already met, including ones finished while offline. + * Only real progress counts: the XP-cap bypass that marks unfinished mandatory quests as claimable never triggers this. + * Request ids are derived from the player and quest, so a repeated sweep replays instead of paying twice. Repeatable quests stay manual. */ + async settleCompleted(actor,{maxPasses=6}={}){ + await player(actor);const settled=[];let failed=0; + for(let pass=0;passq.state==='completed'&&q.canClaim&&q.rewardConfigured&&Number.isSafeInteger(q.revision)&&q.target>0&&q.progress>=q.target&&!types.get(q.id)?.repeatable&&!settled.some(s=>s.id===q.id)); + if(!due.length)break;let paid=0; + for(const q of due)try{ + await service.claim(actor,{definitionId:q.id,revision:q.revision,requestId:deterministicId('login:'+actor.id+':'+view.season.id+':'+q.id)}); + settled.push({id:q.id,title:q.title,xp:q.xp,branch:q.branch});paid++; + }catch{failed++;} + if(!paid)break; + } + return {settled,failed}; + }, async processCompletions({accountId=null}={}){ if(accountId!==null&&!uuid(accountId))throw TypeError('Invalid completion account'); const jobs=await db.query("SELECT * FROM jarvis_progression_outbox WHERE purpose='mandatory-completion' AND state='queued'"+(accountId?' AND account_id=?':'')+' ORDER BY created_at,id LIMIT 20',accountId?[accountId]:[]);let completed=0,failed=0; diff --git a/website/node/progression-runtime.mjs b/website/node/progression-runtime.mjs index 7aa1a75d..5760cb5f 100644 --- a/website/node/progression-runtime.mjs +++ b/website/node/progression-runtime.mjs @@ -11,12 +11,13 @@ import {createQuestProgression} from './progression-quests.mjs'; import {createXPInstruments} from './progression-xp-instruments.mjs'; import {firstLoginState} from './first-login.mjs'; import {can} from './permissions.mjs'; -import {createBankQuestActivities,bankQuestIncome} from './bank-quest-activities.mjs'; +import {createBankQuestActivities,createBankDepositQuestActivity,bankQuestIncome} from './bank-quest-activities.mjs'; import {faithMultipliers,faithAward} from './faith-blessings.mjs'; const first=async(db,sql,args=[])=>{const rows=await db.query(sql,args);return rows[0]||null;}; export function createProgressionRuntime(central,bank,keys,{clock=Date.now,resolveCase=async()=>null,verifyAcquisition=(input,store=central)=>verifyDeedAcquisition(store,bank,input)}={}){ const observer=Object.freeze({internal:'progression-source-reader'}); const collectBankActivities=bank&&keys?createBankQuestActivities(central,bank,keys,{clock}):null; + const collectBankDeposit=bank&&keys?createBankDepositQuestActivity(central,bank,keys,{clock}):null; const resolvePlayer=id=>first(central,"SELECT id,username,display_name,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]); async function authorizePlayer(actor,store){ if(typeof actor.revalidate==='function'&&(await actor.revalidate())?.id!==actor.id)return false; @@ -106,6 +107,7 @@ export function createProgressionRuntime(central,bank,keys,{clock=Date.now,resol if(rows.length>500)throw Error('The conquest registry requires a larger reviewed window'); for(const row of rows){const receipt=JSON.parse(row.manifest_json).receipt;await quests.recordAcquisition(observer,{accountId:actor.id,kind:'clan',entityId:receipt.clanId,origin:'conquest',sourceKeyId:row.key_id});} }); + if(central.personalActivityEventsEnabled&&collectBankDeposit)await source('atm-deposits',['bank-deposit'],()=>collectBankDeposit(actor,season)); if(central.personalActivityEventsEnabled&&collectBankActivities)await source('exchange-purchases',['shop-purchase'],()=>collectBankActivities(actor,season)); if(central.personalActivityEventsEnabled)await source('personal-activity-keys',PERSONAL_ACTIVITY_METRICS,async()=>{ const proof=await activityEvidence(actor);if(!proof)return {pendingMetrics:PERSONAL_ACTIVITY_METRICS}; diff --git a/website/node/travel-bounty-claims.mjs b/website/node/travel-bounty-claims.mjs new file mode 100644 index 00000000..9071f426 --- /dev/null +++ b/website/node/travel-bounty-claims.mjs @@ -0,0 +1,37 @@ +import {createHash} from 'node:crypto'; +import {BankError} from './postbank-service.mjs'; +import {validUuid} from './game-link.mjs'; + +export const TRAVEL_BOUNTY_CLAIM_SCHEMA="CREATE TABLE IF NOT EXISTS pb_travel_bounty_claims(id CHAR(36) PRIMARY KEY,fingerprint CHAR(64) NOT NULL,actor_id CHAR(36) NOT NULL,killer_uuid CHAR(36) NOT NULL,victim_uuid CHAR(36) NOT NULL,server VARCHAR(32) NOT NULL,bounty_id CHAR(36) NULL,amount_minor BIGINT NOT NULL,state VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; +const worlds=new Set(['arrakis','caladan','giedi_prime','kaitain','sigma_draconis_iv']); +const fail=(message,status=409)=>{throw new BankError(message,status);}; + +// Native death reports retain one reference, including when there was no bounty. +// A retry cannot change its victim/world or claim a bounty created after that kill. +export function createTravelBountyClaims(bank,{resolve,clock,payout,enabled}){ + return async function bountyClaim({killer,victim,requestId,server}){ + if(!enabled())return{ok:true,claimed:false,disabled:true}; + if(!validUuid(killer)||!validUuid(victim)||!validUuid(requestId)||!worlds.has(server))fail('Invalid travel bounty report.',400); + const hunter=await resolve(killer);if(!hunter)fail('A linked account is required to claim a bounty.',403); + const fingerprint=createHash('sha256').update(JSON.stringify([killer,victim,server])).digest('hex'); + return bank.transaction(async tx=>{ + const prior=await tx.first('SELECT * FROM pb_travel_bounty_claims WHERE id=? FOR UPDATE',[requestId]); + if(prior){ + if(prior.actor_id!==hunter.id||prior.fingerprint!==fingerprint)fail('This kill reference was already used.'); + if(prior.state==='no_bounty')return{ok:true,claimed:false,replayed:true}; + const bounty=await tx.first('SELECT * FROM pb_travel_bounties WHERE id=?',[prior.bounty_id]); + if(prior.state!=='paid'||!bounty||bounty.state!=='claimed'||bounty.claim_request!==requestId||bounty.claimed_by!==hunter.id||bounty.world!==server||bounty.minecraft_uuid!==victim||Number(bounty.amount_minor)!==Number(prior.amount_minor))fail('This bounty receipt requires review.'); + return{ok:true,claimed:true,replayed:true,amountMinor:Number(prior.amount_minor),traveller:bounty.traveller,world:bounty.world}; + } + const bounty=killer===victim?null:await tx.first("SELECT * FROM pb_travel_bounties WHERE minecraft_uuid=? AND world=? AND state='open' AND actor_id<>? ORDER BY created_at,id LIMIT 1 FOR UPDATE",[victim,server,hunter.id]); + if(!bounty){ + await tx.query("INSERT INTO pb_travel_bounty_claims(id,fingerprint,actor_id,killer_uuid,victim_uuid,server,bounty_id,amount_minor,state,created_at) VALUES(?,?,?,?,?,?,NULL,0,'no_bounty',?)",[requestId,fingerprint,hunter.id,killer,victim,server,clock()]); + return{ok:true,claimed:false}; + } + await payout(tx,{id:bounty.id,hunter,amountMinor:bounty.amount_minor,memo:'Travel bounty · '+bounty.traveller}); + await tx.query("UPDATE pb_travel_bounties SET state='claimed',claimed_by=?,claimed_at=?,claim_request=? WHERE id=?",[hunter.id,clock(),requestId,bounty.id]); + await tx.query("INSERT INTO pb_travel_bounty_claims(id,fingerprint,actor_id,killer_uuid,victim_uuid,server,bounty_id,amount_minor,state,created_at) VALUES(?,?,?,?,?,?,?,?,'paid',?)",[requestId,fingerprint,hunter.id,killer,victim,server,bounty.id,bounty.amount_minor,clock()]); + return{ok:true,claimed:true,amountMinor:Number(bounty.amount_minor),traveller:bounty.traveller,world:bounty.world}; + }); + }; +} diff --git a/website/node/travel-holdings.mjs b/website/node/travel-holdings.mjs new file mode 100644 index 00000000..1228f69f --- /dev/null +++ b/website/node/travel-holdings.mjs @@ -0,0 +1,22 @@ +// Does a traveller have a clan or company registered (Home Block) on a world? Reads the same central +// native state JARVIS projects, so the answer matches what players see in game. +const norm=value=>typeof value==='string'?value.toLowerCase().replaceAll('-','_'):''; +/** Pure matcher over a native-state snapshot. Hidden, retired and office records never count. */ +export function holdsOnWorld(state,uuid,world){ + const target=norm(world),who=String(uuid||'').toLowerCase();if(!target||!who)return false; + for(const group of [state?.clans,state?.companies])for(const record of group||[]){ + const home=record.homeBlock; + if(record.lifecycle!=='active'||record.hidden||norm(record.homeServer)!==target||home?.source!=='minecraft'||!Number.isSafeInteger(home.revision)||home.revision<1||norm(home.worldName)!==target)continue; + if((record.members||[]).some(m=>String(m.uuid||'').toLowerCase()===who))return true; + } + return false; +} +export function createNativeHoldingCheck(db,{ttlMs=60000,clock=Date.now,read=null}={}){ + let cache=null; + async function load(fresh){ + const now=clock();if(!fresh&&cache&&now-cache.atholdsOnWorld(await load(fresh),uuid,world); +} diff --git a/website/node/travel-tariff.mjs b/website/node/travel-tariff.mjs new file mode 100644 index 00000000..f0817c13 --- /dev/null +++ b/website/node/travel-tariff.mjs @@ -0,0 +1,47 @@ +// Open-travel tariff. All amounts are minor units (1 DM = 100). Pure functions, no I/O. +// Race world and Lobby are free. Any other world costs 150 DM for the first trip and 10% more +// (compounding) for each later paid trip, capped at 5000 DM. The counter resets after 30 days +// without a paid trip. A clan or company registered on the destination world halves the fare. +// The bounty placed on an unsanctioned arrival is five times the fare actually paid. +export const TRAVEL_BASE_MINOR=15000; +export const TRAVEL_CAP_MINOR=500000; +export const TRAVEL_STEP_PERCENT=10; +export const TRAVEL_RESET_MS=30*24*60*60*1000; +export const BOUNTY_MULTIPLIER=5; +export const FREE_WORLDS=Object.freeze(['lobby']); + +const whole=(value,max)=>Number.isSafeInteger(value)&&value>=0&&value<=max; + +/** Fare in minor units for the trip number `trips` (0 = first paid trip), before any reduction. */ +export function ladderFare(trips){ + if(!whole(trips,1e9))throw RangeError('Invalid trip count'); + let fare=TRAVEL_BASE_MINOR; + for(let i=0;iMath.ceil(fare/2); + +/** Fare and bounty for a paid route. `reduced` is true when the traveller has a clan or company on that world. */ +export function paidTariff({trips,reduced}){ + const base=ladderFare(trips),fare=reduced?reducedFare(base):base; + return{fareMinor:fare,bountyMinor:fare*BOUNTY_MULTIPLIER,reduced:!!reduced,trip:trips+1}; +} + +/** + * Classifies a destination for a traveller. Free routes carry no fare and no bounty: + * Lobby, the traveller's own race world, and a destination covered by an Emperor free-passage decree. + */ +export function classifyRoute({destination,raceWorld,decree=false}){ + if(FREE_WORLDS.includes(destination))return{free:true,reason:'lobby'}; + if(destination===raceWorld)return{free:true,reason:'race-world'}; + if(decree)return{free:true,reason:'decree'}; + return{free:false,reason:'paid'}; +} diff --git a/website/node/user-voice-permissions.mjs b/website/node/user-voice-permissions.mjs new file mode 100644 index 00000000..216019a7 --- /dev/null +++ b/website/node/user-voice-permissions.mjs @@ -0,0 +1,5 @@ +export const USER_VOICE_NODES=Object.freeze(['voicechat.listen','voicechat.speak','voicechat.groups']); +export function voicePermissions(existing){ + if(!Array.isArray(existing)||existing.some(n=>typeof n!=='string'))throw Error('Invalid stored User permissions'); + return [...new Set([...existing,...USER_VOICE_NODES])]; +} diff --git a/website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md b/website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md new file mode 100644 index 00000000..8c279053 --- /dev/null +++ b/website/ops/LOBBY-ACCOUNT-FIRST-JOIN.md @@ -0,0 +1,60 @@ +# Lobby first-join accounts + +New authenticated Lobby players receive an ordinary website account linked to +their real Java or Floodgate UUID. The standalone Lobby plugin owns first-join +detection and player-only delivery; planets do not install it. Existing links +and passwords are retained. Historical unlinked identities need manual linking. +Website-name collisions use a deterministic UUID suffix, never account takeover. + +The website skips the age question without inserting a declaration. It stores +`no_reply@dunerealms.com` as an unverified placeholder, never a verified mailbox. +Initial website sign-in still requires changing the generated password and +accepting the terms. The usual House selector remains the player's choice. + +The central service provides a free `pb_start` current account (108), with no +monthly charge, through the existing basic-account provisioner. It then posts +exactly 1,000 DM starting funds from the existing capital issuer using a balanced +bank grant. Its immutable payment ID is derived from the verified Minecraft UUID; +retries, reconnects and replacement website identities cannot issue it again. +The account and two ledger entries commit in one bank transaction. A partial +receipt, changed recipient or blocked account requires review, not another grant. +Existing blocked accounts are not bypassed. It also readies the normal Rihla +identity and founding keys. A bank outage retains the exact website account and +request; the plugin retries without creating another user or changing a balance. + +## Private protocol + +`POST /internal/game/lobby-account` uses a dedicated Lobby bearer, not the shared +game bearer. Exact schema-1 provision fields are `action`, `requestId`, `uuid`, +`name`, `schema`; ack omits `name`. Client fields cannot choose an account ID, +role, House, email, age, bank plan or balance. The server fixes these defaults. + +The plugin stores the original UUID/name/request before its first network call. +Only `created` contains the generated password. Retries with the original binding +return that same password until delivery acknowledgement, password change or +seven-day expiry. AES-GCM ciphertext is bound to the UUID/request and stored in +the private central database. Acknowledgement erases it. Expired or changed +credentials require recovery and are never silently reset. Responses and audit +records never log credentials. The player's client may retain its own received DM. + +## Release + +Both web and plugin changes require their exact canonical CI and normal merge. +Run `configure-lobby-account.py --source ` from the independently verified +CI operations artifact (or immutable release) to inspect, then add `--apply` to +prepare private server configuration before promotion. It changes +only three Lobby-account environment settings. It does not restart the website. +Use the existing staged website promotion so schema creation and readiness happen +before the new plugin activates. Never put its generated private material in Git +or a public artifact. + +Transfer the private token directly to `/etc/dunerealms/lobby-account.token` on +Lobby, mode 0600 owned by its service user. The encryption key remains web-only. +Use the plugin's Lobby-only installer and verify authenticated modern Velocity +forwarding, backend loopback binding, current source/artifact hashes and startup. +No retained JAR, resource pack, world or planet installation changes are required. +Use disposable protocol fixtures for credentials/bank tests; do not create real +players or payment transactions just for release checks. + +This starting budget applies only to newly provisioned first-join accounts. It +does not top up existing player accounts or repeat prior one-off console grants. diff --git a/website/ops/SMUGGLER-NAVIGATION.md b/website/ops/SMUGGLER-NAVIGATION.md new file mode 100644 index 00000000..903eaf50 --- /dev/null +++ b/website/ops/SMUGGLER-NAVIGATION.md @@ -0,0 +1,27 @@ +# Navigator route extension + +Deploy the reviewed central release before the paired Navigator plugins. Existing Guild requests and the permitted `destinations` string array remain compatible. `quote` and `smuggler_quote` additionally return `routes`, containing every planet once: `server`, central `name`, `available`, human-readable `reason`, and `fareMinor`. Unavailable destinations remain visible and cannot submit a boarding action. The ordinary Guild still applies its original House/Imperial permission, embargo, boarding clock, personal available funds and prologue rules. Esmar keeps the current personal permission and smuggler fare, evaluated for each destination. Lobby is the origin/return hub, not another planet row. + +New personal smuggler bookings record their actual departure world. Return permission is tied to the latest confirmed arrival on the current world, and returns to that booking's recorded origin. Legacy lobby–Arrakis records still return to Lobby. An owned Home Block ticket does not grant personal Esmar return permission. + +## Owned Home Block contract + +All requests use the existing private `/internal/game/guild` credential and strict action-specific fields. The backend owns `uuid`, `sourceWorld` and the real-world contact proof. The menu cannot supply another player's identity or bank account. Source NPC contact must be rechecked on the server, after returning from the virtual menu world. + +`home_list`, `home_quote` and `home_board` require `origin: {kind,id}` and `sourceLocation: {worldUuid,position:{x,y,z},observedAt}`. The origin must be the player's current owned clan/company Home Block, on the serving world, within ten blocks and thirty seconds of the observed contact. The catalog lists every owned clan/company, including same-world and unregistered destinations with disabled reasons. A manager or parent controller is not treated as an owner. + +`home_quote` additionally takes `target: {kind,id}` and returns current House `keyId`/`version`, `fareMinor`, `affordable`, `expiresAt`, and origin/target references containing `homeBlockId` and `claimRevision`. + +`home_board` adds a durable `requestId`, the exact House key/version and fare, `confirmed:true`, `originHomeBlockId`, `originRevision`, `targetHomeBlockId` and `targetRevision`. An accepted reference is checked before rejecting stale contact proof. Fresh contact proof may be refreshed on an unrecorded retry; immutable quote/home/identity/fare fields must remain identical. The fare is reserved in the original Guild ledger and the returned pending ticket contains its exact destination server and Home Block. + +At the destination, `home_arrive` (`uuid`, `server`) returns `{ok:true,schema:1,ticket}` or a null ticket. Native code checks the actual loaded UUID world, target chunk and safe floor/feet/head space. Only then does `home_ready` (`uuid`, `server`, `requestId`) revalidate current ownership and the Home Block pin and post the original reservation once. It returns the bound ticket with `state:'arrived', paid:true`. A paid ticket remains recoverable after its original reservation deadline; it is not a second purchase. Native code then teleports and durably sends `home_delivered` with the same ID, `arrivedAt`, and `arrival:{worldUuid,position}`. The acknowledgement echoes schema, request ID and `delivered:true` before the native journal can clear it. + +An unfulfilled pending booking expires through the original fare-release worker. A paid receipt whose target changed returns a bound review response, preserving the receipt rather than minting a new payment or inventing refund authority. This is intentionally distinct from silently redirecting a player into a new owner's Home Block. + +## Persistence and validation + +`pb_guild_route_bindings` is additive bank receipt metadata, not another ownership registry. Central deed/account/claim shared read locks remain held through the single atomic bank transaction; central storage is not mutated by this route. No distributed write, cross-database grant or new bank ledger is required. All fares still use `pb_guild_passages`, the existing personal account authority and the In-game Bank Treasury. Ordinary arrival workers skip owned-home tickets, and smuggler markers continue to exclude these journeys from lawful Guild quest rewards. + +Tests cover the existing Guild fare/passage behavior, distinct full catalogs, original confirmed booking replay, recorded return origins, real company/clan owner authority, contact world/distance/time, changed pins, failed ledger rollback, paid receipt recovery, malformed requests and wrong destination/arrival evidence. No real payment or player travel is generated by these checks. Source/build/host readiness and an actual player fare are separate acceptance facts. + +Preserve native booking/arrival journals and bank receipts during an operational rollback. An older central/native release cannot resume this new paid Home Block protocol; do not treat restoring JARs as a refund or erase an unresolved paid delivery. Initial canary checks can use catalogs and navigation without submitting a fare. diff --git a/website/ops/configure-lobby-account.py b/website/ops/configure-lobby-account.py new file mode 100644 index 00000000..8cc3e70f --- /dev/null +++ b/website/ops/configure-lobby-account.py @@ -0,0 +1,66 @@ +"""Prepare private Lobby provisioning credentials for a reviewed website release.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import secrets +import tempfile + +ENV=Path('/home/dunerealms/.config/dunerealms.env') +STATE=Path('/var/lib/dunerealms-operations/lobby-account') +KEYS={'LOBBY_ACCOUNT_ENABLED','LOBBY_ACCOUNT_TOKEN','LOBBY_ACCOUNT_ENCRYPTION_KEY'} + +def reviewed_source(path,source): + if not re.fullmatch(r'[a-f0-9]{40}',source):return False + if path.resolve().parents[1]==Path('/home/dunerealms/apps/dunerealms/releases/ci-'+source):return True + manifest=path.parent/'manifest.json' + if not manifest.is_file():return False + m=json.loads(manifest.read_text()) + record=m.get('files',{}).get(path.name,{}) + return (m.get('sourceRepository')=='https://www.dunerealms.com/git/unimatrix/web.git' + and m.get('sourceCommit')==source + and record.get('sha256')==hashlib.sha256(path.read_bytes()).hexdigest() + and record.get('bytes')==path.stat().st_size) + +def configured(text,token,key): + if not re.fullmatch(r'[A-Za-z0-9_-]{43}',token) or not re.fullmatch(r'[a-f0-9]{64}',key): + raise ValueError('Invalid private provisioning material') + lines=[line for line in text.splitlines() if not re.match(r'^\s*(?:export\s+)?(?:'+ '|'.join(KEYS)+r')\s*=',line)] + return '\n'.join(lines)+f'\nLOBBY_ACCOUNT_ENABLED=true\nLOBBY_ACCOUNT_TOKEN={token}\nLOBBY_ACCOUNT_ENCRYPTION_KEY={key}\n' + +def atomic(path,data,uid,gid): + fd,name=tempfile.mkstemp(prefix='.lobby-account-',dir=path.parent) + try: + with os.fdopen(fd,'w') as stream: + os.fchmod(stream.fileno(),0o600);os.fchown(stream.fileno(),uid,gid) + stream.write(data);stream.flush();os.fsync(stream.fileno()) + os.replace(name,path) + finally: + Path(name).unlink(missing_ok=True) + +def main(): + p=argparse.ArgumentParser(description=__doc__);p.add_argument('--source',required=True);p.add_argument('--apply',action='store_true');a=p.parse_args() + if not reviewed_source(Path(__file__).resolve(),a.source): + raise ValueError('Run the exact immutable release or independently verified CI operations artifact') + if ENV.resolve()!=ENV or not ENV.is_file() or ENV.stat().st_mode&0o077: + raise ValueError('Existing private website environment required') + if not a.apply: + print(json.dumps({'applied':False,'source':a.source,'scope':'Lobby account provisioning only','secretsExposed':False}));return + STATE.mkdir(parents=True,exist_ok=True,mode=0o700) + if STATE.resolve()!=STATE or STATE.stat().st_mode&0o077:raise ValueError('Private canonical state directory required') + material=STATE/'credentials.json' + if material.exists(): + if material.is_symlink() or material.stat().st_mode&0o077:raise ValueError('Private credential file required') + s=json.loads(material.read_text()) + else: + s={'token':secrets.token_urlsafe(32),'key':secrets.token_hex(32)} + fd=os.open(material,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600) + with os.fdopen(fd,'w') as f:json.dump(s,f) + current=ENV.read_text();updated=configured(current,s['token'],s['key']);st=ENV.stat() + atomic(STATE/'lobby-account.token',s['token']+'\n',0,0) + if current!=updated:atomic(ENV,updated,st.st_uid,st.st_gid) + print(json.dumps({'applied':True,'source':a.source,'websiteRestartRequired':True,'privateTokenFile':str(STATE/'lobby-account.token'),'secretsExposed':False})) + +if __name__=='__main__':main() diff --git a/website/ops/enable-staff-tools.mjs b/website/ops/enable-staff-tools.mjs new file mode 100644 index 00000000..86a7cd21 --- /dev/null +++ b/website/ops/enable-staff-tools.mjs @@ -0,0 +1,48 @@ +import {realpath} from 'node:fs/promises'; +import {fileURLToPath,pathToFileURL} from 'node:url'; +import {resolve} from 'node:path'; +import {createOrganisationManagement} from '../node/organisation-management.mjs'; +import {validStaffRole} from '../node/organisation-model.mjs'; +import {OFFICIAL_ACCOUNT} from '../node/official-account.mjs'; +import {openDatabase} from '../node/mysql.mjs'; + +export const STAFF_TOOL_NODES=Object.freeze(['dunestaff.fly','dunestaff.vanish','dunestaff.vanish.see']); +const same=(a,b)=>JSON.stringify([...a].sort())===JSON.stringify([...b].sort()); +export function staffToolPolicyPlan(policies){ + return policies.filter(p=>validStaffRole(p.scope_type,p.scope_key,p.role_key)).flatMap(p=>{ + if(!Array.isArray(p.nodes)||!Number.isSafeInteger(p.version)||p.version<1)throw Error('Invalid current staff policy'); + const nodes=[...new Set([...p.nodes,...STAFF_TOOL_NODES])].sort(); + return same(nodes,p.nodes)?[]:[{scopeType:p.scope_type,scopeKey:p.scope_key,role:p.role_key,version:p.version,before:[...p.nodes],nodes}]; + }); +} +export async function enableStaffTools(db,actor,{apply=false}={}){ + if(actor?.id!==OFFICIAL_ACCOUNT.ownerId||actor?.username!=='unimatrix999')throw Error('Existing verified Owner required'); + const origin='https://cp.dunerealms.com',url=origin+'/api/admin/organisation/policies'; + const route=createOrganisationManagement(db,{origin,authenticate:async()=>actor}); + const read=async()=>{const r=await route(new Request(url));if(r.status!==200)throw Error('Staff policy authority unavailable');const j=await r.json();if(j.canEdit!==true||j.enforcement!=='active')throw Error('Active central policy authority required');return j;}; + const plan=staffToolPolicyPlan((await read()).policies); + if(!apply)return {applied:0,planned:plan.length,nodes:STAFF_TOOL_NODES}; + let applied=0; + for(const p of plan){ + const current=await read(),row=current.policies.find(r=>r.scope_type===p.scopeType&&r.scope_key===p.scopeKey&&r.role_key===p.role); + if(!row||row.version!==p.version||!same(row.nodes,p.before))throw Error('Staff policy changed; review a fresh plan'); + const scope=current.versions.find(r=>r.scope_type===p.scopeType&&r.scope_key===p.scopeKey); + const r=await route(new Request(url,{method:'POST',headers:{origin,'Content-Type':'application/json'},body:JSON.stringify({scopeType:p.scopeType,scopeKey:p.scopeKey,role:p.role,nodes:p.nodes,scopeVersion:Number(scope?.version||1),reason:'Owner requested staff /fly and /vanish for The Wild Update'})})); + if(r.status!==200)throw Error('Original staff policy publisher rejected update: '+r.status); + applied++; + } + return {applied,planned:plan.length,nodes:STAFF_TOOL_NODES}; +} +async function main(){ + const args=process.argv.slice(2),source=args.find(a=>a.startsWith('--source='))?.slice(9); + if(!/^[a-f0-9]{40}$/.test(source||'')||args.some(a=>a!=='--apply'&&!a.startsWith('--source=')))throw Error('Exact reviewed --source required'); + const release=await realpath(fileURLToPath(new URL('..',import.meta.url))); + if(!release.endsWith('/releases/ci-'+source))throw Error('Run only the exact immutable reviewed release'); + process.loadEnvFile('/home/dunerealms/.config/dunerealms.env'); + const db=await openDatabase(process.env); + try{ + const actor=await db.prepare("SELECT id,username FROM site_accounts WHERE id=? AND username='unimatrix999' AND password_hash NOT LIKE '!%'").bind(OFFICIAL_ACCOUNT.ownerId).first(); + console.log(JSON.stringify({source,...await enableStaffTools(db,actor,{apply:args.includes('--apply')})})); + }finally{await db.close();} +} +if(process.argv[1]&&import.meta.url===pathToFileURL(await realpath(resolve(process.argv[1]))).href)await main(); diff --git a/website/ops/grant-user-voice.mjs b/website/ops/grant-user-voice.mjs new file mode 100644 index 00000000..83f0d501 --- /dev/null +++ b/website/ops/grant-user-voice.mjs @@ -0,0 +1,32 @@ +import {readFile} from 'node:fs/promises'; +import {fileURLToPath} from 'node:url'; +import {realpath} from 'node:fs/promises'; +import mysql from 'mysql2/promise'; +import {randomUUID} from 'node:crypto'; +import {OFFICIAL_ACCOUNT} from '../node/official-account.mjs'; +import {accessFor} from '../node/permissions.mjs'; +import {syncGamePermissions} from '../node/game-permission-sync.mjs'; +import {voicePermissions} from '../node/user-voice-permissions.mjs'; + +async function main(){ + const [source,apply]=process.argv.slice(2); + if(!/^[a-f0-9]{40}$/.test(source||'')||apply&&apply!=='--apply')throw Error('Exact reviewed release required'); + if(!(await realpath(fileURLToPath(new URL('..',import.meta.url)))).endsWith('/releases/ci-'+source))throw Error('Run the immutable built release'); + process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');const e=process.env; + const c=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,multipleStatements:false}); + const db={query:async(sql,v=[])=> (await c.execute(sql,v))[0],organisationAccessEnabled:e.ORGANISATION_ACCESS_ENABLED==='true',prepare(sql){let v=[];return {bind(...values){v=values;return this;},async first(){return (await c.execute(sql,v))[0][0]||null;},async all(){return {results:(await c.execute(sql,v))[0]};}};},async readSnapshot(fn){await c.query('START TRANSACTION READ ONLY');try{const r=await fn(db);await c.commit();return r;}catch(err){await c.rollback();throw err;}}}; + try{ + const actor=(await c.execute("SELECT id,username,role FROM site_accounts WHERE id=? AND username='unimatrix999' AND password_hash NOT LIKE '!%'",[OFFICIAL_ACCOUNT.ownerId]))[0][0]; + if(!actor||!(await accessFor(db,actor)).nodes.includes('web.ranks.manage'))throw Error('Existing Owner rank authority required'); + await c.beginTransaction(); + try{ + const row=(await c.execute("SELECT permissions_json,version FROM cp_rank_game_permissions WHERE rank_key='user' FOR UPDATE"))[0][0];if(!row)throw Error('Existing User rank required'); + const before=JSON.parse(row.permissions_json),after=voicePermissions(before),changed=JSON.stringify(before)!==JSON.stringify(after); + if(!apply){await c.rollback();console.log(JSON.stringify({applied:false,rank:'user',added:after.filter(n=>!before.includes(n)),source}));return;} + if(changed){await c.execute("UPDATE cp_rank_game_permissions SET permissions_json=?,version=version+1 WHERE rank_key='user' AND version=?",[JSON.stringify(after),row.version]);await c.execute('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'game-rank-permissions',JSON.stringify({rank:'user',version:row.version,added:after.filter(n=>!before.includes(n)),source}),Date.now()]);} + await c.commit();console.log(JSON.stringify({applied:true,changed,rank:'user',source})); + }catch(err){await c.rollback();throw err;} + await syncGamePermissions(db);console.log(JSON.stringify({nativeSyncConfirmed:true,source})); + }finally{await c.end();} +} +main().catch(()=>{console.error('User voice permission update or synchronization could not be confirmed.');process.exitCode=1;}); diff --git a/website/ops/install-user-voice-catalogue.py b/website/ops/install-user-voice-catalogue.py new file mode 100644 index 00000000..d2a329a6 --- /dev/null +++ b/website/ops/install-user-voice-catalogue.py @@ -0,0 +1,34 @@ +"""Add only the three reviewed player voice nodes to the native permission bridge.""" +import argparse,hashlib,json,os,shutil,subprocess,tempfile +from pathlib import Path +TARGET=Path('/opt/dunerealms/server-control/managed-game-permissions.json') +NODES=('voicechat.listen','voicechat.speak','voicechat.groups') +BASE='bcb6f06da0e0a29a600ca577225ac4c4f94910fd086f5ca7b3be3c59ba71646b' +def extend(old,catalogue): + before=json.loads(old);source=json.loads(catalogue);by_name={n['node']:n for n in source['nodes']};have={n['node']:n for n in before['nodes']} + for name in NODES: + item=by_name[name] + if item.get('highRisk') is not False:raise ValueError('Invalid player voice node') + if name in have and have[name]!=item:raise ValueError('Existing voice node differs') + if name not in have:before['nodes'].append(item) + return (json.dumps(before,indent=2)+'\n').encode() +def main(): + p=argparse.ArgumentParser(description=__doc__);p.add_argument('--catalogue',required=True);p.add_argument('--apply',action='store_true');a=p.parse_args() + old=TARGET.read_bytes();new=extend(old,Path(a.catalogue).read_bytes());digest=lambda b:hashlib.sha256(b).hexdigest() + if digest(old)!=BASE and json.loads(old)!=json.loads(new):raise ValueError('Native bridge baseline changed') + print(json.dumps({'before':digest(old),'after':digest(new),'nodes':NODES,'changed':json.loads(old)!=json.loads(new)})) + if not a.apply or json.loads(old)==json.loads(new):return + if os.getuid()!=0:raise ValueError('Root required') + backup=Path('/var/lib/dunerealms-operations/user-voice-catalogue-before.json');backup.parent.mkdir(mode=0o700,parents=True,exist_ok=True) + if backup.exists() and backup.read_bytes()!=old:raise ValueError('Prior recovery record differs') + backup.write_bytes(old);backup.chmod(0o600);st=TARGET.stat();temp=TARGET.with_name(TARGET.name+'.voice-new') + try: + temp.write_bytes(new);os.chmod(temp,st.st_mode&0o777);os.chown(temp,st.st_uid,st.st_gid) + if TARGET.read_bytes()!=old:raise ValueError('Native bridge catalogue changed before write') + os.replace(temp,TARGET) + try:subprocess.run(['systemctl','restart','dunerealms-server-control.service'],check=True);subprocess.run(['systemctl','is-active','--quiet','dunerealms-server-control.service'],check=True) + except Exception: + TARGET.write_bytes(old);subprocess.run(['systemctl','restart','dunerealms-server-control.service'],check=False);raise + finally:temp.unlink(missing_ok=True) + print(json.dumps({'applied':True,'voiceAdminGranted':False})) +if __name__=='__main__':main() diff --git a/website/ops/publish-cookbook-route.py b/website/ops/publish-cookbook-route.py new file mode 100644 index 00000000..991ee263 --- /dev/null +++ b/website/ops/publish-cookbook-route.py @@ -0,0 +1,43 @@ +"""Route the cookbook to the current tested application instead of an old static copy.""" +import argparse,hashlib,importlib.util,json,os,re,urllib.request +from pathlib import Path +spec=importlib.util.spec_from_file_location('shared',Path(__file__).with_name('publish-shared-design-route.py'));shared=importlib.util.module_from_spec(spec);spec.loader.exec_module(shared) +CURRENT=Path('/home/dunerealms/apps/dunerealms/current') +TARGET=Path('/etc/nginx/snippets/dunerealms-cookbook-e40883ba.conf') +LEGACY='/var/www/dunerealms-cookbook-e40883ba/' +FILES=('imperial-recipe-book.html','lets-play.html','imperial-recipe-book.css','imperial-recipe-book.js','recipe-catalogue.json') +IDS={'dunechest_'+name for name in ('ender_chest','speed_hopper_1','speed_hopper_2','speed_hopper_3','auto_crafter','wrench')} +def route_content(old): + for suffix in (*FILES,'recipe-icons/'): + prefix='^~' if suffix.endswith('/') else '=' + matches=list(re.finditer(r'location\s+'+re.escape(prefix)+r'\s*/'+re.escape(suffix)+r'\s*\{[^{}]*\}',old)) + if not matches:continue + if len(matches)!=1:raise ValueError('Duplicate cookbook route: '+suffix) + match=matches[0] + if not re.search(r'alias\s+'+re.escape(LEGACY+suffix)+r'\s*;',match[0]):raise ValueError('Cookbook route is not the verified legacy alias') + old=old[:match.start()]+old[match.end():] + return old + +def serving_port(config): + ports={int(p) for p in re.findall(r'proxy_pass\s+http://127\.0\.0\.1:(\d+)',config)} & {3000,3100,3200} + if len(ports)!=1:raise ValueError('Ambiguous current application upstream') + return ports.pop() + +def validate_catalogue(payload): + recipes=json.loads(payload);found={r['id']:r for r in recipes if r.get('id') in IDS} + if set(found)!=IDS or any(len(r.get('grid',[]))!=9 for r in found.values()):raise ValueError('Current built cookbook is incomplete') + return len(recipes) +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--expected-release',required=True);parser.add_argument('--apply',action='store_true');parser.add_argument('--plan-hash');args=parser.parse_args() + if not re.fullmatch('[a-f0-9]{40}',args.expected_release) or CURRENT.resolve().name!='ci-'+args.expected_release:raise ValueError('Active built release changed') + port=serving_port(Path('/etc/nginx/sites-enabled/dunerealms-migration').read_text()) + request=urllib.request.Request(f'http://127.0.0.1:{port}/recipe-catalogue.json',headers={'Host':'www.dunerealms.com'}) + with urllib.request.urlopen(request,timeout=15) as response:payload=response.read(1000000) + count=validate_catalogue(payload);old=TARGET.read_text();new=route_content(old);sha=lambda b:hashlib.sha256(b).hexdigest() + plan={'release':args.expected_release,'target':str(TARGET),'before':sha(old.encode()),'after':sha(new.encode()),'catalogueSha256':sha(payload),'recipes':count} + digest=sha(json.dumps(plan,sort_keys=True).encode());print(json.dumps({**plan,'planHash':digest,'applied':False})) + if args.apply: + if os.getuid()!=0 or args.plan_hash!=digest:raise ValueError('Root and matching reviewed plan required') + backup=Path('/home/dunerealms/backups/cookbook-route-'+args.expected_release)/TARGET.name + changed=shared.replace_config(TARGET,new,backup);print(json.dumps({'applied':True,'changed':changed,'backup':str(backup)})) +if __name__=='__main__':main() diff --git a/website/ops/publish-release.mjs b/website/ops/publish-release.mjs index 774f207e..f0abf1bc 100644 --- a/website/ops/publish-release.mjs +++ b/website/ops/publish-release.mjs @@ -25,7 +25,7 @@ async function main(){ const release=await realpath(fileURLToPath(new URL('..',import.meta.url))); if(!release.endsWith('/releases/ci-'+source))throw Error('Run only the exact immutable reviewed release helper'); const manifest=JSON.parse(await readFile(resolve(release,'web/release.json'),'utf8')); - if(manifest.stage!=='beta'||manifest.version!=='1.0.2.0')throw Error('Reviewed Pillager release metadata required'); + if(manifest.stage!=='beta'||manifest.version!=='1.0.3.0'||manifest.scope!=='The Wild Update')throw Error('Reviewed Wild release metadata required'); process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');const e=process.env; const c=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,multipleStatements:false}); const db={query:async(sql,v=[])=> (await c.execute(sql,v))[0],prepare(sql){let values=[];return {bind(...v){values=v;return this;},async first(){return (await c.execute(sql,values))[0][0]||null;},async run(){return {meta:{changes:(await c.execute(sql,values))[0].affectedRows}};}};}}; diff --git a/website/ops/release-owner-homeblock.mjs b/website/ops/release-owner-homeblock.mjs index 5c7665f1..1cea572c 100644 --- a/website/ops/release-owner-homeblock.mjs +++ b/website/ops/release-owner-homeblock.mjs @@ -7,8 +7,8 @@ import {createOrganisationKeys} from '../node/organisation-keys.mjs'; import {createCodexEditions} from '../node/codex-editions.mjs'; import {currentCodexEdition} from '../node/organisation-key-service.mjs'; async function main(){ - const args=process.argv.slice(2),value=name=>args.find(a=>a.startsWith('--'+name+'='))?.slice(name.length+3),source=value('source'),requestId=value('request-id'); - if(!/^[a-f0-9]{40}$/.test(source||'')||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(requestId||'')||args.some(a=>a!=='--apply'&&!/^--(?:source|request-id)=/.test(a)))throw Error('Reviewed source and stable operation UUID required'); + const args=process.argv.slice(2),value=name=>args.find(a=>a.startsWith('--'+name+'='))?.slice(name.length+3),source=value('source'),requestId=value('request-id'),kind=value('kind')||'clan'; + if(!['clan','company'].includes(kind)||!/^[a-f0-9]{40}$/.test(source||'')||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(requestId||'')||args.some(a=>a!=='--apply'&&!/^--(?:source|request-id|kind)=/.test(a)))throw Error('Reviewed source, clan/company kind and stable operation UUID required'); const release=await realpath(fileURLToPath(new URL('..',import.meta.url)));if(!release.endsWith('/releases/ci-'+source))throw Error('Run the exact immutable reviewed release helper'); process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');const e=process.env; const c=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,multipleStatements:false});let active=false; @@ -17,9 +17,9 @@ async function main(){ try{ const directory=resolve('/var/lib/dunerealms-operations/owner-homeblock'),state=resolve(directory,requestId+'.json');let prior; try{const st=await lstat(state);if(!st.isFile()||st.isSymbolicLink())throw Error('Invalid operation journal');prior=JSON.parse(await readFile(state,'utf8'));}catch(error){if(error.code!=='ENOENT')throw error;} - const plan=prior?.plan||await ownerHomeBlockPlan(db); - if(prior&&(prior.requestId!==requestId||prior.source!==source))throw Error('Operation journal binding mismatch'); - const summary={source,requestId,clan:plan.clanName,revision:plan.revision,feeMinor:0,financialWrites:false}; + const plan=prior?.plan||await ownerHomeBlockPlan(db,kind); + if(prior&&(prior.requestId!==requestId||prior.source!==source)||(plan.kind||'clan')!==kind)throw Error('Operation journal binding mismatch'); + const summary={source,requestId,kind,organisation:plan.clanName||plan.companyName,revision:plan.revision,feeMinor:0,financialWrites:false}; if(!args.includes('--apply')){console.log(JSON.stringify({applied:false,...summary}));return;} await mkdir(directory,{recursive:true,mode:0o700});if(await realpath(directory)!==directory)throw Error('Noncanonical operation directory'); if(!prior)await writeFile(state,JSON.stringify({source,requestId,plan}),{flag:'wx',mode:0o600}); diff --git a/website/ops/test_cookbook_route.py b/website/ops/test_cookbook_route.py new file mode 100644 index 00000000..9a4c4400 --- /dev/null +++ b/website/ops/test_cookbook_route.py @@ -0,0 +1,19 @@ +import importlib.util,json,unittest +from pathlib import Path +spec=importlib.util.spec_from_file_location('book',Path(__file__).with_name('publish-cookbook-route.py'));book=importlib.util.module_from_spec(spec);spec.loader.exec_module(book) +class CookbookRoute(unittest.TestCase): + def original(self):return '\n'.join('location '+('^~' if p.endswith('/') else '=')+' /'+p+' { alias '+book.LEGACY+p+'; }' for p in (*book.FILES,'recipe-icons/'))+'\n'+book.shared.ROUTE + def test_routes_entire_cookbook_and_preserves_shared_design(self): + after=book.route_content(self.original());self.assertNotIn('proxy_pass',after);self.assertNotIn('recipe-catalogue.json',after);self.assertIn(book.shared.ROUTE,after);self.assertEqual(book.route_content(after),after) + def test_unknown_or_duplicate_route_is_refused(self): + for old in (self.original().replace(book.LEGACY+'recipe-catalogue.json','/unexpected.json'),self.original()+'\nlocation = /recipe-catalogue.json {}'): + with self.assertRaises(ValueError):book.route_content(old) + def test_serving_port_tracks_both_promotion_slots(self): + for port in (3100,3200):self.assertEqual(book.serving_port(f'proxy_pass http://127.0.0.1:{port};'),port) + with self.assertRaises(ValueError):book.serving_port('proxy_pass http://127.0.0.1:3100; proxy_pass http://127.0.0.1:3200;') + def test_old_catalogue_or_missing_recipe_grid_is_refused(self): + recipes=[{'id':key,'grid':[None]*9} for key in book.IDS];self.assertEqual(book.validate_catalogue(json.dumps(recipes)),6) + with self.assertRaises(ValueError):book.validate_catalogue('[]') + recipes[0]['grid']=[] + with self.assertRaises(ValueError):book.validate_catalogue(json.dumps(recipes)) +if __name__=='__main__':unittest.main() diff --git a/website/ops/test_lobby_account_config.py b/website/ops/test_lobby_account_config.py new file mode 100644 index 00000000..b0a74af6 --- /dev/null +++ b/website/ops/test_lobby_account_config.py @@ -0,0 +1,28 @@ +import importlib.util +from pathlib import Path +import unittest +import tempfile +import json +import hashlib + +s=importlib.util.spec_from_file_location('lobby_config',Path(__file__).with_name('configure-lobby-account.py')) +m=importlib.util.module_from_spec(s);s.loader.exec_module(m) + +class ConfigTests(unittest.TestCase): + def test_only_three_settings_change_and_replay_is_stable(self): + old='# private config\nDB_PASSWORD=untouched\nLOBBY_ACCOUNT_ENABLED=false\nexport LOBBY_ACCOUNT_TOKEN=old\nOTHER=true\n' + result=m.configured(old,'a'*43,'b'*64) + self.assertIn('DB_PASSWORD=untouched',result);self.assertIn('OTHER=true',result) + self.assertNotIn('=old',result);self.assertEqual(result,m.configured(result,'a'*43,'b'*64)) + self.assertEqual(result.count('LOBBY_ACCOUNT_TOKEN='),1) + def test_invalid_material_cannot_enter_environment(self): + with self.assertRaises(ValueError):m.configured('',"x\nBAD=true",'b'*64) + def test_artifact_source_and_helper_bytes_must_match(self): + with tempfile.TemporaryDirectory() as folder: + p=Path(folder)/'configure-lobby-account.py';p.write_bytes(b'verified') + manifest={'sourceRepository':'https://www.dunerealms.com/git/unimatrix/web.git','sourceCommit':'a'*40,'files':{p.name:{'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'bytes':8}}} + (p.parent/'manifest.json').write_text(json.dumps(manifest)) + self.assertTrue(m.reviewed_source(p,'a'*40));self.assertFalse(m.reviewed_source(p,'b'*40)) + p.write_bytes(b'changed!');self.assertFalse(m.reviewed_source(p,'a'*40)) + +if __name__=='__main__':unittest.main() diff --git a/website/ops/test_user_voice_catalogue.py b/website/ops/test_user_voice_catalogue.py new file mode 100644 index 00000000..b0414f21 --- /dev/null +++ b/website/ops/test_user_voice_catalogue.py @@ -0,0 +1,9 @@ +import importlib.util,json,unittest +from pathlib import Path +spec=importlib.util.spec_from_file_location('voice',Path(__file__).with_name('install-user-voice-catalogue.py'));v=importlib.util.module_from_spec(spec);spec.loader.exec_module(v) +class VoiceCatalogue(unittest.TestCase): + def test_only_new_player_nodes_are_added_and_existing_roles_retained(self): + old={'version':1,'nodes':[{'node':'existing','highRisk':True}],'suggestedRoles':[{'id':'user','permissions':{'existing':True}}]};catalogue={'nodes':[{'node':n,'highRisk':False} for n in v.NODES]+[{'node':'voicechat.admin','highRisk':True}]};new=json.loads(v.extend(json.dumps(old),json.dumps(catalogue)));self.assertEqual(new['suggestedRoles'],old['suggestedRoles']);self.assertEqual(new['nodes'][0],old['nodes'][0]);self.assertEqual(len(new['nodes']),4);self.assertNotIn('voicechat.admin',[n['node'] for n in new['nodes']]);self.assertEqual(json.loads(v.extend(json.dumps(new),json.dumps(catalogue))),new) + def test_existing_conflicting_node_is_refused(self): + with self.assertRaises(ValueError):v.extend(json.dumps({'nodes':[{'node':'voicechat.listen','highRisk':True}]}),json.dumps({'nodes':[{'node':n,'highRisk':False} for n in v.NODES]})) +if __name__=='__main__':unittest.main() diff --git a/website/scripts/deployment-package.mjs b/website/scripts/deployment-package.mjs index c5d63cc4..187d0b6c 100644 --- a/website/scripts/deployment-package.mjs +++ b/website/scripts/deployment-package.mjs @@ -6,7 +6,7 @@ import {createHash} from 'node:crypto'; export function packageDeploymentScripts(output,sourceCommit=null,{sourceDirectory=fileURLToPath(new URL('../ops/',import.meta.url))}={}){ if(sourceCommit!==null&&!/^[a-f0-9]{40}$/.test(sourceCommit))throw Error('Invalid deployment source commit'); const files={}; - for(const name of ['dunerealms-ci-trigger','dunerealms-build-release']){ + for(const name of ['dunerealms-ci-trigger','dunerealms-build-release','configure-lobby-account.py']){ const bytes=Buffer.from(readFileSync(path.join(sourceDirectory,name),'utf8').replaceAll('\r\n','\n')); files[name]={sha256:createHash('sha256').update(bytes).digest('hex'),bytes:bytes.length}; mkdirSync(output,{recursive:true});writeFileSync(path.join(output,name),bytes); diff --git a/website/scripts/homepage-header.css b/website/scripts/homepage-header.css index 078cfb86..c5b5173f 100644 --- a/website/scripts/homepage-header.css +++ b/website/scripts/homepage-header.css @@ -8,6 +8,8 @@ dune-shared-header[hidden]{display:none!important} :host .nav-inner{width:calc(100% - 64px);max-width:none;margin-inline:32px} @media(max-width:1120px){:host .nav-inner{width:calc(100% - 40px);margin-inline:20px}} @media(max-width:640px){:host .nav-inner{width:calc(100% - 28px);margin-inline:14px}} +/* Centre the shared desktop menu and its account controls as one compact row. */ +@media(min-width:1121px){:host .nav-inner{max-width:1180px;margin-inline:auto;justify-content:center;gap:40px}} :host [hidden]{display:none!important} :host .nav-actions .button{min-height:42px;font-size:14px;border-radius:4px;font-family:var(--font);font-weight:700} :host .shared-account-group{position:relative} diff --git a/website/scripts/news-announcements.json b/website/scripts/news-announcements.json index 81f28c8a..9dd11a65 100644 --- a/website/scripts/news-announcements.json +++ b/website/scripts/news-announcements.json @@ -11,5 +11,11 @@ "title": "Happy Beta! · DuneRealms Beta 1.0.0.0", "body": "The caravan endures. Welcome to DuneRealms Beta 1.0.0.0!\n\nThank you to our Alpha testers and the community that brought our worlds to life. The Beta era is now open. The realm’s worlds and economy remain intact as a new political chapter begins.\n\nYour House. Your destiny. Write your chapter.", "artwork": "assets/happy-beta-launch.png" + }, + { + "id": "wild-update-beta-1-0-3-0", + "publishedAt": "2026-12-03T23:17:00Z", + "title": "The Wild Update · DuneRealms Beta 1.0.3.0", + "body": "The Wild Update is live across Lobby and all five planets. Beta 1.0.3.0 brings a new look to the worlds, clearer missions, fixed smuggler contacts, spice-powered crafting and staff tools.\n\nA new look for the worlds\n\nLoad the updated server resource pack to see the new Dune item artwork and the lighter, realistic stone and ore family. Stone, cobblestone, andesite, granite, diorite, deepslate, tuff, gravel and the other covered rock families now have coordinated surfaces. Their stairs, slabs, walls and worked variants use the matching materials. Ores remain distinct in both stone and deepslate. This is an appearance update: it does not regenerate worlds or change where ores are found.\n\nThe circular backgrounds behind the affected graded tools have been removed. Your tools keep their enchantments, stats, MK and Quality. The vanilla pack also brings a softer amber enchantment glint.\n\nPeople and smugglers\n\nQuest characters, Quartermasters, House Registrars, Navigators, spice sellers and Home Block contacts now use Citizens player-style NPCs. Some characters still have a generic appearance while their individual skins are being prepared.\n\nArrakis has two fixed smuggler contacts near spawn. Esmar Tuek starts the delivery and Staban Tuek receives it. Fixed-NPC contracts are enabled, while roaming smugglers remain disabled. The contacts stay in separate locations, and the existing contract requirements, time limits, rewards and passage rules remain in place. The journal's find action points you towards the contact.\n\nA clearer mission journal\n\nThe new journal groups missions into story arcs and brings briefings, objectives, progress and rewards together. Track a mission to follow it in the sidebar and the in-game boss bar. Tracking advances within the same arc as you finish its missions. Mission steps opens the detailed screen for special actions such as briefings, turn-ins, refining and bounties.\n\nVerified completed, non-repeatable missions are settled when you log into the game or open the web journal. Repeatable missions remain manual claims. An XP-cap shortcut alone cannot trigger a payout for an unfinished objective.\n\nThe missing fauna and contract observation routes now default to enabled. New qualifying actions count from activation; actions that were never recorded cannot receive retrospective credit. The Personal Experience season cap is now level 100. Raising it does not grant free XP.\n\nSpice cookers and railway fuel\n\nCraft Spice-Infused Furnaces, Smokers, Blast Furnaces, Campfires and Soul Campfires to cook twice as fast. Combine raw Melange with coal or charcoal to make Spice Coal: each piece fuels 50 smelts and can power furnace minecarts. A minecart plus genuine Spice Coal makes the Spice Fuel Cart.\n\nAll seven new recipes are in the in-game Cookbook and the website Cookbook, with their ingredients, Quality and MK. Each recipe advances one MK beyond its base crafting step. The Cookbook also replaces the old sample Item Lore Archive menu.\n\nGuild passage\n\nYour own House's world remains free. Other paid passages start at 150 DM, increasing by 10% after each paid trip up to 5,000 DM; the fare ladder resets after 30 days without a paid trip. A qualifying clan or company Home Block at the destination halves the fare. Applicable free-passage decrees still apply.\n\nPaid arrivals carry a bounty worth five times the fare paid, claimable only on the destination world under the existing combat rules. Review the displayed fare and warning before confirming passage. Smuggler passage keeps its existing rules.\n\nEveryday fixes\n\nEmpty buckets left after lava is used as furnace fuel keep their origin world, including when a hopper collects them. Picking up lava preserves an existing bucket origin, and newly dropped saplings from naturally decaying leaves receive their origin world.\n\nThe Sigma soil-weathering bug that added snow during clear weather is fixed. Existing snow has been left in place.\n\nJoining no longer automatically puts another Imperial Codex item in your inventory. Open the menu with /drgui; /drgui item remains available if you want the item yourself. Authorised staff now have /fly and /vanish.\n\nHow to load the update\n\nReconnect and allow the server resource pack to finish downloading. Once the artwork-loaded message appears, reopen your menu. F3 + T reloads downloaded textures; reconnecting fetches the new pack." } ] diff --git a/website/scripts/recipe-catalogue.mjs b/website/scripts/recipe-catalogue.mjs index 3a26805d..e8ce28e7 100644 --- a/website/scripts/recipe-catalogue.mjs +++ b/website/scripts/recipe-catalogue.mjs @@ -4,6 +4,9 @@ const source = new URL('../data/cookbook/crafting/', import.meta.url); const smoker = new URL('../data/cookbook/survival-food-recipes.json', import.meta.url); const repairParts = new URL('../data/cookbook/starter-repair-parts.json', import.meta.url); +const duneChest = new URL('../data/cookbook/dunechest-recipes.json', import.meta.url); +const spiceCrafting = new URL('../data/cookbook/spice-crafting.json', import.meta.url); +const itemGrades = new URL('../data/cookbook/item-grades.json', import.meta.url); const arrakisItems = new URL('../data/cookbook/items/', import.meta.url); const vanillaFoodSaturation = { beef: 1.8, enchanted_golden_apple: 9.6 }; const itemSummaries = { @@ -40,6 +43,20 @@ function entry(id, name, material = id, custom = false) { return { id, name, material, custom }; } +export function withRecipeGrade(output, definition) { + if (!definition || definition.material !== output.material) throw Error('Missing or mismatched Cookbook grade for ' + output.id); + if (definition.mode === 'input') { + if (output.quality !== undefined || output.equipmentMark !== undefined || definition.quality !== undefined || definition.equipmentMark !== undefined) throw Error('Input-dependent item has a fixed grade: ' + output.id); + return { ...output, metadataMode: 'input' }; + } + const { quality, equipmentMark } = definition; + if (!['common', 'uncommon', 'rare', 'very_rare', 'legendary', 'mythic', 'relic'].includes(quality) + || (quality === 'relic' ? equipmentMark !== 'infinite' : !Number.isInteger(equipmentMark) || equipmentMark < 0 || equipmentMark > 14)) throw Error('Invalid Cookbook grade for ' + output.id); + if (output.quality !== undefined && output.quality !== quality + || output.equipmentMark !== undefined && output.equipmentMark !== equipmentMark) throw Error('Cookbook grade conflicts with its item definition: ' + output.id); + return { ...output, quality, equipmentMark }; +} + function item(command) { const material = command.match(/^minecraft:([a-z0-9_]+)/)?.[1]; if (!material) throw Error('Unrecognised recipe item ' + command); @@ -58,6 +75,8 @@ function item(command) { export function recipeCatalogue() { const recipes = []; + const metadata = JSON.parse(readFileSync(itemGrades, 'utf8')); + if (metadata.schema !== 1 || metadata.policy !== 's1-item-metadata-v1') throw Error('Unsupported Cookbook item metadata'); const spice = entry('spice', 'Melange Spice', 'orange_dye', true); const requiresSpice = new Set(['dunesponge.yml', 'spice_paste.yml', 'spice_dough.yml', 'weirding_module.yml']); for (const file of readdirSync(source).filter(name => name.endsWith('.yml')).sort()) { @@ -96,6 +115,48 @@ export function recipeCatalogue() { recipes.push({ id: 'brew_water_vial', station: 'Brewing stand', inputs: [blood, spice], output: water, amount: 1, possible: true, notes: brew }); recipes.push({ id: 'brew_water_of_life', station: 'Brewing stand', inputs: [blood, spice], output: life, amount: 1, possible: true, notes: brew + ' Drinking Water of Life has a 1% fatal chance.' }); recipes.push({ id: 'spice_boosted_potion', station: 'Brewing stand', inputs: [entry('imported_potion', 'Imported Potion', 'potion'), spice], output: entry('spice_boosted_potion', 'Spice-Boosted Potion', 'potion', true), amount: 1, notes: 'Brew once on Arrakis. Effect levels are multiplied by 1.25 and rounded to the nearest whole level; duration stays the same.' }); + const storage = JSON.parse(readFileSync(duneChest, 'utf8')); + for (const recipe of storage.recipes) { + if (recipe.shapeless) { + if (!Array.isArray(recipe.shapeless) || !recipe.shapeless.length || recipe.shapeless.length > 9) throw Error('Invalid shapeless DuneChest recipe'); + const inputs = recipe.shapeless.map(ingredient => item(ingredient)); + recipes.push({id: 'dunechest_' + recipe.id, station: crafting, inputs, + grid: Array.from({length: 9}, (_, index) => inputs[index] ?? null), + output: storage.items[recipe.id], amount: 1, shaped: false, notes: recipe.notes}); + continue; + } + if (recipe.pattern.length !== 3 || recipe.pattern.some(row => row.length !== 3)) throw Error('Invalid DuneChest crafting grid'); + const grid = recipe.pattern.flatMap(row => [...row].map(symbol => { + if (symbol === ' ') return null; + const ingredient = recipe.ingredients[symbol]; + const value = ingredient?.startsWith('minecraft:') ? item(ingredient) : storage.items[ingredient]; + if (!value) throw Error('Missing DuneChest ingredient ' + symbol); + return value; + })); + recipes.push({id: 'dunechest_' + recipe.id, station: crafting, inputs: grid.filter(Boolean), grid, + output: storage.items[recipe.id], amount: 1, shaped: true, + notes: 'Available on all six servers, including Lobby.'}); + } + for (const spec of JSON.parse(readFileSync(spiceCrafting, 'utf8'))) { + const output = {...entry(spec.id, spec.name, spec.material.toLowerCase(), true), summary: spec.details}; + let inputs, grid, shaped; + if (spec.id === 'spice_coal') { + inputs = [spice, entry('coal', 'Coal or Charcoal', 'coal')]; + shaped = false; + } else if (spec.id === 'spice_tender') { + inputs = [entry('minecart', 'Minecart', 'minecart'), entry('spice_coal', 'Spice Coal', 'coal', true)]; + shaped = false; + } else { + const iron = entry('iron_ingot', 'Iron Ingot', 'iron_ingot'); + const cooker = entry(output.material, output.material.replaceAll('_', ' ').replace(/\b\w/g, c => c.toUpperCase()), output.material); + grid = [iron, spice, iron, spice, cooker, spice, iron, spice, iron]; + inputs = grid.filter(Boolean); + shaped = true; + } + grid ??= Array.from({length: 9}, (_, index) => inputs[index] ?? null); + recipes.push({id: spec.id, station: crafting, inputs, grid, output, amount: 1, shaped, + notes: spec.details + (spec.id === 'spice_coal' ? ' Requires genuine raw Melange; ordinary orange dye will not work. One Spice Coal smelts 50 items.' : spec.id === 'spice_tender' ? ' Requires genuine Spice Coal; ordinary coal will not work.' : ' Requires genuine raw Melange and the matching vanilla cooker.')}); + } for (const recipe of recipes) { if (foodIds.has(recipe.output.id)) { const definition = JSON.parse(readFileSync(new URL(recipe.output.id + '.yml', arrakisItems), 'utf8')); @@ -104,7 +165,8 @@ export function recipeCatalogue() { if (!Number.isFinite(saturation)) throw Error('Missing saturation for ' + recipe.output.id); recipe.output = { ...recipe.output, material, stats: [{ label: 'Saturation per serving', value: '+' + saturation + ' points' }] }; } - const summary = itemSummaries[recipe.output.id]; + recipe.output = withRecipeGrade(recipe.output, metadata.items[recipe.output.id]); + const summary = itemSummaries[recipe.output.id] ?? recipe.output.summary; if (!summary) throw Error('Missing item summary for ' + recipe.output.id); recipe.output = { ...recipe.output, summary }; for (const ingredient of [...recipe.inputs, recipe.output]) { diff --git a/website/tests/bank-quest-activities.test.mjs b/website/tests/bank-quest-activities.test.mjs index f51f074b..17c3577f 100644 --- a/website/tests/bank-quest-activities.test.mjs +++ b/website/tests/bank-quest-activities.test.mjs @@ -32,3 +32,36 @@ test('earned DM is cumulative settled income across personal accounts, including assert.deepEqual(await bankQuestIncome(bank,'unknown',1000,2000),{wages:0,earned:0}); }finally{db.close();} }); +test('the first completed bank voucher redemption counts once for the current linked player',async()=>{ + const {createBankDepositQuestActivity}=await import('../node/bank-quest-activities.mjs'); + const f=await systemCharacterFixture(),sql=new DatabaseSync(':memory:'); + try{ + await initializeProgression(f.db); + await ensureProgressionPolicy(f.db,f.keys,{clock:()=>1000}); + await initializePersonalActivityEvents(f.db); + const player=f.people.Member,uuid=randomUUID(),clock=()=>2000,season={season_id:'S01',starts_at:1000}; + await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,player.id]); + sql.exec('CREATE TABLE ria_cash_redemptions(id TEXT PRIMARY KEY,owner_id TEXT,player_uuid TEXT,mode TEXT,state TEXT,amount_minor TEXT,created_at INT)'); + const insert=(mode,state,amount,at=1500,owner=player.id,link=uuid)=>{ + const id=randomUUID(); + sql.prepare('INSERT INTO ria_cash_redemptions VALUES(?,?,?,?,?,?,?)').run(id,owner,link,mode,state,amount,at); + return id; + }; + insert('cash','redeemed','100'); + insert('bank','prepared','100'); + insert('bank','redeemed','0'); + insert('bank','redeemed','100',999); + insert('bank','redeemed','100',2001); + insert('bank','redeemed','100',1500,f.people.Other.id); + insert('bank','redeemed','100',1500,player.id,randomUUID()); + const bank={query:async(text,args)=>sql.prepare(text).all(...args)}; + const collect=createBankDepositQuestActivity(f.db,bank,f.keys,{clock}); + assert.deepEqual(await collect(player,season),{pendingMetrics:['bank-deposit']}); + const id=insert('bank','redeemed','100'); + assert.deepEqual(await collect(player,season),{pendingMetrics:[]}); + await collect(player,season); + const proof=await verifiedPersonalActivities(f.db,f.keys,{accountId:player.id,minecraftUuid:uuid,seasonId:'S01',startsAt:1000,endsAt:100000,now:2000}); + assert.equal(proof.totals.get('bank-deposit'),1); + assert.deepEqual((await f.db.query('SELECT event_id FROM jarvis_personal_activity_events')).map(row=>row.event_id),[id]); + }finally{sql.close();f.db.close();} +}); diff --git a/website/tests/cookbook-item-grades.test.mjs b/website/tests/cookbook-item-grades.test.mjs new file mode 100644 index 00000000..33f6cadb --- /dev/null +++ b/website/tests/cookbook-item-grades.test.mjs @@ -0,0 +1,50 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {recipeCatalogue,withRecipeGrade} from '../scripts/recipe-catalogue.mjs'; +import {itemLoreModel} from '../control-panel/public/item-lore-model.mjs'; + +test('all Cookbook outputs have source-bound grades or explicitly preserve input metadata',()=>{ + const recipes=recipeCatalogue(),metadata=JSON.parse(readFileSync(new URL('../data/cookbook/item-grades.json',import.meta.url))); + assert.equal(recipes.length,46);assert.equal(new Set(recipes.map(r=>r.output.id)).size,39); + assert.equal(metadata.sourceRepository,'unimatrix/plugins');assert.match(metadata.sourceCommit,/^[a-f0-9]{40}$/); + for(const hash of Object.values(metadata.files))assert.match(hash,/^[a-f0-9]{64}$/); + for(const recipe of recipes){ + const definition=metadata.items[recipe.output.id];assert.ok(definition,recipe.id);assert.equal(recipe.output.material,definition.material); + if(definition.mode==='input'){ + assert.equal(recipe.id,'spice_boosted_potion');assert.equal(recipe.output.metadataMode,'input'); + assert.equal(recipe.output.quality,undefined);assert.equal(recipe.output.equipmentMark,undefined);continue; + } + const card=itemLoreModel({...recipe.output,nativeMetadata:true}); + assert.equal(card.quality,definition.quality);assert.equal(card.mark,definition.equipmentMark); + assert.doesNotMatch(card.qualityLabel,/not registered/);assert.doesNotMatch(card.markLabel,/not registered/); + } +}); + +test('previously missing output grades reach the shared item card without deriving them from device names',()=>{ + const recipes=recipeCatalogue(),get=id=>recipes.find(r=>r.output.id===id).output; + for(const [id,quality,mark] of [ + ['jerboa_leather','uncommon',3],['spice_bread','very_rare',9], + ['spice_block','uncommon',2],['smuggled_spice_block','uncommon',3], + ['crafted_elytra','very_rare',11],['jerboa_water_vial','rare',6],['water_of_life','very_rare',7], + ['dunechest_ender_chest','very_rare',9],['dunechest_auto_crafter','uncommon',3], + ['dunechest_wrench','very_rare',10],['dunechest_dune_beacon','rare',8], + ...[1,2,3].map(t=>['dunechest_speed_hopper_'+t,'uncommon',3]), + ]){assert.equal(get(id).quality,quality,id);assert.equal(get(id).equipmentMark,mark,id);} + const powercore=itemLoreModel(get('dunechest_dune_beacon')); + assert.match(powercore.title,/MK XIV/);assert.equal(powercore.markLabel,'MK VIII');assert.equal(powercore.qualityLabel,'Rare'); + assert.equal(get('dunechest_ender_chest').material,'ender_chest'); + const ingredient=recipes.find(r=>r.id==='dunechest_speed_hopper_2').grid[4]; + assert.equal(ingredient.id,'dunechest_speed_hopper_1'); +}); + +test('missing, conflicting or material-mismatched metadata cannot silently produce unknown item grades',()=>{ + const output={id:'fixture',material:'hopper'}; + const grade={material:'hopper',quality:'uncommon',equipmentMark:3}; + assert.throws(()=>withRecipeGrade(output,undefined),/Missing/); + assert.throws(()=>withRecipeGrade(output,{...grade,material:'barrel'}),/mismatched/); + assert.throws(()=>withRecipeGrade(output,{...grade,equipmentMark:15}),/Invalid/); + assert.throws(()=>withRecipeGrade({...output,quality:'legendary'},grade),/conflicts/); + assert.throws(()=>withRecipeGrade(output,{...grade,mode:'input'}),/fixed grade/); + assert.equal(withRecipeGrade({...output,name:'Anything MK XIV'},grade).equipmentMark,3); +}); diff --git a/website/tests/deployment-package.test.mjs b/website/tests/deployment-package.test.mjs index 55bf510f..73be1648 100644 --- a/website/tests/deployment-package.test.mjs +++ b/website/tests/deployment-package.test.mjs @@ -8,7 +8,7 @@ import {packageDeploymentScripts} from '../scripts/deployment-package.mjs'; test('built operational scripts have deterministic bytes, exact hashes and recorded source identity',()=>{ const folder=mkdtempSync(path.join(tmpdir(),'dune-web-deployment-')),source=path.join(folder,'source'),output=path.join(folder,'output');mkdirSync(source); - for(const name of ['dunerealms-ci-trigger','dunerealms-build-release'])writeFileSync(path.join(source,name),'#!/bin/bash\r\necho verified\r\n'); + for(const name of ['dunerealms-ci-trigger','dunerealms-build-release','configure-lobby-account.py'])writeFileSync(path.join(source,name),'#!/bin/bash\r\necho verified\r\n'); const commit='a'.repeat(40),manifest=packageDeploymentScripts(output,commit,{sourceDirectory:source}); assert.equal(manifest.sourceCommit,commit);assert.equal(manifest.sourceRepository,'https://www.dunerealms.com/git/unimatrix/web.git'); for(const [name,record] of Object.entries(manifest.files)){ diff --git a/website/tests/dunechest-cookbook.test.mjs b/website/tests/dunechest-cookbook.test.mjs new file mode 100644 index 00000000..6a577a60 --- /dev/null +++ b/website/tests/dunechest-cookbook.test.mjs @@ -0,0 +1,33 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {createHash} from 'node:crypto'; +import {recipeCatalogue,recipeIcons} from '../scripts/recipe-catalogue.mjs'; + +test('DuneChest cookbook preserves shaped gaps, exact custom upgrade ingredients and all seven outputs',()=>{ + const all=recipeCatalogue(),recipes=all.filter(r=>r.id.startsWith('dunechest_')); + assert.equal(recipes.length,7);assert.equal(new Set(recipes.map(r=>r.output.id)).size,7); + const by=id=>recipes.find(r=>r.id==='dunechest_'+id); + const wrench=by('wrench');assert.deepEqual(wrench.grid.map(i=>i?.material??null),['iron_ingot',null,'iron_ingot',null,'iron_ingot',null,null,'stick',null]);assert.equal(wrench.inputs.length,4); + for(const [tier,previous] of [[2,1],[3,2]]){ + const upgrade=by('speed_hopper_'+tier),core=upgrade.grid[4];assert.equal(core.id,'dunechest_speed_hopper_'+previous);assert.equal(core.custom,true);assert.ok(all.some(r=>r.output.id===core.id)); + } + assert.equal(by('ender_chest').inputs.filter(i=>i.material==='obsidian').length,7); + for(const r of recipes.filter(r=>r.shaped)){assert.equal(r.grid.length,9);assert.equal(r.amount,1);assert.equal(r.shaped,true);assert.match(r.notes,/all six servers, including Lobby/);assert.ok(r.output.quality);assert.ok(Number.isInteger(r.output.equipmentMark));} + const icons=new Map(recipeIcons(recipes));assert.equal(icons.size,6);for(const bytes of icons.values())assert.equal(bytes.subarray(0,8).toString('hex'),'89504e470d0a1a0a'); + const provenance=JSON.parse(readFileSync(new URL('../data/cookbook/dunechest-source.json',import.meta.url)));assert.equal(provenance.sourceCommit,'56346a273d1b014fa256d26d34b4a4e33cc1d6b5');assert.equal(Object.keys(provenance.files).length,2); + for(const [path,source] of Object.entries(provenance.icons))assert.equal(createHash('sha256').update(readFileSync(new URL('../data/cookbook/'+path,import.meta.url))).digest('hex'),source.sha256); +}); + +// This recipe must remain shapeless; the existing six shaped recipes retain their layouts. +test('Ixian names and the beamless powercore recipe use stable custom identities',()=>{ + const recipes=recipeCatalogue(),by=id=>recipes.find(r=>r.id==='dunechest_'+id); + for(const tier of [1,2,3])assert.equal(by('speed_hopper_'+tier).output.name,'Ixian sorting devices MK '+tier); + assert.equal(by('auto_crafter').output.name,'Ixian Replicator MK XIV'); + const beacon=by('dune_beacon');assert.equal(beacon.output.name,'Ixian Powercore MK XIV');assert.equal(beacon.output.id,'dunechest_dune_beacon'); + assert.deepEqual(beacon.inputs.map(i=>[i.material,i.custom]),[['beacon',false],['ender_eye',false]]); + assert.equal(beacon.shaped,false);assert.equal(beacon.grid.length,9);assert.equal(beacon.grid.filter(Boolean).length,2);assert.match(beacon.notes,/all six servers, including Lobby/); + assert.equal(beacon.output.equipmentMark,8);assert.equal(beacon.output.quality,'rare'); + const provenance=JSON.parse(readFileSync(new URL('../data/cookbook/dunechest-source.json',import.meta.url))); + assert.equal(createHash('sha256').update(readFileSync(new URL('../data/cookbook/'+provenance.beacon.icon.path,import.meta.url))).digest('hex'),provenance.beacon.icon.sha256); +}); diff --git a/website/tests/elytra-merge.test.mjs b/website/tests/elytra-merge.test.mjs new file mode 100644 index 00000000..9474b762 --- /dev/null +++ b/website/tests/elytra-merge.test.mjs @@ -0,0 +1,64 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {systemCharacterFixture} from './system-character-fixture.mjs'; +import {initializePOLProgression,ensurePOLProgressionPolicy,ensureElytraQuestPolicy,ensureElytraMergePolicy} from '../node/progression-pol.mjs'; +import {initializePOLActivityEvents} from '../node/pol-activity-events.mjs'; +import {createGameQuestEventsAPI} from '../node/game-quest-events.mjs'; +import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs'; +import {applyElytraAlternative} from '../node/elytra-quest-policy.mjs'; + +const secret='elytra-merge-fixture-secret-at-least-32-characters'; + +test('ordinary elytra acquisition never fabricates a physical armour merge',()=>{ + const facts=new Map([['flight-elytra-acquired',1]]); + applyElytraAlternative(facts); + assert.equal(facts.get('flight-crafted'),1); + assert.equal(facts.has('flight-merged'),false); + facts.set('flight-merged',1);applyElytraAlternative(facts); + assert.equal(facts.get('flight-merged'),1); +}); + +test('v10 installs only the merge configuration and preserves existing season and custom rewards',async()=>{ + const f=await systemCharacterFixture();try{ + await initializePOLProgression(f.db); + await ensureElytraQuestPolicy(f.db,f.keys,{clock:()=>1000}); + await f.db.query("UPDATE jarvis_pol_quest_config SET xp=321 WHERE definition_id='POL-ELYTRA-CRAFT'"); + const before=await f.db.query('SELECT * FROM jarvis_pol_quest_config ORDER BY definition_id'); + const season=await f.db.first('SELECT * FROM jarvis_pol_progression_seasons'); + await ensureElytraMergePolicy(f.db,f.keys,{clock:()=>2000}); + await ensureElytraMergePolicy(f.db,f.keys,{clock:()=>3000}); + assert.deepEqual(await f.db.query("SELECT * FROM jarvis_pol_quest_config WHERE definition_id<>'POL-ELYTRA-MERGE' ORDER BY definition_id"),before); + assert.deepEqual(await f.db.first('SELECT * FROM jarvis_pol_progression_seasons'),season); + assert.equal((await f.db.first("SELECT xp FROM jarvis_pol_quest_config WHERE definition_id='POL-ELYTRA-MERGE'")).xp,0); + assert.equal((await f.db.first("SELECT COUNT(*) n FROM organisation_keys WHERE scope_id='policy:POL:S01:v10'")).n,1); + }finally{f.db.close();} +}); + +test('one authenticated native merge receipt completes only the merge, replays once and cannot assert a bulk or wrong-dimension merge',async()=>{ + const f=await systemCharacterFixture();try{ + const clock=()=>2000; + await f.characters.provision(f.people.Owner,'esmar_tuek'); + await initializePOLProgression(f.db);await ensurePOLProgressionPolicy(f.db,f.keys,{clock:()=>1000}); + await ensureElytraMergePolicy(f.db,f.keys,{clock:()=>1000}); + await initializePOLActivityEvents(f.db);f.db.polActivityEventsEnabled=true; + const uuid=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,f.people.Member.id]); + const api=createGameQuestEventsAPI(f.db,f.keys,{GAME_LINK_SECRET:secret},{clock}); + const input={eventId:randomUUID(),uuid,kind:'flight_merged',server:'sigma-draconis-iv',occurredAt:2000,quantity:1,dimension:'NORMAL'}; + const send=(body,authenticated=true)=>api(new Request('https://cp.dunerealms.com/internal/game/quest-events',{method:'POST',headers:{...(authenticated?{authorization:'Bearer '+secret}:{}),'content-type':'application/json'},body:JSON.stringify(body)})); + assert.equal((await send(input,false)).status,401); + for(const bad of [{quantity:2},{quantity:0},{dimension:'NETHER'},{dimension:'THE_END'},{server:'lobby'},{source:'web'},{accountId:f.people.Owner.id}])assert.equal((await send({...input,...bad})).status,400); + assert.equal((await send({...input,uuid:randomUUID()})).status,403); + assert.equal((await send(input)).status,200); + const replay=await (await send(input)).json();assert.equal(replay.replayed,true); + assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_pol_activity_events')).n,1); + const runtime=createPOLProgressionRuntime(f.db,f.keys,{clock});await runtime.collect(f.people.Member); + const view=await runtime.quests.list(f.people.Member),merge=view.quests.find(q=>q.id==='POL-ELYTRA-MERGE'); + assert.equal(merge.progress,1);assert.equal(merge.canClaim,true);assert.equal(merge.xp,0); + assert.equal(view.quests.find(q=>q.id==='POL-ELYTRA-CRAFT').progress,0); + await runtime.quests.claim(f.people.Member,{definitionId:merge.id,revision:merge.revision,requestId:randomUUID()}); + const after=await runtime.quests.list(f.people.Member); + assert.equal(after.profile.totalXP,view.profile.totalXP); + assert.equal(after.quests.find(q=>q.id===merge.id).state,'claimed'); + }finally{f.db.close();} +}); diff --git a/website/tests/elytra-quests.test.mjs b/website/tests/elytra-quests.test.mjs index 4808bb46..dba8d074 100644 --- a/website/tests/elytra-quests.test.mjs +++ b/website/tests/elytra-quests.test.mjs @@ -4,4 +4,4 @@ import {defaultItemDesign,validateItemDesign} from '../control-panel/public/item test('new crafted Elytra grade preserves already published original Elytra definitions',()=>{for(const template of [elytraTemplate('basic'),CRAFTED_ELYTRA_TEMPLATE]){const design=defaultItemDesign(template.id);assert.equal(validateItemDesign(design).equipmentMark,template.equipmentMark);}assert.equal(elytraTemplate('basic').equipmentMark,13);assert.equal(CRAFTED_ELYTRA_TEMPLATE.equipmentMark,11);assert.equal(CRAFTED_ELYTRA_TEMPLATE.quality,'very_rare');}); import {questAwardXP} from '../node/progression-definitions.mjs';import {systemCharacterFixture} from './system-character-fixture.mjs';import {initializePOLProgression,ensurePOLProgressionPolicy} from '../node/progression-pol.mjs';import {initializePOLActivityEvents,createPOLActivityEvents} from '../node/pol-activity-events.mjs';import {createPOLProgressionRuntime} from '../node/progression-pol-runtime.mjs';import {ELYTRA_QUESTS} from '../control-panel/public/cp-v2/cp-v2-elytra-quests.mjs';import {flightDossier} from '../node/elytra-quest-policy.mjs'; test('elytra recipe remains outside the locked final dossier',()=>{const q={id:'POL-ELYTRA-CRAFT',state:'not-started',canStart:false};assert.equal(flightDossier(q).recipe,undefined);assert.equal(flightDossier({...q,canStart:true}).recipe.grid.length,3);assert.equal(flightDossier({...q,state:'active'}).recipe.grid.length,3);}); -test('one verified acquired Elytra completes only its Reputation branch and pays every remaining reward once',async()=>{const f=await systemCharacterFixture();try{const clock=()=>2000;await f.characters.provision(f.people.Owner,'esmar_tuek');await initializePOLProgression(f.db);await ensurePOLProgressionPolicy(f.db,f.keys,{clock});await initializePOLActivityEvents(f.db);f.db.polActivityEventsEnabled=true;const minecraftUuid=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[minecraftUuid,f.people.Member.id]);const producer={},events=createPOLActivityEvents(f.db,f.keys,{clock,authorizeProducer:async p=>p===producer}),runtime=createPOLProgressionRuntime(f.db,f.keys,{clock});await events.record(producer,{eventId:randomUUID(),accountId:f.people.Member.id,minecraftUuid,seasonId:'S01',metric:'flight-elytra-acquired',quantity:1,occurredAt:2000,reference:'verified-paid-delivery'});await runtime.collect(f.people.Member);let view=await runtime.quests.list(f.people.Member);assert.equal(view.quests.filter(q=>q.branch==='elytra'&&q.state==='claimed').length,ELYTRA_QUESTS.length);assert.equal(view.profile.totalXP,ELYTRA_QUESTS.reduce((sum,q)=>sum+questAwardXP(q,q.xp),0));assert.equal(view.quests.filter(q=>q.branch!=='elytra'&&q.state==='claimed').length,0);await runtime.collect(f.people.Member);assert.equal((await runtime.quests.list(f.people.Member)).profile.totalXP,2250);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_pol_quest_claims')).n,12);}finally{f.db.close();}}); +test('one verified acquired Elytra completes only its Reputation branch and pays every remaining reward once',async()=>{const f=await systemCharacterFixture();try{const clock=()=>2000;await f.characters.provision(f.people.Owner,'esmar_tuek');await initializePOLProgression(f.db);await ensurePOLProgressionPolicy(f.db,f.keys,{clock});await initializePOLActivityEvents(f.db);f.db.polActivityEventsEnabled=true;const minecraftUuid=randomUUID();await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[minecraftUuid,f.people.Member.id]);const producer={},events=createPOLActivityEvents(f.db,f.keys,{clock,authorizeProducer:async p=>p===producer}),runtime=createPOLProgressionRuntime(f.db,f.keys,{clock});await events.record(producer,{eventId:randomUUID(),accountId:f.people.Member.id,minecraftUuid,seasonId:'S01',metric:'flight-elytra-acquired',quantity:1,occurredAt:2000,reference:'verified-paid-delivery'});await runtime.collect(f.people.Member);let view=await runtime.quests.list(f.people.Member);assert.equal(view.quests.filter(q=>q.branch==='elytra'&&q.state==='claimed').length,ELYTRA_QUESTS.filter(q=>q.id!=='POL-ELYTRA-MERGE').length);assert.equal(view.profile.totalXP,ELYTRA_QUESTS.reduce((sum,q)=>sum+questAwardXP(q,q.xp),0));assert.equal(view.quests.filter(q=>q.branch!=='elytra'&&q.state==='claimed').length,0);await runtime.collect(f.people.Member);assert.equal((await runtime.quests.list(f.people.Member)).profile.totalXP,2250);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_pol_quest_claims')).n,12);}finally{f.db.close();}}); diff --git a/website/tests/fixtures/navigator-native-wire.json b/website/tests/fixtures/navigator-native-wire.json new file mode 100644 index 00000000..63c87f9a --- /dev/null +++ b/website/tests/fixtures/navigator-native-wire.json @@ -0,0 +1,119 @@ +{ + "home_list": { + "action": "home_list", + "origin": { + "kind": "clan", + "id": "00000000-0000-4000-8000-000000000002" + }, + "uuid": "00000000-0000-4000-8000-000000000001", + "sourceWorld": "caladan", + "sourceLocation": { + "worldUuid": "00000000-0000-4000-8000-000000000004", + "position": { + "x": 14, + "y": 66, + "z": -22 + }, + "observedAt": 1795990000000 + } + }, + "home_quote": { + "target": { + "kind": "company", + "id": "00000000-0000-4000-8000-000000000003" + }, + "action": "home_quote", + "origin": { + "kind": "clan", + "id": "00000000-0000-4000-8000-000000000002" + }, + "uuid": "00000000-0000-4000-8000-000000000001", + "sourceWorld": "caladan", + "sourceLocation": { + "worldUuid": "00000000-0000-4000-8000-000000000004", + "position": { + "x": 14, + "y": 66, + "z": -22 + }, + "observedAt": 1795990000000 + } + }, + "home_board": { + "target": { + "kind": "company", + "id": "00000000-0000-4000-8000-000000000003" + }, + "requestId": "00000000-0000-4000-8000-000000000008", + "confirmed": true, + "keyId": "00000000-0000-4000-8000-000000000005", + "version": 3, + "fareMinor": 12507, + "originHomeBlockId": "00000000-0000-4000-8000-000000000006", + "originRevision": 4, + "targetHomeBlockId": "00000000-0000-4000-8000-000000000007", + "targetRevision": 8, + "action": "home_board", + "origin": { + "kind": "clan", + "id": "00000000-0000-4000-8000-000000000002" + }, + "uuid": "00000000-0000-4000-8000-000000000001", + "sourceWorld": "caladan", + "sourceLocation": { + "worldUuid": "00000000-0000-4000-8000-000000000004", + "position": { + "x": 14, + "y": 66, + "z": -22 + }, + "observedAt": 1795990000000 + } + }, + "home_arrive": { + "action": "home_arrive", + "uuid": "00000000-0000-4000-8000-000000000001", + "server": "kaitain" + }, + "home_ready": { + "action": "home_ready", + "uuid": "00000000-0000-4000-8000-000000000001", + "server": "kaitain", + "requestId": "00000000-0000-4000-8000-000000000008" + }, + "home_delivered": { + "action": "home_delivered", + "uuid": "00000000-0000-4000-8000-000000000001", + "server": "kaitain", + "requestId": "00000000-0000-4000-8000-000000000008", + "arrivedAt": 1795990001000, + "arrival": { + "worldUuid": "00000000-0000-4000-8000-000000000009", + "position": { + "x": 100, + "y": 72, + "z": 200 + } + } + }, + "smuggler_quote": { + "action": "smuggler_quote", + "uuid": "00000000-0000-4000-8000-000000000001", + "sourceWorld": "sigma_draconis_iv" + }, + "smuggler_board": { + "action": "smuggler_board", + "requestId": "00000000-0000-4000-8000-000000000010", + "keyId": "00000000-0000-4000-8000-000000000005", + "version": 3, + "fareMinor": 12507, + "destination": "kaitain", + "uuid": "00000000-0000-4000-8000-000000000001", + "sourceWorld": "sigma_draconis_iv" + }, + "smuggler_return": { + "action": "smuggler_return", + "uuid": "00000000-0000-4000-8000-000000000001", + "sourceWorld": "kaitain" + } +} \ No newline at end of file diff --git a/website/tests/fixtures/quest-categories.plugin.json b/website/tests/fixtures/quest-categories.plugin.json new file mode 100644 index 00000000..9f588c56 --- /dev/null +++ b/website/tests/fixtures/quest-categories.plugin.json @@ -0,0 +1,19 @@ +{ + "version": 1, + "note": "Presentation only. Groups existing quest branches into themed story arcs. Quest ids, rewards, prerequisites and progress are untouched. Branches not listed here appear under 'Other Work'.", + "categories": [ + {"id":"arrival","title":"Arrival","tagline":"First steps beneath a foreign sun.","accent":"#d9b66a","icon":"quests/arrival","branches":["a"]}, + {"id":"coin","title":"Coin of the Realm","tagline":"Solari, ledgers and honest weights.","accent":"#cfa24a","icon":"quests/coin","branches":["b"]}, + {"id":"melange","title":"The Melange Path","tagline":"From raw sand to refined spice.","accent":"#e29a3f","icon":"quests/melange","branches":["c","spice-harvesting","spice-upgrading"]}, + {"id":"deep-desert","title":"Deep Desert","tagline":"Walk where the worms walk.","accent":"#c98b54","icon":"quests/deep-desert","branches":["d","discoveries"]}, + {"id":"place","title":"A Place in the Realm","tagline":"Earn a name, a trade and a seat at the table.","accent":"#bfa77a","icon":"quests/place","branches":["e","f","g"]}, + {"id":"armoury","title":"The Armoury","tagline":"Stillsuits, steel and good design.","accent":"#a89572","icon":"quests/armoury","branches":["h","i","acquisitions"]}, + {"id":"landsraad","title":"The Landsraad Game","tagline":"Four Houses. One game. No mercy.","accent":"#b9863f","icon":"quests/landsraad","branches":["atreides","harkonnen","corrino","ordos"]}, + {"id":"sons","title":"Sons of the Sand","tagline":"Water discipline, worm-sign and tribe.","accent":"#d28b3c","icon":"quests/sons","branches":["fremen","fremen-husbandry"]}, + {"id":"prophecy","title":"The Prophecy","tagline":"Faith, fear and the long game.","accent":"#d8c79a","icon":"quests/prophecy","branches":["faith-sisterhood","faith-church","bene"]}, + {"id":"lanes","title":"Lanes and Shadows","tagline":"Guild lanes, smugglers' routes and hunted bounties.","accent":"#b07a4a","icon":"quests/lanes","branches":["guild","smugglers","bounty-jobs"]}, + {"id":"contracts","title":"Contracts of the Realm","tagline":"Work for clan and company.","accent":"#c3a060","icon":"quests/contracts","branches":["clan","company"]}, + {"id":"wings","title":"Wings across the Realms","tagline":"Five worlds. One elytra.","accent":"#e0c27c","icon":"quests/wings","branches":["elytra"]}, + {"id":"campaign","title":"Campaign Banners","tagline":"Banners raised, ground held.","accent":"#b5653f","icon":"quests/campaign","branches":["war-service"]} + ] +} diff --git a/website/tests/game-guild-open-travel.test.mjs b/website/tests/game-guild-open-travel.test.mjs new file mode 100644 index 00000000..3f3922cb --- /dev/null +++ b/website/tests/game-guild-open-travel.test.mjs @@ -0,0 +1,202 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs'; +import {createGuildService,createGameGuildAPI,GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA,TRAVEL_LADDER_SCHEMA,TRAVEL_BOUNTY_SCHEMA,TRAVEL_BOUNTY_CLAIM_SCHEMA,TRAVEL_OPEN_PASSAGE_SCHEMA} from '../node/game-guild.mjs'; +const DAY=86400000,strip=sql=>sql.replace(/,INDEX \w+\([^)]*\)/,'').replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4',''); +async function fixture({openTravel=true,treasury=5000000,holding=async()=>false,decree=async()=>false}={}){ + const db=new BankFixture();for(const sql of [GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA,TRAVEL_LADDER_SCHEMA,TRAVEL_BOUNTY_SCHEMA,TRAVEL_BOUNTY_CLAIM_SCHEMA,TRAVEL_OPEN_PASSAGE_SCHEMA])await db.query(strip(sql)); + const make=(name,faction)=>{const user={id:randomUUID(),username:name,uuid:randomUUID(),faction,version:1,keyId:randomUUID()};return{user,entity:{id:randomUUID(),kind:'person',key:user.id,name}};}; + const traveller=make('traveller','atreides'),hunter=make('hunter','harkonnen'),people=[traveller,hunter]; + const authority=async u=>({entities:people.filter(p=>!u||p.user.id===u.id).map(p=>({...p.entity,canView:true,canActivate:true,canPay:true}))}),bank=new PostbankService(db,authority); + const accounts={}; + for(const p of people){await bank.activate(p.user,{entityId:p.entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});accounts[p.user.username]=(await db.first("SELECT id FROM pb_accounts WHERE type_code='102' AND system_key IS NULL ORDER BY id DESC LIMIT 1")).id;} + await db.query('UPDATE pb_accounts SET balance_minor=1000000 WHERE id=?',[accounts.traveller]); + await db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES('sys_game_treasury','999','Game treasury',?,0,'active',0)",[treasury]); + await db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES('sys_payroll_po','979','P&O issuer',0,0,'active',0)"); + let now=1200000;const byUuid=new Map(people.map(p=>[p.user.uuid,p.user])); + const service=createGuildService(db,{authority,openTravel,allowJourney:async()=>true,allowArrakis:decree,holdingOnWorld:holding,resolve:async uuid=>byUuid.get(uuid)||null,clock:()=>now}); + const balance=async who=>BigInt((await db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[accounts[who]])).balance_minor); + const issuerBalance=async()=>BigInt((await db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_payroll_po'")).balance_minor); + const treasuryBalance=async()=>BigInt((await db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_game_treasury'")).balance_minor); + const input=(destination,fareMinor)=>({uuid:traveller.user.uuid,requestId:randomUUID(),keyId:traveller.user.keyId,version:1,fareMinor,sourceWorld:'lobby',destination}); + const route=async(world)=>(await service.quote(traveller.user.uuid,'lobby')).routes.find(r=>r.server===world); + return{db,service,traveller:traveller.user,hunter:hunter.user,balance,treasuryBalance,issuerBalance,input,route,setTime:v=>now=v,advance:v=>now+=v,now:()=>now}; +} +test('the race world is free and every other world is quoted 150 DM with a bounty of five times that',async()=>{ + const f=await fixture();try{ + const home=await f.route('caladan'),other=await f.route('giedi_prime'); + assert.equal(home.fareMinor,0);assert.equal(home.free,true);assert.equal(home.available,true); + assert.equal(other.fareMinor,15000);assert.equal(other.bountyMinor,75000);assert.equal(other.free,false);assert.equal(other.available,true);assert.equal(other.reduced,false); + }finally{f.db.close();} +}); +test('free passage to the race world moves no money, creates no bounty and does not move the fare ladder',async()=>{ + const f=await fixture();try{ + const before=await f.balance('traveller'),booked=await f.service.board(f.input('caladan',0));assert.equal(booked.fareMinor,0); + const arrived=await f.service.arrive(f.traveller.uuid,'caladan');assert.equal(arrived.passage.state,'arrived');assert.equal(arrived.bounty,undefined); + assert.equal(await f.balance('traveller'),before);assert.equal((await f.route('giedi_prime')).fareMinor,15000); + assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_travel_bounties')).n,0); + }finally{f.db.close();} +}); +test('a paid arrival charges the fare, places a bounty of five times the fare and raises the next fare by 10%',async()=>{ + const f=await fixture();try{ + const before=await f.balance('traveller'),treasuryBefore=await f.treasuryBalance(); + await assert.rejects(f.service.board(f.input('giedi_prime',0)),/fare changed/); + await f.service.board(f.input('giedi_prime',15000));assert.equal(await f.balance('traveller'),before); + const arrived=await f.service.arrive(f.traveller.uuid,'giedi_prime'); + assert.equal(await f.balance('traveller'),before-15000n);assert.equal(await f.treasuryBalance(),treasuryBefore+15000n); + assert.deepEqual({world:arrived.bounty.world,amountMinor:arrived.bounty.amountMinor,traveller:arrived.bounty.traveller,state:arrived.bounty.state},{world:'giedi_prime',amountMinor:75000,traveller:'traveller',state:'open'}); + assert.equal((await f.route('giedi_prime')).fareMinor,16500);assert.equal((await f.route('giedi_prime')).bountyMinor,82500);assert.equal((await f.route('giedi_prime')).trip,2); + assert.equal((await f.service.arrive(f.traveller.uuid,'giedi_prime')).passage,null,'the arrival is reported once, so it is announced once'); + }finally{f.db.close();} +}); +test('a clan or company on the destination halves both the fare and the bounty',async()=>{ + const f=await fixture({holding:async(_u,_uuid,world)=>world==='giedi_prime'});try{ + assert.equal((await f.route('giedi_prime')).fareMinor,7500);assert.equal((await f.route('giedi_prime')).reduced,true);assert.equal((await f.route('kaitain')).fareMinor,15000); + await f.service.board(f.input('giedi_prime',7500));const arrived=await f.service.arrive(f.traveller.uuid,'giedi_prime');assert.equal(arrived.bounty.amountMinor,37500); + }finally{f.db.close();} +}); +test('the fare ladder resets after thirty days without a paid trip',async()=>{ + const f=await fixture();try{ + await f.service.board(f.input('giedi_prime',15000));await f.service.arrive(f.traveller.uuid,'giedi_prime');assert.equal((await f.route('giedi_prime')).fareMinor,16500); + f.advance(30*DAY-1);assert.equal((await f.route('giedi_prime')).fareMinor,16500); + f.advance(1);assert.equal((await f.route('giedi_prime')).fareMinor,15000); + }finally{f.db.close();} +}); +test('an Emperor free-passage decree makes Arrakis free and sanctioned: no fare and no bounty',async()=>{ + const f=await fixture({decree:async()=>true});try{ + assert.equal((await f.route('arrakis')).fareMinor,0);const before=await f.balance('traveller'); + await f.service.board(f.input('arrakis',0));const arrived=await f.service.arrive(f.traveller.uuid,'arrakis');assert.equal(arrived.bounty,undefined);assert.equal(await f.balance('traveller'),before); + }finally{f.db.close();} +}); +test('a hunter claims once from fixed P&O, preserving the Guild fare treasury',async()=>{ + const f=await fixture();try{ + await f.service.board(f.input('giedi_prime',15000));await f.service.arrive(f.traveller.uuid,'giedi_prime'); + const hunterBefore=await f.balance('hunter'),treasuryBefore=await f.treasuryBalance(),issuerBefore=await f.issuerBalance(),requestId=randomUUID(); + assert.deepEqual(await f.service.bountyClaim({killer:f.traveller.uuid,victim:f.traveller.uuid,server:'giedi_prime',requestId:randomUUID()}),{ok:true,claimed:false},'you cannot claim your own bounty'); + const claim=await f.service.bountyClaim({killer:f.hunter.uuid,victim:f.traveller.uuid,server:'giedi_prime',requestId}); + assert.equal(claim.claimed,true);assert.equal(claim.amountMinor,75000);assert.equal(await f.balance('hunter'),hunterBefore+75000n);assert.equal(await f.treasuryBalance(),treasuryBefore);assert.equal(await f.issuerBalance(),issuerBefore-75000n); + assert.equal((await f.service.bountyClaim({killer:f.hunter.uuid,victim:f.traveller.uuid,server:'giedi_prime',requestId})).replayed,true);assert.equal(await f.balance('hunter'),hunterBefore+75000n); + assert.deepEqual(await f.service.bountyClaim({killer:f.hunter.uuid,victim:f.traveller.uuid,server:'giedi_prime',requestId:randomUUID()}),{ok:true,claimed:false}); + }finally{f.db.close();} +}); +test('P&O uses the established issuer path without topping up or debiting Guild funds',async()=>{ + const f=await fixture({treasury:0});try{ + await f.service.board(f.input('giedi_prime',15000));await f.service.arrive(f.traveller.uuid,'giedi_prime'); + await f.db.query("UPDATE pb_accounts SET balance_minor=0 WHERE system_key='sys_game_treasury'"); + const claim=await f.service.bountyClaim({killer:f.hunter.uuid,victim:f.traveller.uuid,server:'giedi_prime',requestId:randomUUID()}); + assert.equal(claim.claimed,true);assert.equal(await f.treasuryBalance(),0n);assert.equal(await f.issuerBalance(),-75000n); + const entries=await f.db.query('SELECT amount_minor FROM pb_entries WHERE order_id=(SELECT id FROM pb_orders WHERE memo LIKE ?)', ['Travel bounty%']); + assert.equal(entries.length,2);assert.equal(entries.reduce((n,r)=>n+BigInt(r.amount_minor),0n),0n); + }finally{f.db.close();} +}); + + +test('a kill on another world cannot collect this destination bounty',async()=>{ + const f=await fixture();try{ + await f.service.board(f.input('giedi_prime',15000));await f.service.arrive(f.traveller.uuid,'giedi_prime'); + const before=await f.balance('hunter'); + assert.deepEqual(await f.service.bountyClaim({killer:f.hunter.uuid,victim:f.traveller.uuid,server:'kaitain',requestId:randomUUID()}),{ok:true,claimed:false}); + assert.equal(await f.balance('hunter'),before);assert.equal((await f.db.first('SELECT state FROM pb_travel_bounties')).state,'open'); + }finally{f.db.close();} +}); + +test('a kill reference cannot be replayed against a different victim or world',async()=>{ + const f=await fixture();try{ + await f.service.board(f.input('giedi_prime',15000));await f.service.arrive(f.traveller.uuid,'giedi_prime'); + const report={killer:f.hunter.uuid,victim:f.traveller.uuid,server:'giedi_prime',requestId:randomUUID()}; + await f.service.bountyClaim(report); + await assert.rejects(f.service.bountyClaim({...report,victim:randomUUID()}),/reference was already used/); + await assert.rejects(f.service.bountyClaim({...report,server:'kaitain'}),/reference was already used/); + assert.equal(await f.balance('hunter'),75000n); + }finally{f.db.close();} +}); + +test('a no-bounty report stays terminal when the victim later buys a passage',async()=>{ + const f=await fixture();try{ + const report={killer:f.hunter.uuid,victim:f.traveller.uuid,server:'giedi_prime',requestId:randomUUID()}; + assert.deepEqual(await f.service.bountyClaim(report),{ok:true,claimed:false}); + await f.service.board(f.input('giedi_prime',15000));await f.service.arrive(f.traveller.uuid,'giedi_prime'); + assert.deepEqual(await f.service.bountyClaim(report),{ok:true,claimed:false,replayed:true}); + assert.equal(await f.balance('hunter'),0n);assert.equal((await f.db.first('SELECT state FROM pb_travel_bounties')).state,'open'); + }finally{f.db.close();} +}); + +test('an inactive P&O issuer rolls back the claim and leaves its bounty open',async()=>{ + const f=await fixture();try{ + await f.service.board(f.input('giedi_prime',15000));await f.service.arrive(f.traveller.uuid,'giedi_prime'); + await f.db.query("UPDATE pb_accounts SET state='blocked' WHERE system_key='sys_payroll_po'"); + const report={killer:f.hunter.uuid,victim:f.traveller.uuid,server:'giedi_prime',requestId:randomUUID()}; + await assert.rejects(f.service.bountyClaim(report),/P&O issuer is unavailable/); + assert.equal(await f.balance('hunter'),0n);assert.equal((await f.db.first('SELECT state FROM pb_travel_bounties')).state,'open'); + assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_travel_bounty_claims')).n,0); + await f.db.query("UPDATE pb_accounts SET state='active' WHERE system_key='sys_payroll_po'"); + assert.equal((await f.service.bountyClaim(report)).claimed,true); + }finally{f.db.close();} +}); + +test('legacy pending passages settle under their original terms without a retroactive travel bounty',async()=>{ + const f=await fixture();try{ + const input=f.input('giedi_prime',15000);await f.service.board(input); + await f.db.query('DELETE FROM pb_guild_open_passages WHERE id=?',[input.requestId]); + const arrived=await f.service.arrive(f.traveller.uuid,'giedi_prime'); + assert.equal(arrived.passage.state,'arrived');assert.equal(arrived.bounty,undefined); + assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_travel_ladder')).n,0); + }finally{f.db.close();} +}); + +test('paid bookings keep existing Guild Lobby origin authority',async()=>{ + const f=await fixture();try{ + await assert.rejects(f.service.board({...f.input('giedi_prime',15000),sourceWorld:'kaitain'}),/Guild Lobby/); + assert.equal((await f.service.quote(f.traveller.uuid,'kaitain')).routes.find(r=>r.server==='giedi_prime').available,false); + }finally{f.db.close();} +}); + + +test('the disabled rollout gate acknowledges native death reports without any payout or progress write',async()=>{ + const f=await fixture({openTravel:false});try{ + const result=await f.service.bountyClaim({killer:f.hunter.uuid,victim:f.traveller.uuid,server:'giedi_prime',requestId:randomUUID()}); + assert.deepEqual(result,{ok:true,claimed:false,disabled:true}); + assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_travel_bounty_claims')).n,0); + assert.equal(await f.balance('hunter'),0n);assert.equal(await f.issuerBalance(),0n); + }finally{f.db.close();} +}); + +test('the authenticated bounty endpoint requires the exact canonical server and refuses amount/account overrides',async()=>{ + const secret='x'.repeat(64),calls=[]; + const api=createGameGuildAPI(null,null,null,{GAME_LINK_SECRET:secret},{service:{openTravel:true,bountyClaim:async input=>{calls.push(input);return{ok:true,claimed:false};}}}); + const body={action:'bounty_claim',uuid:randomUUID(),victim:randomUUID(),requestId:randomUUID(),server:'giedi_prime'}; + const send=(b,token=secret)=>api(new Request('https://cp.dunerealms.com/internal/game/guild',{method:'POST',headers:{authorization:'Bearer '+token,'content-type':'application/json'},body:JSON.stringify(b)})); + assert.equal((await send(body,'bad')).status,401); + const missing={...body};delete missing.server;assert.equal((await send(missing)).status,400); + for(const extra of [{server:'lobby'},{server:'giedi-prime'},{amountMinor:75000},{accountId:'123'}])assert.equal((await send({...body,...extra})).status,400); + assert.equal((await send(body)).status,200);assert.deepEqual(calls,[{killer:body.uuid,victim:body.victim,requestId:body.requestId,server:'giedi_prime'}]); +}); + +test('concurrent native reports cannot post the same bounty twice',async()=>{ + const f=await fixture();try{ + await f.service.board(f.input('giedi_prime',15000));await f.service.arrive(f.traveller.uuid,'giedi_prime'); + const report={killer:f.hunter.uuid,victim:f.traveller.uuid,server:'giedi_prime',requestId:randomUUID()}; + const results=await Promise.all([f.service.bountyClaim(report),f.service.bountyClaim(report)]); + assert.equal(results.filter(r=>r.replayed).length,1);assert.equal(await f.balance('hunter'),75000n); + assert.equal((await f.db.first("SELECT COUNT(*) n FROM pb_orders WHERE memo LIKE 'Travel bounty%'")).n,1); + }finally{f.db.close();} +}); + +test('all five worlds can be picked before departure, but boarding stays timed and paid fares still rise',async()=>{ + const f=await fixture();try{ + const open=(await f.service.quote(f.traveller.uuid,'lobby')).destinations; + assert.equal(open.length,5); + for(let minute=0;minute<60;minute++){ + f.setTime(minute*60000); + const quote=await f.service.quote(f.traveller.uuid,'lobby'); + assert.deepEqual(quote.destinations,open); + assert(quote.routes.every(route=>route.available)); + } + f.setTime(19*60000); + await assert.rejects(f.service.board(f.input('giedi_prime',15000)),/Boarding opens/); + f.setTime(20*60000); + await f.service.board(f.input('giedi_prime',15000)); + await f.service.arrive(f.traveller.uuid,'giedi_prime'); + f.setTime(25*60000); + assert.equal((await f.route('giedi_prime')).fareMinor,16500); + }finally{f.db.close();} +}); diff --git a/website/tests/game-quests-login-settle.test.mjs b/website/tests/game-quests-login-settle.test.mjs new file mode 100644 index 00000000..b2e36424 --- /dev/null +++ b/website/tests/game-quests-login-settle.test.mjs @@ -0,0 +1,25 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {createGameQuestsAPI} from '../node/game-quests.mjs'; +const uuid='11111111-1111-4111-8111-111111111111',userId='22222222-2222-4222-8222-222222222222',secret='example-game-secret-for-tests-only-1234'; +function fixture({personal,pol}){let linked=true;const user={id:userId,username:'player_one',role:'player'}; + const api=createGameQuestsAPI({query:async()=>linked?[user]:[]},{GAME_LINK_SECRET:secret},{personal,pol}); + const request=(body,auth=secret)=>api(new Request('https://cp.dunerealms.com/internal/game/quests',{method:'POST',headers:{authorization:'Bearer '+auth,'content-type':'application/json'},body:JSON.stringify({action:'login_settle',uuid,...body})})); + return {request,unlink:()=>{linked=false;}}; +} +test('login settle pays through the game credential, accepts no client-supplied outcomes and needs no consent flag',async()=>{ + const calls=[],paid=[];const personal={collect:async()=>{},quests:{settleCompleted:async actor=>{calls.push(actor.id);return {settled:[{id:'GAME-1',title:'Game one',xp:50,branch:'a'}],failed:0};}, processCompletions:async()=>{paid.push('personal');}}}; + const pol={collect:async()=>{},quests:{settleCompleted:async()=>({settled:[],failed:0})}}; + const f=fixture({personal,pol}); + assert.equal((await f.request({},'wrong')).status,401); + for(const extra of [{xp:99},{accountId:userId},{definitionId:'GAME-1'},{kind:'pol'},{confirmed:true}])assert.equal((await f.request(extra)).status,400); + assert.equal((await f.request({uuid:'not-a-uuid'})).status,400); + const response=await f.request({});assert.equal(response.status,200); + const body=await response.json();assert.equal(body.ok,true);assert.equal(body.failed,0);assert.deepEqual(body.settled.map(q=>q.id),['GAME-1']);assert.equal(body.settled[0].kind,'personal');assert.deepEqual(calls,[userId]);assert.deepEqual(paid,['personal']); + f.unlink();assert.equal((await f.request({})).status,403); +}); +test('one failing journal does not block the other and is reported, not thrown',async()=>{ + const personal={collect:async()=>{throw Error('down');},quests:{settleCompleted:async()=>({settled:[],failed:0})}}; + const pol={collect:async()=>{},quests:{settleCompleted:async()=>({settled:[{id:'POL-1',title:'Pol one',xp:10,branch:'b'}],failed:0}),processCompletions:async()=>{}}}; + const body=await (await fixture({personal,pol}).request({})).json(); + assert.equal(body.ok,true);assert.equal(body.failed,1);assert.deepEqual(body.settled.map(q=>q.kind+':'+q.id),['pol:POL-1']); +}); diff --git a/website/tests/lobby-account.test.mjs b/website/tests/lobby-account.test.mjs new file mode 100644 index 00000000..87e4c367 --- /dev/null +++ b/website/tests/lobby-account.test.mjs @@ -0,0 +1,105 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {DatabaseSync} from 'node:sqlite'; +import {scryptSync,randomUUID} from 'node:crypto'; +import {writeFile} from 'node:fs/promises'; +import {LOBBY_ACCOUNT_SCHEMA,createLobbyAccountService,createLobbyAccountAPI} from '../node/lobby-account.mjs'; +import {NATIVE_SYNC_SCHEMA} from '../node/native-sync-schema.mjs'; +const key='ab'.repeat(32),token='X'.repeat(43),uuid='5195da0c-ba50-4f82-baa7-1c99a73c810b'; +function fixture(){ + const sql=new DatabaseSync(':memory:');sql.exec(` + CREATE TABLE site_accounts(id TEXT PRIMARY KEY,username TEXT UNIQUE,display_name TEXT,password_salt TEXT,password_hash TEXT,role TEXT,created_at INTEGER); + CREATE TABLE site_game_links(user_id TEXT PRIMARY KEY,minecraft_uuid TEXT UNIQUE,minecraft_name TEXT,linked_at INTEGER); + CREATE TABLE site_game_identities(minecraft_uuid TEXT PRIMARY KEY,first_linked_at INTEGER,last_name TEXT); + CREATE TABLE player_profiles(user_id TEXT PRIMARY KEY,display_name TEXT,minecraft_name TEXT,discord_name TEXT,created_at INTEGER,updated_at INTEGER); + CREATE TABLE site_profiles(user_id TEXT PRIMARY KEY,bio TEXT,public_info TEXT,socials_json TEXT,updated_at INTEGER); + CREATE TABLE site_contact_emails(user_id TEXT PRIMARY KEY,address TEXT,verified_at INTEGER); + CREATE TABLE site_first_login(user_id TEXT PRIMARY KEY,password_changed INTEGER,created_at INTEGER); + CREATE TABLE site_age_declarations(user_id TEXT PRIMARY KEY,age_band TEXT,declared_at INTEGER); + CREATE TABLE account_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,details TEXT,created_at INTEGER); + ${LOBBY_ACCOUNT_SCHEMA.replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4','')};${NATIVE_SYNC_SCHEMA}`); + const clean=s=>s.replace(/ FOR UPDATE/g,''); + const tx={async first(s,v=[]){return sql.prepare(clean(s)).get(...v)||null;},async query(s,v=[]){return sql.prepare(clean(s)).run(...v);}}; + const db={async transaction(work){sql.exec('BEGIN');try{const r=await work(tx);sql.exec('COMMIT');return r;}catch(e){sql.exec('ROLLBACK');throw e;}}}; + let now=1000000;const service=createLobbyAccountService(db,{encryptionKey:key,clock:()=>now}); + const input={schema:1,action:'provision',requestId:randomUUID(),uuid,name:'Torch5907'}; + return {sql,db,service,input,advance:ms=>now+=ms}; +} +test('new account, verified game link and encrypted replay commit together; age undeclared and placeholder unverified',async()=>{ + const f=fixture();try{ + const a=await f.service.execute(f.input),b=await f.service.execute(f.input); + assert.equal(a.state,'created');assert.equal(a.username,'torch5907');assert.equal(a.password,b.password);assert.equal(a.password.length,32); + const account=f.sql.prepare('SELECT * FROM site_accounts').get();assert.equal(account.role,'user');assert.equal(scryptSync(a.password,account.password_salt,64).toString('hex'),account.password_hash); + assert.equal(f.sql.prepare('SELECT minecraft_uuid FROM site_game_links').get().minecraft_uuid,uuid); + const email=f.sql.prepare('SELECT * FROM site_contact_emails').get();assert.equal(email.address,'no_reply@dunerealms.com');assert.equal(email.verified_at,null); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM site_age_declarations').get().n,0); + assert.equal(f.sql.prepare('SELECT password_changed FROM site_first_login').get().password_changed,0); + const sync=f.sql.prepare('SELECT * FROM native_sync_outbox').get();assert.equal(sync.job_key,'memberships');assert.equal(sync.attempts,0);assert.equal(sync.next_attempt_at,0); + const raw=f.sql.prepare('SELECT * FROM site_lobby_account_provisions').get();assert.ok(!JSON.stringify(raw).includes(a.password));assert.ok(!f.sql.prepare('SELECT details FROM account_audit').get().details.includes(a.password)); + if(process.env.LOBBY_ACCOUNT_WIRE_OUTPUT){ + const ack=await f.service.execute({schema:1,action:'ack',uuid,requestId:f.input.requestId}); + const delivered=await f.service.execute(f.input); + await writeFile(process.env.LOBBY_ACCOUNT_WIRE_OUTPUT,JSON.stringify({syntheticTestOnly:true,request:f.input,responses:{created:a,replayed:b,ack,delivered}},null,2)); + } + }finally{f.sql.close();} +}); +test('ack is durable, input-bound and erases password ciphertext; no credential replay after delivery',async()=>{ + const f=fixture();try{ + await f.service.execute(f.input); + await assert.rejects(f.service.execute({...f.input,requestId:randomUUID()}),/original/); + await assert.rejects(f.service.execute({...f.input,name:'Other'}),/original/); + const ack={schema:1,action:'ack',uuid,requestId:f.input.requestId};assert.equal((await f.service.execute(ack)).state,'delivered');assert.equal((await f.service.execute(ack)).state,'delivered'); + assert.equal(f.sql.prepare('SELECT ciphertext FROM site_lobby_account_provisions').get().ciphertext,null); + assert.equal((await f.service.execute(f.input)).password,undefined); + }finally{f.sql.close();} +}); +test('existing links are not reset, renamed or reassigned; historical unlinked identity requires manual linking',async()=>{ + const f=fixture();try{ + f.sql.exec("INSERT INTO site_accounts VALUES('existing','original','Original','salt','unchanged','user',1);INSERT INTO site_game_links VALUES('existing','"+uuid+"','Torch5907',1)"); + const r=await f.service.execute(f.input);assert.equal(r.state,'existing');assert.equal(r.password,undefined);assert.equal(r.username,'original');assert.equal(f.sql.prepare('SELECT password_hash FROM site_accounts').get().password_hash,'unchanged'); + f.sql.exec('DELETE FROM site_game_links');f.sql.prepare('INSERT INTO site_game_identities VALUES(?,1,?)').run(uuid,'Torch5907'); + assert.equal((await f.service.execute(f.input)).state,'manual_link_required');assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM site_accounts').get().n,1); + }finally{f.sql.close();} +}); +test('username collision and Bedrock punctuation never take over an existing website account',async()=>{ + const f=fixture();try{ + f.sql.exec("INSERT INTO site_accounts VALUES('existing','torch5907','Original','salt','unchanged','user',1)"); + const r=await f.service.execute(f.input);assert.match(r.username,/^torch5907_5195da0cba504f82$/);assert.equal(f.sql.prepare("SELECT password_hash FROM site_accounts WHERE id='existing'").get().password_hash,'unchanged'); + const bedrock=await f.service.execute({...f.input,uuid:randomUUID(),requestId:randomUUID(),name:'.A'});assert.equal(bedrock.username,'mc__a'); + }finally{f.sql.close();} +}); +test('password change and expiry suppress old credentials without resetting the password',async()=>{ + for(const expired of [false,true]){const f=fixture();try{ + await f.service.execute(f.input);if(expired)f.advance(7*86400000);else f.sql.exec("UPDATE site_accounts SET password_hash='changed'"); + const r=await f.service.execute(f.input);assert.equal(r.state,'recovery_required');assert.equal(r.password,undefined);assert.equal(f.sql.prepare('SELECT ciphertext FROM site_lobby_account_provisions').get().ciphertext,null); + }finally{f.sql.close();}} +}); +test('failed link insertion rolls the entire new account back',async()=>{ + const f=fixture();try{ + f.sql.exec("CREATE TRIGGER broken_link BEFORE INSERT ON site_game_links BEGIN SELECT RAISE(ABORT,'link unavailable');END"); + await assert.rejects(f.service.execute(f.input),/link unavailable/); + for(const name of ['site_accounts','player_profiles','site_profiles','site_lobby_account_provisions','account_audit','native_sync_outbox'])assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM '+name).get().n,0); + }finally{f.sql.close();} +}); +test('bank outage retains the account and original secret; retry completes readiness without another account',async()=>{ + const f=fixture();let unavailable=true,actor; + const service=createLobbyAccountService(f.db,{encryptionKey:key,clock:()=>1000000,onProvisioned:async user=>{actor=user;if(unavailable)throw Error('Bank unavailable');}}); + try{ + await assert.rejects(service.execute(f.input),/Bank unavailable/); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM site_accounts').get().n,1); + const ciphertext=f.sql.prepare('SELECT ciphertext FROM site_lobby_account_provisions').get().ciphertext; + unavailable=false;const r=await service.execute(f.input);assert.equal(r.state,'created');assert.equal(r.username,actor.username);assert.ok(actor.id); + assert.equal(f.sql.prepare('SELECT ciphertext FROM site_lobby_account_provisions').get().ciphertext,ciphertext); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM site_accounts').get().n,1); + }finally{f.sql.close();} +}); +test('dedicated bearer, schema, exact fields and body bounds protect the Lobby-only endpoint',async()=>{ + let called=0;const settings={LOBBY_ACCOUNT_ENABLED:'true',LOBBY_ACCOUNT_TOKEN:token}; + const api=createLobbyAccountAPI(null,settings,{service:{async execute(b){called++;return {ok:true,...b,state:'existing',username:'old'};}}}); + const request=(body,auth=token)=>new Request('https://cp.dunerealms.com/internal/game/lobby-account',{method:'POST',headers:{Authorization:'Bearer '+auth,'Content-Type':'application/json'},body:JSON.stringify(body)}); + assert.equal((await api(request({action:'provision'},'shared-game-token'))).status,401); + assert.equal((await api(request({schema:1,action:'provision',uuid,requestId:randomUUID(),name:'Player',server:'arrakis'}))).status,400); + assert.equal((await api(request({blob:'x'.repeat(1100)}))).status,413);assert.equal(called,0); + const r=await api(request({schema:1,action:'provision',uuid,requestId:randomUUID(),name:'Player'}));assert.equal(r.status,200);assert.equal(r.headers.get('cache-control'),'no-store');assert.equal(called,1); + assert.equal((await createLobbyAccountAPI(null,{})(request({}))).status,401); +}); diff --git a/website/tests/lobby-starting-budget.test.mjs b/website/tests/lobby-starting-budget.test.mjs new file mode 100644 index 00000000..2ebd39f2 --- /dev/null +++ b/website/tests/lobby-starting-budget.test.mjs @@ -0,0 +1,61 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {DatabaseSync} from 'node:sqlite'; +import {randomUUID} from 'node:crypto'; +import {provisionLobbyStartingBank,lobbyBudgetId} from '../node/lobby-starting-budget.mjs'; +const actor={id:'11111111-1111-4111-a111-111111111111',uuid:'22222222-2222-4222-a222-222222222222',username:'new_player'}; +function fixture(){ + const sql=new DatabaseSync(':memory:');sql.exec(` + CREATE TABLE pb_entities(id TEXT PRIMARY KEY,kind TEXT,external_key TEXT,display_name TEXT,active INTEGER,created_at INTEGER); + CREATE TABLE pb_clients(client_number TEXT PRIMARY KEY,entity_id TEXT UNIQUE,created_at INTEGER); + CREATE TABLE pb_packages(id TEXT PRIMARY KEY,client_number TEXT,package_key TEXT,monthly_minor INTEGER,terms_version TEXT,accepted_by TEXT,accepted_at INTEGER,state TEXT); + CREATE TABLE pb_accounts(id INTEGER PRIMARY KEY AUTOINCREMENT,client_number TEXT,package_id TEXT,type_code TEXT,display_name TEXT,account_number TEXT,balance_minor INTEGER DEFAULT 0,reserved_minor INTEGER DEFAULT 0,state TEXT,created_at INTEGER,system_key TEXT UNIQUE); + CREATE TABLE pb_activations(entity_id TEXT PRIMARY KEY,package_id TEXT); + CREATE TABLE pb_orders(id TEXT PRIMARY KEY,actor_id TEXT,source_id INTEGER,target_id INTEGER,fingerprint TEXT,amount_minor INTEGER,memo TEXT,mode TEXT,state TEXT,created_at INTEGER,posted_at INTEGER); + CREATE TABLE pb_entries(order_id TEXT,account_id INTEGER,amount_minor INTEGER,balance_after_minor INTEGER,created_at INTEGER,UNIQUE(order_id,account_id)); + CREATE TABLE pb_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,entity_id TEXT,details TEXT,created_at INTEGER); + INSERT INTO pb_accounts(id,type_code,display_name,state,system_key) VALUES(1,'979','Capital issuer','active','sys_bank_capital_issuer');`); + const clean=s=>s.replace(/ FOR UPDATE/g,'').replace(/ON DUPLICATE KEY UPDATE id=id/,'ON CONFLICT(id) DO NOTHING').replace(/ON DUPLICATE KEY UPDATE entity_id=entity_id/,'ON CONFLICT(entity_id) DO NOTHING'); + const tx={async first(s,v=[]){return sql.prepare(clean(s)).get(...v)||null;},async query(s,v=[]){const q=sql.prepare(clean(s));if(/^SELECT/.test(s))return q.all(...v);const r=q.run(...v);return {insertId:r.lastInsertRowid};}}; + const bank={async transaction(work){sql.exec('BEGIN');try{const r=await work(tx);sql.exec('COMMIT');return r;}catch(e){sql.exec('ROLLBACK');throw e;}}}; + return {sql,bank}; +} +test('new basic account receives exactly 1000 DM with two balanced entries; rejoin/retry cannot credit it twice',async()=>{ + const f=fixture();try{ + const a=await provisionLobbyStartingBank(f.bank,actor),b=await provisionLobbyStartingBank(f.bank,actor); + assert.equal(a.replayed,false);assert.equal(b.replayed,true);assert.equal(a.paymentId,b.paymentId); + const p=f.sql.prepare('SELECT * FROM pb_packages').get();assert.equal(p.package_key,'pb_start');assert.equal(p.monthly_minor,0); + const current=f.sql.prepare('SELECT * FROM pb_accounts WHERE id=?').get(a.accountId);assert.equal(current.type_code,'108');assert.equal(current.balance_minor,100000);assert.equal(current.reserved_minor,0); + assert.equal(f.sql.prepare('SELECT balance_minor FROM pb_accounts WHERE id=1').get().balance_minor,-100000); + assert.equal(f.sql.prepare('SELECT COUNT(*) n,SUM(amount_minor) total FROM pb_entries').get().n,2);assert.equal(f.sql.prepare('SELECT SUM(amount_minor) total FROM pb_entries').get().total,0); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_orders').get().n,1); + }finally{f.sql.close();} +}); +test('failed ledger entry rolls back account creation and grant together; exact retry posts once',async()=>{ + const f=fixture();try{ + f.sql.exec("CREATE TRIGGER broken_credit BEFORE INSERT ON pb_entries WHEN NEW.amount_minor>0 BEGIN SELECT RAISE(ABORT,'posting unavailable');END"); + await assert.rejects(provisionLobbyStartingBank(f.bank,actor),/posting unavailable/); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_packages').get().n,0);assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_orders').get().n,0);assert.equal(f.sql.prepare('SELECT balance_minor FROM pb_accounts WHERE id=1').get().balance_minor,0); + f.sql.exec('DROP TRIGGER broken_credit');assert.equal((await provisionLobbyStartingBank(f.bank,actor)).replayed,false); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_entries').get().n,2); + }finally{f.sql.close();} +}); +test('same Minecraft UUID cannot claim another starting budget with a different website account',async()=>{ + const f=fixture();try{ + await provisionLobbyStartingBank(f.bank,actor); + await assert.rejects(provisionLobbyStartingBank(f.bank,{...actor,id:randomUUID()}),/original starting-budget/); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_packages').get().n,1);assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_orders').get().n,1); + }finally{f.sql.close();} +}); +test('blocked current account and incomplete prior receipt fail closed without replacement or another grant',async()=>{ + const f=fixture();try{ + const a=await provisionLobbyStartingBank(f.bank,actor);f.sql.prepare("UPDATE pb_accounts SET state='blocked' WHERE id=?").run(a.accountId); + await assert.rejects(provisionLobbyStartingBank(f.bank,actor),/needs review/); + f.sql.prepare("UPDATE pb_accounts SET state='active' WHERE id=?").run(a.accountId);f.sql.exec('DELETE FROM pb_entries WHERE amount_minor>0'); + await assert.rejects(provisionLobbyStartingBank(f.bank,actor),/ledger requires review/); + assert.equal(f.sql.prepare('SELECT COUNT(*) n FROM pb_orders').get().n,1); + }finally{f.sql.close();} +}); +test('payment reference is bound to the Minecraft UUID and cannot be chosen by the client',()=>{ + assert.equal(lobbyBudgetId(actor.uuid),lobbyBudgetId(actor.uuid));assert.notEqual(lobbyBudgetId(actor.uuid),lobbyBudgetId(randomUUID()));assert.throws(()=>lobbyBudgetId('arbitrary'),/verified/); +}); diff --git a/website/tests/menu-badges.test.mjs b/website/tests/menu-badges.test.mjs index 5c64462e..d419453b 100644 --- a/website/tests/menu-badges.test.mjs +++ b/website/tests/menu-badges.test.mjs @@ -34,7 +34,7 @@ test('release version is 4.1-only, shared publicly, audited and preserved by bad }finally{db.close();} }); -test('Beta defaults to 1.0.2.0 and does not inherit an unstaged Alpha override',async()=>{const db=fixture();try{await db.prepare('INSERT INTO website_settings(setting_key,setting_value,updated_at) VALUES(?,?,?)').bind('main_menu_badges',JSON.stringify({releaseVersion:'1.0.1.3'}),1).run();const data=await readMenuBadges(db);assert.equal(data.stage,'beta');assert.equal(data.releaseVersion,'1.0.2.0');}finally{db.close();}}); +test('Beta defaults to 1.0.3.0 and does not inherit an unstaged Alpha override',async()=>{const db=fixture();try{await db.prepare('INSERT INTO website_settings(setting_key,setting_value,updated_at) VALUES(?,?,?)').bind('main_menu_badges',JSON.stringify({releaseVersion:'1.0.1.3'}),1).run();const data=await readMenuBadges(db);assert.equal(data.stage,'beta');assert.equal(data.releaseVersion,'1.0.3.0');}finally{db.close();}}); test('both header scripts use a validated stage and four-part release version',async()=>{ const api='/api/menu-badges',badge={}; @@ -50,7 +50,7 @@ test('both header scripts use a validated stage and four-part release version',a assert.deepEqual(paths,[api,'/release.json']); assert.equal(badge.textContent,'Alpha 1.0.1.2'); await updateReleaseBadge(badge,api,RELEASE,async()=>Response.json({stage:'alpha',releaseVersion:'1.0.1',version:'1.0.1'})); - assert.equal(badge.textContent,'Beta 1.0.2.0'); + assert.equal(badge.textContent,'Beta 1.0.3.0'); }); test('homepage Trade fallback and shared menu point Equipment and kits to the same route',()=>{ diff --git a/website/tests/mission-journal-model.test.mjs b/website/tests/mission-journal-model.test.mjs new file mode 100644 index 00000000..23568776 --- /dev/null +++ b/website/tests/mission-journal-model.test.mjs @@ -0,0 +1,72 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {advanceTracked,buildJournal,pickSelection,nextInArc,briefing,objectives,rewards,actions,currentObjective,completions,questStatus,orderArc} from '../control-panel/public/cp-v2/cp-v2-mission-journal-model.mjs'; +const q=(id,over={})=>({id,title:id.toUpperCase(),branch:'a',metric:'m-'+id,target:1,progress:0,state:'not-started',canStart:false,canClaim:false,rewardConfigured:true,revision:1,xp:50,requires:[],objective:'Do the thing. Then do more.',...over}); +const data=quests=>({state:'active',branches:[{id:'a',title:'Citizen path'},{id:'b',title:'Smuggler path'}],quests}); + +test('tracking advances a paid mission within its own arc and clears after its last mission',()=>{ + const journal=buildJournal(data([q('a1',{state:'claimed'}),q('a2',{requires:['a1'],state:'active'}),q('b1',{branch:'b',canStart:true})])); + assert.equal(advanceTracked(journal,'a1'),'a2'); + assert.equal(advanceTracked(journal,'a2'),'a2'); + assert.equal(advanceTracked(buildJournal(data([q('a1',{state:'claimed'}),q('b1',{branch:'b',canStart:true})])),'a1'),null); + assert.equal(advanceTracked(journal,null),null); +}); + +test('reward panel includes the server-provided funded reward and personal XP',()=>{ + assert.deepEqual(rewards(q('x',{xp:50,personalXP:25,baseDMMinor:15000}),{xpType:'pol'}),[ + {label:'Reputation',value:'50 XP'},{label:'Personal experience',value:'25 XP'},{label:'Base funded reward',value:'150.00 DM'} + ]); +}); +test('missions group by story arc in prerequisite order with done, active and locked marked',()=>{ + const journal=buildJournal(data([q('a3',{requires:['a2']}),q('a1',{state:'claimed',canStart:true}),q('a2',{requires:['a1'],state:'active',progress:0}),q('b1',{branch:'b',canStart:true})])); + assert.deepEqual(journal.arcs.map(a=>a.title),['Citizen path','Smuggler path']); + assert.deepEqual(journal.arcs[0].quests.map(x=>x.id+':'+x.status),['a1:done','a2:active','a3:locked']); + assert.equal(journal.arcs[0].done,1);assert.equal(journal.arcs[0].total,3);assert.equal(journal.arcs[0].quests[2].lockedBy,'Complete A2 first.'); +}); +test('statuses never promote a locked or unclaimable mission',()=>{ + assert.equal(questStatus(q('x',{state:'completed',canClaim:true,progress:1})),'ready'); + assert.equal(questStatus(q('x',{state:'not-started'})),'locked');assert.equal(questStatus(q('x',{canStart:true})),'available');assert.equal(questStatus(q('x',{state:'claimed'})),'done'); +}); +test('selection prefers the pick, then the tracked mission, then what needs attention',()=>{ + const journal=buildJournal(data([q('a1',{state:'claimed'}),q('a2',{requires:['a1'],state:'active'}),q('a3',{requires:['a2'],state:'completed',canClaim:true,progress:1})])); + assert.equal(pickSelection(journal,{preferred:'a2'}),'a2');assert.equal(pickSelection(journal,{preferred:'zzz',tracked:'a2'}),'a2');assert.equal(pickSelection(journal,{}),'a3'); + assert.equal(pickSelection(buildJournal(data([])),{}),null); +}); +test('the next unfinished mission in the same arc is chosen, never one from another arc',()=>{ + const journal=buildJournal(data([q('a1',{state:'claimed'}),q('a2',{requires:['a1'],state:'claimed'}),q('a3',{requires:['a2'],canStart:true}),q('b1',{branch:'b',canStart:true})])); + assert.equal(nextInArc(journal,'a2'),'a3');assert.equal(nextInArc(journal,'a3'),null);assert.equal(nextInArc(journal,'nope'),null); +}); +test('briefing is one short sentence and objectives carry a progress bar and money formatting',()=>{ + assert.equal(briefing(q('x')),'Do the thing.');assert.equal(briefing(q('x',{objective:'x'.repeat(400)}),50).length,50);assert.equal(briefing(q('x',{objective:''})),'Follow your objective below.'); + const [o]=objectives(q('x',{metric:'spent-minor',target:50000,progress:12500}));assert.equal(o.percent,25);assert.equal(o.text,'125.00 DM / 500.00 DM');assert.equal(o.done,false); + assert.equal(objectives(q('x',{target:4,progress:99}))[0].percent,100); +}); +test('rewards panel shows XP or reputation and flags an unconfigured reward',()=>{ + assert.deepEqual(rewards(q('x',{xp:250})),[{label:'Experience',value:'250 XP'}]);assert.equal(rewards(q('x',{xp:10}),{xpType:'pol'})[0].label,'Reputation'); + assert.equal(rewards(q('x',{xp:null,rewardConfigured:false})).at(-1).value,'Not configured yet'); +}); +test('one Track button always, Claim only when unpaid, Start only when it can begin',()=>{ + const ready=buildJournal(data([q('r',{state:'completed',canClaim:true,progress:1})])).all[0]; + assert.deepEqual(actions(ready,{tracked:null}).map(a=>a.kind),['track','claim']); + const active=buildJournal(data([q('p',{state:'active'})])).all[0];assert.deepEqual(actions(active,{tracked:'p'}).map(a=>a.kind+':'+a.label),['track:Tracking']); + const open=buildJournal(data([q('o',{canStart:true})])).all[0];assert.deepEqual(actions(open).map(a=>a.kind),['track','start']); + const done=buildJournal(data([q('d',{state:'claimed'})])).all[0];assert.equal(actions(done)[0].disabled,true);assert.equal(actions(done).length,1); +}); +test('the sidebar objective follows the tracked mission and falls back to the first active one',()=>{ + const journal=buildJournal(data([q('a1',{state:'active',progress:0,target:4}),q('a2',{state:'active',progress:2,target:4,requires:['a1']})])); + assert.equal(currentObjective(journal,'a2').percent,50);assert.equal(currentObjective(journal,null).id,'a1');assert.equal(currentObjective(buildJournal(data([])),null),null); +}); +test('completion banners fire once when a mission becomes ready or paid between loads',()=>{ + const before=buildJournal(data([q('a1',{state:'active'}),q('a2',{requires:['a1']})])); + const after=buildJournal(data([q('a1',{state:'claimed'}),q('a2',{requires:['a1'],canStart:true,state:'active'})])); + assert.deepEqual(completions(before,after),[{id:'a1',title:'A1',claimed:true}]);assert.deepEqual(completions(after,after),[]);assert.deepEqual(completions(null,after),[]); +}); +test('ordering keeps catalogue order for independent missions and survives cycles',()=>{ + assert.deepEqual(orderArc([q('z'),q('y')]).map(x=>x.id),['z','y']); + assert.equal(orderArc([q('a',{requires:['b']}),q('b',{requires:['a']})]).length,2); +}); +test('the sidebar report shows the tracked quest when it is still open, else the first open one',async()=>{ + const {xpReport}=await import('../control-panel/public/cp-v2/cp-v2-progression-sidebar.mjs'); + const open=(id,state='active')=>({id,keyId:'k-'+id,state,progress:0,target:1}); + const data={state:'active',profile:{level:3,effectiveXP:100,totalXP:100,reserveXP:0},season:{id:'S01',curveBase:25,levelCap:100},quests:[open('a'),open('b')]}; + assert.equal(xpReport(data).quest.id,'a');assert.equal(xpReport(data,{tracked:'b'}).quest.id,'b');assert.equal(xpReport(data,{tracked:'gone'}).quest.id,'a'); +}); diff --git a/website/tests/mission-journal-render.test.mjs b/website/tests/mission-journal-render.test.mjs new file mode 100644 index 00000000..3794a2a8 --- /dev/null +++ b/website/tests/mission-journal-render.test.mjs @@ -0,0 +1,63 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {renderMissionJournal} from '../control-panel/public/cp-v2/cp-v2-mission-journal.mjs'; +import {buildJournal} from '../control-panel/public/cp-v2/cp-v2-mission-journal-model.mjs'; + +class Element { + constructor(tag){this.tagName=tag;this.children=[];this.dataset={};this.attributes={};this.style={};} + append(...children){this.children.push(...children);} + setAttribute(key,value){this.attributes[key]=value;} +} +const descendants=node=>[node,...node.children.flatMap(descendants)]; + +test('journal renders a separate mission-steps route and keeps claim bound to the displayed mission',()=>{ + const before=globalThis.document;globalThis.document={createElement:tag=>new Element(tag),querySelector:()=>null,head:new Element('head')}; + try{ + const mission={id:'fremen-turnin',title:'Deliver supplies',branch:'fremen',state:'completed',progress:1,target:1,canClaim:true,rewardConfigured:true,xp:50,requires:[]}; + const journal=buildJournal({branches:[{id:'fremen',title:'Fremen'}],quests:[mission]}); + const root=new Element('main'),calls=[]; + renderMissionJournal(root,{journal,selected:mission.id,tracked:null},{onSelect:()=>{},onTrack:()=>{},onAct:q=>calls.push(['claim',q.id]),onSteps:q=>calls.push(['steps',q.id])}); + const buttons=descendants(root).filter(e=>e.tagName==='button'); + buttons.find(e=>e.textContent==='Mission steps').onclick(); + buttons.find(e=>e.textContent==='Claim reward').onclick(); + assert.deepEqual(calls,[['steps',mission.id],['claim',mission.id]]); + assert.equal(buttons.filter(e=>e.textContent==='Track').length,1); + }finally{globalThis.document=before;} +}); + +test('busy journal prevents both mission steps and reward actions',()=>{ + const before=globalThis.document;globalThis.document={createElement:tag=>new Element(tag),querySelector:()=>null,head:new Element('head')}; + try{ + const mission={id:'ready',title:'Ready',branch:'a',state:'completed',progress:1,target:1,canClaim:true,rewardConfigured:true,requires:[]}; + const journal=buildJournal({quests:[mission]}),root=new Element('main'); + renderMissionJournal(root,{journal,selected:mission.id,busy:true},{onSelect:()=>{},onTrack:()=>{},onAct:()=>{},onSteps:()=>{}}); + for(const name of ['Mission steps','Claim reward'])assert.equal(descendants(root).find(e=>e.textContent===name).disabled,true); + }finally{globalThis.document=before;} +}); + + +test('current journal groups categories without hiding unknown branches or changing mission actions',()=>{ + const before=globalThis.document;globalThis.document={createElement:tag=>new Element(tag),querySelector:()=>null,head:new Element('head')}; + try{ + const missions=[{id:'wing',title:'Wings and Armour',branch:'elytra',state:'completed',progress:1,target:1,canClaim:true,rewardConfigured:true,xp:0,requires:[]},{id:'unknown',title:'New story',branch:'new-branch',state:'active',progress:0,target:1,requires:[]}]; + const journal=buildJournal({branches:[{id:'elytra',title:'Flight'},{id:'new-branch',title:'New work'}],quests:missions}),root=new Element('main'),calls=[]; + renderMissionJournal(root,{journal,selected:'wing'},{onSelect:id=>calls.push(id),onTrack:()=>{},onAct:()=>{},onSteps:()=>{}}); + const all=descendants(root),headings=all.filter(e=>e.className==='quest-category-heading'); + assert.deepEqual(headings.map(h=>h.children.find(e=>e.tagName==='span').textContent),['Wings across the Realms','Other Work']); + const unknown=all.find(e=>e.tagName==='button'&&e.children.some(c=>c.textContent==='New story'));assert.ok(unknown);unknown.onclick();assert.deepEqual(calls,['unknown']); + assert.equal(all.filter(e=>e.textContent==='Claim reward').length,1);assert.equal(all.filter(e=>e.className==='quest-category-hero').length,1); + }finally{globalThis.document=before;} +}); + +test('one named story arc combines former letter branches once in prerequisite order',()=>{ + const before=globalThis.document;globalThis.document={createElement:tag=>new Element(tag),querySelector:()=>null,head:new Element('head')}; + try{ + const mission=(id,branch,requires=[])=>({id,title:'Mission '+id,branch,requires,state:'active',progress:0,target:1}); + const journal=buildJournal({branches:[{id:'e',title:'E'},{id:'f',title:'F'},{id:'g',title:'G'}],quests:[mission('third','g',['second']),mission('first','e'),mission('second','f',['first'])]}),root=new Element('main'),calls=[]; + renderMissionJournal(root,{journal,selected:'first',tracked:'second'},{onSelect:id=>calls.push(id),onTrack:()=>{},onAct:()=>{},onSteps:()=>{}}); + const all=descendants(root),headings=all.filter(e=>e.tagName==='summary');assert.equal(headings.length,1);assert.equal(headings[0].children.find(e=>e.tagName==='span').textContent,'A Place in the Realm'); + const picks=all.filter(e=>e.className==='mj-mission');assert.deepEqual(picks.map(e=>e.children[0].textContent),['Mission first','Mission second','Mission third']); + assert.equal(new Set(picks.map(e=>e.children[0].textContent)).size,3);picks[1].onclick();assert.deepEqual(calls,['second']); + assert.ok(!all.some(e=>['E','F','G'].includes(e.textContent))); + }finally{globalThis.document=before;} +}); diff --git a/website/tests/organisation-runtime.test.mjs b/website/tests/organisation-runtime.test.mjs index 2d235069..501c818a 100644 --- a/website/tests/organisation-runtime.test.mjs +++ b/website/tests/organisation-runtime.test.mjs @@ -46,7 +46,7 @@ test('Safe persisted citizen features survive while accidental staff grants on U assert(result.nodes.includes('web.mail.internal.view'));assert(result.nodes.includes('web.quests.view'));assert(result.nodes.includes('duneess.chat.colors'));assert(result.ranks.includes('vip'));assert(!result.nodes.includes('web.bank.staff.manage'));assert(!result.nodes.includes('web.accounts.assign')); }); test('Citizen ranks cannot retain staff powers through CP aliases, ticket scopes or native administration',async()=>{ - const unwanted=['cp.community.manage','web.tickets.dev','web.tickets.sales','web.forum.admin','dune.items.give','dunelobby.admin','dunelobby.build']; + const unwanted=['cp.community.manage','web.tickets.dev','web.tickets.sales','web.forum.admin','dune.items.give','dunelobby.admin','dunelobby.build','dunestaff.fly','dunestaff.vanish','dunestaff.vanish.see']; const base={...DEFAULT_RANKS[0],nodes:[...DEFAULT_RANKS[0].nodes,...unwanted]}; const result=await organisationRuntimeAccess(database({assignments:[]}),user,{registry:NODES,basicRank:base,legacyRanks:[],clock:()=>10}); for(const node of unwanted)assert(!result.nodes.includes(node),node); diff --git a/website/tests/owned-smuggler-routes.test.mjs b/website/tests/owned-smuggler-routes.test.mjs new file mode 100644 index 00000000..60bed180 --- /dev/null +++ b/website/tests/owned-smuggler-routes.test.mjs @@ -0,0 +1,59 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs'; +import {initializeClans} from '../control-panel/clans.mjs'; +import {createOwnedSmugglerRoutes} from '../node/owned-smuggler-routes.mjs'; +import {organisationRuntimeAccess} from '../node/organisation-runtime.mjs'; +import {DEFAULT_RANKS,NODES} from '../node/permissions.mjs'; +async function fixture(){ + const f=await companyFixture(),owner=f.people.Owner,uuid=randomUUID(),origin=await f.create();let now=1200000; + await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,owner.id]); + const key=await f.keys.issue({accountId:owner.id,keyType:'character-allegiance',scopeId:'house:'+owner.id+':v1',authorize:async()=>{}}); + f.db.sqlite.exec('CREATE TABLE site_character_choices(user_id TEXT,version INT);CREATE TABLE jarvis_house_selections(account_id TEXT,key_id TEXT);');await f.db.query('INSERT INTO site_character_choices VALUES(?,1)',[owner.id]);await f.db.query('INSERT INTO jarvis_house_selections VALUES(?,?)',[owner.id,key.id]); + async function company(name){const id=randomUUID();await f.db.query("INSERT INTO corrino_companies(id,slug,name,description,status,founded_by,created_at,updated_at) VALUES(?,?,?,'','active',?,1,1)",[id,name.toLowerCase(),name,owner.id]);await f.db.query("INSERT INTO site_company_deeds(company_id,owner_account_id,created_at,updated_at) VALUES(?,?,1,1)",[id,owner.id]);await f.db.query('INSERT INTO site_company_members VALUES(?,?,1)',[id,owner.id]);return id;} + async function claim(kind,id,world){const h={id:randomUUID(),worldUuid:randomUUID(),worldName:world,position:{x:8,y:64,z:8}};await f.db.query('INSERT INTO site_claim_registry VALUES(?,?,?,1,1)',[kind,id,JSON.stringify({organisationId:id,source:'minecraft',homeBlock:h,usedChunks:1})]);return h;} + const target=await company('Target'),unregistered=await company('Unregistered'),oh=await claim('company',origin,'caladan'),th=await claim('company',target,'arrakis'),user={...owner,keyId:key.id,version:1,faction:'atreides'}; + const resolve=async(id,store=f.db)=>{const row=await store.first("SELECT a.id FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE l.minecraft_uuid=? AND a.password_hash NOT LIKE '!%'",[id]);const k=await store.first('SELECT revoked_at FROM organisation_keys WHERE id=?',[key.id]);return row?.id===owner.id&&k&&k.revoked_at==null?user:null;}; + const routes=createOwnedSmugglerRoutes(f.db,{resolve,clock:()=>now}),input={uuid,sourceWorld:'caladan',origin:{kind:'company',id:origin},target:{kind:'company',id:target},sourceLocation:{worldUuid:oh.worldUuid,position:{x:8.5,y:64,z:8.5},observedAt:now},originHomeBlockId:oh.id,originRevision:1,targetHomeBlockId:th.id,targetRevision:1}; + return {...f,owner,uuid,key,user,origin,target,unregistered,oh,th,routes,input,claim,setTime:v=>now=v}; +} +test('actual company owner catalog retains same-world and unregistered rows and current Home Block pins',async()=>{ + const f=await fixture();try{const result=await f.routes.list(f.user,f.input);assert.equal(result.destinations.length,3);assert.equal(result.destinations.find(r=>r.id===f.origin).available,false);assert.equal(result.destinations.find(r=>r.id===f.unregistered).available,false);assert.equal(result.destinations.find(r=>r.id===f.target).available,true);assert.equal((await f.routes.quote(f.user,f.input)).target.homeBlockId,f.th.id);}finally{f.db.close();} +}); +test('company management alone does not grant owned-home travel, and stale target revision cannot enter the bank callback',async()=>{ + const f=await fixture();try{await f.db.query('INSERT INTO site_company_members VALUES(?,?,1)',[f.target,f.people.Other.id]);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Other.id,f.target]);await f.db.query('UPDATE corrino_companies SET ceo_account_id=? WHERE id=?',[f.owner.id,f.target]);let called=false;await assert.rejects(f.routes.withLock(f.user,f.input,'board',async()=>called=true),/own active company/);assert.equal(called,false);await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.owner.id,f.target]);await f.db.query("UPDATE site_claim_registry SET revision=2 WHERE organisation_kind='company' AND organisation_id=?",[f.target]);await assert.rejects(f.routes.withLock(f.user,f.input,'board',async()=>called=true),/Home Block changed/);assert.equal(called,false);}finally{f.db.close();} +}); +test('NPC contact is world-, position- and time-bound, and linked character revocation is rechecked under locks',async()=>{ + const f=await fixture();try{for(const sourceLocation of [{...f.input.sourceLocation,worldUuid:randomUUID()},{...f.input.sourceLocation,position:{x:1000,y:64,z:1000}},{...f.input.sourceLocation,observedAt:1}])await assert.rejects(f.routes.quote(f.user,{...f.input,sourceLocation}),/Reopen the Navigator/);await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[f.key.id]);await assert.rejects(f.routes.withLock(f.user,f.input,'board',async()=>assert.fail('No bank callback allowed')),/character changed/);}finally{f.db.close();} +}); +test('original clan deed ownership participates in the same catalog without adding a clan or changing membership',async()=>{ + const f=await fixture();try{f.db.sqlite.exec('DROP TABLE site_clan_members;DROP TABLE site_clans;');await initializeClans(f.db,{mysql:false});const id=randomUUID();await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,owner_id,home_world,created_at,updated_at) VALUES(?,'Clan','clan','CLAN','',?,'arrakduin',1,1)",[id,f.owner.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[f.owner.id,f.uuid,id]);await f.db.query('INSERT INTO site_clan_deeds(clan_id,updated_at) VALUES(?,1)',[id]);await f.claim('clan',id,'arrakis');const result=await f.routes.list(f.user,f.input);assert.equal(result.destinations.length,4);assert.equal(result.destinations.find(r=>r.kind==='clan'&&r.id===id).available,true);let entered=false;await f.routes.withLock(f.user,{...f.input,target:{kind:'clan',id},targetHomeBlockId:result.destinations.find(r=>r.id===id).homeBlockId},'board',async()=>{entered=true;});assert.equal(entered,true);assert.equal((await f.db.first('SELECT COUNT(*) n FROM site_clan_members')).n,1);}finally{f.db.close();} +}); + +test('all identity, key, deed and claim locking reads precede the first consistent read',async()=>{ + const f=await fixture();try{ + const reads=[],base=f.db,tracked={...base,transaction:work=>base.transaction(tx=>work({...tx,query:async(sql,args)=>{reads.push(sql);return tx.query(sql,args);},first:async(sql,args)=>{reads.push(sql);return tx.first(sql,args);}}))}; + const routes=createOwnedSmugglerRoutes(tracked,{clock:()=>1200000,resolve:async()=>{ + assert.ok(reads.some(s=>s.includes('FROM organisation_keys')&&s.endsWith('FOR SHARE'))); + assert.equal(reads.filter(s=>s.includes('FROM site_claim_registry')&&s.endsWith('FOR SHARE')).length,2); + assert.equal(reads.filter(s=>s.includes('FROM site_company_deeds')&&s.endsWith('FOR SHARE')).length,2); + assert.ok(reads.every(s=>s.endsWith('FOR SHARE')),'No earlier consistent read may freeze a stale snapshot'); + return f.user; + }}); + let entered=false;await routes.withLock(f.user,f.input,'board',async()=>{entered=true;});assert.equal(entered,true); + }finally{f.db.close();} +}); + +test('activated organisation permissions resolve on the held route snapshot without another pooled reader',async()=>{ + const f=await fixture();try{ + f.db.organisationAccessEnabled=true;f.db.readSnapshot=async()=>assert.fail('Must not open a second pooled snapshot'); + f.db.sqlite.exec('CREATE TABLE org_control_principals(user_id TEXT,principal_kind TEXT);CREATE TABLE org_assignments(id TEXT,user_id TEXT,scope_type TEXT,scope_key TEXT,role_key TEXT,status TEXT,starts_at INT,ends_at INT);CREATE TABLE org_role_policies(scope_type TEXT,scope_key TEXT,role_key TEXT,permissions_json TEXT,version INT);'); + await f.routes.withLock(f.user,f.input,'board',async(ctx,user,reader)=>{ + assert.equal(reader.organisationAccessEnabled,true); + assert.equal(await reader.readSnapshot(snapshot=>snapshot),reader); + const access=await organisationRuntimeAccess(reader,user,{registry:NODES,basicRank:DEFAULT_RANKS[0],legacyRanks:[],clock:()=>1200000}); + assert.ok(access.nodes.includes('web.bank.personal.view'));assert.ok(!access.nodes.includes('web.bank.staff.manage')); + }); + }finally{f.db.close();} +}); diff --git a/website/tests/owner-homeblock-release.test.mjs b/website/tests/owner-homeblock-release.test.mjs index 4f60dad8..220a1191 100644 --- a/website/tests/owner-homeblock-release.test.mjs +++ b/website/tests/owner-homeblock-release.test.mjs @@ -17,6 +17,36 @@ async function ownerFixture(){ const snapshot={organisationId:clan,source:'minecraft',tier:'KC_T4',usedChunks:16,homeBlock:{id:randomUUID(),worldUuid:randomUUID(),worldName:'arrakis',position:{x:594,y:58,z:-2053}},estates:[{id:randomUUID(),chunks:16,worldguard:{regionId:'old-region'}}]}; await f.db.query("INSERT INTO site_claim_registry VALUES('clan',?,?,4,1)",[clan,JSON.stringify(snapshot)]);return {...f,clan,snapshot}; } +async function ownerCompanyFixture(){ + const f=await ownerFixture(),company=await f.create(); + await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[OFFICIAL_ACCOUNT.ownerId,company]); + await f.db.query('INSERT INTO site_company_members(company_id,user_id,joined_at) VALUES(?,?,1)',[company,OFFICIAL_ACCOUNT.ownerId]); + const companySnapshot={...f.snapshot,organisationId:company,homeBlock:{...f.snapshot.homeBlock,id:randomUUID(),worldName:'sigma_draconis_iv'}}; + await f.db.query("INSERT INTO site_claim_registry VALUES('company',?,?,4,1)",[company,JSON.stringify(companySnapshot)]); + return {...f,company,companySnapshot}; +} + +test('Owner company release uses its deed owner and the same consumed free-replacement key without touching the clan',async()=>{ + const f=await ownerCompanyFixture();try{ + const plan=await ownerHomeBlockPlan(f.db,'company'),requestId=randomUUID();assert.equal(plan.companyId,f.company); + const result=await applyOwnerHomeBlockRelease(f.db,f.keys,plan,{requestId});assert.equal(result.kind,'company'); + const read=async kind=>JSON.parse((await f.db.first('SELECT snapshot_json FROM site_claim_registry WHERE organisation_kind=?',[kind])).snapshot_json); + assert.deepEqual(await read('company'),{...f.companySnapshot,homeBlock:null});assert.deepEqual(await read('clan'),f.snapshot); + const newer={...f.companySnapshot,homeBlock:{...f.companySnapshot.homeBlock,id:randomUUID()}}; + await f.db.query("UPDATE site_claim_registry SET snapshot_json=?,revision=6 WHERE organisation_kind='company'",[JSON.stringify(newer)]); + await applyOwnerHomeBlockRelease(f.db,f.keys,plan,{requestId});assert.deepEqual(await read('company'),newer); + assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM account_audit')).n,1); + }finally{f.db.close();} +}); + +test('company release refuses transferred deeds and non-owner kinds without issuing a release key',async()=>{ + const f=await ownerCompanyFixture();try{ + const plan=await ownerHomeBlockPlan(f.db,'company');await f.db.query('UPDATE site_company_deeds SET owner_account_id=? WHERE company_id=?',[f.people.Other.id,f.company]); + await assert.rejects(applyOwnerHomeBlockRelease(f.db,f.keys,plan,{requestId:randomUUID()}));await assert.rejects(ownerHomeBlockPlan(f.db,'protected')); + assert.ok(JSON.parse((await f.db.first("SELECT snapshot_json FROM site_claim_registry WHERE organisation_kind='company'")).snapshot_json).homeBlock); + assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,0); + }finally{f.db.close();} +}); test('Owner free release consumes original staff key, preserves estate and tier, bounds audit, and replays without clearing a later Home Block',async()=>{ const f=await ownerFixture();try{ const p=await ownerHomeBlockPlan(f.db),requestId=randomUUID(),r=await applyOwnerHomeBlockRelease(f.db,f.keys,p,{requestId});assert.equal(r.released,true); diff --git a/website/tests/personal-activity-events.test.mjs b/website/tests/personal-activity-events.test.mjs index fea9ce1b..61a0989a 100644 --- a/website/tests/personal-activity-events.test.mjs +++ b/website/tests/personal-activity-events.test.mjs @@ -21,5 +21,5 @@ test('revoked, altered or relinked Personal proof cannot be claimed from a previ if(change==='revoked')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.keyId]);if(change==='altered')await f.db.query('UPDATE jarvis_personal_activity_events SET quantity=101 WHERE key_id=?',[receipt.keyId]);if(change==='relinked')await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[randomUUID(),f.people.Member.id]); assert.equal((await f.runtime.quests.list(f.people.Member)).quests.find(q=>q.id==='S1-C-01').canClaim,false);await assert.rejects(f.runtime.quests.claim(f.people.Member,{definitionId:'S1-C-01',requestId:randomUUID(),revision:1}));assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_quest_claims')).n,0); }finally{f.db.close();}}}); -test('mandatory XP-threshold settlement records completion without fabricating game proof',async()=>{const f=await setup();try{await f.runtime.quests.start(f.people.Member,{definitionId:'S1-C-01'});await f.db.query('UPDATE jarvis_progression_accounts SET total_xp=60375,effective_xp=60375,level_no=70 WHERE account_id=?',[f.people.Member.id]);await f.runtime.quests.claim(f.people.Member,{definitionId:'S1-C-01',requestId:randomUUID(),revision:1});assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_personal_activity_events')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_progression_facts')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_quest_claims')).n,1);}finally{f.db.close();}}); +test('mandatory XP-threshold settlement records completion without fabricating game proof',async()=>{const f=await setup();try{await f.runtime.quests.start(f.people.Member,{definitionId:'S1-C-01'});await f.db.query('UPDATE jarvis_progression_accounts SET total_xp=123750,effective_xp=123750,level_no=100 WHERE account_id=?',[f.people.Member.id]);await f.runtime.quests.claim(f.people.Member,{definitionId:'S1-C-01',requestId:randomUUID(),revision:1});assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_personal_activity_events')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_progression_facts')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_quest_claims')).n,1);}finally{f.db.close();}}); test('Personal transport binds its namespace on the server and rejects identity and channel overrides',async()=>{const f=await setup();try{const secret='s'.repeat(32),api=createPersonalActivityAPI(f.db,f.keys,{GAME_LINK_SECRET:secret},{clock:f.clock}),request=(input,path='personal',auth='Bearer '+secret)=>new Request('https://cp.dunerealms.com/internal/progression/'+path+'/event',{method:'POST',headers:{authorization:auth,'content-type':'application/json'},body:JSON.stringify(input)});assert.equal((await api(request(f.input,'pol'))).status,404);assert.equal((await api(request({...f.input,namespace:'pol'}))).status,409);assert.equal((await api(request(f.input,'personal','browser'))).status,401);assert.equal((await api(request(f.input))).status,200);}finally{f.db.close();}}); diff --git a/website/tests/postbank-payroll-accounts.test.mjs b/website/tests/postbank-payroll-accounts.test.mjs index e90e106e..7a3ffea4 100644 --- a/website/tests/postbank-payroll-accounts.test.mjs +++ b/website/tests/postbank-payroll-accounts.test.mjs @@ -1,6 +1,6 @@ import {test} from 'node:test'; import assert from 'node:assert/strict'; -import {ensurePayrollCurrentAccount} from '../node/postbank-payroll-accounts.mjs'; +import {ensurePayrollCurrentAccount,ensureBasicCurrentAccount} from '../node/postbank-payroll-accounts.mjs'; const recipient={id:'f3ffda37-01e4-41ea-b89d-fbeda82e453e',username:'unimatrix999'}; function fixture(accounts=[],hasClient=true){ const writes=[];return {writes, @@ -39,3 +39,11 @@ test('an inactive package cannot be bypassed by reusing its otherwise active acc await assert.rejects(ensurePayrollCurrentAccount(tx,recipient),/needs review/); assert.equal(tx.writes.some(w=>w.sql.includes('INSERT INTO pb_packages')),false); }); +test('Lobby provisioning uses a free basic current account with honest source attribution and no ledger credit',async()=>{ + const tx=fixture([],false),r=await ensureBasicCurrentAccount(tx,recipient,{source:'lobby'}); + assert.equal(r.created,true);assert.match(tx.writes.find(w=>w.sql.includes('INSERT INTO pb_packages')).sql,/lobby-provisioned-basic-v1/); + assert.match(tx.writes.find(w=>w.sql.includes('INSERT INTO pb_packages')).sql,/'pb_start',0/); + assert.match(tx.writes.find(w=>w.sql.includes('INSERT INTO pb_audit')).sql,/lobby_account_provisioned/); + assert.equal(tx.writes.some(w=>w.sql.includes('pb_entries')||w.sql.includes('pb_orders')),false); + await assert.rejects(ensureBasicCurrentAccount(fixture(),recipient,{source:'untrusted'}),/reviewed/); +}); diff --git a/website/tests/progression-pol.test.mjs b/website/tests/progression-pol.test.mjs index edb4b0f0..1504e090 100644 --- a/website/tests/progression-pol.test.mjs +++ b/website/tests/progression-pol.test.mjs @@ -43,7 +43,7 @@ test('POL policy is independently keyed, uncapped and preserves personal policy/ const {ensureProgressionPolicy}=await import('../node/progression-policy.mjs'); await initializeProgression(f.db);await initializePOLProgression(f.db); await ensureProgressionPolicy(f.db,f.keys,{clock:()=>2000});await ensurePOLProgressionPolicy(f.db,f.keys,{clock:()=>2000}); - assert.equal((await f.db.first('SELECT level_cap FROM jarvis_progression_seasons')).level_cap,70); + assert.equal((await f.db.first('SELECT level_cap FROM jarvis_progression_seasons')).level_cap,100); assert.equal((await f.db.first('SELECT level_cap FROM jarvis_pol_progression_seasons')).level_cap,0); assert.equal((await f.db.query('SELECT * FROM jarvis_pol_quest_config')).length,POL_QUEST_DEFINITIONS.filter(d=>!d.faction&&!['bounty-jobs','spice-upgrading'].includes(d.branch)).length); assert.equal((await ensurePOLProgressionPolicy(f.db,f.keys)).replayed,true); diff --git a/website/tests/progression-sidebar.test.mjs b/website/tests/progression-sidebar.test.mjs index b82c639b..7f31f255 100644 --- a/website/tests/progression-sidebar.test.mjs +++ b/website/tests/progression-sidebar.test.mjs @@ -22,6 +22,7 @@ test('ordinary player Mentats use the existing bound House choice without invent }); +const branchButtons=directory=>directory.children.flatMap(child=>child.children||[]).filter(node=>typeof node.onclick==='function'); test('mission branches and directory persist through decisions/history and stay scoped to the selected journal',async()=>{ const {createProgressionSidebar}=await import('../control-panel/public/cp-v2/cp-v2-progression-sidebar.mjs'); class Node{constructor(){this.children=[];this.style={};this.attributes={};this.classList={remove(){}};this.isConnected=true;}append(...nodes){this.children.push(...nodes);}prepend(...nodes){this.children.unshift(...nodes);}insertBefore(node){this.children.push(node);}replaceChildren(...nodes){this.children=nodes;}setAttribute(k,v){this.attributes[k]=v;}remove(){}querySelector(){return null;}} @@ -29,7 +30,7 @@ test('mission branches and directory persist through decisions/history and stay const right=new Node(),left=new Node(),banner=new Node(),shell=new Node();right.parentElement=shell;right.querySelector=()=>banner;shell.querySelector=s=>s==='#sidebar'?left:right; globalThis.document={createElement:()=>new Node(),querySelector:()=>null};globalThis.location={hash:'#quests/quests'};globalThis.history={replaceState(){}}; const host={closest:()=>({parentElement:shell})},requests=[],selected=[]; - const data=kind=>({state:'active',branches:[{id:kind,title:kind}],quests:[{branch:kind}],player:{}}); + const data=kind=>{const branch=kind==='personal'?'a':'fremen';return {state:'active',branches:[{id:branch,title:kind==='personal'?'A':'Fremen'}],quests:[{branch}],player:{}};}; let sidebar; try{ sidebar=createProgressionSidebar(host,{onBranch:id=>selected.push(id),fetcher:async path=>{requests.push(path);return Response.json(path==='/api/progression/pol'?data('pol'):path==='/api/progression'?data('personal'):{});}}); @@ -37,8 +38,8 @@ test('mission branches and directory persist through decisions/history and stay const directory=left.children.find(n=>n.attributes['aria-label']==='Mission branches'); assert.equal(directory.hidden,false);assert.equal(banner.hidden,false); sidebar.setNavigation('personal','history');sidebar.showBranches(true);assert.equal(directory.hidden,false); - directory.children[1].children[0].onclick();assert.deepEqual(selected,['personal']); - sidebar.setNavigation('pol','decisions');assert.equal(directory.children[1].children[0].children[1].textContent,'pol'); + branchButtons(directory)[0].onclick();assert.deepEqual(selected,['category:arrival']); + sidebar.setNavigation('pol','decisions');assert.equal(branchButtons(directory)[0].children[1].textContent,'Sons of the Sand'); assert.equal(requests.filter(p=>p==='/api/progression').length,1); }finally{sidebar?.dispose();for(const [key,value]of Object.entries(before)){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}} }); diff --git a/website/tests/quest-categories.test.mjs b/website/tests/quest-categories.test.mjs new file mode 100644 index 00000000..1b13acf8 --- /dev/null +++ b/website/tests/quest-categories.test.mjs @@ -0,0 +1,47 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import {fileURLToPath} from 'node:url'; +import {QUEST_CATEGORIES,OTHER_CATEGORY,categoryFor,groupBranches,orderChapters,bannerUrl,iconUrl} from '../control-panel/public/cp-v2/cp-v2-quest-categories.mjs'; +import {POL_QUEST_BRANCHES} from '../control-panel/public/cp-v2/cp-v2-pol-quest-catalogue.mjs'; +import {MISSION_BRANCHES} from '../control-panel/public/cp-v2/cp-v2-progression-catalogue.mjs'; + +const known=[...new Set([...MISSION_BRANCHES.map(b=>b.id),'acquisitions','spice-harvesting',...POL_QUEST_BRANCHES.map(b=>b.id)])]; + +test('every known quest branch belongs to exactly one themed category',()=>{ + const seen=new Map(); + for(const c of QUEST_CATEGORIES)for(const b of c.branches){assert.ok(!seen.has(b),'branch twice: '+b);seen.set(b,c.id);} + for(const b of known)assert.notEqual(categoryFor(b),OTHER_CATEGORY,'unmapped branch '+b); + assert.equal(QUEST_CATEGORIES.length,13); + assert.equal(new Set(QUEST_CATEGORIES.map(c=>c.id)).size,13); +}); +test('the website catalogue matches the in-game catalogue file',()=>{ + const game=JSON.parse(fs.readFileSync(new URL('./fixtures/quest-categories.plugin.json',import.meta.url),'utf8')).categories; + assert.deepEqual(JSON.parse(JSON.stringify(QUEST_CATEGORIES)),game); +}); +test('every category ships a banner and an icon',()=>{ + for(const c of [...QUEST_CATEGORIES,OTHER_CATEGORY]){ + for(const url of [bannerUrl(c),iconUrl(c)])assert.ok(fs.existsSync(fileURLToPath(url)),'missing '+url); + assert.match(c.accent,/^#[0-9a-f]{6}$/);assert.ok(c.title&&c.tagline); + } +}); +test('branches regroup by category in catalogue order and unmapped ones are kept last',()=>{ + const rows=[{id:'elytra',title:'E'},{id:'atreides',title:'A'},{id:'a',title:'Prologue'},{id:'ordos',title:'O'},{id:'brand-new',title:'N'}]; + const groups=groupBranches(rows); + assert.deepEqual(groups.map(g=>g.category.id),['arrival','landsraad','wings','other']); + assert.deepEqual(groups[1].rows.map(r=>r.id),['atreides','ordos']); + assert.deepEqual(groups[3].rows.map(r=>r.id),['brand-new']); + assert.deepEqual(groupBranches([]),[]); +}); +test('chapters follow prerequisites, stay stable and survive cycles',()=>{ + const q=(id,requires=[])=>({id,requires}); + assert.deepEqual(orderChapters([q('c',['b']),q('a'),q('b',['a'])]).map(r=>r.id),['a','b','c']); + assert.deepEqual(orderChapters([q('x'),q('y'),q('z')]).map(r=>r.id),['x','y','z']); + assert.deepEqual(orderChapters([q('p',['q']),q('q',['p'])]).map(r=>r.id).sort(),['p','q']); + assert.deepEqual(orderChapters([q('m',['missing'])]).map(r=>r.id),['m']); + assert.deepEqual(orderChapters([{id:'k',requires:[],requiresAny:['j']},{id:'j'}]).map(r=>r.id),['j','k']); +}); +test('the category layer never changes quest data',()=>{ + const rows=Object.freeze([Object.freeze({id:'a',requires:Object.freeze([]),reward:5})]); + assert.deepEqual(orderChapters(rows),rows); +}); diff --git a/website/tests/quest-category-art-routes.test.mjs b/website/tests/quest-category-art-routes.test.mjs new file mode 100644 index 00000000..97c37d43 --- /dev/null +++ b/website/tests/quest-category-art-routes.test.mjs @@ -0,0 +1,21 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFile} from 'node:fs/promises'; +import {createPanel} from '../control-panel/server.mjs'; +import {LocalD1} from './d1-adapter.mjs'; +import {QUEST_CATEGORIES,OTHER_CATEGORY} from '../control-panel/public/cp-v2/cp-v2-quest-categories.mjs'; + +test('real CP routes serve all authored arc PNGs with correct GET and HEAD semantics',async()=>{ + const db=new LocalD1(),app=createPanel(db),origin='https://cp.dunerealms.com'; + try{ + for(const category of [...QUEST_CATEGORIES,OTHER_CATEGORY])for(const kind of ['icon','banner']){ + const name=category.id+'-'+kind+'.png',url=origin+'/v2/art/quests/'+name; + const response=await app(new Request(url));assert.equal(response.status,200,name);assert.equal(response.headers.get('content-type'),'image/png');assert.equal(response.headers.get('x-content-type-options'),'nosniff'); + assert.deepEqual(Buffer.from(await response.arrayBuffer()),await readFile(new URL('../control-panel/public/cp-v2/art/quests/'+name,import.meta.url))); + const head=await app(new Request(url,{method:'HEAD'}));assert.equal(head.status,200);assert.equal(head.headers.get('content-type'),'image/png');assert.equal(await head.text(),''); + } + assert.equal((await app(new Request(origin+'/cp-v2/art/quests/arrival-icon.png'))).status,200); + const post=await app(new Request(origin+'/v2/art/quests/arrival-icon.png',{method:'POST'}));assert.equal(post.status,405); + for(const path of ['/v2/art/quests/unknown-icon.png','/v2/art/quests/arrival-icon.png.js','/v2/art/quests/arrival%2Ficon.png','/v2/art/quests/../../server.mjs'])assert.equal((await app(new Request(origin+path))).status,404,path); + }finally{db.close();} +}); diff --git a/website/tests/quest-login-settle.test.mjs b/website/tests/quest-login-settle.test.mjs new file mode 100644 index 00000000..8e1a5271 --- /dev/null +++ b/website/tests/quest-login-settle.test.mjs @@ -0,0 +1,48 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs';import {initializeProgression} from '../node/progression-schema.mjs';import {createQuestProgression} from '../node/progression-quests.mjs'; +const definitions=[ + {id:'S1-TEST-01',title:'First objective',branch:'a',season:'S01',metric:'first',target:1,requires:[],requiresAny:[],revision:1,optional:false}, + {id:'S1-TEST-02',title:'Hard objective',branch:'a',season:'S01',metric:'hard',target:1000,requires:['S1-TEST-01'],requiresAny:[],revision:1,optional:false}, + {id:'S1-TEST-03',title:'Side objective',branch:'i',season:'S01',metric:'side',target:1,requires:[],requiresAny:[],revision:1,optional:true}, + {id:'S1-TEST-04',title:'Repeatable chore',branch:'i',season:'S01',metric:'chore',target:1,requires:[],requiresAny:[],revision:1,optional:true,repeatable:true,cooldownMs:1000,cooldownGroup:'CHORE'} +]; +async function fixture(){const f=await companyFixture();await initializeProgression(f.db); + await f.db.query("INSERT INTO jarvis_progression_seasons(season_id,starts_at,ends_at,level_cap,curve_base,state) VALUES('S01',0,5000,3,25,'active')"); + for(const [i,d] of definitions.entries())await f.db.query('INSERT INTO jarvis_quest_config(definition_id,revision,xp,reward_json,updated_by,updated_at) VALUES(?,1,?,NULL,?,0)',[d.id,i===0?50:25,f.people.Owner.id]); + const token={},service=createQuestProgression(f.db,f.keys,{definitions,clock:()=>2000,authorizePlayer:async a=>a.id===f.people.Member.id,authorizeObservation:async a=>a===token,verifyAcquisition:async a=>a===token,resolvePlayer:async id=>id===f.people.Member.id?f.people.Member:null}); + const observe=(metric,value)=>service.observe(token,{accountId:f.people.Member.id,seasonId:'S01',metric,value,eventId:randomUUID(),source:'verified-test'}); + return {...f,service,observe,me:f.people.Member}; +} +const xp=async f=>Number((await f.db.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.me.id]))?.total_xp||0); +test('quests finished while offline are paid once on the next login and a repeat sweep pays nothing',async()=>{ + const f=await fixture();try{ + await f.observe('first',1);await f.observe('side',1); + const result=await f.service.settleCompleted(f.me); + assert.deepEqual(result.settled.map(q=>q.id).sort(),['S1-TEST-01','S1-TEST-03']);assert.equal(result.failed,0);assert.equal(await xp(f),100); + const again=await f.service.settleCompleted(f.me);assert.deepEqual(again.settled,[]);assert.equal(await xp(f),100); + assert.equal((await f.db.query('SELECT key_id FROM jarvis_quest_claims')).length,2); + }finally{f.db.close();} +}); +test('a finished quest chain is settled in one sweep and the unfinished successor is never paid',async()=>{ + const f=await fixture();try{ + await f.observe('first',1);await f.observe('hard',1000); + assert.deepEqual((await f.service.settleCompleted(f.me)).settled.map(q=>q.id),['S1-TEST-01','S1-TEST-02']); + assert.equal(await xp(f),75); + }finally{f.db.close();} +}); +test('the XP-cap bypass never pays a quest whose objective was not met',async()=>{ + const f=await fixture();try{ + await f.observe('side',1);await f.service.claim(f.me,{definitionId:'S1-TEST-03',revision:1,requestId:randomUUID()}); + await f.observe('first',1);await f.service.claim(f.me,{definitionId:'S1-TEST-01',revision:1,requestId:randomUUID()}); + const before=await xp(f),view=await f.service.list(f.me),hard=view.quests.find(q=>q.id==='S1-TEST-02'); + assert.equal(hard.canClaim,true);assert.equal(hard.progress,0); + assert.deepEqual((await f.service.settleCompleted(f.me)).settled,[]);assert.equal(await xp(f),before); + assert.equal(view.quests.find(q=>q.id==='S1-TEST-02').state==='claimed',false); + }finally{f.db.close();} +}); +test('repeatable quests stay manual and an unlinked caller is rejected',async()=>{ + const f=await fixture();try{ + await f.observe('chore',1);assert.deepEqual((await f.service.settleCompleted(f.me)).settled,[]); + await assert.rejects(f.service.settleCompleted({id:randomUUID()}),/identity/); + }finally{f.db.close();} +}); diff --git a/website/tests/smuggler-navigation.test.mjs b/website/tests/smuggler-navigation.test.mjs new file mode 100644 index 00000000..8a4d56b6 --- /dev/null +++ b/website/tests/smuggler-navigation.test.mjs @@ -0,0 +1,75 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {BankFixture} from './postbank-fixture.mjs'; +import {PostbankService,BankError} from '../node/postbank-service.mjs'; +import {BANK_VERSION} from '../node/postbank-catalogue.mjs'; +import {createGuildService,createGameGuildAPI,GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA} from '../node/game-guild.mjs'; +import {GUILD_ROUTE_SCHEMA} from '../node/guild-route-bindings.mjs'; +import {readFile,writeFile} from 'node:fs/promises'; +async function fixture(){ + const bank=new BankFixture();for(const s of [GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA,GUILD_ROUTE_SCHEMA])await bank.query(s.replace(/,INDEX guild_pending\([^)]*\)/,'').replace(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4','')); + const user={id:randomUUID(),username:'traveller',uuid:randomUUID(),faction:'atreides',version:1,keyId:randomUUID()},entity={id:randomUUID(),kind:'person',key:null,name:'traveller'};entity.key=user.id; + const authority=async()=>({entities:[{...entity,canView:true,canActivate:true,canPay:true}]}),products=new PostbankService(bank,authority); + await products.activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const source=(await bank.first("SELECT id FROM pb_accounts WHERE type_code='102' AND system_key IS NULL")).id; + await bank.query('UPDATE pb_accounts SET balance_minor=40000 WHERE id=?',[source]);await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,reserved_minor,state,created_at) VALUES('sys_game_treasury','999','Game treasury',0,0,'active',0)"); + let now=1200000,embargo=false,owned=true,originOwned=true,revision=2,permit={keyId:randomUUID(),expiresAt:9000000}; + const origin={kind:'clan',id:randomUUID(),name:'Origin',homeBlockId:randomUUID(),claimRevision:1,server:'caladan',home:{worldUuid:randomUUID(),worldName:'caladan',position:{x:8,y:64,z:8}}},target={kind:'company',id:randomUUID(),name:'Destination',homeBlockId:randomUUID(),claimRevision:2,server:'arrakis',home:{worldUuid:randomUUID(),worldName:'arrakis',position:{x:100,y:64,z:100}}}; + const ref=h=>({kind:h.kind,id:h.id}); + const check=(input,stage)=>{ + if(!owned)throw new BankError('Current target owner required',403);if(stage!=='ready'&&!originOwned)throw new BankError('Current source owner required',403); + if(stage!=='ready'&&(Math.abs(now-input.sourceLocation.observedAt)>30000||input.sourceLocation.worldUuid!==origin.home.worldUuid))throw new BankError('Stale NPC contact',403); + if(stage!=='quote'&&input.targetRevision!==revision)throw new BankError('Home Block changed',409);return {origin,target:{...target,claimRevision:revision}}; + }; + const homeRoutes={list:async()=>({origin,destinations:[{...origin,available:false,reason:'Already on this world.'},{...target,available:true,reason:''},{kind:'company',id:randomUUID(),name:'Unregistered',home:null,server:null,homeBlockId:null,claimRevision:0,available:false,reason:'No registered Home Block.'}]}),quote:async(_u,i)=>check(i,'quote'),withLock:async(_u,i,stage,work)=>work(check(i,stage),user)}; + const opts={authority,resolve:async uuid=>uuid===user.uuid?user:null,clock:()=>now,routeBindings:true,homeRoutes,allowSmuggling:async()=>permit,allowJourney:async()=>!embargo}; + const service=createGuildService(bank,opts),input=()=>({action:'home_board',uuid:user.uuid,sourceWorld:'caladan',origin:ref(origin),target:ref(target),sourceLocation:{worldUuid:origin.home.worldUuid,position:{x:8,y:64,z:8},observedAt:now},requestId:randomUUID(),keyId:user.keyId,version:1,fareMinor:10000,confirmed:true,originHomeBlockId:origin.homeBlockId,originRevision:1,targetHomeBlockId:target.homeBlockId,targetRevision:2}); + return {bank,user,source,origin,target,service,opts,input,setTime:n=>now=n,setOwned:v=>owned=v,setOriginOwned:v=>originOwned=v,setRevision:n=>revision=n,setEmbargo:v=>embargo=v,setPermit:p=>permit=p,account:()=>bank.first('SELECT balance_minor,reserved_minor FROM pb_accounts WHERE id=?',[source]),ready:i=>service.home_ready({action:'home_ready',uuid:user.uuid,server:'arrakis',requestId:i.requestId})}; +} +test('ordinary Guild catalog contains every canonical world once, retaining lawful compatibility order and disabled reasons',async()=>{ + const f=await fixture();try{const q=await f.service.quote(f.user.uuid);assert.equal(q.routes.length,5);assert.equal(new Set(q.routes.map(r=>r.server)).size,5);assert.equal(q.routes.filter(r=>r.name==='Arrakis').length,1);assert.deepEqual(q.destinations,['caladan']);assert.equal(q.routes.find(r=>r.server==='caladan').available,true);assert.match(q.routes.find(r=>r.server==='giedi_prime').reason,/no Imperial passage/);f.setEmbargo(true);assert.match((await f.service.quote(f.user.uuid)).routes.find(r=>r.server==='caladan').reason,/embargoed/);}finally{f.bank.close();} +}); +test('Esmar routes use destination eligibility and record actual origin for confirmed return, binding retries to the same origin',async()=>{ + const f=await fixture();try{const q=await f.service.quoteSmuggler(f.user.uuid,'arrakis');assert.equal(q.routes.length,5);assert.equal(q.routes.find(r=>r.server==='giedi_prime').available,true);assert.equal(q.routes.find(r=>r.server==='arrakis').available,false);assert.match(q.routes.find(r=>r.server==='caladan').reason,/ordinary Guild/); + const i={uuid:f.user.uuid,requestId:randomUUID(),keyId:f.user.keyId,version:1,fareMinor:10000,sourceWorld:'arrakis',destination:'giedi_prime'};await f.service.board(i,true);assert.equal((await f.account()).balance_minor,40000);await assert.rejects(f.service.board({...i,sourceWorld:'kaitain'},true),/already used/);await f.service.arrive(f.user.uuid,'giedi_prime');assert.equal((await f.account()).balance_minor,30000);assert.equal((await f.service.smugglerReturn(f.user.uuid,'giedi_prime')).destination,'arrakis');await assert.rejects(f.service.smugglerReturn(f.user.uuid,'kaitain'),/No confirmed/); + }finally{f.bank.close();} +}); +test('an old pending lobby-Arrakis booking remains retryable when route metadata is enabled',async()=>{ + const f=await fixture();try{const legacy=createGuildService(f.bank,{...f.opts,routeBindings:false,homeRoutes:null}),i={uuid:f.user.uuid,requestId:randomUUID(),keyId:f.user.keyId,version:1,fareMinor:10000,sourceWorld:'lobby',destination:'arrakis'};await legacy.board(i,true);assert.equal((await f.service.board(i,true)).replayed,true);assert.equal((await f.account()).reserved_minor,10000);await f.service.arrive(f.user.uuid,'arrakis');assert.equal((await f.service.smugglerReturn(f.user.uuid,'arrakis')).destination,'lobby');}finally{f.bank.close();} +}); +test('owned list retains unavailable organisations and one reservation settles only after matching destination preflight',async()=>{ + const f=await fixture();try{const i=f.input(),list=await f.service.home_list(i);assert.equal(list.destinations.length,3);assert.equal(list.destinations.filter(r=>!r.available).length,2);const quote=await f.service.home_quote(i);assert.equal(quote.fareMinor,10000);assert.equal(quote.affordable,true); + await f.service.home_board(i);assert.equal((await f.account()).reserved_minor,10000);assert.equal((await f.service.arrive(f.user.uuid,'arrakis')).passage,null);assert.equal((await f.account()).balance_minor,40000); + assert.equal((await f.service.home_arrive({uuid:f.user.uuid,server:'kaitain'})).ticket,null);assert.equal((await f.service.home_arrive({uuid:f.user.uuid,server:'arrakis'})).ticket.requestId,i.requestId); + const paid=await f.ready(i);assert.equal(paid.paid,true);assert.equal((await f.account()).balance_minor,30000);f.setTime(1500000);assert.equal((await f.ready(i)).replayed,true);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,1); + const ack={action:'home_delivered',uuid:f.user.uuid,server:'arrakis',requestId:i.requestId,arrivedAt:1500000,arrival:{worldUuid:f.target.home.worldUuid,position:{x:100.5,y:64,z:100.5}}};await f.service.home_delivered(ack);assert.equal((await f.service.home_delivered(ack)).replayed,true);assert.equal((await f.service.home_arrive({uuid:f.user.uuid,server:'arrakis'})).ticket,null);await assert.rejects(f.service.home_delivered({...ack,arrivedAt:1500001}),/conflict/);await assert.rejects(f.service.smugglerReturn(f.user.uuid,'arrakis'),/No confirmed/); + }finally{f.bank.close();} +}); +test('accepted board replays stale contact proof, but new requests and changed binding cannot reserve another fare',async()=>{ + const f=await fixture();try{const i=f.input();await f.service.home_board(i);f.setTime(1240000);assert.equal((await f.service.home_board(i)).replayed,true);await assert.rejects(f.service.home_board({...i,targetRevision:3}),/already used/);await assert.rejects(f.service.home_board({...i,requestId:randomUUID()}),/Stale NPC/);assert.equal((await f.account()).reserved_minor,10000);}finally{f.bank.close();} +}); +test('changed ownership before settlement leaves money untouched and expires; after settlement it preserves a paid review receipt',async()=>{ + const f=await fixture();try{let i=f.input();await f.service.home_board(i);f.setOwned(false);await assert.rejects(f.ready(i),/owner/);assert.equal((await f.account()).balance_minor,40000);f.setTime(1320001);await f.service.expire();assert.equal((await f.account()).reserved_minor,0);f.setOwned(true);i=f.input();await f.service.home_board(i);await f.ready(i);f.setRevision(3);const review=await f.ready(i);assert.equal(review.needsReview,true);assert.equal(review.paid,true);assert.equal(review.requestId,i.requestId);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.bank.close();} +}); +test('failed ledger posting rolls back exactly one reservation and metadata cannot create orphan fares',async()=>{ + const f=await fixture();try{const i=f.input();await f.service.home_board(i);f.bank.sqlite.exec("CREATE TRIGGER reject_entry BEFORE INSERT ON pb_entries BEGIN SELECT RAISE(ABORT,'ledger down');END");await assert.rejects(f.ready(i),/ledger down/);assert.equal((await f.account()).balance_minor,40000);assert.equal((await f.account()).reserved_minor,10000);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);f.bank.sqlite.exec('DROP TRIGGER reject_entry');await f.ready(i);assert.equal((await f.account()).reserved_minor,0);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.bank.close();} +}); +test('owned and ordinary bookings share the same pending-fare guard and arrival rejects wrong server or position',async()=>{ + const f=await fixture();try{const i=f.input();await f.service.home_board(i);await assert.rejects(f.service.board({uuid:f.user.uuid,requestId:randomUUID(),keyId:f.user.keyId,version:1,fareMinor:10000,destination:'caladan'}),/previous passage/);await assert.rejects(f.service.home_ready({uuid:f.user.uuid,server:'kaitain',requestId:i.requestId}),/unavailable/);await f.ready(i);await assert.rejects(f.service.home_delivered({uuid:f.user.uuid,server:'arrakis',requestId:i.requestId,arrivedAt:1200000,arrival:{worldUuid:f.target.home.worldUuid,position:{x:1000,y:64,z:1000}}}),/matching native/);}finally{f.bank.close();} +}); +test('home protocol rejects browser credentials, account overrides and malformed proof before service calls',async()=>{ + const f=await fixture();try{const secret='s'.repeat(64),api=createGameGuildAPI(null,null,null,{GAME_LINK_SECRET:secret},{service:f.service}),send=(b,auth=secret)=>api(new Request('https://cp.dunerealms.com/internal/game/guild',{method:'POST',headers:{authorization:'Bearer '+auth,'content-type':'application/json'},body:JSON.stringify(b)}));const i=f.input();assert.equal((await send(i,'browser')).status,401);assert.equal((await send({...i,accountId:'other'})).status,400);assert.equal((await send({...i,sourceLocation:{...i.sourceLocation,worldUuid:'bad'}})).status,400);assert.equal((await send(i)).status,200);assert.equal((await f.account()).reserved_minor,10000);}finally{f.bank.close();} +}); +test('actual Java wire-builder fixture passes every strict central action parser',async()=>{ + const fixture=JSON.parse(await readFile(new URL('./fixtures/navigator-native-wire.json',import.meta.url),'utf8')),calls=[],service=Object.fromEntries(['home_list','home_quote','home_board','home_arrive','home_ready','home_delivered'].map(action=>[action,async b=>{calls.push(b.action);return {ok:true,schema:1};}])); + service.quoteSmuggler=async()=>{calls.push('smuggler_quote');return {ok:true};};service.board=async()=>{calls.push('smuggler_board');return {ok:true};};service.smugglerReturn=async()=>{calls.push('smuggler_return');return {ok:true};}; + const secret='s'.repeat(64),api=createGameGuildAPI(null,null,null,{GAME_LINK_SECRET:secret},{service}); + for(const [action,body]of Object.entries(fixture)){const result=await api(new Request('https://cp.dunerealms.com/internal/game/guild',{method:'POST',headers:{authorization:'Bearer '+secret,'content-type':'application/json'},body:JSON.stringify(body)}));assert.equal(result.status,200,action+': '+await result.text());} + assert.deepEqual(calls,Object.keys(fixture)); +}); +test('central response fixture comes from actual synthetic reservation, posting and delivery methods',async()=>{ + const f=await fixture();try{const i=f.input(),responses={guild_quote:await f.service.quote(f.user.uuid),smuggler_quote:await f.service.quoteSmuggler(f.user.uuid),home_list:await f.service.home_list(i),home_quote:await f.service.home_quote(i)};responses.home_board=await f.service.home_board(i);responses.home_arrive=await f.service.home_arrive({uuid:f.user.uuid,server:'arrakis'});responses.home_ready=await f.ready(i);f.setRevision(3);responses.home_review=await f.ready(i);f.setRevision(2);const delivered={action:'home_delivered',uuid:f.user.uuid,server:'arrakis',requestId:i.requestId,arrivedAt:1200000,arrival:{worldUuid:f.target.home.worldUuid,position:{x:100.5,y:64,z:100.5}}};responses.home_delivered=await f.service.home_delivered(delivered);assert.equal(responses.home_ready.paid,true);assert.equal(responses.home_delivered.delivered,true);const expired=f.input();await f.service.home_board(expired);f.setTime(1320001);responses.home_expired=await f.ready(expired);assert.equal(responses.home_expired.cancelled,true);if(process.env.NAVIGATOR_WIRE_OUTPUT)await writeFile(process.env.NAVIGATOR_WIRE_OUTPUT,JSON.stringify({request:i,deliveryRequest:delivered,responses},null,2));}finally{f.bank.close();} +}); +test('owned reservations and settlement reuse the held central reader for authority instead of opening another pool connection',async()=>{ + const f=await fixture();try{const pinned={},original=f.opts.homeRoutes.withLock;let scopes=0;const service=createGuildService(f.bank,{...f.opts,homeRoutes:{...f.opts.homeRoutes,withLock:(u,i,s,work)=>original(u,i,s,(ctx,user)=>work(ctx,user,pinned))},authorityForStore:reader=>{assert.equal(reader,pinned);scopes++;return f.opts.authority;}}),i=f.input();await service.home_board(i);await service.home_ready({uuid:f.user.uuid,server:'arrakis',requestId:i.requestId});assert.equal(scopes,2);assert.equal((await f.account()).balance_minor,30000);}finally{f.bank.close();} +}); diff --git a/website/tests/spice-crafting-cookbook.test.mjs b/website/tests/spice-crafting-cookbook.test.mjs new file mode 100644 index 00000000..63139988 --- /dev/null +++ b/website/tests/spice-crafting-cookbook.test.mjs @@ -0,0 +1,44 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {createHash} from 'node:crypto'; +import {recipeCatalogue,recipeIcons} from '../scripts/recipe-catalogue.mjs'; +import {itemLoreModel} from '../control-panel/public/item-lore-model.mjs'; + +const catalogue=JSON.parse(readFileSync(new URL('../data/cookbook/spice-crafting.json',import.meta.url))); +const grades=JSON.parse(readFileSync(new URL('../data/cookbook/item-grades.json',import.meta.url))); +const records=recipeCatalogue().filter(r=>catalogue.some(s=>s.id===r.output.id)); + +test('all seven new recipe cards use the exact native catalogue grade, base plus one',()=>{ + assert.equal(records.length,7); + for(const spec of catalogue){ + const recipe=records.find(r=>r.output.id===spec.id),card=itemLoreModel({...recipe.output,nativeMetadata:true}); + assert.equal(card.quality,spec.quality);assert.equal(card.mark,spec.baseMark+1); + assert.equal(recipe.output.material,spec.material.toLowerCase()); + assert.equal(recipe.output.name,spec.name);assert.equal(recipe.output.custom,true); + } + assert.equal(records.find(r=>r.output.id==='spice_soul_campfire').output.equipmentMark,4); + assert.equal(records.find(r=>r.output.id==='spice_campfire').output.equipmentMark,5); +}); + +test('cooker recipes preserve the raw-spice cross and four iron corners',()=>{ + for(const recipe of records.filter(r=>r.shaped)){ + assert.equal(recipe.station,'Crafting table');assert.equal(recipe.amount,1);assert.equal(recipe.grid.length,9); + for(const slot of [0,2,6,8])assert.equal(recipe.grid[slot].id,'iron_ingot'); + for(const slot of [1,3,5,7]){assert.equal(recipe.grid[slot].id,'spice');assert.equal(recipe.grid[slot].custom,true);} + assert.equal(recipe.grid[4].material,recipe.output.material);assert.equal(recipe.grid[4].custom,false); + } + const coal=records.find(r=>r.id==='spice_coal');assert.equal(coal.shaped,false); + assert.deepEqual(coal.inputs.map(i=>i.id),['spice','coal']);assert.match(coal.inputs[1].name,/Charcoal/); + const tender=records.find(r=>r.id==='spice_tender');assert.equal(tender.shaped,false); + assert.deepEqual(tender.inputs.map(i=>[i.id,i.custom]),[['minecart',false],['spice_coal',true]]); +}); + +test('the seven Cookbook icons and catalogue are bound to the reviewed plugin source',()=>{ + const source=grades.additionalSources.spiceCookersAndRails; + assert.equal(source.sourceCommit,'13a8f23247497ac5cd9d59b6869e19097ee307be'); + const bytes=readFileSync(new URL('../data/cookbook/spice-crafting.json',import.meta.url)); + assert.equal(createHash('sha256').update(bytes).digest('hex'),source.files['network/content-assets/cookbook/spice-crafting.json']); + const icons=new Map(recipeIcons(records));assert.equal(icons.size,7); + for(const icon of Object.values(source.icons))assert.equal(createHash('sha256').update(readFileSync(new URL('../data/cookbook/'+icon.path,import.meta.url))).digest('hex'),icon.sha256); +}); diff --git a/website/tests/staff-tools-permissions.test.mjs b/website/tests/staff-tools-permissions.test.mjs new file mode 100644 index 00000000..9468bec3 --- /dev/null +++ b/website/tests/staff-tools-permissions.test.mjs @@ -0,0 +1,24 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {STAFF_TOOL_NODES,staffToolPolicyPlan,enableStaffTools} from '../ops/enable-staff-tools.mjs'; +import {defaultOrganisationPolicies} from '../node/organisation-default-policies.mjs'; +import {GAME_NODE_SET} from '../node/game-ranks.mjs'; + +test('staff-tool plan adds only the three explicit nodes to existing staff policies',()=>{ + const staff={scope_type:'branch',scope_key:'news_media',role_key:'officer',version:7,nodes:['web.posts.edit']}; + const civil={scope_type:'clan',scope_key:'test',role_key:'officer',version:1,nodes:['dune.clans.view']}; + const plan=staffToolPolicyPlan([staff,civil]); + assert.equal(plan.length,1);assert.equal(plan[0].version,7); + assert.deepEqual(plan[0].nodes,[...STAFF_TOOL_NODES,'web.posts.edit'].sort()); + assert.deepEqual(staff.nodes,['web.posts.edit']); + assert.deepEqual(staffToolPolicyPlan([{...staff,nodes:plan[0].nodes}]),[]); +}); + +test('staff utility defaults are registered for native sync and absent from ordinary membership',()=>{ + for(const node of STAFF_TOOL_NODES)assert(GAME_NODE_SET.has(node)); + for(const p of defaultOrganisationPolicies().filter(p=>p.role!=='branch_lead'))for(const node of STAFF_TOOL_NODES)assert(p.nodes.includes(node)); +}); + +test('the policy operator rejects a caller other than the verified Owner before any database access',async()=>{ + await assert.rejects(enableStaffTools({},{id:'other',username:'unimatrix999'},{apply:true}),/verified Owner/); +}); diff --git a/website/tests/travel-holdings.test.mjs b/website/tests/travel-holdings.test.mjs new file mode 100644 index 00000000..71153c11 --- /dev/null +++ b/website/tests/travel-holdings.test.mjs @@ -0,0 +1,29 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {holdsOnWorld,createNativeHoldingCheck} from '../node/travel-holdings.mjs'; +const U='11111111-1111-1111-1111-111111111111'; +const state={clans:[{lifecycle:'active',hidden:false,homeServer:'giedi-prime',homeBlock:{source:'minecraft',revision:1,worldName:'giedi_prime'},members:[{uuid:U.toUpperCase()}]},{lifecycle:'archived',hidden:false,homeServer:'kaitain',members:[{uuid:U}]}], + companies:[{lifecycle:'active',hidden:true,homeServer:'caladan',members:[{uuid:U}]},{lifecycle:'active',hidden:false,homeServer:'sigma_draconis_iv',homeBlock:{source:'minecraft',revision:1,worldName:'sigma_draconis_iv'},members:[{uuid:U}]}]}; +test('an active clan or company with a Home Block on the world counts, whatever the spelling of the world',()=>{ + assert.equal(holdsOnWorld(state,U,'giedi_prime'),true);assert.equal(holdsOnWorld(state,U,'sigma-draconis-iv'),true); +}); +test('archived, hidden and foreign records and unknown people do not count',()=>{ + assert.equal(holdsOnWorld(state,U,'kaitain'),false);assert.equal(holdsOnWorld(state,U,'caladan'),false);assert.equal(holdsOnWorld(state,'22222222-2222-2222-2222-222222222222','giedi_prime'),false); + assert.equal(holdsOnWorld(null,U,'giedi_prime'),false);assert.equal(holdsOnWorld(state,'', 'giedi_prime'),false); +}); +test('the central state is cached for a minute',async()=>{ + let reads=0,now=0;const check=createNativeHoldingCheck(null,{clock:()=>now,read:async()=>{reads++;return state;}}); + assert.equal(await check(null,U,'giedi_prime'),true);assert.equal(await check(null,U,'giedi_prime'),true);assert.equal(reads,1);now=60001;await check(null,U,'giedi_prime');assert.equal(reads,2); +}); + + +test('a registration world without a current native Home Block does not give a discount',()=>{ + const record={lifecycle:'active',hidden:false,homeServer:'giedi_prime',members:[{uuid:U}]}; + assert.equal(holdsOnWorld({clans:[record]},U,'giedi_prime'),false); + assert.equal(holdsOnWorld({clans:[{...record,homeBlock:{source:'minecraft',revision:1,worldName:'caladan'}}]},U,'giedi_prime'),false); +}); + +test('booking re-reads current membership instead of spending a cached discount',async()=>{ + let snapshot=state,reads=0;const check=createNativeHoldingCheck(null,{read:async()=>{reads++;return snapshot;}}); + assert.equal(await check(null,U,'giedi_prime'),true);snapshot={clans:[],companies:[]}; + assert.equal(await check(null,U,'giedi_prime',{fresh:true}),false);assert.equal(reads,2); +}); diff --git a/website/tests/travel-tariff.test.mjs b/website/tests/travel-tariff.test.mjs new file mode 100644 index 00000000..b1356bd9 --- /dev/null +++ b/website/tests/travel-tariff.test.mjs @@ -0,0 +1,32 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {ladderFare,effectiveTrips,reducedFare,paidTariff,classifyRoute,TRAVEL_BASE_MINOR,TRAVEL_CAP_MINOR,TRAVEL_RESET_MS,BOUNTY_MULTIPLIER} from '../node/travel-tariff.mjs'; +test('the ladder starts at 150 DM and compounds 10% per paid trip',()=>{ + assert.equal(ladderFare(0),15000);assert.equal(ladderFare(1),16500);assert.equal(ladderFare(2),18150);assert.equal(ladderFare(3),19965); + for(let i=0;i<60;i++)assert.ok(ladderFare(i+1)>=ladderFare(i)); +}); +test('the ladder never exceeds 5000 DM and stays there',()=>{ + assert.equal(ladderFare(1000),TRAVEL_CAP_MINOR);assert.equal(ladderFare(1e9),TRAVEL_CAP_MINOR); + let first=0;while(ladderFare(first){ + const now=10*TRAVEL_RESET_MS; + assert.equal(effectiveTrips(7,now-TRAVEL_RESET_MS+1,now),7);assert.equal(effectiveTrips(7,now-TRAVEL_RESET_MS,now),0);assert.equal(effectiveTrips(7,null,now),0); +}); +test('a clan or company on the destination halves the fare and the bounty',()=>{ + const full=paidTariff({trips:0,reduced:false}),half=paidTariff({trips:0,reduced:true}); + assert.equal(full.fareMinor,15000);assert.equal(full.bountyMinor,75000);assert.equal(half.fareMinor,7500);assert.equal(half.bountyMinor,37500); + assert.equal(half.bountyMinor*2,full.bountyMinor);assert.equal(full.bountyMinor,TRAVEL_BASE_MINOR*BOUNTY_MULTIPLIER); +}); +test('the bounty is five times the fare actually paid, at every step',()=>{ + for(const trips of [0,1,5,40,500])for(const reduced of [false,true]){const t=paidTariff({trips,reduced});assert.equal(t.bountyMinor,t.fareMinor*5);assert.ok(t.fareMinor>=1);} + assert.equal(reducedFare(1),1);assert.equal(reducedFare(15001),7501); +}); +test('lobby, the race world and decrees are free; every other world is paid',()=>{ + assert.deepEqual(classifyRoute({destination:'lobby',raceWorld:'caladan'}),{free:true,reason:'lobby'}); + assert.deepEqual(classifyRoute({destination:'caladan',raceWorld:'caladan'}),{free:true,reason:'race-world'}); + assert.deepEqual(classifyRoute({destination:'arrakis',raceWorld:'caladan',decree:true}),{free:true,reason:'decree'}); + assert.deepEqual(classifyRoute({destination:'arrakis',raceWorld:'caladan'}),{free:false,reason:'paid'}); +}); +test('invalid input is rejected instead of producing a fare',()=>{ + assert.throws(()=>ladderFare(-1),RangeError);assert.throws(()=>ladderFare(1.5),RangeError);assert.throws(()=>effectiveTrips(-1,0,0),RangeError); +}); diff --git a/website/tests/user-voice-permissions.test.mjs b/website/tests/user-voice-permissions.test.mjs new file mode 100644 index 00000000..d68b978b --- /dev/null +++ b/website/tests/user-voice-permissions.test.mjs @@ -0,0 +1,6 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {USER_VOICE_NODES,voicePermissions} from '../node/user-voice-permissions.mjs'; +import {GAME_CATALOG,validateGameNodes} from '../node/game-ranks.mjs'; +test('voice addition preserves existing permissions and is replay safe',()=>{const existing=['duneess.basics','dune.quests.view'];const result=voicePermissions(existing);assert.deepEqual(result,[...existing,...USER_VOICE_NODES]);assert.deepEqual(voicePermissions(result),result);assert.deepEqual(existing,['duneess.basics','dune.quests.view']);}); +test('only three non-administrative nodes are registered for ordinary users',()=>{assert.deepEqual(GAME_CATALOG.nodes.filter(n=>n.node.startsWith('voicechat.')).map(n=>n.node),USER_VOICE_NODES);assert.ok(validateGameNodes(USER_VOICE_NODES,'user'));assert.equal(validateGameNodes(['voicechat.admin'],'user'),false);assert.equal(validateGameNodes(['voicechat.*'],'user'),false);for(const node of USER_VOICE_NODES)assert.equal(GAME_CATALOG.suggestedRoles.find(r=>r.id==='user').permissions[node],true);}); diff --git a/website/tests/web-repository-scope.test.mjs b/website/tests/web-repository-scope.test.mjs index d94f5b60..258fa272 100644 --- a/website/tests/web-repository-scope.test.mjs +++ b/website/tests/web-repository-scope.test.mjs @@ -7,11 +7,23 @@ import {MAIN_MENU_GROUPS} from '../scripts/main-menu.mjs'; import {PORTAL_NAV} from '../scripts/portal-navigation.mjs'; import {SHARED_FOOTER} from '../scripts/site-chrome.mjs'; -test('website-only inputs preserve all 32 published recipes and their exact icon bytes',()=>{ +test('website-only inputs preserve all 32 published recipes and icons apart from verified grade enrichment',()=>{ const baseline=JSON.parse(readFileSync(new URL('./fixtures/cookbook-before-repository-split.json',import.meta.url))); const hash=bytes=>createHash('sha256').update(bytes).digest('hex'),recipes=recipeCatalogue(); - assert.equal(recipes.length,baseline.recipes);assert.equal(hash(JSON.stringify(recipes)),baseline.catalogueSha256); - assert.deepEqual(Object.fromEntries(recipeIcons(recipes).map(([name,bytes])=>[name,hash(bytes)])),baseline.icons); + const additionalIds=['spice_furnace','spice_smoker','spice_blast_furnace','spice_campfire','spice_soul_campfire','spice_coal','spice_tender']; + const additional=recipes.filter(recipe=>additionalIds.includes(recipe.id)); + assert.deepEqual(additional.map(recipe=>recipe.id).sort(),[...additionalIds].sort()); + assert.deepEqual(additional.map(recipe=>recipe.output.id).sort(),[...additionalIds].sort()); + assert.deepEqual(recipeIcons(additional).map(([name])=>name).sort(),additionalIds.map(id=>`/recipe-icons/${id}.png`).sort()); + const original=recipes.filter(recipe=>!recipe.id.startsWith('dunechest_')&&!additionalIds.includes(recipe.id)); + const enriched=new Set(['jerboa_leather','spice_bread','spice_block','smuggled_spice_block','crafted_elytra','jerboa_water_vial','water_of_life','spice_boosted_potion']); + const previous=original.map(recipe=>{ + if(!enriched.has(recipe.output.id))return recipe; + const output={...recipe.output};delete output.quality;delete output.equipmentMark;delete output.metadataMode; + return {...recipe,output}; + }); + assert.equal(original.length,baseline.recipes);assert.equal(hash(JSON.stringify(previous)),baseline.catalogueSha256); + assert.deepEqual(Object.fromEntries(recipeIcons(original).map(([name,bytes])=>[name,hash(bytes)])),baseline.icons); }); test('shared menus expose the existing DuneForge workspace and root DuneGit register',()=>{ diff --git a/website/tests/xp-season-cap.test.mjs b/website/tests/xp-season-cap.test.mjs new file mode 100644 index 00000000..890e6752 --- /dev/null +++ b/website/tests/xp-season-cap.test.mjs @@ -0,0 +1,6 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {XP_POLICY,xpAtLevel,levelForXP} from '../node/progression-definitions.mjs'; +test('the personal season cap is level 100 and the curve stays inside the supported range',()=>{ + assert.equal(XP_POLICY.seasonCap,100);assert.equal(xpAtLevel(100,XP_POLICY.base),123750); + assert.equal(levelForXP(60375,{base:25,cap:XP_POLICY.seasonCap}),70);assert.equal(levelForXP(123750,{base:25,cap:XP_POLICY.seasonCap}),100);assert.equal(levelForXP(10**9,{base:25,cap:XP_POLICY.seasonCap}),100); +}); diff --git a/website/web/assets/promos/nexustorage-promo-card.png b/website/web/assets/promos/nexustorage-promo-card.png new file mode 100644 index 00000000..30c9e863 Binary files /dev/null and b/website/web/assets/promos/nexustorage-promo-card.png differ diff --git a/website/web/assets/promos/nexustorage-workshop.png b/website/web/assets/promos/nexustorage-workshop.png new file mode 100644 index 00000000..cf235e3b Binary files /dev/null and b/website/web/assets/promos/nexustorage-workshop.png differ diff --git a/website/web/imperial-recipe-book.js b/website/web/imperial-recipe-book.js index 79503511..37af08ae 100644 --- a/website/web/imperial-recipe-book.js +++ b/website/web/imperial-recipe-book.js @@ -69,6 +69,9 @@ try { get('recipe-result').replaceChildren(icon(selected.output)); get('recipe-result').setAttribute('aria-label', selected.output.name); const card = itemLoreCard({ ...selected.output, nativeMetadata: true }); + if (selected.output.metadataMode === 'input') { + card.querySelector('.item-lore-identity').replaceChildren(node('strong', 'Quality follows input'), node('em', 'MK follows input')); + } if (selected.output.icon) card.querySelector('.item-lore-name img').src = selected.output.icon; get('recipe-item-summary').textContent = selected.output.summary; get('recipe-item-card').replaceChildren(card); @@ -77,7 +80,7 @@ try { const cooking = selected.station === 'Furnace' || selected.station === 'Smoker'; get('recipe-station-layout').classList.toggle('recipe-station--crafting', crafting); get('recipe-station-layout').classList.toggle('recipe-station--cooking', cooking); - const slots = crafting ? Array.from({ length: 9 }, (_, index) => selected.inputs[index]) : selected.inputs; + const slots = crafting ? selected.grid ?? Array.from({ length: 9 }, (_, index) => selected.inputs[index]) : selected.inputs; get('recipe-grid').replaceChildren(...slots.map(item => { const slot = node('li', ''); if (item) { diff --git a/website/web/release.json b/website/web/release.json index 46899fe5..cf42242c 100644 --- a/website/web/release.json +++ b/website/web/release.json @@ -1,8 +1,8 @@ { - "version": "1.0.2.0", + "version": "1.0.3.0", "stage": "beta", - "updatedAt": "2026-11-29T00:00:00.000Z", - "scope": "The Pillager Update", + "updatedAt": "2026-12-03T23:17:00.000Z", + "scope": "The Wild Update", "menuUpdates": [ { "href": "https://clans.dunerealms.com/",