Add audited staff assignments and central policy mapping editor

This commit is contained in:
unimatrixgit 2026-11-14 23:41:54 +01:00
commit 396d2f3e2e
3 changed files with 408 additions and 9 deletions

View file

@ -56,7 +56,10 @@ export function createCitizenDirectory(db,{authenticate=identity,authorize=can,c
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});
const match=url.pathname.match(/^\/api\/admin\/citizens\/([0-9a-f-]{36})$/i);
if(match){
const row=await db.prepare(`SELECT ${fields} FROM site_accounts a WHERE a.id=?${filter.where?' AND '+filter.where.slice(7):''}`).bind(match[1],...filter.values).first();
// Staff managers may open a human candidate before their first appointment.
// The directory list remains staff-only; service accounts are never candidates.
const candidateGuard=filter.context==='staff'?' AND NOT EXISTS (SELECT 1 FROM site_account_policies service WHERE service.user_id=a.id AND service.game_link_exempt=1)':'';
const row=await db.prepare(`SELECT ${fields} FROM site_accounts a WHERE a.id=?${candidateGuard}`).bind(match[1]).first();
if(!row)return reply({message:'Account not found.'},404);
const current=await assignments([row.id],filter.context);
const account={...project(row),assignments:current.map(assignmentLabel)};

View file

@ -0,0 +1,126 @@
import {randomUUID} from 'node:crypto';
import {identity} from './auth.mjs';
import {can,NODES} from './permissions.mjs';
import {staffScopes,validStaffRole,assignmentLabel} from './organisation-model.mjs';
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}});
const fault=(message,status=409)=>Object.assign(new Error(message),{status});
const identifier=value=>typeof value==='string'&&/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value);
const globalPrincipal=kind=>['owner','executive','service'].includes(kind);
const active=row=>row.status==='active';
export function canAssignRole(authority,scopeType,scopeKey,role){
if(!validStaffRole(scopeType,scopeKey,role)||role==='owner_ceo')return false;
if(scopeType==='organisation')return globalPrincipal(authority.principal);
if(globalPrincipal(authority.principal))return true;
const scope=staffScopes().find(s=>s.type===scopeType&&s.key===scopeKey);
return authority.assignments.some(a=>active(a)&&(
a.scope_type==='department'&&a.role_key==='department_head'&&scopeType==='branch'&&scope.department===a.scope_key||
a.scope_type==='branch'&&a.role_key==='branch_lead'&&scopeType==='branch'&&scopeKey===a.scope_key&&role==='officer'
));
}
const nativeEditorNodes=new Set(['web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor']);
export function validatePolicyNodes(nodes,scopeType,role){
if(!Array.isArray(nodes)||nodes.length>500||nodes.some(n=>typeof n!=='string'))throw fault('Choose registered permission nodes.',400);
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(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);
}
return unique;
}
export function createOrganisationManagement(db,{origin='https://cp.dunerealms.com',authenticate=identity,authorize=can,clock=Date.now}={}){
async function authority(tx,userId){
const actor=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' FOR SHARE",[userId]);
if(!actor)throw fault('Account authority changed.',403);
const principal=await tx.first('SELECT principal_kind FROM org_control_principals WHERE user_id=? FOR SHARE',[userId]);
const assignments=await tx.query("SELECT scope_type,scope_key,role_key,status FROM org_assignments WHERE user_id=? AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) FOR SHARE",[userId,clock(),clock()]);
return {principal:principal?.principal_kind||null,assignments};
}
async function readAuthority(id){
const result=await db.transaction(tx=>authority(tx,id));
return {...result,editable:staffScopes().flatMap(scope=>['executive','department_head','branch_lead','officer'].filter(role=>canAssignRole(result,scope.type,scope.key,role)).map(role=>({...scope,role})))};
}
async function scopeLock(tx,b){
await tx.query('INSERT IGNORE INTO org_scope_versions(scope_type,scope_key,version) VALUES(?,?,1)',[b.scopeType,b.scopeKey]);
const current=await tx.first('SELECT version FROM org_scope_versions WHERE scope_type=? AND scope_key=? FOR UPDATE',[b.scopeType,b.scopeKey]);
if(Number(current.version)!==b.scopeVersion)throw fault('This scope changed. Refresh before saving.');
}
async function audit(tx,actor,b,action,before,after,assignmentId=null){
await tx.query('INSERT INTO org_assignment_events(id,user_id,assignment_id,actor_id,action,scope_type,scope_key,reason,before_json,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)',[randomUUID(),b.userId||null,assignmentId,actor.id,action,b.scopeType,b.scopeKey,b.reason,before?JSON.stringify(before):null,JSON.stringify(after),clock()]);
}
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(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'});
if(policy){
const {results:policies}=await db.prepare('SELECT scope_type,scope_key,role_key,permissions_json,version,updated_at FROM org_role_policies ORDER BY scope_type,scope_key,role_key').all();
const {results:versions}=await db.prepare('SELECT scope_type,scope_key,version FROM org_scope_versions').all();
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('/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')";
const {results}=await db.prepare(`SELECT e.id,e.action,e.scope_type,e.scope_key,e.reason,e.created_at,a.username AS actor FROM org_assignment_events e LEFT JOIN site_accounts a ON a.id=e.actor_id WHERE e.user_id=? AND e.scope_type ${clause} ORDER BY e.created_at DESC,e.id DESC LIMIT 50`).bind(userId).all();return reply({events:results});
}
const {results:assignments}=await db.prepare("SELECT id,user_id,scope_type,scope_key,role_key,source_kind,status,starts_at,ends_at,version FROM org_assignments WHERE user_id=? AND scope_type IN ('organisation','department','branch') AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) ORDER BY scope_type,scope_key,role_key").bind(userId,clock(),clock()).all();
const {results:versions}=await db.prepare('SELECT scope_type,scope_key,version FROM org_scope_versions').all();
return reply({assignments:assignments.map(a=>({...assignmentLabel(a),editable:a.source_kind==='manual'&&canAssignRole(auth,a.scope_type,a.scope_key,a.role_key)})),editable:auth.editable,versions,permissionsChanged:false,enforcement:'preparing'});
}
if(request.method!=='POST'||!['/api/admin/organisation/assignments','/api/admin/organisation/policies'].includes(url.pathname))return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);
if(!request.headers.get('content-type')?.startsWith('application/json'))return reply({message:'Send JSON.'},415);
if(!await authorize(db,actor,policy?'web.ranks.manage':'web.accounts.assign'))return reply({message:'Assignment permission required.'},403);
let b;try{const raw=await request.text();if(Buffer.byteLength(raw)>32000)throw Error();b=JSON.parse(raw);}catch{return reply({message:'Invalid request.'},400);}
if(!b||typeof b!=='object'||Array.isArray(b)||typeof b.reason!=='string'||b.reason.trim().length<3||b.reason.length>500||!validStaffRole(b.scopeType,b.scopeKey,b.role)||!Number.isSafeInteger(b.scopeVersion)||b.scopeVersion<1)return reply({message:'Choose a scope, role and a reason of 3–500 characters.'},400);
const allowed=policy?['scopeType','scopeKey','role','reason','scopeVersion','nodes']:['scopeType','scopeKey','role','reason','scopeVersion','userId','action','assignmentId','version'];
if(Object.keys(b).some(key=>!allowed.includes(key)))return reply({message:'Unexpected request fields.'},400);
b.reason=b.reason.trim();
try{
const result=await db.transaction(async tx=>{
// Fresh authority and version checks are in the same transaction as the change.
const auth=await authority(tx,actor.id);
if(policy){
if(!globalPrincipal(auth.principal))throw fault('Policy changes require Executive or Dev service authority.',403);
const nodes=validatePolicyNodes(b.nodes,b.scopeType,b.role);await scopeLock(tx,b);
const before=await tx.first('SELECT permissions_json,version FROM org_role_policies WHERE scope_type=? AND scope_key=? AND role_key=? FOR UPDATE',[b.scopeType,b.scopeKey,b.role]);
const after={nodes,version:Number(before?.version||0)+1};
await tx.query('INSERT INTO org_role_policies(scope_type,scope_key,role_key,permissions_json,version,updated_by,updated_at) VALUES(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE permissions_json=VALUES(permissions_json),version=VALUES(version),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)',[b.scopeType,b.scopeKey,b.role,JSON.stringify(nodes),after.version,actor.id,clock()]);
await audit(tx,actor,b,'policy',before,after);
}else{
if(!identifier(b.userId)||!['assign','revoke'].includes(b.action))throw fault('Invalid assignment request.',400);
if(!canAssignRole(auth,b.scopeType,b.scopeKey,b.role))throw fault('This role is outside your management scope.',403);
const target=await tx.first("SELECT a.id,p.game_link_exempt FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.id=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[b.userId]);
if(!target)throw fault('Account not found.',404);if(target.game_link_exempt)throw fault('Service accounts are outside the human staff structure.',403);
await scopeLock(tx,b);
if(b.action==='assign'){
const current=await tx.query("SELECT id,user_id,role_key FROM org_assignments WHERE scope_type=? AND scope_key=? AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) FOR UPDATE",[b.scopeType,b.scopeKey,clock(),clock()]);
if(current.some(a=>a.user_id===b.userId&&a.role_key===b.role))throw fault('This assignment already exists.');
if(['branch_lead','department_head'].includes(b.role)&&current.some(a=>a.role_key===b.role))throw fault('This scope already has an accountable lead. Revoke that assignment before appointing another.');
const id=randomUUID(),after={userId:b.userId,scopeType:b.scopeType,scopeKey:b.scopeKey,role:b.role,source:'manual'};
await tx.query("INSERT INTO org_assignments(id,user_id,scope_type,scope_key,role_key,source_kind,starts_at,created_by,created_at) VALUES(?,?,?,?,?,'manual',?,?,?)",[id,b.userId,b.scopeType,b.scopeKey,b.role,clock(),actor.id,clock()]);
await audit(tx,actor,b,'assign',null,after,id);
}else{
if(!identifier(b.assignmentId)||!Number.isSafeInteger(b.version)||b.version<1)throw fault('Select the current assignment version.',400);
const before=await tx.first('SELECT * FROM org_assignments WHERE id=? FOR UPDATE',[b.assignmentId]);
if(!before||before.user_id!==b.userId||before.scope_type!==b.scopeType||before.scope_key!==b.scopeKey||before.role_key!==b.role)throw fault('Assignment not found.',404);
if(before.source_kind!=='manual')throw fault('Automatic assignments must be changed at their source.',403);
if(before.status!=='active'||Number(before.version)!==b.version)throw fault('Assignment changed. Refresh before retrying.');
await tx.query("UPDATE org_assignments SET status='revoked',version=version+1 WHERE id=?",[b.assignmentId]);await audit(tx,actor,b,'revoke',before,{status:'revoked'},b.assignmentId);
}
}
await tx.query('UPDATE org_scope_versions SET version=version+1 WHERE scope_type=? AND scope_key=?',[b.scopeType,b.scopeKey]);
return {ok:true,scopeVersion:b.scopeVersion+1,permissionsChanged:false,enforcement:'preparing'};
});return reply(result);
}catch(e){
if(e.status)return reply({message:e.message},e.status);
if(['ER_LOCK_DEADLOCK','ER_LOCK_WAIT_TIMEOUT'].includes(e.code))return reply({message:'A concurrent management change was detected. Refresh before retrying.'},409);
throw e;
}
};
}

View file

@ -33,6 +33,29 @@ export function assignmentLabel(row){
id:row.id,version:Number(row.version||1)};
}
export const organisationSchema = [
`CREATE TABLE IF NOT EXISTS org_control_principals (
user_id CHAR(36) PRIMARY KEY, principal_kind VARCHAR(24) NOT NULL,
created_by CHAR(36) NOT NULL, created_at BIGINT NOT NULL,
FOREIGN KEY(user_id) REFERENCES site_accounts(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS org_scope_versions (
scope_type VARCHAR(24) NOT NULL, scope_key VARCHAR(80) NOT NULL,
version INT NOT NULL DEFAULT 1, PRIMARY KEY(scope_type,scope_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS org_role_policies (
scope_type VARCHAR(24) NOT NULL, scope_key VARCHAR(80) NOT NULL,
role_key VARCHAR(40) NOT NULL, permissions_json TEXT NOT NULL,
version INT NOT NULL DEFAULT 1, updated_by CHAR(36) NOT NULL, updated_at BIGINT NOT NULL,
PRIMARY KEY(scope_type,scope_key,role_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS org_assignment_events (
id CHAR(36) PRIMARY KEY, user_id CHAR(36) NULL, assignment_id CHAR(36) NULL,
actor_id CHAR(36) NOT NULL, action VARCHAR(24) NOT NULL,
scope_type VARCHAR(24) NOT NULL, scope_key VARCHAR(80) NOT NULL,
reason VARCHAR(500) NOT NULL, before_json TEXT NULL, after_json TEXT NOT NULL,
created_at BIGINT NOT NULL,
INDEX org_events_target(user_id,created_at), INDEX org_events_scope(scope_type,scope_key,created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS org_assignments (
id CHAR(36) PRIMARY KEY, user_id CHAR(36) NOT NULL,
scope_type VARCHAR(24) NOT NULL, scope_key VARCHAR(80) NOT NULL, role_key VARCHAR(40) NOT NULL,
@ -54,3 +77,12 @@ export async function initializeOrganisation(db){
for(const sql of organisationSchema)await db.prepare(sql).run();
// No automatic appointments, account rewrites, rank resets or game grants.
}
export function staffScopes(){
return [{type:'organisation',key:'dunerealms',label:'DuneRealms'},...ORGANISATION.flatMap(d=>[
{type:'department',key:d.key,label:d.label},...d.branches.map(b=>({type:'branch',key:b.key,label:b.label,department:d.key}))
])];
}
export function validStaffRole(type,key,role){
return staffScopes().some(s=>s.type===type&&s.key===key)&&ASSIGNMENT_ROLES[type]?.some(r=>r.key===role);
}