Preview effective organisation rights and expose scoped staff access provenance

This commit is contained in:
unimatrixgit 2026-11-15 01:07:58 +01:00
commit 85339bc152
3 changed files with 92 additions and 3 deletions

View 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};
}

View file

@ -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')";

View file

@ -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',