MC/website/node/organisation-management.mjs

138 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {effectiveOrganisationAccess} from './organisation-effective.mjs';
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.forum.admin','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(['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);
}
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','/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:db.organisationAccessEnabled?'active':'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:db.organisationAccessEnabled?'active':'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,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);
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:db.organisationAccessEnabled?'active':'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]);
if(db.organisationAccessEnabled)await tx.query("INSERT INTO native_sync_outbox(job_key,revision,attempts,next_attempt_at,lease_token,lease_until,created_at,last_error) VALUES('memberships',?,0,0,'',0,?,'') ON DUPLICATE KEY UPDATE revision=VALUES(revision),attempts=0,next_attempt_at=0,created_at=VALUES(created_at),last_error=''",[randomUUID(),clock()]);
return {ok:true,scopeVersion:b.scopeVersion+1,permissionsChanged:!!db.organisationAccessEnabled,nativeSyncPending:!!db.organisationAccessEnabled,enforcement:db.organisationAccessEnabled?'active':'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;
}
};
}