diff --git a/website/control-panel/public/cp-v2/citizen-directory.mjs b/website/control-panel/public/cp-v2/citizen-directory.mjs index 574b814e..2f0a584d 100644 --- a/website/control-panel/public/cp-v2/citizen-directory.mjs +++ b/website/control-panel/public/cp-v2/citizen-directory.mjs @@ -12,10 +12,10 @@ export function mountCitizenDirectory(host){ const root=element('section',undefined,'migration-directory'); const css=document.createElement('link');css.rel='stylesheet';css.href='/v2/citizen-directory.css';root.append(css); const view=element('div');const status=element('p','Loading directory…','md-status');status.setAttribute('role','status'); - const diagnostics=element('details',undefined,'md-diagnostics');diagnostics.append(element('summary','+ Workspace details'),element('p','Central account directory. Assignment catalogue preparation does not change existing permissions.'),button('Reload workspace',()=>load())); + const diagnostics=element('details',undefined,'md-diagnostics');diagnostics.append(element('summary','+ Workspace details'),element('p','Central account directory. Function changes are versioned and audited.'),button('Reload workspace',()=>load())); root.append(status,view,diagnostics);host.replaceChildren(root); let context='users',page=1,query='',filter='',department='',branch='',selected=null,tab='overview',disposed=false,controller,sequence=0,catalogue={departments:[]},assignmentData=null; - let searchTimer; + let searchTimer,assignmentMode='unknown'; function heading(){applyShellHeading(host,{title:selected?(context==='staff'?'Manage Staff':'Manage User'):'Citizen Directory',description:selected?selected.displayName+' · '+selected.username:'Find a citizen, then manage their account or staff responsibilities.',artwork:context==='staff'?'nav-staff-v2.webp':'nav-account-v2.webp'});} function box(title){const section=element('section',undefined,'md-box');section.append(element('h3',title));return section;} function detail(label,value){const row=element('div',undefined,'md-detail');row.append(element('span',label),element('strong',String(value??'Not recorded')));return row;} @@ -24,7 +24,10 @@ export function mountCitizenDirectory(host){ function assignments(){const panel=box(context==='staff'?'Staff assignments':'Memberships & offices'); if(selected.assignments.length){for(const a of selected.assignments){const card=element('div',undefined,'md-assignment');card.append(element('strong',a.roleLabel),element('p',a.scopeLabel),badge(a.source||'Recorded assignment'));if(a.endsAt)card.append(element('small','Until '+date(a.endsAt)));panel.append(card);}} else panel.append(element('p',context==='staff'?'No new-model staff assignments have been activated for this account.':'No memberships or offices have been registered in the new assignment model yet. Existing memberships remain in their source systems.','md-muted')); - panel.append(element('p','The new assignment register is being prepared. Recorded changes do not replace existing permissions until migration activation.','md-note')); + if(context==='staff'){ + panel.append(element('p',assignmentMode==='active'?'Staff assignments control current access. Function changes update central permissions and synchronise connected services.':assignmentMode==='preparing'?'The assignment register is being prepared. Permission activation is pending.':'Current functions are listed above. Open Staff assignments to manage access.','md-note')); + if(tab!=='assignments')panel.append(button('Manage assignments',()=>{tab='assignments';renderAccount();})); + } return panel; } function scopeVersion(a){return Number(assignmentData.versions.find(v=>v.scope_type===a.scopeType&&v.scope_key===a.scopeKey)?.version||1);} @@ -69,11 +72,11 @@ export function mountCitizenDirectory(host){ const target=selected.id;panel.append(element('p','Checking the central role mapping…','md-muted')); try{const data=await request('/api/admin/organisation/effective?userId='+encodeURIComponent(target),controller?.signal); if(disposed||selected?.id!==target||context!=='staff'||tab!=='permissions'||!panel.isConnected)return; - panel.replaceChildren(element('h3','Effective access preview'),element('p','Preparation only. These mapped permissions have not replaced live access.','md-note')); + panel.replaceChildren(element('h3','Effective function permissions'),element('p',data.enforcement==='active'?'These function permissions are active. Ordinary citizen and membership benefits are added separately.':'Preparation only. These mapped permissions have not replaced live access.','md-note')); for(const source of data.sources){const row=element('details',undefined,'md-assignment');row.append(element('summary',source.scopeKey.replaceAll('_',' ')+' · '+source.role.replaceAll('_',' ')+' · '+source.nodes.length+' permissions'));for(const node of source.nodes)row.append(element('p',node,'md-muted'));panel.append(row);} panel.append(element('p',data.nodes.length+' unique permissions · '+data.missingPolicies.length+' missing policy mappings · '+data.blocked.length+' unsafe grants blocked.')); for(const missing of data.missingPolicies)panel.append(element('p','Mapping required: '+missing.scopeKey+' / '+missing.role,'md-note')); - if(!data.sources.length&&!data.missingPolicies.length)panel.append(element('p','No active mapped staff functions. Existing live rights remain unchanged.')); + if(!data.sources.length&&!data.missingPolicies.length)panel.append(element('p','No active mapped staff functions.')); }catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.replaceChildren(element('p',e.message,'md-note'));} } function renderAccount(){ @@ -117,7 +120,7 @@ export function mountCitizenDirectory(host){ catch(error){if(panel.isConnected)results.replaceChildren(element('p',error.message));}finally{find.disabled=false;} }; } - async function open(id){controller?.abort();controller=new AbortController();const current=++sequence;status.textContent='Loading account…';try{const data=await request(API+'/'+encodeURIComponent(id)+'?context='+context,controller.signal);if(disposed||current!==sequence)return;selected=data.account;tab='overview';renderAccount();status.textContent='';}catch(e){if(!disposed&&e.name!=='AbortError')status.textContent=e.message;}} - async function load(){controller?.abort();controller=new AbortController();const current=++sequence;status.textContent='Loading '+context+'…';try{if(context==='staff'&&!catalogue.departments.length)catalogue=await request(API+'/catalogue?context=staff',controller.signal);const params=new URLSearchParams({context,page:String(page),q:query,status:filter,department,branch});const data=await request(API+'?'+params,controller.signal);if(disposed||current!==sequence)return;selected=null;renderList(data);status.textContent=data.accounts.length+' records on this page · search covers the complete directory.';}catch(e){if(!disposed&&e.name!=='AbortError'){view.replaceChildren();status.textContent=e.message;}}} + async function open(id){controller?.abort();controller=new AbortController();const current=++sequence;status.textContent='Loading account…';try{const data=await request(API+'/'+encodeURIComponent(id)+'?context='+context,controller.signal);if(disposed||current!==sequence)return;assignmentMode=data.assignmentMode;selected=data.account;tab='overview';renderAccount();status.textContent='';}catch(e){if(!disposed&&e.name!=='AbortError')status.textContent=e.message;}} + async function load(){controller?.abort();controller=new AbortController();const current=++sequence;status.textContent='Loading '+context+'…';try{if(context==='staff'&&!catalogue.departments.length)catalogue=await request(API+'/catalogue?context=staff',controller.signal);const params=new URLSearchParams({context,page:String(page),q:query,status:filter,department,branch});const data=await request(API+'?'+params,controller.signal);if(disposed||current!==sequence)return;assignmentMode=data.assignmentMode;selected=null;renderList(data);status.textContent=data.accounts.length+' records on this page · search covers the complete directory.';}catch(e){if(!disposed&&e.name!=='AbortError'){view.replaceChildren();status.textContent=e.message;}}} void load();return()=>{disposed=true;sequence++;clearTimeout(searchTimer);controller?.abort();root.remove();}; } diff --git a/website/control-panel/public/cp-v2/organisation-permissions.mjs b/website/control-panel/public/cp-v2/organisation-permissions.mjs index dd3ca14a..42eb914e 100644 --- a/website/control-panel/public/cp-v2/organisation-permissions.mjs +++ b/website/control-panel/public/cp-v2/organisation-permissions.mjs @@ -10,7 +10,7 @@ export function mountOrganisationPermissions(host){ applyShellHeading(host,{title:'Imperial Permissions',description:'Map existing permissions to departments, branches and functions.',artwork:'nav-staff-v2.webp'}); async function api(body){const r=await fetch(API,{credentials:'same-origin',cache:'no-store',signal:controller.signal,...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});const d=await r.json().catch(()=>({}));if(!r.ok)throw Error(d.message||'Policy service unavailable.');return d;} function render(){ - content.replaceChildren();content.append(el('p','Preparation mode: saved mappings are versioned and audited. Current live permissions remain unchanged until the migration is activated.','md-note')); + content.replaceChildren();content.append(el('p',data.enforcement==='active'?'Active permission policies: saved changes update central access and synchronise connected services. All changes are versioned and audited.':'Preparation mode: saved mappings are versioned and audited. Current live permissions remain unchanged until the migration is activated.','md-note')); const tools=el('div',undefined,'md-tools'),scopes=el('select'),ranks=el('select');scopes.setAttribute('aria-label','Department or branch');ranks.setAttribute('aria-label','Function'); for(const s of data.scopes){const o=el('option',s.label+' · '+s.type);o.value=s.type+':'+s.key;scopes.append(o);}scopes.value=selection; const [type,key]=selection.split(':');for(const value of roles[type]){const o=el('option',roleNames[value]);o.value=value;ranks.append(o);}if(!roles[type].includes(role))role=roles[type][0];ranks.value=role; @@ -22,8 +22,8 @@ export function mountOrganisationPermissions(host){ for(const item of data.catalogue){const option=el('label',undefined,'md-permission');const check=el('input');check.type='checkbox';check.checked=chosen.has(item.node);check.disabled=!data.canEdit;const label=el('span');label.append(el('strong',item.label),el('small',item.node));option.append(check,label);option.dataset.search=(item.node+' '+item.label).toLowerCase();check.onchange=()=>{dirty=true;check.checked?chosen.add(item.node):chosen.delete(item.node);count.textContent=chosen.size+' mapped permissions';filter();};matrix.append(option);} const filter=()=>{for(const row of matrix.children)row.hidden=!!search.value&&!row.dataset.search.includes(search.value.toLowerCase())||assignedOnly.checked&&!row.querySelector('input').checked;};search.oninput=filter;assignedOnly.onchange=filter;content.append(matrix); const count=el('p',chosen.size+' mapped permissions','md-note');const reason=el('textarea');reason.rows=2;reason.required=true;reason.minLength=3;reason.maxLength=500;reason.placeholder='Reason for this policy change';reason.setAttribute('aria-label','Reason for policy change');const save=el('button','Save policy mapping');save.type='submit';save.disabled=!data.canEdit;const form=el('form',undefined,'md-assignment-form');form.append(count,reason,save);content.append(form); - form.onsubmit=async e=>{e.preventDefault();if(busy||!data.canEdit||!form.reportValidity()||!confirm('Save this mapping? Live activation is a separate migration step.'))return;busy=true;save.disabled=true; - try{const version=Number(data.versions.find(v=>v.scope_type===type&&v.scope_key===key)?.version||1);await api({scopeType:type,scopeKey:key,role,nodes:[...chosen],scopeVersion:version,reason:reason.value});dirty=false;await load();status.textContent='Policy mapping saved and audited. Live permissions unchanged.';}catch(error){if(!disposed)status.textContent=error.message;}finally{busy=false;if(save.isConnected)save.disabled=!data.canEdit;} + form.onsubmit=async e=>{e.preventDefault();if(busy||!data.canEdit||!form.reportValidity()||!confirm(data.enforcement==='active'?'Save this policy and update current access?':'Save this mapping? Live activation is a separate migration step.'))return;busy=true;save.disabled=true; + try{const version=Number(data.versions.find(v=>v.scope_type===type&&v.scope_key===key)?.version||1);await api({scopeType:type,scopeKey:key,role,nodes:[...chosen],scopeVersion:version,reason:reason.value});dirty=false;await load();status.textContent=data.enforcement==='active'?'Policy saved and audited. Central access updated; native synchronisation queued.':'Policy mapping saved and audited. Live permissions unchanged.';}catch(error){if(!disposed)status.textContent=error.message;}finally{busy=false;if(save.isConnected)save.disabled=!data.canEdit;} }; if(!data.canEdit)content.append(el('p','Read-only mapping. Editing requires Executive or Dev service authority.','md-note')); const advanced=el('details');advanced.append(el('summary','+ Workspace details'),el('p','Central policy register · version '+(policy?.version||0)+' · no native rank editor or wildcard grants'));content.append(advanced); diff --git a/website/node/citizen-directory.mjs b/website/node/citizen-directory.mjs index 28c8339c..9c14e1bd 100644 --- a/website/node/citizen-directory.mjs +++ b/website/node/citizen-directory.mjs @@ -52,8 +52,9 @@ export function createCitizenDirectory(db,{authenticate=identity,authorize=can,c if(request.method!=='GET')return reply({message:'This directory endpoint is read-only.'},405); const actor=await authenticate(request,db);if(!actor)return reply({message:'Sign in first.'},401); if(!await authorize(db,actor,'web.accounts.view'))return reply({message:'Account directory permission required.'},403); + const assignmentMode=db.organisationAccessEnabled?'active':'preparing'; const url=new URL(request.url);let filter;try{filter=directoryFilters(url,clock());}catch(e){return reply({message:e.message},400);} - if(url.pathname==='/api/admin/citizens/catalogue')return reply({departments:filter.context==='staff'?ORGANISATION:[],roles:Object.fromEntries(Object.entries(ASSIGNMENT_ROLES).filter(([key])=>STAFF_SCOPE_TYPES.includes(key)===(filter.context==='staff'))),assignmentMode:'preparing',permissionsChanged:false}); + if(url.pathname==='/api/admin/citizens/catalogue')return reply({departments:filter.context==='staff'?ORGANISATION:[],roles:Object.fromEntries(Object.entries(ASSIGNMENT_ROLES).filter(([key])=>STAFF_SCOPE_TYPES.includes(key)===(filter.context==='staff'))),assignmentMode,permissionsChanged:false}); const match=url.pathname.match(/^\/api\/admin\/citizens\/([0-9a-f-]{36})$/i); if(match){ // Staff managers may open a human candidate before their first appointment. @@ -68,11 +69,11 @@ export function createCitizenDirectory(db,{authenticate=identity,authorize=can,c const {results}=await db.prepare('SELECT source_name,source_ref,imported_at FROM staff_source_members WHERE user_id=? ORDER BY source_key').bind(row.id).all(); account.staffSources=results.map(s=>({name:s.source_name,reference:s.source_ref,importedAt:Number(s.imported_at)})); } - return reply({account,context:filter.context,assignmentMode:'preparing',permissionsChanged:false}); + return reply({account,context:filter.context,assignmentMode,permissionsChanged:false}); } if(url.pathname!=='/api/admin/citizens')return reply({message:'Not found.'},404); const {results}=await db.prepare(`SELECT ${fields} FROM site_accounts a${filter.where} ORDER BY a.username,a.id LIMIT ? OFFSET ?`).bind(...filter.values,26,(filter.page-1)*25).all(); const rows=results.slice(0,25),current=await assignments(rows.map(a=>a.id),filter.context); - return reply({accounts:rows.map(row=>({...project(row),assignments:current.filter(a=>a.user_id===row.id).map(assignmentLabel)})),page:filter.page,pageSize:25,hasMore:results.length>25,context:filter.context,assignmentMode:'preparing'}); + return reply({accounts:rows.map(row=>({...project(row),assignments:current.filter(a=>a.user_id===row.id).map(assignmentLabel)})),page:filter.page,pageSize:25,hasMore:results.length>25,context:filter.context,assignmentMode}); }; } diff --git a/website/node/managed-game-permissions.json b/website/node/managed-game-permissions.json index a3016f8f..119e46b3 100644 --- a/website/node/managed-game-permissions.json +++ b/website/node/managed-game-permissions.json @@ -240,6 +240,96 @@ "label": "All WorldGuard tools", "source": "Approved plugin wildcard: network administrator only", "highRisk": true + }, + { + "node": "dune.items.give", + "label": "Issue registered custom items", + "source": "DuneRealms central registered permission catalogue", + "highRisk": true + }, + { + "node": "dune.staff.ban.local", + "label": "Ban from one server", + "source": "DuneRealms central registered permission catalogue", + "highRisk": true + }, + { + "node": "dune.staff.ban.network", + "label": "Ban from the network", + "source": "DuneRealms central registered permission catalogue", + "highRisk": true + }, + { + "node": "dune.staff.history", + "label": "View punishment history", + "source": "DuneRealms central registered permission catalogue", + "highRisk": true + }, + { + "node": "dune.staff.kick", + "label": "Kick players", + "source": "DuneRealms central registered permission catalogue", + "highRisk": true + }, + { + "node": "dune.staff.mute", + "label": "Mute players", + "source": "DuneRealms central registered permission catalogue", + "highRisk": true + }, + { + "node": "dune.staff.open", + "label": "Open staff GUI", + "source": "DuneRealms central registered permission catalogue", + "highRisk": true + }, + { + "node": "dune.staff.warn", + "label": "Warn players", + "source": "DuneRealms central registered permission catalogue", + "highRisk": true + }, + { + "node": "duneess.exchange", + "label": "Exchange shop", + "source": "DuneRealms central registered permission catalogue", + "highRisk": false + }, + { + "node": "duneess.shops.use", + "label": "Use NPC shops", + "source": "DuneRealms central registered permission catalogue", + "highRisk": false + }, + { + "node": "duneess.tokens.buy", + "label": "Buy guild tokens", + "source": "DuneRealms central registered permission catalogue", + "highRisk": false + }, + { + "node": "duneess.travel", + "label": "Guild travel", + "source": "DuneRealms central registered permission catalogue", + "highRisk": false + }, + { + "node": "dunelobby.admin", + "label": "Lobby administration", + "source": "DuneRealms central registered permission catalogue", + "highRisk": true + }, + { + "node": "dunelobby.build", + "label": "Build in protected lobby", + "source": "DuneRealms central registered permission catalogue", + "highRisk": true + }, + { + "node": "dunelobby.visit", + "label": "Visit lobby", + "source": "DuneRealms central registered permission catalogue", + "highRisk": false } ], "networkAdministratorRoles": [ diff --git a/website/node/organisation-management.mjs b/website/node/organisation-management.mjs index f25119e3..e5273ad6 100644 --- a/website/node/organisation-management.mjs +++ b/website/node/organisation-management.mjs @@ -72,7 +72,7 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c const policies=await tx.query('SELECT scope_type,scope_key,role_key,permissions_json,version FROM org_role_policies',[]); const principal=await tx.first('SELECT principal_kind FROM org_control_principals WHERE user_id=?',[userId]); return effectiveOrganisationAccess({assignments,policies,registry:NODES,principalKind:principal?.principal_kind,now}); - });return reply(result); + });return reply({...result,enforcement:db.organisationAccessEnabled?'active':'preparing'}); } if(url.pathname.endsWith('/activity')){ const context=url.searchParams.get('context')||'users';if(!['users','staff'].includes(context))return reply({message:'Invalid context.'},400); diff --git a/website/tests/citizen-directory.test.mjs b/website/tests/citizen-directory.test.mjs index 83a8c172..85db88b5 100644 --- a/website/tests/citizen-directory.test.mjs +++ b/website/tests/citizen-directory.test.mjs @@ -6,9 +6,9 @@ import {ORGANISATION,initializeOrganisation} from '../node/organisation-model.mj const id='49d2fe76-7977-4d49-bd39-e48fc8c648b8'; const row={id,username:'example',display_name:'Example',created_at:100,account_status:'active',minecraft_name:'Example',minecraft_uuid:id}; const assignment=(type,key,role)=>({id:'assignment',user_id:id,scope_type:type,scope_key:key,role_key:role,source_kind:'appointment',starts_at:1,ends_at:null}); -function fixture({rows=[row],grants=[assignment('clan','clan-example','member'),assignment('branch','trust_safety','officer')],authenticated=true,allowed=true}={}){ +function fixture({rows=[row],grants=[assignment('clan','clan-example','member'),assignment('branch','trust_safety','officer')],authenticated=true,allowed=true,active=false}={}){ const queries=[]; - const db={prepare(sql){let args=[];queries.push({sql,get args(){return args;}});return {bind(...v){args=v;return this;},async first(){return rows.find(r=>r.id===args[0])||null;},async all(){ + const db={organisationAccessEnabled:active,prepare(sql){let args=[];queries.push({sql,get args(){return args;}});return {bind(...v){args=v;return this;},async first(){return rows.find(r=>r.id===args[0])||null;},async all(){ if(sql.includes('FROM org_assignments WHERE'))return {results:grants.filter(g=>sql.includes("scope_type NOT IN")?!['organisation','department','branch'].includes(g.scope_type):['organisation','department','branch'].includes(g.scope_type))}; if(sql.includes('FROM staff_source_members WHERE'))return {results:[{source_name:'.bedrock',source_ref:'private-staff-source',imported_at:10}]}; return {results:rows}; @@ -16,6 +16,13 @@ function fixture({rows=[row],grants=[assignment('clan','clan-example','member'), return {queries,api:createCitizenDirectory(db,{authenticate:async()=>authenticated?{id,role:'user'}:null,authorize:async()=>allowed,clock:()=>50})}; } const req=(path='?context=users',method='GET')=>new Request('https://cp.dunerealms.com/api/admin/citizens'+path,{method}); + +test('directory reports actual activation in list, account and catalogue responses',async()=>{ + for(const active of [false,true])for(const suffix of ['?context=staff','/'+id+'?context=staff','/catalogue?context=staff']){ + const data=await (await fixture({active}).api(req(suffix))).json(); + assert.equal(data.assignmentMode,active?'active':'preparing'); + } +}); test('directory rejects guests and unprivileged users before database reads',async()=>{ for(const [options,status]of [[{authenticated:false},401],[{allowed:false},403]]){const f=fixture(options);assert.equal((await f.api(req())).status,status);assert.equal(f.queries.length,0);} });