forked from unimatrix/web
Preview effective organisation rights and expose scoped staff access provenance
This commit is contained in:
parent
9e400357b7
commit
85339bc152
6 changed files with 92 additions and 3 deletions
|
|
@ -65,11 +65,22 @@ export function mountCitizenDirectory(host){
|
|||
for(const event of data.events){const row=element('div',undefined,'md-assignment');row.append(element('strong',event.action+' · '+event.scope_key.replaceAll('_',' ')),element('p',event.reason),element('small',(event.actor||'System')+' · '+new Date(Number(event.created_at)).toLocaleString('en-GB')));panel.append(row);}
|
||||
}catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.append(element('p',e.message,'md-note'));}
|
||||
}
|
||||
async function loadAccessPreview(panel){
|
||||
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'));
|
||||
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.'));
|
||||
}catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.replaceChildren(element('p',e.message,'md-note'));}
|
||||
}
|
||||
function renderAccount(){
|
||||
view.replaceChildren();heading();const back=button('← '+(context==='staff'?'Staff Directory':'User Directory'),()=>{selected=null;void load();});view.append(back);
|
||||
const hero=element('header',undefined,'md-identity');const avatar=element('img');avatar.alt='';avatar.width=56;avatar.height=56;avatar.src=selected.minecraftUuid?'/api/avatars/minecraft/'+encodeURIComponent(selected.minecraftUuid):'https://www.dunerealms.com/assets/nav-account-v2.webp';
|
||||
const names=element('div');names.append(element('h2',selected.displayName),element('p',selected.username,'md-muted'));const publicLink=element('a','View public profile →');publicLink.href='https://www.dunerealms.com/people/'+encodeURIComponent(selected.username);hero.append(avatar,names,badge(selected.status),publicLink);view.append(hero);
|
||||
const tabs=context==='staff'?[['overview','Overview'],['account','Account'],['assignments','Staff assignments'],['honours','Seals & honours'],['activity','Activity']]:[['overview','Overview'],['account','Account'],['assignments','Memberships & offices'],['honours','Seals & honours'],['activity','Activity']];
|
||||
const tabs=context==='staff'?[['overview','Overview'],['account','Account'],['assignments','Staff assignments'],['permissions','Access preview'],['honours','Seals & honours'],['activity','Activity']]:[['overview','Overview'],['account','Account'],['assignments','Memberships & offices'],['honours','Seals & honours'],['activity','Activity']];
|
||||
const nav=element('nav',undefined,'md-tabs');nav.setAttribute('aria-label','Manage '+(context==='staff'?'staff':'user'));for(const[key,label]of tabs){const b=button(label,()=>{tab=key;renderAccount();});b.setAttribute('aria-current',String(tab===key));nav.append(b);}view.append(nav);
|
||||
if(tab==='overview'){
|
||||
const grid=element('div',undefined,'md-grid'),identity=box('Account summary');identity.append(detail('Minecraft',selected.minecraftName||'Not linked'),detail('Joined',date(selected.createdAt)),detail('Status',selected.status));grid.append(identity,assignments());view.append(grid);
|
||||
|
|
@ -77,6 +88,7 @@ export function mountCitizenDirectory(host){
|
|||
}else if(tab==='account'){
|
||||
const identity=box('Linked identity');identity.append(detail('Username',selected.username),detail('Display name',selected.displayName),detail('Minecraft',selected.minecraftName||'Not linked'),detail('Status',selected.status));const advanced=element('details');advanced.append(element('summary','+ Advanced account details'),detail('Account ID',selected.id),detail('Minecraft UUID',selected.minecraftUuid||'Not linked'));identity.append(advanced);view.append(identity);
|
||||
}else if(tab==='assignments'){const panel=assignments();view.append(panel);if(context==='staff')void loadAssignments(panel);}
|
||||
else if(tab==='permissions'&&context==='staff'){const panel=box('Effective access preview');view.append(panel);void loadAccessPreview(panel);}
|
||||
else if(tab==='honours'){const panel=box('Seals & honours');panel.append(element('p','Existing awards are preserved. The new seal ledger and compact award controls follow in the recognition batch.','md-muted'));panel.append(publicLink.cloneNode(true));view.append(panel);}
|
||||
else{const panel=box('Account activity');view.append(panel);void loadActivity(panel);}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -94,3 +94,5 @@ or four-hour compensation queue. Reuse existing posting/audit infrastructure.
|
|||
|
||||
Cash conversion is reserved for the future in-game GUI + central API in both
|
||||
directions. No cash web page, redeem code flow or game changes in this batch.
|
||||
|
||||
Effective-access preview: GET /api/admin/organisation/effective?userId=UUID requires web.ranks.manage and computes explicit new-model grants with provenance. Branch Leads inherit their own Officer policy. Missing policies and blocked unsafe grants are reported. Staff Directory has an Access preview tab; User context does not. Payroll requires a pinned Big Four control principal (Dev service exception), never an Executive title alone. No live rank mutation or native projection is activated by this endpoint.
|
||||
|
|
|
|||
28
website/node/organisation-effective.mjs
Normal file
28
website/node/organisation-effective.mjs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import {validStaffRole} from './organisation-model.mjs';
|
||||
const nativeEditors=new Set(['web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor']);
|
||||
const officialBank=new Set(['web.bank.staff.manage','cp.bank.staff.manage','web.bank.staff.deposit','cp.bank.staff.deposit']);
|
||||
// Pure preview: never changes legacy ranks or grants native product permissions.
|
||||
export function effectiveOrganisationAccess({assignments,policies,registry,principalKind=null,now=Date.now()}){
|
||||
const nodes=new Set(),sources=[],missing=[],blocked=[];
|
||||
for(const a of assignments){
|
||||
if(a.status!=='active'||Number(a.starts_at)>now||a.ends_at!==null&&a.ends_at!==undefined&&Number(a.ends_at)<=now)continue;
|
||||
if(!validStaffRole(a.scope_type,a.scope_key,a.role_key))continue;
|
||||
const roles=a.scope_type==='branch'&&a.role_key==='branch_lead'?['officer','branch_lead']:[a.role_key];
|
||||
for(const role of roles){
|
||||
const p=policies.find(p=>p.scope_type===a.scope_type&&p.scope_key===a.scope_key&&p.role_key===role);
|
||||
const source={scopeType:a.scope_type,scopeKey:a.scope_key,role,assignmentId:a.id};
|
||||
if(!p){missing.push(source);continue;}
|
||||
let requested;try{requested=JSON.parse(p.permissions_json);}catch{throw Error('Invalid stored organisation policy.');}
|
||||
if(!Array.isArray(requested)||requested.some(n=>typeof n!=='string'))throw Error('Invalid stored organisation policy.');
|
||||
const granted=[];
|
||||
for(const n of requested){
|
||||
const management=a.scope_type==='organisation'&&['owner_ceo','executive'].includes(role)||a.scope_type==='department'&&role==='department_head';
|
||||
const payroll=['web.payroll.manage','cp.payroll.manage'].includes(n);
|
||||
if(!Object.hasOwn(registry,n)||n.includes('*')||/(^|\.)op($|\.)/.test(n)||nativeEditors.has(n)||officialBank.has(n)&&!management||payroll&&!(['owner','executive','service'].includes(principalKind)&&a.scope_type==='organisation'&&['owner_ceo','executive'].includes(role))){blocked.push({...source,node:n});continue;}
|
||||
nodes.add(n);granted.push(n);
|
||||
}
|
||||
sources.push({...source,version:Number(p.version),nodes:[...new Set(granted)].sort()});
|
||||
}
|
||||
}
|
||||
return {nodes:[...nodes].sort(),sources,missingPolicies:missing,blocked,enforcement:'preparing',permissionsChanged:false};
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import {effectiveOrganisationAccess} from './organisation-effective.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {identity} from './auth.mjs';
|
||||
import {can,NODES} from './permissions.mjs';
|
||||
|
|
@ -24,6 +25,7 @@ export function validatePolicyNodes(nodes,scopeType,role){
|
|||
const unique=[...new Set(nodes)].sort();
|
||||
for(const n of unique){
|
||||
if(!Object.hasOwn(NODES,n)||n.includes('*')||/(^|\.)op($|\.)/.test(n))throw fault('Unregistered or unrestricted permission: '+n,400);
|
||||
if(['web.payroll.manage','cp.payroll.manage'].includes(n)&&!(scopeType==='organisation'&&['owner_ceo','executive'].includes(role)))throw fault('Payroll management is reserved for the Big Four.',400);
|
||||
if(nativeEditorNodes.has(n))throw fault('Native permission editors remain reserved for the Dev service.',400);
|
||||
if(['web.bank.staff.manage','cp.bank.staff.manage','web.bank.staff.deposit','cp.bank.staff.deposit'].includes(n)&&!((scopeType==='organisation'&&['owner_ceo','executive'].includes(role))||(scopeType==='department'&&role==='department_head')))throw fault('Official banking management is reserved for executives and department heads.',400);
|
||||
}
|
||||
|
|
@ -52,8 +54,8 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c
|
|||
return async request=>{
|
||||
const actor=await authenticate(request,db);if(!actor)return reply({message:'Sign in first.'},401);
|
||||
const url=new URL(request.url),policy=url.pathname==='/api/admin/organisation/policies';
|
||||
if(!['/api/admin/organisation/assignments','/api/admin/organisation/policies','/api/admin/organisation/activity','/api/admin/organisation/authority'].includes(url.pathname))return reply({message:'Not found.'},404);
|
||||
if(!await authorize(db,actor,policy?'web.ranks.manage':'web.accounts.view'))return reply({message:'Central management permission required.'},403);
|
||||
if(!['/api/admin/organisation/assignments','/api/admin/organisation/policies','/api/admin/organisation/activity','/api/admin/organisation/authority','/api/admin/organisation/effective'].includes(url.pathname))return reply({message:'Not found.'},404);
|
||||
if(!await authorize(db,actor,(policy||url.pathname.endsWith('/effective'))?'web.ranks.manage':'web.accounts.view'))return reply({message:'Central management permission required.'},403);
|
||||
if(request.method==='GET'){
|
||||
const auth=await readAuthority(actor.id);
|
||||
if(url.pathname.endsWith('/authority'))return reply({editable:auth.editable,canEditPolicies:globalPrincipal(auth.principal),enforcement:'preparing'});
|
||||
|
|
@ -63,6 +65,15 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c
|
|||
return reply({scopes:staffScopes(),versions,policies:policies.map(p=>({...p,nodes:JSON.parse(p.permissions_json),permissions_json:undefined})),catalogue:Object.entries(NODES).filter(([n])=>!n.includes('*')).map(([node,label])=>({node,label})),canEdit:globalPrincipal(auth.principal),enforcement:'preparing'});
|
||||
}
|
||||
const userId=url.searchParams.get('userId');if(!identifier(userId))return reply({message:'Select a registered account.'},400);
|
||||
if(url.pathname.endsWith('/effective')){
|
||||
const now=clock();
|
||||
const result=await db.transaction(async tx=>{
|
||||
const assignments=await tx.query('SELECT id,scope_type,scope_key,role_key,status,starts_at,ends_at FROM org_assignments WHERE user_id=?',[userId]);
|
||||
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);
|
||||
}
|
||||
if(url.pathname.endsWith('/activity')){
|
||||
const context=url.searchParams.get('context')||'users';if(!['users','staff'].includes(context))return reply({message:'Invalid context.'},400);
|
||||
const clause=context==='staff'?"IN ('organisation','department','branch')":"NOT IN ('organisation','department','branch')";
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
export const NODES={
|
||||
'web.payroll.manage':'Manage P&O payroll (Big Four only)',
|
||||
'web.bank.projects.approve':'Approve Support requests for temporary project bank accounts',
|
||||
'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',
|
||||
|
|
|
|||
35
website/tests/organisation-effective.test.mjs
Normal file
35
website/tests/organisation-effective.test.mjs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import {createOrganisationManagement} from '../node/organisation-management.mjs';
|
||||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {effectiveOrganisationAccess} from '../node/organisation-effective.mjs';
|
||||
const registry={'web.posts.view':'read','web.posts.manage':'write','web.bank.staff.manage':'bank','web.payroll.manage':'payroll','web.luckperms.edit':'native'};
|
||||
const position=(role,scope='news_media',type='branch')=>({id:role,scope_type:type,scope_key:scope,role_key:role,status:'active',starts_at:10,ends_at:null});
|
||||
const policy=(role,nodes,scope='news_media',type='branch')=>({scope_type:type,scope_key:scope,role_key:role,permissions_json:JSON.stringify(nodes),version:2});
|
||||
const run=(assignments,policies,principalKind=null)=>effectiveOrganisationAccess({assignments,policies,registry,principalKind,now:100});
|
||||
test('Lead inherits only its own branch officer policy; multiple assignments union explicit grants',()=>{
|
||||
const result=run([position('branch_lead')],[policy('officer',['web.posts.view']),policy('branch_lead',['web.posts.manage']),policy('officer',['web.bank.staff.manage'],'engineering')]);
|
||||
assert.deepEqual(result.nodes,['web.posts.manage','web.posts.view']);assert.equal(result.sources.length,2);assert.equal(result.permissionsChanged,false);
|
||||
});
|
||||
test('Expired, revoked, future and invalid assignments cannot contribute',()=>{
|
||||
const result=run([{...position('officer'),ends_at:100},{...position('officer'),status:'revoked'},{...position('officer'),starts_at:101},position('officer','invented')],[policy('officer',['web.posts.manage'])]);assert.deepEqual(result.nodes,[]);
|
||||
});
|
||||
test('Stored unsafe nodes are blocked even if an old policy bypassed current validation',()=>{
|
||||
const result=run([position('officer')],[policy('officer',['web.posts.view','web.bank.staff.manage','web.payroll.manage','web.luckperms.edit','*'])]);assert.deepEqual(result.nodes,['web.posts.view']);assert.equal(result.blocked.length,4);
|
||||
});
|
||||
test('Department heads have bank management but payroll remains executive-only',()=>{
|
||||
const head=run([position('department_head','community_operations','department')],[policy('department_head',['web.bank.staff.manage','web.payroll.manage'],'community_operations','department')]);assert.deepEqual(head.nodes,['web.bank.staff.manage']);
|
||||
const exec=run([position('executive','dunerealms','organisation')],[policy('executive',['web.bank.staff.manage','web.payroll.manage'],'dunerealms','organisation')],'executive');assert.deepEqual(exec.nodes,['web.bank.staff.manage','web.payroll.manage']);
|
||||
});
|
||||
test('Missing policies are explicit and corrupt stored data fails closed',()=>{
|
||||
assert.equal(run([position('officer')],[]).missingPolicies.length,1);
|
||||
assert.throws(()=>run([position('officer')],[{...policy('officer',[]),permissions_json:'bad'}]),/Invalid stored/);
|
||||
});
|
||||
|
||||
test('Executive title alone cannot bypass the pinned Big Four payroll boundary',()=>{const result=run([position('executive','dunerealms','organisation')],[policy('executive',['web.payroll.manage'],'dunerealms','organisation')]);assert.deepEqual(result.nodes,[]);assert.equal(result.blocked.length,1);});
|
||||
|
||||
test('Effective access endpoint requires policy-view authority and returns a non-mutating target preview',async()=>{
|
||||
const actor={id:'11111111-1111-4111-8111-111111111111'},target='22222222-2222-4222-8222-222222222222';const queries=[];
|
||||
const tx={first:async(sql,args)=>{queries.push([sql,args]);return sql.includes('site_accounts')?actor:{principal_kind:'executive'};},query:async(sql,args)=>{queries.push([sql,args]);if(sql.startsWith('SELECT id,scope_type'))return [position('officer')];if(sql.includes('org_role_policies'))return [policy('officer',['web.posts.view'])];return [];}};
|
||||
const db={transaction:fn=>fn(tx)};const endpoint=new Request('https://cp.dunerealms.com/api/admin/organisation/effective?userId='+target);
|
||||
const denied=createOrganisationManagement(db,{authenticate:async()=>actor,authorize:async()=>false});assert.equal((await denied(endpoint)).status,403);assert.equal(queries.length,0);
|
||||
const api=createOrganisationManagement(db,{authenticate:async()=>actor,authorize:async(_db,_user,node)=>node==='web.ranks.manage',clock:()=>100});const response=await api(endpoint);assert.equal(response.status,200);const data=await response.json();assert.deepEqual(data.nodes,['web.posts.view']);assert.equal(data.permissionsChanged,false);assert(queries.every(([sql])=>sql.startsWith('SELECT')));assert(queries.some(([sql,args])=>sql.startsWith('SELECT id,scope_type')&&args[0]===target));
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff