diff --git a/docs/CP-FEATURE-MANUAL-20261028.md b/docs/CP-FEATURE-MANUAL-20261028.md new file mode 100644 index 00000000..a4be3b73 --- /dev/null +++ b/docs/CP-FEATURE-MANUAL-20261028.md @@ -0,0 +1,31 @@ +# Control panel: feature manual and permissions + +Published 28 October 2026 at https://cp.dunerealms.com/#staff-manual. +Release directory: /home/dunerealms/apps/dunerealms/releases/20261028-cp-feature-guides. + +The staff manual has 13 searchable feature categories, including CoreProtect, WorldEdit, WorldGuard, Chat, Permissions, Moderation, Inventory, Economy, Tickets, Travel, Quests, Politics and Server operations. Guides explicitly distinguish live behaviour from pending integrations. Reading the guide requires cp.menu.staffmanual, checked on the server as well as in the menu. + +Account menu sections now open one view below the navigation. Ranks & permissions provides a checkbox matrix, lower-rank creation and protected owner accounts. Both existing accounts unimatrix_admin_44a5a3 and grmacken were assigned Owners without changing passwords. Game permissions await the DuneEss/LuckPerms deployment; this release publishes the website controls and private game snapshot endpoint only. + +Validation: 67 website tests passed locally and on the live host before switching the release. Both HTTPS health checks passed; unauthenticated staff manual returned 401. Browser verified Owners session and separate Staff manual view with feature categories. Core and Ess local builds passed, but those game changes were not deployed in this release. + +Changed source paths: +- website/control-panel/public/index.html +- website/control-panel/public/pages.mjs +- website/control-panel/public/panel.js +- website/control-panel/public/ranks.css +- website/control-panel/public/ranks.mjs +- website/control-panel/public/staff-manual.mjs +- website/control-panel/server-control.mjs +- website/control-panel/server.mjs +- website/control-panel/staff-manual.mjs +- website/node/account-admin.mjs +- website/node/auth.mjs +- website/node/community-rewards.mjs +- website/node/permissions.mjs +- website/node/rank-admin.mjs +- website/node/schema.sql +- website/node/server.mjs +- website/tests/node-host.test.mjs +- website/tests/rank-permissions.test.mjs +- website/tests/server-control.test.mjs diff --git a/website/control-panel/public/index.html b/website/control-panel/public/index.html index 31bfcd94..fcd6fcd7 100644 --- a/website/control-panel/public/index.html +++ b/website/control-panel/public/index.html @@ -1 +1 @@ -Account control panel · dunerealms.com

DUNEREALMS.COM / ACCOUNT CONTROL PANEL

Welcome, traveller.

Your identity. Your journeys. Your place in the caravan.

Website accountVerified game identityCommunity rewards

THE CARAVANS MUST ENDURE

One account.
A world of journeys.

Link your Minecraft identity and keep your earned rewards in one place.

Your website password is separate from Minecraft. We never ask for your Microsoft or Minecraft password.

+Account control panel · dunerealms.com

DUNEREALMS.COM / ACCOUNT CONTROL PANEL

Welcome, traveller.

Your identity. Your journeys. Your place in the caravan.

Website accountVerified game identityCommunity rewards

THE CARAVANS MUST ENDURE

One account.
A world of journeys.

Link your Minecraft identity and keep your earned rewards in one place.

Your website password is separate from Minecraft. We never ask for your Microsoft or Minecraft password.

diff --git a/website/control-panel/public/pages.mjs b/website/control-panel/public/pages.mjs new file mode 100644 index 00000000..0bfe2948 --- /dev/null +++ b/website/control-panel/public/pages.mjs @@ -0,0 +1,17 @@ +const dashboard=document.getElementById('dashboard'),nav=dashboard?.querySelector('nav'); +const pages={game:'cp.menu.game','planetary-inventory':'cp.menu.inventory',rewards:'cp.menu.rewards',security:'cp.menu.security','server-operations':'cp.menu.servers',staff:'cp.menu.administration',permissions:'cp.menu.permissions',items:'cp.menu.items','staff-manual':'cp.menu.staffmanual'}; +let permissions=[],authenticated=false; +document.body.classList.add('cp-pages-ready'); +function update(focus=false){ + if(!dashboard||!nav)return; + const available=Object.keys(pages).filter(key=>permissions.includes(pages[key])&&document.getElementById(key)); + let active=location.hash.slice(1);if(!available.includes(active))active=available[0]; + for(const section of dashboard.querySelectorAll(':scope > section')){section.dataset.cpPage='';section.classList.toggle('cp-page-active',authenticated&§ion.id===active);} + for(const link of nav.querySelectorAll('a[href^="#"]')){const key=link.hash.slice(1),allowed=available.includes(key);link.hidden=!allowed;link.dataset.permission=pages[key]||'';if(key===active)link.setAttribute('aria-current','page');else link.removeAttribute('aria-current');} + if(active){const section=document.getElementById(active);if(focus){const heading=section.querySelector('h2');if(heading){heading.tabIndex=-1;heading.focus({preventScroll:true});}}} +} +nav?.addEventListener('click',event=>{const link=event.target.closest('a[href^="#"]');if(!link||link.hidden)return;event.preventDefault();history.pushState(null,'',link.hash);update(true);}); +window.addEventListener('hashchange',()=>update());window.addEventListener('popstate',()=>update()); +window.addEventListener('dune:session',event=>{authenticated=!!event.detail;permissions=event.detail?.permissions||[];update();}); +if(dashboard)new MutationObserver(()=>update()).observe(dashboard,{childList:true}); +const response=await fetch('/api/auth/session',{cache:'no-store'});if(response.ok){const data=await response.json();authenticated=data.authenticated;permissions=data.user?.permissions||[];update();} diff --git a/website/control-panel/public/panel.js b/website/control-panel/public/panel.js index 4f6a7e24..135ecf82 100644 --- a/website/control-panel/public/panel.js +++ b/website/control-panel/public/panel.js @@ -15,8 +15,8 @@ $('refresh-rewards').onclick=()=>action($('refresh-rewards'),rewards); $('password-form').onsubmit=event=>{event.preventDefault();action(event.target.querySelector('button'),async()=>{await api('auth/password',Object.fromEntries(new FormData(event.target)));event.target.reset();notice('Password changed. Other sessions have been signed out.');});}; async function campaigns(){const data=await api('community/campaigns');$('campaigns').replaceChildren();for(const row of data.campaigns){const card=el('article');card.className='reward';card.append(el('h3',row.month),el('p',new Intl.NumberFormat(undefined,{style:'currency',currency:'EUR'}).format(row.received_cents/100)+' / '+new Intl.NumberFormat(undefined,{style:'currency',currency:'EUR'}).format(row.target_cents/100)),el('p',row.reward_amount+' Dunemarks per UUID · '+(row.reached_at?'Goal reached':'Not reached')));$('campaigns').append(card);}} for(const [form,endpoint]of [['campaign-form','community/campaigns'],['total-form','community/verify-total']])$(form).onsubmit=event=>{event.preventDefault();action(event.target.querySelector('button'),async()=>{const data=Object.fromEntries(new FormData(event.target));for(const key of ['targetCents','rewardAmount','receivedCents'])if(key in data)data[key]=Number(data[key]);if(!confirm(endpoint.endsWith('verify-total')?'Confirm that this total is verified against payment records? Reaching the target unlocks rewards.':'Create this goal? The target and reward cannot be edited afterward.'))return;await api(endpoint,data);notice('Saved.');await campaigns();});}; -async function load(){const data=await api('auth/session');session=data.user;document.querySelector('.account-summary').textContent=data.authenticated?'Signed in as '+data.user.username:'Your dunerealms.com account';$('auth').hidden=data.authenticated;$('dashboard').hidden=!data.authenticated;$('logout').hidden=!data.authenticated;$('welcome').textContent=data.authenticated?'Welcome, '+data.user.username+'.':'Welcome, traveller.';if(data.authenticated){$('staff').hidden=!data.user.staff;$('staff-tab').hidden=!data.user.staff;await linking();await rewards();if(data.user.staff){await serverControls();await campaigns();await accounts();}}} -async function accounts(){const data=await api('admin/accounts');$('accounts').replaceChildren();for(const row of data.accounts){const card=el('article');card.className='reward';card.append(el('h3',row.username+' · '+row.role),el('p',row.minecraft_uuid?'Linked UUID: '+row.minecraft_uuid:'No verified game account'));const revoke=el('button','Sign out this account');revoke.onclick=()=>{if(confirm('Revoke current sessions for '+row.username+'?'))action(revoke,async()=>{await api('admin/revoke-sessions',{userId:row.id});notice('Sessions revoked.');});};card.append(revoke);$('accounts').append(card);}} +async function load(){const data=await api('auth/session');session=data.user;document.querySelector('.account-summary').textContent=data.authenticated?'Signed in as '+data.user.username+' · '+data.user.rankLabel:'Your dunerealms.com account';$('auth').hidden=data.authenticated;$('dashboard').hidden=!data.authenticated;$('logout').hidden=!data.authenticated;$('welcome').textContent=data.authenticated?'Welcome, '+data.user.username+'.':'Welcome, traveller.';window.dispatchEvent(new CustomEvent('dune:session',{detail:session}));if(data.authenticated){const has=node=>data.user.permissions.includes(node);$('staff').hidden=!has('cp.menu.administration');$('staff-tab').hidden=!has('cp.menu.administration');const work=[];if(has('cp.menu.game'))work.push(linking());if(has('cp.menu.rewards'))work.push(rewards());if(has('cp.menu.servers'))work.push(serverControls());if(has('cp.community.manage'))work.push(campaigns());if(has('cp.accounts.view'))work.push(accounts());await Promise.allSettled(work);}} +async function accounts(){const data=await api('admin/accounts');$('accounts').replaceChildren();for(const row of data.accounts){const card=el('article');card.className='reward';card.append(el('h3',row.username+' · '+row.role),el('p',row.minecraft_uuid?'Linked UUID: '+row.minecraft_uuid:'No verified game account'));const revoke=el('button','Sign out this account');revoke.onclick=()=>{if(confirm('Revoke current sessions for '+row.username+'?'))action(revoke,async()=>{await api('admin/revoke-sessions',{userId:row.id});notice('Sessions revoked.');});};if(session?.permissions?.includes('cp.accounts.revoke'))card.append(revoke);if(session?.permissions?.includes('cp.accounts.assign')&&row.role!=='owners'){const button=el('button','Assign rank');button.onclick=()=>assignRank(card,row,button);card.append(button);}$('accounts').append(card);}} $('refresh-accounts').onclick=()=>action($('refresh-accounts'),accounts); load().catch(error=>notice(error.message)); // Embedded parent receives only layout information, never credentials, UUIDs or reward codes. @@ -24,3 +24,5 @@ new ResizeObserver(()=>{if(parent!==window)for(const origin of ['https://www.dun async function serverControls(){let allowed=false;try{await api('servers');allowed=true;}catch{}$('servers-tab').hidden=!allowed;$('server-operations').hidden=!allowed;const frame=$('server-controls-frame');if(allowed&&!frame.getAttribute('src'))frame.src='/servers?embedded=1';if(!allowed)frame.removeAttribute('src');} window.addEventListener('message',event=>{const frame=$('server-controls-frame');if(event.origin!==location.origin||event.source!==frame.contentWindow||event.data?.type!=='dune-server-panel-height')return;const height=event.data.height;if(Number.isFinite(height))frame.style.height=Math.max(700,Math.min(4000,height))+'px';}); + +async function assignRank(card,row,button){button.disabled=true;try{const data=await api('ranks'),select=el('select');select.setAttribute('aria-label','Rank for '+row.username);for(const rank of data.ranks.filter(r=>r.kind==='access'&&(session.rank==='owners'||r.levelaction(save,async()=>{await api('ranks/assign',{userId:row.id,rank:select.value});notice('Rank saved; previous sessions revoked.');await accounts();});card.append(select,save);}catch(error){notice(error.message);button.disabled=false;}} diff --git a/website/control-panel/public/ranks.css b/website/control-panel/public/ranks.css new file mode 100644 index 00000000..fe9ed24d --- /dev/null +++ b/website/control-panel/public/ranks.css @@ -0,0 +1,4 @@ +.cp-pages-ready #dashboard>section:not(.cp-page-active){display:none!important}.tabs a[aria-current=page]{background:#c4a35b;color:#142a28;border-color:#e6cc87;box-shadow:inset 0 -3px #81622a}.rank-matrix{min-width:0}.matrix-scroll{max-width:100%;overflow:auto;border:1px solid #8e7846;margin:16px 0 30px}.rank-matrix table{border-collapse:collapse;min-width:900px;width:100%;font-size:12px}.rank-matrix th,.rank-matrix td{padding:12px;border:1px solid #627357;text-align:center;vertical-align:middle}.rank-matrix th:first-child{text-align:left;min-width:230px;position:sticky;left:0;background:#17382e;z-index:1}.rank-matrix thead th{background:#254c3d;position:sticky;top:0}.rank-matrix code,.rank-matrix small{display:block;font-size:10px;margin:6px 0}.rank-matrix input[type=checkbox]{width:20px;height:20px;padding:0;box-shadow:none;accent-color:#ceac62}.rank-matrix button{padding:7px 12px}.rank-create{display:flex;gap:14px;align-items:end;flex-wrap:wrap;max-width:none}.rank-create h3{width:100%}.rank-create label{flex:1;min-width:150px}.rank-create select{padding:13px;background:#163329;color:#eadbb8;border:3px solid #7d744e}.rank-create>button{margin-bottom:16px}.tabs a[href='#permissions']:before,.tabs a[href='#server-operations']:before{background-image:url('assets/menu-9.webp')} + +#staff-manual details{border:1px solid #627357;margin:12px 0;background:#132f26b3}#staff-manual summary{padding:16px;color:#e4ca83;font-weight:bold;cursor:pointer}#staff-manual details[open]>:not(summary){margin-left:20px;margin-right:20px}#staff-manual li{margin:9px 0;line-height:1.6}#staff-manual summary:focus-visible{outline:3px solid #ceac62;outline-offset:2px} + diff --git a/website/control-panel/public/ranks.mjs b/website/control-panel/public/ranks.mjs new file mode 100644 index 00000000..56cd9432 --- /dev/null +++ b/website/control-panel/public/ranks.mjs @@ -0,0 +1,17 @@ +const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n;}; +const dashboard=document.getElementById('dashboard');let current=null,loading=false; +const section=el('section');section.id='permissions';section.hidden=true;section.append(el('p','ACCESS CONTROL'),el('h2','Ranks & permissions'),el('p','Each checkbox grants its permission node to that rank. House and political groups are added in game alongside the access rank. Owners are protected.')); +const status=el('p');status.role='status';section.append(status); +const create=el('form');create.className='rank-create';create.append(el('h3','Create a rank')); +function field(text,name,type='text'){const label=el('label',text),input=el('input');input.name=name;input.type=type;input.required=true;label.append(input);create.append(label);return input;} +const key=field('Rank ID · lowercase letters, digits and underscores','key');key.pattern='[a-z][a-z0-9_]{2,15}';key.maxLength=16; +field('Display name','label').maxLength=40; +const baseLabel=el('label','Copy permissions from'),base=el('select');base.name='base';for(const name of ['user','vip','staff','corestaff']){const option=el('option',name);option.value=name;base.append(option);}baseLabel.append(base);create.append(baseLabel);const createButton=el('button','Create rank');createButton.type='submit';create.append(createButton);section.append(create); +const refresh=el('button','Refresh matrix');refresh.type='button';section.append(refresh);const wrapper=el('div');wrapper.className='rank-matrix';section.append(wrapper);dashboard?.append(section); +const tab=el('a','Ranks & permissions');tab.id='permissions-tab';tab.href='#permissions';tab.hidden=true;dashboard?.querySelector('nav').append(tab); +async function api(path,body){const response=await fetch('/api/ranks'+path,{cache:'no-store',...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});const data=await response.json();if(!response.ok)throw Error(data.message||'Rank request failed.');return data;} +async function load(){if(loading)return;loading=true;try{current=await api('');section.hidden=false;tab.hidden=false;render();status.textContent='Saved ranks loaded. Minecraft updates are applied by DuneEss during its next sync.';}catch(error){status.textContent=error.message;}finally{loading=false;}} +function render(){wrapper.replaceChildren();for(const kind of ['access','house','office','path']){const ranks=current.ranks.filter(r=>r.kind===kind);if(!ranks.length)continue;wrapper.append(el('h3',kind==='access'?'Access ranks':kind==='house'?'House groups':kind==='office'?'Political appointments':'Smuggler paths'));const scroll=el('div');scroll.className='matrix-scroll';const table=el('table'),head=el('thead'),row=el('tr');row.append(el('th','Permission node'));for(const rank of ranks){const cell=el('th',rank.label);cell.append(el('small',rank.key));if(rank.editable){const save=el('button','Save');save.type='button';save.onclick=async()=>{save.disabled=true;try{const nodes=[...table.querySelectorAll('input[type="checkbox"]')].filter(x=>x.dataset.rank===rank.key&&x.checked).map(x=>x.value);await api('/permissions',{rank:rank.key,nodes,version:rank.version});await load();status.textContent='Saved '+rank.label+'.';}catch(error){status.textContent=error.message;save.disabled=false;}};cell.append(save);}else cell.append(el('small','Protected / read only'));row.append(cell);}head.append(row);table.append(head);const body=el('tbody');for(const item of current.catalog.filter(item=>kind==='access'||item.scope==='Minecraft')){const row=el('tr'),label=el('th');label.append(el('span',item.label),el('code',item.node));row.append(label);for(const rank of ranks){const cell=el('td'),input=el('input');input.type='checkbox';input.value=item.node;input.dataset.rank=rank.key;input.checked=rank.key==='owners'||rank.nodes.includes(item.node);input.disabled=!rank.editable||current.actor.rank!=='owners'&&!current.actor.nodes.includes(item.node);input.setAttribute('aria-label',rank.label+': '+item.label);cell.append(input);row.append(cell);}body.append(row);}table.append(body);scroll.append(table);wrapper.append(scroll);}} +create.onsubmit=async event=>{event.preventDefault();createButton.disabled=true;try{await api('/create',Object.fromEntries(new FormData(create)));create.reset();await load();}catch(error){status.textContent=error.message;}finally{createButton.disabled=false;}};refresh.onclick=load; +window.addEventListener('dune:session',event=>{const allowed=event.detail?.permissions?.includes('cp.ranks.manage');section.hidden=!allowed;tab.hidden=!allowed;if(allowed)load();}); +const response=await fetch('/api/auth/session',{cache:'no-store'});if(response.ok){const data=await response.json();if(data.user?.permissions?.includes('cp.ranks.manage'))load();} diff --git a/website/control-panel/public/staff-manual.mjs b/website/control-panel/public/staff-manual.mjs new file mode 100644 index 00000000..0fdb82ad --- /dev/null +++ b/website/control-panel/public/staff-manual.mjs @@ -0,0 +1,15 @@ +const dashboard=document.getElementById('dashboard'),nav=dashboard?.querySelector('nav'); +function el(tag,text){const node=document.createElement(tag);if(text!==undefined)node.textContent=text;return node;} +if(dashboard&&nav){ + const section=el('section');section.id='staff-manual';section.hidden=true; + const tab=el('a','Staff manual');tab.href='#staff-manual';tab.hidden=true;nav.append(tab); + section.append(el('h2','Staff manual'),el('p','Browse by feature. Each guide lists its permissions and clearly marks work that is still awaiting integration or deployment.')); + const searchLabel=el('label','Find a feature or permission'),search=el('input');search.type='search';search.placeholder='CoreProtect, chat, inventory…';searchLabel.append(search);section.append(searchLabel); + const notice=el('p');notice.setAttribute('role','status');const content=el('div');section.append(notice,content);dashboard.append(section); + let categories=[],generation=0; + function render(){content.replaceChildren();const term=search.value.trim().toLowerCase();const matches=categories.filter(c=>[c.title,c.module,...c.nodes,...c.steps,...c.checks].join(' ').toLowerCase().includes(term));notice.textContent=matches.length+' feature guides';for(const c of matches){const details=el('details'),summary=el('summary',c.title);details.open=!!term;details.append(summary,el('p',c.module+' · '+c.status));const steps=el('ol');for(const step of c.steps)steps.append(el('li',step));details.append(steps,el('h3','Permission nodes'));if(c.nodes.length){const list=el('ul');for(const name of c.nodes){const item=el('li');item.append(el('code',name));list.append(item);}details.append(list);}else details.append(el('p','No new permission nodes are active for this integration yet.'));details.append(el('h3','Checks & limitations'));const checks=el('ul');for(const check of c.checks)checks.append(el('li',check));details.append(checks);content.append(details);}} + search.addEventListener('input',render); + async function session(user){const token=++generation,allowed=user?.permissions?.includes('cp.menu.staffmanual');tab.hidden=!allowed;section.hidden=!allowed;categories=[];content.replaceChildren();if(!allowed)return;notice.textContent='Loading feature guides…';try{const response=await fetch('/api/staff/manual',{cache:'no-store'});if(token!==generation)return;if(!response.ok)throw Error(response.status===403?'You no longer have permission to read the staff manual.':'Staff manual is unavailable.');const data=await response.json();if(token!==generation)return;categories=data.categories;render();}catch(error){if(token===generation)notice.textContent=error.message;}} + window.addEventListener('dune:session',event=>session(event.detail)); + const response=await fetch('/api/auth/session',{cache:'no-store'});if(response.ok){const data=await response.json();await session(data.user);} +} diff --git a/website/control-panel/server-control.mjs b/website/control-panel/server-control.mjs index c9e87b00..092df64c 100644 --- a/website/control-panel/server-control.mjs +++ b/website/control-panel/server-control.mjs @@ -1,13 +1,17 @@ +import {can} from '../node/permissions.mjs'; import {randomUUID} from 'node:crypto'; import {identity} from '../node/auth.mjs'; const json=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store','Vary':'Cookie'}}); export function createServerControl(db,settings,{fetcher=fetch}={}){ const origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin; - const operators=new Set((settings.SERVER_CONTROL_OPERATORS||'').split(',').map(x=>x.trim().toLowerCase()).filter(Boolean)); return async request=>{ const user=await identity(request,db); if(!user)return json({message:'Sign in to the account panel first.'},401); - if(user.role!=='staff'||!operators.has(user.username.toLowerCase()))return json({message:'Server operator access is required.'},403); + const path=new URL(request.url).pathname; + let node=path.endsWith('/logs')?'cp.servers.logs':path.endsWith('/action')?'cp.servers.power':'cp.servers.view'; + if(!await can(db,user,'cp.menu.servers'))return json({message:'Server operator access is required.'},403); + if(path.endsWith('/action')){try{if((await request.clone().json()).action==='command')node='cp.servers.console';}catch{}} + if(!await can(db,user,node))return json({message:'Permission required: '+node},403); if(!settings.SERVER_CONTROL_TOKEN||settings.SERVER_CONTROL_TOKEN.length<64)return json({message:'Server controls are not configured.'},503); const url=new URL(request.url);let target,body; if(request.method==='GET'&&url.pathname==='/api/servers'&&!url.search)target='/servers'; diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 50c6ee92..381543aa 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,6 @@ +import {createRankAdmin} from '../node/rank-admin.mjs'; +import {createStaffManual} from './staff-manual.mjs'; +import {initializeRanks,can} from '../node/permissions.mjs'; import {createServer} from 'node:http'; import {readFile} from 'node:fs/promises'; import {pathToFileURL} from 'node:url'; @@ -16,6 +19,8 @@ export function createPanel(db,settings={},dependencies={}){ const origin=new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin; const auth=createAuth(db,origin),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin); const admin=createAccountAdmin(db,origin); + const ranks=createRankAdmin(db,settings,origin); + const manual=createStaffManual(db); const servers=createServerControl(db,settings,dependencies.serverControl); const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}}; const inventoryOptions={authenticate:request=>identity(request,db),verifiedMinecraftUuid:async accountId=>(await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(accountId).first())?.minecraft_uuid||null,pool,logger:dependencies.logger||console}; @@ -23,6 +28,10 @@ export function createPanel(db,settings={},dependencies={}){ const market=(settings.EXCHANGE_READ_TOKEN||'').length>=32?createMarketBridge({pool,readToken:settings.EXCHANGE_READ_TOKEN}):null; return async request=>{ const path=new URL(request.url).pathname; + if(path==='/api/staff/manual')return manual(request); + if(path==='/api/game/permissions'||path==='/api/ranks'||path.startsWith('/api/ranks/'))return ranks(request); + const menu=path==='/api/inventory'||path==='/api/exchange/sales-history'?'cp.menu.inventory':(path==='/api/game-link'||path.startsWith('/api/game-link/')&&path!=='/api/game-link/consume')?'cp.menu.game':path==='/api/community/rewards'?'cp.menu.rewards':null; + if(menu){const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401);if(!await can(db,user,menu))return json({message:'Permission required: '+menu},403);} if(path==='/api/servers'||path.startsWith('/api/servers/'))return servers(request); if(path==='/api/inventory')return inventory(request); if(path==='/api/exchange/sales-history')return sales(request); @@ -35,14 +44,14 @@ export function createPanel(db,settings={},dependencies={}){ if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405}); if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});} const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1); - if(!['index.html','panel.js','panel.css','servers.html','servers.js','servers.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); + if(!['index.html','panel.js','panel.css','servers.html','servers.js','servers.css','pages.mjs','ranks.mjs','ranks.css','staff-manual.mjs','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}}); }; } export async function startPanel(settings=process.env){ let inventoryPool=null; if(settings.DUNE_INVENTORY_DATABASE_URL){const {Pool}=await import('pg');inventoryPool=new Pool({connectionString:settings.DUNE_INVENTORY_DATABASE_URL,max:3,connectionTimeoutMillis:5000,idleTimeoutMillis:30000});inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.'));} - const db=await openDatabase(settings),handle=createPanel(db,settings,{inventoryPool}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const db=await openDatabase(settings);await initializeRanks(db);const handle=createPanel(db,settings,{inventoryPool}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self'; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com"}; const server=createServer(async(req,res)=>{try{ req.setTimeout(15000);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>16384){res.writeHead(413,security);res.end();return;}chunks.push(chunk);} diff --git a/website/control-panel/staff-manual.mjs b/website/control-panel/staff-manual.mjs new file mode 100644 index 00000000..aebf2d13 --- /dev/null +++ b/website/control-panel/staff-manual.mjs @@ -0,0 +1,28 @@ +import {identity} from '../node/auth.mjs'; +import {can} from '../node/permissions.mjs'; +import {json} from '../node/game-link.mjs'; + +// Describe verified behaviour separately from work awaiting integration and deployment. +export const STAFF_MANUAL=[ + {id:'permissions',title:'Permissions & ranks',module:'DuneEss / LuckPerms',status:'Website controls available; game bridge awaiting deployment',nodes:['cp.menu.permissions','cp.ranks.manage','cp.accounts.assign'],steps:['Open Ranks & permissions. Choose a rank column and tick the permissions it should receive. Save that column.','Corestaff can create and manage ranks below their own level. Owners are protected against demotion through this page.','Access ranks, houses, political appointments and smuggler paths are separate groups. A house membership must not replace a staff rank.'],checks:['A saved website permission applies to subsequent requests. Game permissions require the DuneEss bridge and LuckPerms to be running.','Use a separate test account to check the result before changing staff access.']}, + {id:'coreprotect',title:'CoreProtect',module:'DuneProtect / CoreProtect',status:'Integration pending',nodes:['duneprotect.inspect','duneprotect.lookup','duneprotect.rollback','duneprotect.restore'],steps:['Record the location, time window and suspected player before looking up changes.','Inspect the relevant history before selecting a rollback. Keep the affected area and time window as small as practical.','Preview the proposed changes using the installed CoreProtect tools before applying a rollback or restore.'],checks:['The DuneProtect integration and its permission mapping are not deployed yet. These nodes do not currently confirm access to CoreProtect commands.','CoreProtect is the history backend; WorldEdit and WorldGuard have different purposes.']}, + {id:'worldedit',title:'WorldEdit',module:'DuneProtect / WorldEdit',status:'Integration pending',nodes:['duneprotect.worldedit'],steps:['Select the intended area and check the selection boundaries.','Make a backup before a large edit. Check the result before leaving the area.'],checks:['WorldEdit is for building and editing. It is not a substitute for investigating player changes with CoreProtect.','The integration must be deployed before the DuneProtect permission grants WorldEdit access.']}, + {id:'worldguard',title:'WorldGuard',module:'DuneProtect / WorldGuard',status:'Integration pending',nodes:['duneprotect.regions'],steps:['Identify the region and its owners, members and flags before making changes.','Check protections with a normal player account after changing a lobby or portal region.'],checks:['Avoid removing global protection to fix a single portal.','The integration must be deployed before the DuneProtect permission grants region administration.']}, + {id:'chat',title:'Chat',module:'DuneEss',status:'Integration pending',nodes:['duneess.chat.network','duneess.chat.nearby','duneess.chat.team','duneess.chat.faction','duneess.chat.imperial','duneess.chat.colors','duneess.chat.format'],steps:['Local and Proxy refer to the same network channel. Nearby is a separate channel with a 50-block range.','Team and house channels restrict their recipients. Imperial chat is intended for the emperor, house leaders, guild staff and political appointments.'],checks:['The new channel implementation is not deployed. Do not treat private-channel delivery as verified until integration tests pass.','Moderation must apply to channel commands as well as ordinary chat.']}, + {id:'moderation',title:'Bans, kicks & moderation',module:'DuneCore / LibertyBans',status:'Integration pending',nodes:['dune.staff.open','dune.staff.history','dune.staff.kick','dune.staff.warn','dune.staff.mute','dune.staff.ban.local','dune.staff.ban.network'],steps:['Check the player UUID and relevant ticket before acting. Review their history.','Choose the intended scope: one server or the whole network. Add a clear reason and check any duration before confirming.'],checks:['The new moderation GUI and LibertyBans integration are pending.','Never use a real player as a test ban. A local ban and a network ban are separate actions.']}, + {id:'inventory',title:'Inventory & custom items',module:'DuneCore',status:'Player inventory view available; staff editor pending',nodes:['cp.menu.inventory','cp.menu.items','cp.items.manage','dune.items.give'],steps:['Use Inventory & sales to view the inventory projection for your verified Minecraft UUID.','The staff inventory editor and custom item designer are planned as separate tools.'],checks:['Do not edit a player inventory owned by another active server session.','Custom item definitions must not mint currency or execute arbitrary commands.']}, + {id:'economy',title:'Economy & shops',module:'DuneEss',status:'Existing economy available; staff GUI pending',nodes:['duneess.exchange','duneess.shops.use','cp.community.manage'],steps:['Use the exchange and configured shops for ordinary transactions.','Record the reason and target UUID when correcting an economic issue. The requested staff GUI is still being integrated.'],checks:['DuneEss owns economic changes; inventory tools must not bypass its ledger.','Player overhead balances are intended to show Dunemarks. Ordinary players’ carried spice and water remain private; smuggler cargo is public. The new labels are not deployed yet.']}, + {id:'tickets',title:'Tickets & case handling',module:'DuneCore / website support',status:'Shared in-game workflow pending',nodes:[],steps:['The website support system is the canonical ticket record. In-game tickets must use the same record and conversation.','The requested workflow is: take the ticket, resolve any suspect to a UUID, and carry that context into the appropriate staff menu.','Teleport actions belong in the teleport menu; suspect inventory actions belong in the inventory menu.'],checks:['The in-game ticket GUI, case assignment and suspect context are pending. No new ticket permission nodes are active yet.','Teleporting to a ticket creator must require an assigned ticket, permission and an online target.']}, + {id:'travel',title:'Guild travel & lobby',module:'DuneEss / DuneLobby',status:'Existing travel available; token integration pending',nodes:['duneess.travel','duneess.tokens.buy','dunelobby.visit','dunelobby.build','dunelobby.admin'],steps:['Use the guild travel interface to choose an available destination.','The requested one-use token system will be managed by DuneEss; lobby portals will delegate to it.'],checks:['Only configured, online destinations may be sold. Four additional planet backends remain unconfigured.','A failed transfer must not consume a paid travel token. The new token flow is not deployed yet.']}, + {id:'quests',title:'NPCs & quests',module:'DuneNPC / Quests',status:'Quest engine integration pending',nodes:[],steps:['DuneNPC owns NPC interactions and the quest entry point.','Quest payments and shop actions must use DuneEss.'],checks:['Quests has been selected as the backend, but its integration has not been deployed. No new quest commands or permissions are documented as available.']}, + {id:'politics',title:'Houses & political appointments',module:'DuneCore / DuneEss',status:'Existing politics available; staff GUI pending',nodes:['dune.admin'],steps:['Keep house membership separate from a player’s access rank.','Political appointments must follow their current term and be removed when they expire.'],checks:['The requested faction and political staff menus are pending.','The new LuckPerms group synchronisation is local work awaiting deployment.']}, + {id:'servers',title:'Server operations',module:'Account control panel',status:'Available',nodes:['cp.menu.servers','cp.servers.view','cp.servers.logs','cp.servers.power','cp.servers.console'],steps:['Open Servers and check status before issuing an action.','Read the relevant logs when investigating a startup failure. Use console commands only when needed.','Check status again after a start, stop or restart.'],checks:['Proxy, lobby and Arrakis are configured. Other planet backends are not configured.','The Arrakis reset has already been completed. Do not repeat it as part of this update.']} +]; + +export function createStaffManual(db){return async request=>{ + const user=await identity(request,db); + if(!user)return json({message:'Sign in first.'},401); + if(!await can(db,user,'cp.menu.staffmanual'))return json({message:'Permission required: cp.menu.staffmanual'},403); + if(request.method!=='GET')return json({message:'Method not allowed'},405); + return json({title:'Staff manual',categories:STAFF_MANUAL}); +};} diff --git a/website/node/account-admin.mjs b/website/node/account-admin.mjs index 964c90a5..060d76a3 100644 --- a/website/node/account-admin.mjs +++ b/website/node/account-admin.mjs @@ -1,8 +1,9 @@ +import {can,rankFor} from './permissions.mjs'; import {randomUUID} from 'node:crypto'; import {identity} from './auth.mjs'; import {json} from './game-link.mjs'; export function createAccountAdmin(db,origin){return async request=>{ - const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401);if(user.role!=='staff')return json({message:'Staff access required.'},403); + const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401);if(!await can(db,user,request.method==='GET'?'cp.accounts.view':'cp.accounts.revoke'))return json({message:'Account administration permission required.'},403); const path=new URL(request.url).pathname; if(request.method==='GET'&&path==='/api/admin/accounts'){ const {results}=await db.prepare('SELECT a.id,a.username,a.role,a.created_at,l.minecraft_uuid,l.minecraft_name FROM site_accounts a LEFT JOIN site_game_links l ON l.user_id=a.id ORDER BY a.created_at DESC LIMIT 200').all();return json({accounts:results}); @@ -13,6 +14,6 @@ export function createAccountAdmin(db,origin){return async request=>{ if(typeof data.userId!=='string'||data.userId.length!==36)return json({message:'Invalid account'},400); const target=await db.prepare('SELECT id,role FROM site_accounts WHERE id=?').bind(data.userId).first(); if(!target)return json({message:'Account not found'},404); - if(target.role==='staff'&&target.id!==user.id)return json({message:'Other staff sessions require operator review.'},403); + if((await rankFor(db,target.role)).level>=(await rankFor(db,user.role)).level&&target.id!==user.id)return json({message:'Other staff sessions require operator review.'},403); await db.batch([db.prepare('DELETE FROM site_sessions WHERE user_id=?').bind(target.id),db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'sessions-revoked',target.id,Date.now())]);return json({ok:true}); };} diff --git a/website/node/auth.mjs b/website/node/auth.mjs index 9f1d600f..48aaae89 100644 --- a/website/node/auth.mjs +++ b/website/node/auth.mjs @@ -1,3 +1,4 @@ +import {publicUser} from './permissions.mjs'; import {randomBytes,randomUUID,createHash,scrypt as rawScrypt,timingSafeEqual} from 'node:crypto'; import {promisify} from 'node:util'; const scrypt=promisify(rawScrypt),cookieName='__Host-dune_session'; @@ -12,10 +13,10 @@ export async function identity(request,db){ export function createAuth(db,origin){ const attempts=new Map(); function allowed(key,max=10,window=900000){const now=Date.now();if(attempts.size>5000)for(const [k,v]of attempts)if(v.until5000)return false;let row=attempts.get(key);if(!row||row.until{ const path=new URL(request.url).pathname; - if(path==='/api/auth/session'&&request.method==='GET'){const user=await identity(request,db);return json({authenticated:!!user,user:user?{username:user.username,staff:user.role==='staff'}:null});} + if(path==='/api/auth/session'&&request.method==='GET'){const user=await identity(request,db);return json({authenticated:!!user,user:user?await publicUser(db,user):null});} if(request.method!=='POST')return json({message:'Method not allowed.'},405); if(request.headers.get('Origin')!==origin)return json({message:'Request origin rejected.'},403); if(path==='/api/auth/password'){ @@ -42,10 +43,10 @@ export function createAuth(db,origin){ if(!allowed('registrations',60,3600000))return json({message:'Registration is temporarily limited. Please try later.'},429); const salt=randomBytes(16).toString('hex'),hash=(await scrypt(password,salt,64)).toString('hex'),id=randomUUID(),now=Date.now(); try{await db.batch([ - db.prepare('INSERT INTO site_accounts(id,username,display_name,password_salt,password_hash,role,created_at) VALUES(?,?,?,?,?,?,?)').bind(id,username,username,salt,hash,'player',now), + db.prepare('INSERT INTO site_accounts(id,username,display_name,password_salt,password_hash,role,created_at) VALUES(?,?,?,?,?,?,?)').bind(id,username,username,salt,hash,'user',now), db.prepare('INSERT INTO player_profiles(user_id,display_name,minecraft_name,discord_name,created_at,updated_at) VALUES(?,?,?,?,?,?)').bind(id,username,'','',now,now) ]);}catch(error){if(error.code==='ER_DUP_ENTRY'||String(error.message).includes('UNIQUE constraint'))return json({message:'That username is unavailable.'},409);throw error;} - return issue({id,username,role:'player'}); + return issue({id,username,role:'user'}); } const user=await db.prepare('SELECT * FROM site_accounts WHERE username=?').bind(username).first(); const actual=await scrypt(password,user?.password_salt||'00000000000000000000000000000000',64); diff --git a/website/node/community-rewards.mjs b/website/node/community-rewards.mjs index 884438ea..b60abb5b 100644 --- a/website/node/community-rewards.mjs +++ b/website/node/community-rewards.mjs @@ -1,3 +1,4 @@ +import {can} from './permissions.mjs'; import {randomBytes,randomUUID} from 'node:crypto'; import {identity} from './auth.mjs'; import {json,gameAuthorized,validUuid} from './game-link.mjs'; @@ -43,7 +44,7 @@ export function createCommunityRewards(db,settings,origin){ const {results}=await db.prepare('SELECT r.month,r.personal_code,r.issued_at,c.reward_amount,q.delivered_at FROM community_rewards r JOIN community_campaigns c ON c.month=r.month LEFT JOIN community_claims q ON q.minecraft_uuid=r.minecraft_uuid AND q.month=r.month WHERE r.minecraft_uuid=? ORDER BY r.month DESC').bind(link.minecraft_uuid).all(); return json({linked:true,eligibleSince:link.first_linked_at,available:results.filter(r=>!r.delivered_at),history:results.filter(r=>r.delivered_at).map(({personal_code,...row})=>row)}); } - if(user.role!=='staff')return json({message:'Staff access required.'},403); + if(!await can(db,user,'cp.community.manage'))return json({message:'Community management permission required.'},403); if(request.method!=='POST')return json({message:'Method not allowed'},405); if(request.headers.get('origin')!==origin)return json({message:'Origin rejected'},403); let data;try{data=await request.json();}catch{return json({message:'Invalid request'},400);} diff --git a/website/node/permissions.mjs b/website/node/permissions.mjs new file mode 100644 index 00000000..2c7d13d1 --- /dev/null +++ b/website/node/permissions.mjs @@ -0,0 +1,43 @@ +export const NODES={ + 'cp.menu.staffmanual':'Read the staff manual', + 'cp.menu.items':'Custom item designer page','cp.items.manage':'Design and publish custom items','dune.items.give':'Issue registered custom items', + 'cp.menu.game':'Game identity page','cp.menu.inventory':'Inventory & sales page','cp.menu.rewards':'Reward codes page','cp.menu.security':'Account security page','cp.menu.administration':'Administration page','cp.menu.servers':'Servers page','cp.menu.permissions':'Ranks & permissions page', + 'cp.accounts.view':'View website accounts','cp.accounts.revoke':'Revoke account sessions','cp.accounts.assign':'Assign account ranks','cp.community.manage':'Manage community funding goals','cp.ranks.manage':'Create ranks and edit the permission matrix', + 'cp.servers.view':'View server status','cp.servers.logs':'Read server logs','cp.servers.power':'Start, stop and restart servers','cp.servers.console':'Send server console commands', + 'dune.admin':'DuneCore administration','dune.staff.open':'Open staff GUI','dune.staff.history':'View punishment history','dune.staff.kick':'Kick players','dune.staff.warn':'Warn players','dune.staff.mute':'Mute players','dune.staff.ban.local':'Ban from one server','dune.staff.ban.network':'Ban from the network', + 'duneess.basics':'Essentials player commands','duneess.travel':'Guild travel','duneess.tokens.buy':'Buy guild tokens','duneess.exchange':'Exchange shop','duneess.shops.use':'Use NPC shops', + 'duneess.chat.network':'Local / Proxy chat','duneess.chat.nearby':'Nearby chat · 50 blocks','duneess.chat.team':'Team chat','duneess.chat.faction':'House chat','duneess.chat.imperial':'Imperial chat','duneess.chat.colors':'Chat colours and gradients','duneess.chat.format':'Advanced chat formatting', + 'duneprotect.inspect':'Inspect block history','duneprotect.lookup':'Look up changes','duneprotect.rollback':'Roll back changes','duneprotect.restore':'Restore changes','duneprotect.regions':'Manage protected regions','duneprotect.worldedit':'Use WorldEdit tools', + 'dunelobby.visit':'Visit lobby','dunelobby.build':'Build in protected lobby','dunelobby.admin':'Lobby administration' +}; +const basic=['cp.menu.game','cp.menu.inventory','cp.menu.rewards','cp.menu.security','duneess.basics','duneess.travel','duneess.tokens.buy','duneess.exchange','duneess.shops.use','duneess.chat.network','duneess.chat.nearby','duneess.chat.team','duneess.chat.faction','dunelobby.visit']; +const staff=[...basic,'cp.menu.staffmanual','cp.menu.administration','cp.accounts.view','cp.accounts.revoke','cp.community.manage','dune.staff.open','dune.staff.history','dune.staff.kick','dune.staff.warn','dune.staff.mute','duneprotect.inspect','duneprotect.lookup']; +const core=[...staff,'cp.menu.items','cp.items.manage','dune.items.give','cp.menu.servers','cp.menu.permissions','cp.accounts.assign','cp.ranks.manage','cp.servers.view','cp.servers.logs','cp.servers.power','cp.servers.console','dune.admin','dune.staff.ban.local','dune.staff.ban.network','duneess.chat.imperial','duneess.chat.colors','duneess.chat.format','duneprotect.rollback','duneprotect.restore','duneprotect.regions','duneprotect.worldedit','dunelobby.build','dunelobby.admin']; +export const DEFAULT_RANKS=[ + {key:'user',label:'User',level:10,kind:'access',nodes:basic}, + {key:'vip',label:'VIP',level:20,kind:'access',nodes:[...basic,'duneess.chat.colors']}, + {key:'staff',label:'Staff',level:50,kind:'access',nodes:staff}, + {key:'corestaff',label:'Corestaff',level:80,kind:'access',nodes:core}, + {key:'owners',label:'Owners',level:100,kind:'access',nodes:Object.keys(NODES)}, + ...['aerdrecht','harkveen','korenholt','oordwijk','vrijduin','vaerkring'].map(key=>({key:'house_'+key,label:key[0].toUpperCase()+key.slice(1),level:1,kind:'house',nodes:[]})), + ...['spice_smuggler','water_smuggler'].map(key=>({key:'path_'+key,label:key.replaceAll('_',' '),level:1,kind:'path',nodes:[]})), + ...['emperor','house_leader','specerhuis','welvaart','guild_staff','landsraad'].map(key=>({key:'office_'+key,label:key.replaceAll('_',' '),level:2,kind:'office',nodes:['duneess.chat.imperial']})) +]; +export const rankKey=role=>role==='player'?'user':role; +export async function rankFor(db,key){ + const row=await db.prepare('SELECT rank_key,label,rank_level,kind,permissions_json,version FROM cp_ranks WHERE rank_key=?').bind(rankKey(key)).first(); + if(typeof row?.permissions_json==='string')return{key:row.rank_key,label:row.label,level:Number(row.rank_level),kind:row.kind,nodes:JSON.parse(row.permissions_json),version:Number(row.version)}; + return DEFAULT_RANKS.find(r=>r.key===rankKey(key))||{key:rankKey(key),label:'Unknown rank',level:0,kind:'access',nodes:[]}; +} +export async function accessFor(db,user){ + if(!user)return null; + const rank=await rankFor(db,user.role); + const nodes=rank.key==='owners'?Object.keys(NODES):rank.nodes.filter(n=>Object.hasOwn(NODES,n)); + return{rank:rank.key,label:rank.label,level:rank.level,nodes}; +} +export async function can(db,user,node){return !!user&&(await accessFor(db,user)).nodes.includes(node);} +export async function publicUser(db,user){if(!user)return null;const access=await accessFor(db,user);return{username:user.username,staff:access.nodes.includes('cp.menu.administration'),rank:access.rank,rankLabel:access.label,rankLevel:access.level,permissions:access.nodes};} +export async function initializeRanks(db){ + for(const rank of DEFAULT_RANKS)await db.prepare('INSERT INTO cp_ranks(rank_key,label,rank_level,kind,permissions_json,version) VALUES(?,?,?,?,?,1) ON CONFLICT(rank_key) DO UPDATE SET rank_key=excluded.rank_key').bind(rank.key,rank.label,rank.level,rank.kind,JSON.stringify(rank.nodes)).run(); + await db.prepare("UPDATE site_accounts SET role='user' WHERE role='player'").run(); +} diff --git a/website/node/rank-admin.mjs b/website/node/rank-admin.mjs new file mode 100644 index 00000000..17d3ada9 --- /dev/null +++ b/website/node/rank-admin.mjs @@ -0,0 +1,51 @@ +import {randomUUID} from 'node:crypto'; +import {identity} from './auth.mjs'; +import {json,gameAuthorized} from './game-link.mjs'; +import {NODES,DEFAULT_RANKS,accessFor,rankFor,rankKey,can} from './permissions.mjs'; +const validKey=value=>typeof value==='string'&&/^[a-z][a-z0-9_]{2,39}$/.test(value); +export function createRankAdmin(db,settings,origin){return async request=>{ + const url=new URL(request.url); + if(url.pathname==='/api/game/permissions'){ + if(request.method!=='GET'||url.search||!gameAuthorized(request,settings))return json({message:'Unauthorized'},401); + const {results:ranks}=await db.prepare('SELECT rank_key,label,rank_level,kind,permissions_json,version FROM cp_ranks ORDER BY rank_level,rank_key').all(); + const {results:members}=await db.prepare('SELECT a.role,l.minecraft_uuid FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id').all(); + return json({version:1,catalog:Object.keys(NODES).filter(n=>!n.startsWith('cp.')),ranks:ranks.map(r=>({key:r.rank_key,label:r.label,level:Number(r.rank_level),kind:r.kind,nodes:JSON.parse(r.permissions_json).filter(n=>!n.startsWith('cp.'))})),members:members.map(m=>({uuid:m.minecraft_uuid,rank:rankKey(m.role)}))}); + } + const user=await identity(request,db);if(!user)return json({message:'Sign in first.'},401); + const access=await accessFor(db,user); + if(!access.nodes.includes('cp.ranks.manage'))return json({message:'Rank-management permission required.'},403); + if(request.method==='GET'&&url.pathname==='/api/ranks'&&!url.search){ + const {results}=await db.prepare('SELECT rank_key,label,rank_level,kind,permissions_json,version FROM cp_ranks ORDER BY rank_level,rank_key').all(); + return json({catalog:Object.entries(NODES).map(([node,label])=>({node,label,scope:node.startsWith('cp.')?'Website':'Minecraft'})),ranks:results.map(r=>({key:r.rank_key,label:r.label,level:Number(r.rank_level),kind:r.kind,nodes:JSON.parse(r.permissions_json),version:Number(r.version),editable:r.rank_key!=='owners'&&(access.rank==='owners'||Number(r.rank_level)db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,action,details,Date.now()); + if(url.pathname==='/api/ranks/create'){ + if(!validKey(body.key)||body.key.length>16||DEFAULT_RANKS.some(r=>r.key===body.key)||typeof body.label!=='string'||!body.label.trim()||body.label.length>40||!['user','vip','staff','corestaff'].includes(body.base))return json({message:'Use a unique rank ID of 3–16 lowercase letters, digits or underscores, a label, and a base rank.'},400); + const base=await rankFor(db,body.base); + if(access.rank!=='owners'&&base.level>=access.level)return json({message:'You can only create ranks below your own.'},403); + const nodes=base.nodes.filter(n=>access.nodes.includes(n)); + try{await db.batch([db.prepare('INSERT INTO cp_ranks(rank_key,label,rank_level,kind,permissions_json,version) VALUES(?,?,?,?,?,1)').bind(body.key,body.label.trim(),base.level,'access',JSON.stringify(nodes)),audit('rank-created',body.key)]);}catch(error){if(error.code==='ER_DUP_ENTRY'||String(error.message).includes('UNIQUE'))return json({message:'That rank already exists.'},409);throw error;} + return json({ok:true},201); + } + if(url.pathname==='/api/ranks/permissions'){ + if(!validKey(body.rank)||!Array.isArray(body.nodes)||body.nodes.length>Object.keys(NODES).length||!Number.isInteger(body.version))return json({message:'Invalid permission matrix.'},400); + const rank=await rankFor(db,body.rank),nodes=[...new Set(body.nodes)]; + if(rank.key==='owners'||rank.level===0||access.rank!=='owners'&&rank.level>=access.level)return json({message:'This rank is protected.'},403); + if(nodes.some(n=>!Object.hasOwn(NODES,n)||access.rank!=='owners'&&!access.nodes.includes(n)||rank.kind!=='access'&&n.startsWith('cp.')))return json({message:'You cannot grant these permissions.'},403); + const result=await db.batch([db.prepare('UPDATE cp_ranks SET permissions_json=?,version=version+1 WHERE rank_key=? AND version=?').bind(JSON.stringify(nodes),rank.key,body.version),audit('rank-permissions',rank.key+': matrix update attempted')]); + return result[0].meta.changes?json({ok:true}):json({message:'This matrix changed in another session. Refresh before saving.'},409); + } + if(url.pathname==='/api/ranks/assign'){ + if(!await can(db,user,'cp.accounts.assign'))return json({message:'Account rank assignment permission required.'},403); + if(typeof body.userId!=='string'||body.userId.length!==36||!validKey(body.rank))return json({message:'Invalid assignment.'},400); + const target=await db.prepare('SELECT id,role FROM site_accounts WHERE id=?').bind(body.userId).first();if(!target)return json({message:'Account not found.'},404); + const rank=await rankFor(db,body.rank),previous=await rankFor(db,target.role); + if(rank.kind!=='access'||rank.level===0||previous.key==='owners'||access.rank!=='owners'&&(rank.level>=access.level||previous.level>=access.level||target.id===user.id))return json({message:'That assignment is protected. Owner accounts cannot be demoted here.'},403); + await db.batch([db.prepare('UPDATE site_accounts SET role=? WHERE id=? AND role=?').bind(rank.key,target.id,target.role),db.prepare('DELETE FROM site_sessions WHERE user_id=?').bind(target.id),audit('account-rank',target.id+' -> '+rank.key)]); + return json({ok:true}); + } + return json({message:'Not found.'},404); +};} diff --git a/website/node/schema.sql b/website/node/schema.sql index 4608b106..b2b1fac0 100644 --- a/website/node/schema.sql +++ b/website/node/schema.sql @@ -77,3 +77,7 @@ CREATE TABLE IF NOT EXISTS account_audit ( id CHAR(36) PRIMARY KEY, actor_id CHAR(36) NOT NULL, action VARCHAR(40) NOT NULL, details VARCHAR(500) NOT NULL, created_at BIGINT NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +CREATE TABLE IF NOT EXISTS cp_ranks ( + rank_key VARCHAR(40) PRIMARY KEY, label VARCHAR(40) NOT NULL, rank_level INTEGER NOT NULL, + kind VARCHAR(16) NOT NULL, permissions_json TEXT NOT NULL, version INTEGER NOT NULL DEFAULT 1 +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/website/node/server.mjs b/website/node/server.mjs index 5b54b3a6..a255ba34 100644 --- a/website/node/server.mjs +++ b/website/node/server.mjs @@ -1,3 +1,4 @@ +import {initializeRanks,can} from './permissions.mjs'; import {createServer} from 'node:http'; import {readFile} from 'node:fs/promises'; import {pathToFileURL} from 'node:url'; @@ -36,7 +37,7 @@ export function createApplication(db,settings={}) { const headers=new Headers(request.headers); for(const key of [...headers.keys()])if(key.startsWith('oai-')||key.startsWith('x-internal-'))headers.delete(key); const user=await identity(request,db); - if(user){headers.set('oai-authenticated-user-id',user.id);if(user.role==='staff')headers.set('oai-authenticated-user-email','verified-staff@dunerealms.internal');} + if(user){headers.set('oai-authenticated-user-id',user.id);if(await can(db,user,'cp.accounts.view'))headers.set('oai-authenticated-user-email','verified-staff@dunerealms.internal');} const forwarded=new Request(request.url,{method:request.method,headers,body:['GET','HEAD'].includes(request.method)?undefined:request.body,duplex:'half'}); const response=await worker.fetch(forwarded,{...settings,DB:db,FORUM_ADMIN_EMAILS:'verified-staff@dunerealms.internal',SUPPORT_STAFF_EMAILS:'verified-staff@dunerealms.internal'}); const type=response.headers.get('Content-Type')||''; @@ -49,7 +50,7 @@ export function createApplication(db,settings={}) { }; } export async function start(settings=process.env) { - const db=await openDatabase(settings),handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin; + const db=await openDatabase(settings);await initializeRanks(db);const handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin; const forgejo=createForgejoProxy(settings); const server=createServer(async(req,res)=>{ try{ diff --git a/website/tests/node-host.test.mjs b/website/tests/node-host.test.mjs index c43ec629..11f0d889 100644 --- a/website/tests/node-host.test.mjs +++ b/website/tests/node-host.test.mjs @@ -7,17 +7,18 @@ import {mysqlSql} from '../node/mysql.mjs'; const schema=['0000_forums','0001_profiles_tickets'].map(n=>readFileSync(new URL('../drizzle/'+n+'.sql',import.meta.url),'utf8')).join('\n')+` 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_sessions(token_hash TEXT PRIMARY KEY,user_id TEXT,expires_at INTEGER);`; +const oldSchema=schema; const origin='https://dunerealms.com'; function request(path,method='GET',body,headers={}){return new Request(origin+path,{method,headers:{Origin:origin,'Content-Type':'application/json',...headers},...(body?{body:JSON.stringify(body)}:{})});} test('External hosting rejects forged identity, protects sessions and keeps private data private',async()=>{ - const db=new LocalD1(schema),app=createApplication(db); + const db=new LocalD1(schema+`CREATE TABLE cp_ranks(rank_key TEXT PRIMARY KEY,label TEXT,rank_level INTEGER,kind TEXT,permissions_json TEXT,version INTEGER);`),app=createApplication(db); try{ assert.equal((await app(request('/api/profile','GET',null,{'oai-authenticated-user-id':'admin','oai-authenticated-user-email':'verified-staff@dunerealms.internal'}))).status,401); const account={username:'desert_test',password:'A long test password 123',role:'staff'}; assert.equal((await app(request('/api/auth/register','POST',account,{Origin:'https://evil.test'}))).status,403); const created=await app(request('/api/auth/register','POST',account));assert.equal(created.status,200); const cookie=created.headers.get('set-cookie');assert.match(cookie,/HttpOnly; Secure; SameSite=Lax/); - const row=await db.prepare('SELECT * FROM site_accounts').first();assert.equal(row.role,'player');assert.notEqual(row.password_hash,account.password); + const row=await db.prepare('SELECT * FROM site_accounts').first();assert.equal(row.role,'user');assert.notEqual(row.password_hash,account.password); const session=await db.prepare('SELECT * FROM site_sessions').first();assert.ok(!cookie.includes(session.token_hash)); const authenticated={Cookie:cookie.split(';')[0]}; assert.equal((await app(request('/api/profile','GET',null,authenticated))).status,200); diff --git a/website/tests/rank-permissions.test.mjs b/website/tests/rank-permissions.test.mjs new file mode 100644 index 00000000..c665ec85 --- /dev/null +++ b/website/tests/rank-permissions.test.mjs @@ -0,0 +1,33 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +import {LocalD1} from './d1-adapter.mjs'; +import {createPanel} from '../control-panel/server.mjs'; +import {initializeRanks,can} from '../node/permissions.mjs'; +import {STAFF_MANUAL} from '../control-panel/staff-manual.mjs'; +import {NODES} from '../node/permissions.mjs'; +const origin='https://cp.dunerealms.com',secret='private-game-bridge-token-with-32-characters'; +test('staff guides use feature categories and documented permission nodes',()=>{ + const categories=new Set(STAFF_MANUAL.map(c=>c.id)); + for(const name of ['coreprotect','worldedit','worldguard','chat','permissions','inventory','economy','tickets','moderation','quests'])assert.ok(categories.has(name),name); + assert.equal(categories.size,STAFF_MANUAL.length); + for(const category of STAFF_MANUAL){assert.ok(category.status);assert.ok(category.steps.length);for(const node of category.nodes)assert.ok(Object.hasOwn(NODES,node),node);} +}); +test('staff manual is protected on the server and responds to permission revocation',async()=>{ + const r=await setup();try{ + assert.equal((await r.req('/api/staff/manual')).status,401); + assert.equal((await r.req('/api/staff/manual',r.accounts.member.cookie)).status,403); + const allowed=await r.req('/api/staff/manual',r.accounts.core.cookie);assert.equal(allowed.status,200);assert.equal((await allowed.json()).categories.length,STAFF_MANUAL.length); + const nodes=(await r.db.prepare("SELECT permissions_json FROM cp_ranks WHERE rank_key='corestaff'").first()).permissions_json; + await r.db.prepare("UPDATE cp_ranks SET permissions_json=? WHERE rank_key='corestaff'").bind(JSON.stringify(JSON.parse(nodes).filter(n=>n!=='cp.menu.staffmanual'))).run(); + assert.equal((await r.req('/api/staff/manual',r.accounts.core.cookie)).status,403); + assert.equal((await r.req('/api/staff/manual',r.accounts.owner.cookie,{})).status,405); + }finally{r.db.close();} +}); +const schema=`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_sessions(token_hash TEXT PRIMARY KEY,user_id TEXT,expires_at INTEGER);CREATE TABLE player_profiles(user_id TEXT PRIMARY KEY,display_name TEXT,minecraft_name TEXT,discord_name TEXT,created_at INTEGER,updated_at INTEGER);`+readFileSync(new URL('../node/schema.sql',import.meta.url),'utf8').split('CREATE TABLE IF NOT EXISTS site_game_links')[1].replace(/^/,'CREATE TABLE IF NOT EXISTS site_game_links').replace(/ ENGINE=InnoDB DEFAULT CHARSET=utf8mb4/g,''); +async function setup(){const db=new LocalD1(schema);await initializeRanks(db);const app=createPanel(db,{GAME_LINK_SECRET:secret}),req=(path,cookie,body,Origin=origin)=>app(new Request(origin+path,{method:body?'POST':'GET',headers:{Origin,'Content-Type':'application/json',...(cookie?{Cookie:cookie}:{})},...(body?{body:JSON.stringify(body)}:{})}));const accounts={};for(const [username,role] of [['owner','owners'],['core','corestaff'],['member','user']]){const r=await req('/api/auth/register',null,{username,password:'long test password 123',role:'owners'});const cookie=r.headers.get('set-cookie').split(';')[0];const account=await db.prepare('SELECT id,role FROM site_accounts WHERE username=?').bind(username).first();assert.equal(account.role,'user');await db.prepare('UPDATE site_accounts SET role=? WHERE id=?').bind(role,account.id).run();accounts[username]={id:account.id,cookie,role};}return{db,app,req,accounts};} +test('session exports effective rank/node permissions; unprivileged rank requests fail',async()=>{const r=await setup();try{const session=await(await r.req('/api/auth/session',r.accounts.owner.cookie)).json();assert.equal(session.user.rank,'owners');assert.ok(session.user.permissions.includes('cp.ranks.manage'));assert.equal((await r.req('/api/ranks',r.accounts.member.cookie)).status,403);assert.equal((await r.req('/api/ranks')).status,401);}finally{r.db.close();}}); +test('corestaff creates lower ranks but cannot edit owners or assign owner access',async()=>{const r=await setup();try{const core=r.accounts.core.cookie;assert.equal((await r.req('/api/ranks/create',core,{key:'builders',label:'Builders',base:'user'})).status,201);assert.equal((await r.req('/api/ranks/create',core,{key:'evilrank',label:'No',base:'corestaff'})).status,403);assert.equal((await r.req('/api/ranks/permissions',core,{rank:'owners',version:1,nodes:[]})).status,403);assert.equal((await r.req('/api/ranks/assign',core,{userId:r.accounts.member.id,rank:'owners'})).status,403);assert.equal((await r.req('/api/ranks/assign',r.accounts.owner.cookie,{userId:r.accounts.owner.id,rank:'user'})).status,403);}finally{r.db.close();}}); +test('matrix edits change backend access immediately and stale saves cannot overwrite',async()=>{const r=await setup();try{const owner=r.accounts.owner.cookie;assert.equal((await r.req('/api/ranks/permissions',owner,{rank:'user',version:1,nodes:['cp.menu.security']})).status,200);assert.equal((await r.req('/api/game-link',r.accounts.member.cookie)).status,403);assert.equal((await r.req('/api/ranks/permissions',owner,{rank:'user',version:1,nodes:['cp.menu.game']})).status,409);assert.equal(await can(r.db,{role:'user'},'cp.menu.game'),false);assert.equal((await r.req('/api/ranks/permissions',owner,{rank:'user',version:2,nodes:['invented.node']})).status,403);assert.equal((await r.req('/api/ranks/create',owner,{key:'another',label:'Another',base:'user'},'https://attacker.invalid')).status,403);}finally{r.db.close();}}); +test('rank assignment invalidates the target sessions and owner accounts remain protected',async()=>{const r=await setup();try{assert.equal((await r.req('/api/ranks/assign',r.accounts.core.cookie,{userId:r.accounts.member.id,rank:'vip'})).status,200);const session=await(await r.req('/api/auth/session',r.accounts.member.cookie)).json();assert.equal(session.authenticated,false);assert.equal((await r.req('/api/ranks/assign',r.accounts.core.cookie,{userId:r.accounts.owner.id,rank:'user'})).status,403);}finally{r.db.close();}}); +test('game rank snapshot is private and exports only verified UUIDs and Minecraft nodes',async()=>{const r=await setup();try{assert.equal((await r.app(new Request(origin+'/api/game/permissions'))).status,401);const response=await r.app(new Request(origin+'/api/game/permissions',{headers:{Authorization:'Bearer '+secret}}));assert.equal(response.status,200);const snapshot=await response.json();assert.deepEqual(snapshot.members,[]);assert.ok(snapshot.ranks.some(x=>x.key==='house_aerdrecht'));assert.ok(snapshot.ranks.some(x=>x.key==='office_emperor'));assert.ok(snapshot.ranks.every(x=>x.nodes.every(node=>!node.startsWith('cp.'))));}finally{r.db.close();}}); diff --git a/website/tests/server-control.test.mjs b/website/tests/server-control.test.mjs index daccd74f..0f463c17 100644 --- a/website/tests/server-control.test.mjs +++ b/website/tests/server-control.test.mjs @@ -7,14 +7,14 @@ test('server controls require session, staff role and explicit operator allowlis for(const [user,status] of [[null,401],[{id:'1',username:'owner',role:'player'},403],[{id:'2',username:'otherstaff',role:'staff'},403]]){const r=rig(user);assert.equal((await r.request()).status,status);assert.equal(r.calls.length,0);} }); test('operator status/log paths are fixed and reject arbitrary targets',async()=>{ - const r=rig({id:'1',username:'owner',role:'staff'}); + const r=rig({id:'1',username:'owner',role:'owners'}); assert.equal((await r.request()).status,200);assert.equal(r.calls[0].url,'http://127.0.0.1:15433/servers'); assert.equal((await r.request('/api/servers/logs?server=lobby')).status,200); for(const path of ['/api/servers?url=https://attacker.test','/api/servers/logs?server=ssh','/api/servers/logs?server=lobby&server=proxy'])assert.equal((await r.request(path)).status,400); assert.equal(r.calls.length,2); }); test('mutations enforce origin and single command, overwrite spoofed actor, and audit intent',async()=>{ - const r=rig({id:'1',username:'owner',role:'staff'}),body={server:'arrakis',action:'command',command:'list',actor:'intruder'}; + const r=rig({id:'1',username:'owner',role:'owners'}),body={server:'arrakis',action:'command',command:'list',actor:'intruder'}; assert.equal((await r.request('/api/servers/action',body,'https://attacker.test')).status,403); for(const command of ['list\nstop','/op player'])assert.equal((await r.request('/api/servers/action',{...body,command})).status,400); assert.equal((await r.request('/api/servers/action',{...body,server:'proxy'})).status,400); @@ -22,7 +22,7 @@ test('mutations enforce origin and single command, overwrite spoofed actor, and assert.equal(JSON.parse(r.calls[0].options.body).actor,'owner');assert.equal(r.audit.length,1);assert.equal(r.audit[0][2],'server-control');assert.ok(!r.audit[0][3].includes('list')); }); test('upstream failures do not expose secrets',async()=>{ - const db={prepare(){return{bind(){return{async first(){return{id:'1',username:'owner',role:'staff'};}};}};}}; + const db={prepare(){return{bind(){return{async first(){return{id:'1',username:'owner',role:'owners'};}};}};}}; const handle=createServerControl(db,{SERVER_CONTROL_TOKEN:'t'.repeat(64),SERVER_CONTROL_OPERATORS:'owner'},{fetcher:async()=>{throw Error('password secret');}}); const response=await handle(new Request(origin+'/api/servers',{headers:{Cookie:cookie}}));assert.equal(response.status,503);assert.ok(!(await response.text()).includes('password')); });