Add audited staff assignments and central policy mapping editor
This commit is contained in:
parent
95b18e8279
commit
396d2f3e2e
11 changed files with 408 additions and 9 deletions
|
|
@ -5,3 +5,4 @@
|
|||
.migration-directory .md-tools{display:flex;align-items:end;flex-wrap:wrap;gap:12px;margin-bottom:18px}.migration-directory input,.migration-directory select{background:var(--md-bg);color:#f2e7c8;border:1px solid var(--md-line);border-radius:8px;padding:11px;min-width:0;max-width:100%;box-sizing:border-box}.migration-directory input[type=search]{flex:1 1 260px}.migration-directory .md-field{display:grid;gap:4px;flex:1 1 150px;color:var(--md-muted)}
|
||||
.migration-directory .md-table-wrap{overflow:auto;border:1px solid var(--md-line);border-radius:12px}.migration-directory .md-table{border-collapse:collapse;width:100%;table-layout:auto;background:var(--md-bg)}.migration-directory .md-table th{padding:12px;text-align:left;color:var(--md-gold);background:#244b39;font-size:12px;text-transform:uppercase;letter-spacing:.04em}.migration-directory .md-table td{padding:12px;border-top:1px solid #355741;vertical-align:middle;overflow-wrap:anywhere}.migration-directory .md-table tr:nth-child(even){background:#153528}.migration-directory .md-table td:first-child button{background:transparent;border:0;padding:0;text-align:left;font-weight:600}.migration-directory .md-table td:last-child{white-space:nowrap}.migration-directory .md-badge{display:inline-block;border:1px solid #778b61;border-radius:20px;padding:3px 10px;font-size:12px;color:#d7e9c9}
|
||||
.migration-directory .md-pager{display:flex;justify-content:end;align-items:center;gap:14px;margin-top:16px}.migration-directory .md-identity{display:flex;align-items:center;flex-wrap:wrap;gap:16px;margin:18px 0 22px;padding-bottom:20px;border-bottom:1px solid var(--md-line)}.migration-directory .md-identity img{object-fit:contain;border-radius:9px}.migration-directory .md-identity a{margin-left:auto}.migration-directory .md-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.migration-directory .md-box{border:1px solid var(--md-line);border-radius:12px;background:linear-gradient(130deg,#1d4230,#102b22);padding:20px;display:grid;gap:14px;margin-bottom:18px}.migration-directory .md-detail{display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px;padding:9px 0;border-bottom:1px solid #355741}.migration-directory .md-detail span{color:var(--md-muted)}.migration-directory .md-detail strong{overflow-wrap:anywhere}.migration-directory .md-assignment{border-left:3px solid #c7ad62;padding:8px 12px;background:#153326}.migration-directory .md-assignment strong{color:var(--md-gold)}.migration-directory .md-note{color:var(--md-muted);padding-top:12px}.migration-directory details{margin-top:12px}.migration-directory summary{color:var(--md-gold);cursor:pointer}.migration-directory .md-diagnostics{border-top:1px solid #476046;padding-top:16px}.migration-directory .md-diagnostics p{margin:12px 0}.migration-directory .md-status:empty{display:none}@media(max-width:850px){.migration-directory .md-grid{grid-template-columns:1fr}.migration-directory .md-table{min-width:650px}}
|
||||
.migration-directory .md-assignment-form{display:grid;gap:12px;margin-top:18px}.migration-directory textarea{font:inherit;background:#102b22;color:#f2e7c8;border:1px solid #66846b;border-radius:8px;padding:11px;box-sizing:border-box;width:100%}.migration-directory .md-policy-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px;margin-top:14px}.migration-directory .md-permission{display:flex;align-items:start;gap:10px;padding:10px;background:#153528;border-radius:8px;overflow-wrap:anywhere}.migration-directory .md-permission input{margin-top:5px}.migration-directory .md-permission strong{font-weight:500}.migration-directory .md-permission small{display:block}.migration-directory .md-permission[hidden]{display:none}@media(max-width:850px){.migration-directory .md-policy-grid{grid-template-columns:1fr}}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ const button=(label,action)=>{const b=element('button',label);b.type='button';b.
|
|||
const date=value=>value?new Date(Number(value)).toLocaleDateString('en-GB'):'Not recorded';
|
||||
const roleDescription=a=>a.assignments.map(x=>x.scopeLabel+' · '+x.roleLabel).join(' / ');
|
||||
async function request(path,signal){const r=await fetch(path,{credentials:'same-origin',cache:'no-store',signal});const data=await r.json().catch(()=>({}));if(!r.ok)throw Error(data.message||'Directory unavailable.');return data;}
|
||||
async function send(body){const r=await fetch('/api/admin/organisation/assignments',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const data=await r.json().catch(()=>({}));if(!r.ok)throw Error(data.message||'Assignment could not be saved.');return data;}
|
||||
|
||||
export function mountCitizenDirectory(host){
|
||||
const root=element('section',undefined,'migration-directory');
|
||||
|
|
@ -13,7 +14,7 @@ export function mountCitizenDirectory(host){
|
|||
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()));
|
||||
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:[]};
|
||||
let context='users',page=1,query='',filter='',department='',branch='',selected=null,tab='overview',disposed=false,controller,sequence=0,catalogue={departments:[]},assignmentData=null;
|
||||
let searchTimer;
|
||||
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;}
|
||||
|
|
@ -23,9 +24,47 @@ 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','Assignment editing and automatic source integration are the next migration batch. Existing rights have not been replaced.','md-note'));
|
||||
panel.append(element('p','The new assignment register is being prepared. Recorded changes do not replace existing permissions until migration activation.','md-note'));
|
||||
return panel;
|
||||
}
|
||||
function scopeVersion(a){return Number(assignmentData.versions.find(v=>v.scope_type===a.scopeType&&v.scope_key===a.scopeKey)?.version||1);}
|
||||
async function loadAssignments(panel){
|
||||
const target=selected.id;panel.append(element('p','Loading assignment controls…','md-muted'));
|
||||
try{
|
||||
const data=await request('/api/admin/organisation/assignments?userId='+encodeURIComponent(target),controller?.signal);
|
||||
if(disposed||selected?.id!==target||context!=='staff'||tab!=='assignments'||!panel.isConnected)return;
|
||||
assignmentData=data;selected.assignments=data.assignments;panel.replaceChildren(element('h3','Staff assignments'),element('p','Changes are audited in the new register. Live permission activation follows after the mapping is verified.','md-note'));
|
||||
const message=element('p','');message.setAttribute('role','status');
|
||||
for(const a of data.assignments){
|
||||
const row=element('div',undefined,'md-assignment');row.append(element('strong',a.roleLabel),element('p',a.scopeLabel),badge(a.source));
|
||||
if(a.editable){const revoke=button('Remove assignment',async()=>{
|
||||
const reason=prompt('Reason for removing '+a.roleLabel+' from '+selected.username+' (3–500 characters):');if(reason===null)return;
|
||||
if(!confirm('Remove '+a.roleLabel+' in '+a.scopeLabel+'?'))return;revoke.disabled=true;
|
||||
try{await send({action:'revoke',userId:target,assignmentId:a.id,version:a.version,scopeType:a.scopeType,scopeKey:a.scopeKey,role:a.role,scopeVersion:scopeVersion(a),reason});message.textContent='Assignment removal recorded.';await loadAssignments(panel);}catch(e){message.textContent=e.message;revoke.disabled=false;}
|
||||
});row.append(revoke);}else row.append(element('small',a.source==='manual'?'Outside your management scope.':'Automatic assignment — manage at its source.'));panel.append(row);
|
||||
}
|
||||
if(!data.assignments.length)panel.append(element('p','No new-model staff assignments recorded.','md-muted'));
|
||||
if(data.editable.length){
|
||||
const form=element('form',undefined,'md-assignment-form');const scope=element('select');scope.setAttribute('aria-label','Assignment scope');const role=element('select');role.setAttribute('aria-label','Role within scope');
|
||||
const unique=[...new Map(data.editable.map(s=>[s.type+':'+s.key,s])).values()];for(const s of unique){const o=element('option',s.label+' · '+s.type);o.value=s.type+':'+s.key;scope.append(o);}
|
||||
const updateRoles=()=>{role.replaceChildren();const[type,key]=scope.value.split(':');for(const s of data.editable.filter(s=>s.type===type&&s.key===key)){const o=element('option',s.role.replaceAll('_',' '));o.value=s.role;role.append(o);}};scope.onchange=updateRoles;updateRoles();
|
||||
const reason=element('textarea');reason.required=true;reason.minLength=3;reason.maxLength=500;reason.rows=2;reason.placeholder='Reason for the appointment';reason.setAttribute('aria-label','Reason for appointment');
|
||||
const save=button('Save assignment',()=>{});save.type='submit';
|
||||
for(const[label,input]of [['Department or branch',scope],['Role',role],['Reason',reason]]){const wrap=element('label',label,'md-field');wrap.append(input);form.append(wrap);}form.append(save);
|
||||
form.onsubmit=async e=>{e.preventDefault();if(!form.reportValidity())return;const[type,key]=scope.value.split(':');if(!confirm('Record '+role.selectedOptions[0].textContent+' for '+selected.username+'?'))return;save.disabled=true;
|
||||
try{await send({action:'assign',userId:target,scopeType:type,scopeKey:key,role:role.value,scopeVersion:scopeVersion({scopeType:type,scopeKey:key}),reason:reason.value});await loadAssignments(panel);status.textContent='Assignment recorded; current live permissions remain unchanged.';}catch(error){message.textContent=error.message;save.disabled=false;}
|
||||
};panel.append(form);
|
||||
}else panel.append(element('p','You have no assignment-management authority in this register.','md-muted'));
|
||||
panel.append(message);
|
||||
}catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.append(element('p',e.message,'md-note'));}
|
||||
}
|
||||
async function loadActivity(panel){
|
||||
const target=selected.id,currentContext=context;
|
||||
try{const data=await request('/api/admin/organisation/activity?userId='+encodeURIComponent(target)+'&context='+context,controller?.signal);if(disposed||selected?.id!==target||context!==currentContext||tab!=='activity'||!panel.isConnected)return;
|
||||
if(!data.events.length)panel.append(element('p','No changes recorded in the new management register. Older account history remains preserved.','md-muted'));
|
||||
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'));}
|
||||
}
|
||||
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';
|
||||
|
|
@ -37,13 +76,14 @@ export function mountCitizenDirectory(host){
|
|||
if(context==='staff'&&selected.staffSources?.length){const source=box('Imported staff record');for(const row of selected.staffSources)source.append(detail('Source account',row.name),detail('Imported',date(row.importedAt)));source.append(element('p','Imported identity is evidence of the staff cohort, not a new permission grant.','md-muted'));view.append(source);}
|
||||
}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')view.append(assignments());
|
||||
}else if(tab==='assignments'){const panel=assignments();view.append(panel);if(context==='staff')void loadAssignments(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');panel.append(element('p','The audited assignment timeline will be connected with assignment editing. No historical account records have been removed.','md-muted'));view.append(panel);}
|
||||
else{const panel=box('Account activity');view.append(panel);void loadActivity(panel);}
|
||||
}
|
||||
function renderList(data){
|
||||
const restoreSearch=document.activeElement===view.querySelector('input[type="search"]');
|
||||
view.replaceChildren();heading();const nav=element('nav',undefined,'md-tabs');nav.setAttribute('aria-label','Directory type');for(const[key,label]of [['users','Users'],['staff','Staff']]){const b=button(label,()=>{if(context===key)return;context=key;page=1;department='';branch='';void load();});b.setAttribute('aria-current',String(context===key));nav.append(b);}view.append(nav);
|
||||
if(context==='staff')nav.append(button('Add staff member',()=>pickCandidate()));
|
||||
const toolbar=element('form',undefined,'md-tools');const search=element('input');search.type='search';search.value=query;search.placeholder='Name, Minecraft UUID or account ID';search.setAttribute('aria-label','Search all directory records');search.oninput=()=>{query=search.value;clearTimeout(searchTimer);searchTimer=setTimeout(()=>{page=1;void load();},350);};
|
||||
toolbar.onsubmit=e=>{e.preventDefault();clearTimeout(searchTimer);page=1;void load();};toolbar.append(search,choices('Status',[['','All statuses'],['active','Active'],['banned','Banned'],['deleted','Deleted']],filter,value=>{filter=value;page=1;void load();}));
|
||||
if(context==='staff'){
|
||||
|
|
@ -58,6 +98,13 @@ export function mountCitizenDirectory(host){
|
|||
const pager=element('div',undefined,'md-pager'),previous=button('Previous',()=>{page--;void load();}),next=button('Next',()=>{page++;void load();});previous.disabled=page===1;next.disabled=!data.hasMore;pager.append(previous,element('span','Page '+page),next);view.append(pager);
|
||||
if(context==='staff'&&(department||branch))view.append(element('p','Department and branch filters use new-model assignments. Imported accounts appear in All staff until their assignments are migrated.','md-note'));
|
||||
}
|
||||
function pickCandidate(){
|
||||
view.replaceChildren(button('← Staff Directory',()=>load()));const panel=box('Find a citizen to appoint'),form=element('form',undefined,'md-tools'),input=element('input'),find=button('Find citizen',()=>{}),results=element('div');input.type='search';input.required=true;input.minLength=3;input.maxLength=80;input.placeholder='Username or Minecraft identity';input.setAttribute('aria-label','Find a staff candidate');find.type='submit';form.append(input,find);panel.append(form,results);view.append(panel);
|
||||
form.onsubmit=async e=>{e.preventDefault();if(!form.reportValidity())return;find.disabled=true;results.replaceChildren(element('p','Finding citizens…'));
|
||||
try{const data=await request(API+'?context=users&q='+encodeURIComponent(input.value),controller?.signal);if(!panel.isConnected||disposed)return;results.replaceChildren();for(const account of data.accounts.filter(a=>a.status==='active')){const row=element('div',undefined,'md-detail');row.append(element('span',account.displayName+' · '+account.username),button('Manage staff assignments',async()=>{await open(account.id);if(selected?.id===account.id){tab='assignments';renderAccount();}}));results.append(row);}if(!results.children.length)results.append(element('p','No active citizens found.'));if(data.hasMore)results.append(element('p','Refine the name to narrow the results.','md-note'));}
|
||||
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;}}}
|
||||
void load();return()=>{disposed=true;sequence++;clearTimeout(searchTimer);controller?.abort();root.remove();};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,33 @@
|
|||
import {applyShellHeading} from './cp-v2-page-template.mjs';
|
||||
const el=(tag,value,cls)=>{const e=document.createElement(tag);if(value!==undefined)e.textContent=value;if(cls)e.className=cls;return e;};
|
||||
const roleNames={owner_ceo:'Owner & CEO',executive:'Executive',department_head:'Department Head',branch_lead:'Branch Lead',officer:'Officer'};
|
||||
const roles={organisation:['owner_ceo','executive'],department:['department_head'],branch:['branch_lead','officer']};
|
||||
const API='/api/admin/organisation/policies';
|
||||
export function mountOrganisationPermissions(host){
|
||||
let disposed=false,data,selection='branch:news_media',role='officer',dirty=false,busy=false;const controller=new AbortController();
|
||||
const root=el('section',undefined,'migration-directory');const css=el('link');css.rel='stylesheet';css.href='/v2/citizen-directory.css';
|
||||
const status=el('p','Loading the central permission matrix…');status.setAttribute('role','status');const content=el('div');root.append(css,status,content);host.replaceChildren(root);
|
||||
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'));
|
||||
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;
|
||||
const choose=callback=>{if(busy)return;if(dirty&&!confirm('Discard unsaved mapping changes?'))return;dirty=false;callback();render();};scopes.onchange=()=>choose(()=>{selection=scopes.value;});ranks.onchange=()=>choose(()=>{role=ranks.value;});tools.append(scopes,ranks);content.append(tools);
|
||||
const policy=data.policies.find(p=>p.scope_type===type&&p.scope_key===key&&p.role_key===role),chosen=new Set(policy?.nodes||[]);
|
||||
const heading=el('h3',roleNames[role]+' · '+data.scopes.find(s=>s.type===type&&s.key===key).label);content.append(heading);
|
||||
const search=el('input');search.type='search';search.placeholder='Find existing permission';search.setAttribute('aria-label','Filter permission catalogue');const assignedOnly=el('input');assignedOnly.type='checkbox';const assignedLabel=el('label','Show assigned only');assignedLabel.prepend(assignedOnly);const filters=el('div',undefined,'md-tools');filters.append(search,assignedLabel);content.append(filters);
|
||||
const matrix=el('div',undefined,'md-policy-grid');
|
||||
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;}
|
||||
};
|
||||
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);
|
||||
}
|
||||
async function load(){try{data=await api();if(disposed)return;render();status.textContent='';}catch(e){if(!disposed&&e.name!=='AbortError')status.textContent=e.message;}}
|
||||
void load();return()=>{disposed=true;controller.abort();root.remove();};
|
||||
}
|
||||
|
|
@ -206,6 +206,7 @@ if(w.id==='bureau'&&item.id==='user-management'){
|
|||
history.replaceState(null,'','#'+w.id+'/'+item.id);
|
||||
return;
|
||||
}
|
||||
if(w.id==='bureau'&&item.id==='permissions'&&new URL(location.href).searchParams.get('migration')==='1'){const host=el('div','citizen-live-host');overview.append(host);import('/v2/organisation-permissions.mjs').then(({mountOrganisationPermissions})=>{if(host.isConnected)disposePage=mountOrganisationPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent=error.message});history.replaceState(null,'','#bureau/permissions');return;}
|
||||
if(w.id==='bureau'&&item.id==='permissions'){const host=el('div','citizen-live-host');overview.append(host);host.append(el('p','alpha-muted','Loading Imperial Permissions…'));import('/v2/imperial-permissions.mjs?v=rankdelete-20261112a').then(({mountImperialPermissions})=>{if(host.isConnected)mountImperialPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent='Imperial Permissions unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;}
|
||||
if(w.id==='bureau'&&item.id==='manual-seals'){const host=el('div','citizen-live-host');overview.append(host);host.append(el('p','alpha-muted','Loading Honours & Seals…'));import('/v2/honours-seals.mjs?v=sealupload-20261112a').then(({mountHonoursSeals})=>{if(host.isConnected)mountHonoursSeals(host)}).catch(error=>{if(host.isConnected)host.textContent='Honours & Seals unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;}
|
||||
if(w.id==='bureau'&&['company-management','company-management-v2','company-audit','staff-bank','server-kits','kit-publishing','kit-claims','exchange-admin','shop-admin','items','website-posts','staff-tickets','bans','ban-evidence','forum-admin','quests-admin','community-goals','support-management','server-operations','hosting-control','dev-approvals'].includes(item.id)){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-bureau-pages.mjs?v=bureau-registers-20261112c').then(({mountBureauPlaceholder})=>{if(host.isConnected)disposePage=mountBureauPlaceholder(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Bureau page unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;}
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ import {initializeStaffBureau} from '../node/staff-bureau-schema.mjs';
|
|||
import {createStaffBureauReadApi} from '../node/staff-bureau-read-api.mjs';
|
||||
import {initializeOrganisation} from '../node/organisation-model.mjs';
|
||||
import {createCitizenDirectory} from '../node/citizen-directory.mjs';
|
||||
import {createOrganisationManagement} from '../node/organisation-management.mjs';
|
||||
import {initializeRanks,initializeCommunityAccess,initializeQuestAccess,initializeBankAccess,can,accessFor} from '../node/permissions.mjs';
|
||||
import {createServer} from 'node:http';
|
||||
import {createV1PersonalBank} from './api-v1-personal-bank.mjs';
|
||||
|
|
@ -108,6 +109,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
const manual=createStaffManual(db);
|
||||
const staffBureauRead=createStaffBureauReadApi(db);
|
||||
const citizenDirectory=createCitizenDirectory(db);
|
||||
const organisationManagement=createOrganisationManagement(db,{origin});
|
||||
const luckperms=createLuckPerms(db,settings,dependencies.luckperms);
|
||||
const servers=createServerControl(db,settings,dependencies.serverControl);
|
||||
const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}};
|
||||
|
|
@ -159,6 +161,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(path==='/api/politics/preview')return politicsPreview(request);
|
||||
if(path==='/api/admin/register-user')return adminRegistration(request);
|
||||
if(path==='/api/admin/citizens'||path.startsWith('/api/admin/citizens/'))return citizenDirectory(request);
|
||||
if(path.startsWith('/api/admin/organisation/'))return organisationManagement(request);
|
||||
if(path==='/api/account/email')return contactEmail(request);
|
||||
if(path.startsWith('/api/people/'))return memberProfiles(request);
|
||||
if(path==='/profile-login'&&request.method==='GET'){
|
||||
|
|
@ -248,7 +251,7 @@ export function createPanel(db,settings={},dependencies={}){
|
|||
if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});}
|
||||
if(path==='/federal-reserve'||path==='/federal-reserve/')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/reserve-ledger.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}});
|
||||
// V2 shell is public; private data and writes retain their authenticated API gates.
|
||||
if(['/v2/citizen-directory.mjs','/v2/citizen-directory.css'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice('/v2/'.length),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
|
||||
if(['/v2/citizen-directory.mjs','/v2/citizen-directory.css','/v2/organisation-permissions.mjs'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice('/v2/'.length),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
|
||||
if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-authorisations.mjs','/v2/cp-v2-tax-treasury.mjs','/v2/cp-v2-reserve-ledger.mjs','/v2/cp-v2-reserve-entry.mjs','/v2/cp-v2-postbank-credit.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){
|
||||
const moduleFile=path.endsWith('.mjs')||path.endsWith('.js');
|
||||
const file=path.endsWith('.mjs')?path.slice('/v2/'.length):path.endsWith('.js')?'v2.js':path.endsWith('.css')?'v2.css':'index.html';
|
||||
|
|
|
|||
|
|
@ -20,9 +20,8 @@ Included:
|
|||
and staff provenance. Staff views retain imported source identity for review.
|
||||
- Existing account administration and all live permissions remain unchanged.
|
||||
|
||||
Not claimed complete: assignment writes, permission activation/projection, native
|
||||
integration migration, the recognition editor and the audit timeline. Their UI
|
||||
states are explicitly marked as subsequent batches. Existing memberships have not
|
||||
Not claimed complete in batch 1: assignment writes, permission activation/projection,
|
||||
native integration migration, the recognition editor and the audit timeline. Existing memberships have not
|
||||
yet been imported into `org_assignments`; an empty new-model list is not a claim
|
||||
that the citizen has no memberships in existing systems.
|
||||
|
||||
|
|
@ -55,3 +54,43 @@ derived rights/seals must follow their lifecycle. Earned honours remain intact.
|
|||
6. Access/lifecycle/privacy verification, release and combined .6/.7 announcement.
|
||||
|
||||
Do not change the public version banner or publish release news before .7 is done.
|
||||
|
||||
## Batch 2: audited assignment editor and policy preparation
|
||||
|
||||
Staff assignments can be recorded and revoked within the manager's scope. One
|
||||
lead per branch/department is enforced under a shared scope lock. A scope version
|
||||
prevents stale forms from overwriting another manager's work. Automatic records
|
||||
must be changed at their source. Service accounts stay outside human appointments.
|
||||
|
||||
The permission matrix at `?migration=1#bureau/permissions` maps registered existing
|
||||
nodes to each function. It rejects wildcard/OP/native-editor nodes and official
|
||||
bank management on ordinary branch roles. Policy writes and assignments share
|
||||
atomic audit and version checks. These are preparatory records: they do not yet
|
||||
replace live roles. No native backend code is rewritten.
|
||||
|
||||
An explicit operator-run `scripts/bootstrap-organisation-control.mjs --apply`
|
||||
pins the existing Big Four and Dev service by account ID for management authority.
|
||||
It is idempotent, checks the established Owner/Dev identities, refuses conflicting
|
||||
existing principals and does not run at application startup. Its audit clearly
|
||||
states that it does not activate live permission projection.
|
||||
|
||||
## Additional Owner-approved bank work
|
||||
|
||||
After the current management batch, add a staff Client Management context reusing
|
||||
Accounts & Payments components without generic Wire Transfers.
|
||||
|
||||
Add immediate Service Compensation from Payment Control, linked to the original
|
||||
posted payment, with reason, consent, actual actor and a distinct purple type
|
||||
badge in staff/customer histories and statements. Recover funds from the original
|
||||
recipient when possible; otherwise the bank bears the cost. Never erase the
|
||||
original payment or compensate its value more than once across retries/partials.
|
||||
|
||||
The shared budget is the available balance of a dedicated Compensation Reserve.
|
||||
A monthly standing instruction funds it from Website Bank Treasury, initially
|
||||
25,000 DM; unspent funds roll forward. Big Four and the bank CEO may change that
|
||||
standing instruction and transfer reserve funds in/out through Treasury Accounts.
|
||||
No extra Officer cap/counter, CEO override system, support ticket, approval flow,
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -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)};
|
||||
|
|
|
|||
126
website/node/organisation-management.mjs
Normal file
126
website/node/organisation-management.mjs
Normal 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)&¤t.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;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
28
website/scripts/bootstrap-organisation-control.mjs
Normal file
28
website/scripts/bootstrap-organisation-control.mjs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
// One-time, explicit Owner-authorised control baseline. Does not activate role grants.
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {resolve} from 'node:path';
|
||||
import {openDatabase} from '../node/mysql.mjs';
|
||||
import {initializeOrganisation} from '../node/organisation-model.mjs';
|
||||
const OWNER_ID='f3ffda37-01e4-41ea-b89d-fbeda82e453e';
|
||||
const SERVICE_ID='f7b88778-f0bc-41cc-9227-d8ef2f52264d';
|
||||
const desired={unimatrix999:'owner',grmacken:'executive',richwjr:'executive',mr_blueray:'executive',dev:'service'};
|
||||
export async function bootstrapControl(db,{apply=false}={}){
|
||||
const rows=(await db.prepare(`SELECT id,username,role FROM site_accounts WHERE username IN (${Object.keys(desired).map(()=>'?')}) AND password_hash NOT LIKE '!%'`).bind(...Object.keys(desired)).all()).results;
|
||||
if(rows.length!==5||new Set(rows.map(r=>r.username)).size!==5||rows.find(r=>r.username==='unimatrix999')?.id!==OWNER_ID||rows.find(r=>r.username==='dev')?.id!==SERVICE_ID)throw Error('Expected existing control identities do not match.');
|
||||
const policy=await db.prepare('SELECT service_uuid,game_link_exempt FROM site_account_policies WHERE user_id=?').bind(SERVICE_ID).first();
|
||||
if(!policy?.game_link_exempt||policy.service_uuid!=='00000000-0000-4000-8000-00000000de01')throw Error('Dev service exemption mismatch.');
|
||||
const plan=rows.map(r=>({id:r.id,username:r.username,kind:desired[r.username]}));if(!apply)return {applied:false,principals:plan};
|
||||
await db.transaction(async tx=>{
|
||||
for(const p of plan){
|
||||
const existing=await tx.first('SELECT principal_kind FROM org_control_principals WHERE user_id=? FOR UPDATE',[p.id]);
|
||||
if(existing){if(existing.principal_kind!==p.kind)throw Error('Existing control assignment differs; never overwrite automatically.');continue;}
|
||||
const account=await tx.first("SELECT id,username FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' FOR SHARE",[p.id]);if(account?.username!==p.username)throw Error('Identity changed during bootstrap.');
|
||||
const now=Date.now();await tx.query('INSERT INTO org_control_principals(user_id,principal_kind,created_by,created_at) VALUES(?,?,?,?)',[p.id,p.kind,OWNER_ID,now]);
|
||||
await tx.query('INSERT INTO org_assignment_events(id,user_id,actor_id,action,scope_type,scope_key,reason,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[randomUUID(),p.id,OWNER_ID,'control-baseline','organisation','dunerealms','Owner-approved existing Big Four and Dev service control baseline',JSON.stringify({principal:p.kind,livePermissionsChanged:false}),now]);
|
||||
}
|
||||
});return {applied:true,principals:plan,livePermissionsChanged:false};
|
||||
}
|
||||
if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){
|
||||
const db=await openDatabase(process.env);try{await initializeOrganisation(db);console.log(JSON.stringify(await bootstrapControl(db,{apply:process.argv.includes('--apply')})));}finally{await db.close();}
|
||||
}
|
||||
86
website/tests/organisation-management.test.mjs
Normal file
86
website/tests/organisation-management.test.mjs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {canAssignRole,validatePolicyNodes,createOrganisationManagement} from '../node/organisation-management.mjs';
|
||||
import {bootstrapControl} from '../scripts/bootstrap-organisation-control.mjs';
|
||||
const owner='11111111-1111-4111-8111-111111111111',target='22222222-2222-4222-8222-222222222222';
|
||||
const position=(scope_type,scope_key,role_key)=>({scope_type,scope_key,role_key,status:'active'});
|
||||
test('branch and department managers cannot escalate outside their own scope',()=>{
|
||||
const head={assignments:[position('department','community_operations','department_head')]};
|
||||
assert.equal(canAssignRole(head,'branch','customer_support','branch_lead'),true);
|
||||
assert.equal(canAssignRole(head,'branch','engineering','officer'),false);
|
||||
assert.equal(canAssignRole(head,'department','community_operations','department_head'),false);
|
||||
const lead={assignments:[position('branch','news_media','branch_lead')]};
|
||||
assert.equal(canAssignRole(lead,'branch','news_media','officer'),true);assert.equal(canAssignRole(lead,'branch','news_media','branch_lead'),false);assert.equal(canAssignRole(lead,'branch','customer_support','officer'),false);
|
||||
assert.equal(canAssignRole({assignments:[position('branch','news_media','officer')]},'branch','news_media','officer'),false);
|
||||
});
|
||||
test('Big Four and service control are organisation-wide; Owner office stays protected',()=>{
|
||||
for(const principal of ['owner','executive','service']){const auth={principal,assignments:[]};assert.equal(canAssignRole(auth,'organisation','dunerealms','executive'),true);assert.equal(canAssignRole(auth,'branch','engineering','branch_lead'),true);assert.equal(canAssignRole(auth,'organisation','dunerealms','owner_ceo'),false);assert.equal(canAssignRole(auth,'branch','invented','officer'),false);}
|
||||
});
|
||||
test('policy mapping rejects native editors, unregistered permissions and excessive bank power',()=>{
|
||||
assert.throws(()=>validatePolicyNodes(['*'],'organisation','executive'));
|
||||
assert.throws(()=>validatePolicyNodes(['web.luckperms.edit'],'organisation','executive'));
|
||||
assert.throws(()=>validatePolicyNodes(['web.bank.staff.manage'],'branch','officer'));
|
||||
assert.deepEqual(validatePolicyNodes(['web.bank.staff.manage'],'department','department_head'),['web.bank.staff.manage']);
|
||||
assert.deepEqual(validatePolicyNodes(['web.posts.view','web.posts.view'],'branch','officer'),['web.posts.view']);
|
||||
});
|
||||
function fixture({principal='owner',positions=[],scopeVersion=1,current=[],existing=null,service=false,authenticated=true,allowed=true,auditFail=false,dbError=null}={}){
|
||||
const writes=[];
|
||||
const tx={async first(sql,args){
|
||||
if(sql.includes('SELECT a.id,p.game_link_exempt'))return {id:target,game_link_exempt:service?1:0};
|
||||
if(sql.includes('FROM site_accounts'))return {id:owner};
|
||||
if(sql.includes('FROM org_control_principals'))return principal?{principal_kind:principal}:null;
|
||||
if(sql.includes('FROM org_scope_versions'))return {version:scopeVersion};
|
||||
if(sql.includes('SELECT * FROM org_assignments'))return existing;
|
||||
if(sql.includes('FROM org_role_policies'))return null;
|
||||
throw Error('Unexpected SQL: '+sql);
|
||||
},async query(sql,args){
|
||||
if(sql.startsWith('SELECT scope_type'))return positions;
|
||||
if(sql.startsWith('SELECT id,user_id,role_key'))return current;
|
||||
if(auditFail&&sql.includes('INSERT INTO org_assignment_events'))throw Error('audit unavailable');
|
||||
writes.push({sql,args});return [];
|
||||
}};
|
||||
const db={async transaction(fn){if(dbError)throw Object.assign(new Error('Concurrent transaction'),{code:dbError});const start=writes.length;try{return await fn(tx);}catch(e){writes.splice(start);throw e;}},prepare(){return {bind(){return this;},all:async()=>({results:[]})};}};
|
||||
const api=createOrganisationManagement(db,{authenticate:async()=>authenticated?{id:owner}:null,authorize:async()=>allowed,clock:()=>100});return {api,writes};
|
||||
}
|
||||
const body=(extra={})=>({action:'assign',userId:target,scopeType:'branch',scopeKey:'news_media',role:'officer',scopeVersion:1,reason:'Approved appointment',...extra});
|
||||
const request=(data,options={})=>new Request('https://cp.dunerealms.com/api/admin/organisation/'+(options.policy?'policies':'assignments'),{method:'POST',headers:{'Origin':options.origin||'https://cp.dunerealms.com','Content-Type':'application/json'},body:JSON.stringify(data)});
|
||||
test('assignment creates an audited register record without activating live permissions',async()=>{
|
||||
const f=fixture();const r=await f.api(request(body()));assert.equal(r.status,200);const result=await r.json();assert.equal(result.permissionsChanged,false);assert.equal(result.scopeVersion,2);
|
||||
assert.ok(f.writes.some(w=>w.sql.startsWith('INSERT INTO org_assignments')));assert.ok(f.writes.some(w=>w.sql.startsWith('INSERT INTO org_assignment_events')));assert.ok(f.writes.every(w=>!w.sql.includes('cp_account_ranks')&&!w.sql.includes('UPDATE site_accounts')));
|
||||
});
|
||||
test('fresh transaction authority defeats stale or missing scope grants',async()=>{
|
||||
const f=fixture({principal:null});assert.equal((await f.api(request(body()))).status,403);assert.equal(f.writes.length,0);
|
||||
const scoped=fixture({principal:null,positions:[position('branch','customer_support','branch_lead')]});assert.equal((await scoped.api(request(body()))).status,403);
|
||||
});
|
||||
test('stale versions, duplicates and a second lead roll back completely',async()=>{
|
||||
for(const [options,b]of [[{scopeVersion:2},body()],[{current:[{user_id:target,role_key:'officer'}]},body()],[{current:[{user_id:owner,role_key:'branch_lead'}]},body({role:'branch_lead'})]]){const f=fixture(options);assert.equal((await f.api(request(b))).status,409);assert.equal(f.writes.length,0);}
|
||||
});
|
||||
test('automatic assignments cannot be revoked from the manual editor',async()=>{
|
||||
const id='33333333-3333-4333-8333-333333333333';const f=fixture({existing:{id,user_id:target,scope_type:'branch',scope_key:'news_media',role_key:'officer',source_kind:'system',status:'active',version:1}});
|
||||
assert.equal((await f.api(request(body({action:'revoke',assignmentId:id,version:1})))).status,403);assert.equal(f.writes.length,0);
|
||||
});
|
||||
test('service identities stay outside staff appointments and cross-origin writes are denied',async()=>{
|
||||
const f=fixture({service:true});assert.equal((await f.api(request(body()))).status,403);assert.equal(f.writes.length,0);
|
||||
const g=fixture();assert.equal((await g.api(request(body(),{origin:'https://evil.example'}))).status,403);assert.equal(g.writes.length,0);
|
||||
});
|
||||
test('denials and forged request metadata never write to the register',async()=>{
|
||||
for(const [options,status]of [[{authenticated:false},401],[{allowed:false},403]]){const f=fixture(options);assert.equal((await f.api(request(body()))).status,status);assert.equal(f.writes.length,0);}
|
||||
for(const b of [body({source:'election'}),body({reason:' '}),body({userId:'wrong'}),body({scopeVersion:0})]){const f=fixture();assert.equal((await f.api(request(b))).status,400);assert.equal(f.writes.length,0);}
|
||||
});
|
||||
test('audit failure prevents a partial assignment commit',async()=>{
|
||||
const f=fixture({auditFail:true});await assert.rejects(()=>f.api(request(body())),/audit unavailable/);assert.equal(f.writes.length,0);
|
||||
});
|
||||
test('policy changes share the scope version and record their exact node set',async()=>{
|
||||
const f=fixture({principal:'executive'});const {action,userId,...b}=body({nodes:['web.posts.view']});const r=await f.api(request(b,{policy:true}));assert.equal(r.status,200);assert.ok(f.writes.some(w=>w.sql.includes('INSERT INTO org_role_policies')));assert.ok(f.writes.some(w=>w.sql.includes('INSERT INTO org_assignment_events')));
|
||||
});
|
||||
test('database lock races are reported as refreshable conflicts, never partial success',async()=>{
|
||||
for(const dbError of ['ER_LOCK_DEADLOCK','ER_LOCK_WAIT_TIMEOUT']){const f=fixture({dbError});const r=await f.api(request(body()));assert.equal(r.status,409);assert.equal(f.writes.length,0);assert.match((await r.json()).message,/Refresh/);}
|
||||
});
|
||||
test('control bootstrap pins existing identities, is idempotent and rejects conflicting principals',async()=>{
|
||||
const rows=[['unimatrix999','f3ffda37-01e4-41ea-b89d-fbeda82e453e'],['dev','f7b88778-f0bc-41cc-9227-d8ef2f52264d'],['grmacken',owner],['richwjr',target],['mr_blueray','33333333-3333-4333-8333-333333333333']].map(([username,id])=>({username,id}));
|
||||
let commits=0;const principals=new Map();
|
||||
const db={prepare(sql){return{bind(){return this;},async all(){return{results:rows};},async first(){return{game_link_exempt:1,service_uuid:'00000000-0000-4000-8000-00000000de01'};}};},async transaction(work){return work({async first(sql,args){if(sql.includes('org_control_principals'))return principals.has(args[0])?{principal_kind:principals.get(args[0])}:null;return rows.find(r=>r.id===args[0]);},async query(sql,args){if(sql.startsWith('INSERT INTO org_control_principals')){principals.set(args[0],args[1]);commits++;}}});}};
|
||||
assert.equal((await bootstrapControl(db)).applied,false);assert.equal(commits,0);
|
||||
await bootstrapControl(db,{apply:true});await bootstrapControl(db,{apply:true});assert.equal(commits,5);
|
||||
principals.set(owner,'owner');await assert.rejects(()=>bootstrapControl(db,{apply:true}),/differs/);
|
||||
rows[0].id=target;await assert.rejects(()=>bootstrapControl(db),/identities/);
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff