Build the new public staff directory and audited Great Migration appointments

This commit is contained in:
unimatrixgit 2026-11-15 02:31:58 +01:00
commit fc9549ee71
25 changed files with 181 additions and 29 deletions

View file

@ -33,7 +33,7 @@ export function mountCitizenDirectory(host){
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'));
assignmentData=data;selected.assignments=data.assignments;panel.replaceChildren(element('h3','Staff assignments'),element('p',data.enforcement==='active'?'Function changes update central access and queue native synchronisation.':'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));
@ -52,7 +52,7 @@ export function mountCitizenDirectory(host){
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;}
try{const result=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=result.permissionsChanged?'Function assigned. Central access updated; native synchronisation queued.':'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);

File diff suppressed because one or more lines are too long

View file

@ -102,3 +102,5 @@ Default policies now enumerate 22 function mappings (nine branches with Officer/
Runtime integration: ORGANISATION_ACCESS_ENABLED=true opts the central database adapter into fresh, read-snapshot organisation access. The default remains disabled. Enabled accessFor replaces legacy staff/owner bypass with new explicit policies, preserves ordinary/VIP/Order membership, and keeps only the pinned exempt Dev service on its existing access path. Invalid policy data fails closed, never falls back to old admin grants. This switch must not be enabled before control baseline, assignments, policy coverage and native projections are reconciled. This source batch does not enable it in production. Public session exports the account's own active functions.
Native bridge integration: activated game sync sends stable permission-set groups through the existing revision-confirmed /permissions/teams bridge. Explicit canonical game nodes plus retained citizen gameplay perks are combined; wildcard/OP/LuckPerms editor grants and service identities are excluded. Duplicate verified UUIDs abort the projection. Unactivated game sync stays on its existing path. Native agent sync reuses the installed osTicket adapter and maps ticket department tags; active human payloads omit native administration flags while retaining business department access. Dev service payload is unchanged. No game server or native application code is rewritten or deployed by this source batch.
Approved appointments and public staff page: the migration plan resolves 14 existing people into 26 current functions, validates the existing Owner identity and rejects service accounts or conflicting leaders. It defaults to dry-run; explicit application is audited and idempotent. The redesigned staff.html uses the public publication allowlist, one biography card per person, an organigram with explicit vacancies and a separate Crysknife Order gallery. Canonical profile links are retained for Bedrock display names. Active function changes now atomically queue the existing native synchronization outbox; the public process starts its retry worker only in active mode. Forum SSO filters native privilege administration for central human identities while retaining the Dev service path. Existing native products are reused.

View file

@ -5,4 +5,4 @@ export const protectedStaffRanks=ranks=>Array.isArray(ranks)&&ranks.some(isOwner
export function gameStaffSeals(ranks=[]){return [...GAME_STAFF_SEALS,...RECOGNITION.roles].filter(seal=>ranks.includes(seal.rank)||protectedStaffRanks(ranks));}
export function managedRoleSeals(ranks=[]){return [...(ranks.includes('web_streamer')||protectedStaffRanks(ranks)?['rank-streamer']:[]),...(ranks.includes('web_dev')||protectedStaffRanks(ranks)?['rank-dev']:[]),...(ranks.includes('crysknife')?['rank-crysknife']:[]),...gameStaffSeals(ranks).map(s=>s.key)];}
export function currentStaffRanks(ranks=[]){return ranks.some(key=>DEFAULT_RANKS.some(r=>r.key===key&&(key.startsWith('web_')||key.startsWith('game_')||['staff','corestaff','owners','official_account','network_admin'].includes(key))));}
export function currentStaffRanks(ranks=[]){return ranks.some(key=>['org_owner_ceo','org_executive','org_department_head','org_branch_lead','org_officer'].includes(key)||DEFAULT_RANKS.some(r=>r.key===key&&(key.startsWith('web_')||key.startsWith('game_')||['staff','corestaff','owners','official_account','network_admin'].includes(key))));}

View file

@ -1,3 +1,4 @@
import {nativeAgentIdentity} from './organisation-native-projection.mjs';
import {communityBadgeVisible} from './community-badges.mjs';
import {publicProfileFor} from './profile.mjs';
import {badgesFor} from './community-badges.mjs';
@ -43,7 +44,8 @@ export function createIntegrationSSO(db,settings={}){
const access=await accessFor(db,user),link=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(user.id).first();
const age=await db.prepare('SELECT age_band FROM site_age_declarations WHERE user_id=?').bind(user.id).first();
const policy=await db.prepare('SELECT service_uuid,game_link_exempt FROM site_account_policies WHERE user_id=?').bind(user.id).first();
return json({id:user.id,username:user.username,displayName:user.display_name,publicProfile:await publicProfileFor(db,user.id,settings.CP_ORIGIN||'https://cp.dunerealms.com'),role:access.rank,ranks:access.ranks,rankLabel:access.label,rankLevel:access.level,communityBadges:(await badgesFor(db,user.id)).filter(k=>communityBadgeVisible(k,access.ranks)),linked:!!link?.minecraft_uuid,gameLinkExempt:!!policy?.service_uuid&&Number(policy.game_link_exempt)===1,forumAllowed:age?.age_band!=='under15',permissions:access.nodes,sessionRef});
const native=nativeAgentIdentity(user,access);
return json({id:user.id,username:user.username,displayName:user.display_name,publicProfile:await publicProfileFor(db,user.id,settings.CP_ORIGIN||'https://cp.dunerealms.com'),role:access.rank,ranks:access.ranks,rankLabel:access.label,rankLevel:access.level,communityBadges:(await badgesFor(db,user.id)).filter(k=>communityBadgeVisible(k,access.ranks)),linked:!!link?.minecraft_uuid,gameLinkExempt:!!policy?.service_uuid&&Number(policy.game_link_exempt)===1,forumAllowed:age?.age_band!=='under15',permissions:native.permissions,...(native.nativePermissionManagement===false?{nativePermissionManagement:false}:{}),sessionRef});
}
};
}

View file

@ -7,7 +7,7 @@ import{badgesFor,BADGES,communityBadgeVisible}from './community-badges.mjs';
export function visibleCommunityBadges(keys,ranks){return keys.filter(key=>BADGES.includes(key)&&ranks.length>0&&communityBadgeVisible(key,ranks));}
export function staffSealFor(account,manifest){
const ranks=Array.isArray(account.ranks)?account.ranks:[account.role];
const role=ranks.includes('owners')?'OWNER':ranks.includes('web_net_admin')?'MAINNETWORKADMIN':ranks.includes('corestaff')?'CORESTAFF':(ranks.includes('network_admin')||ranks.includes('network_admin'))?'NETWORKSTAFF':'';
const role=(ranks.includes('owners')||ranks.includes('org_owner_ceo'))?'OWNER':ranks.includes('web_net_admin')?'MAINNETWORKADMIN':ranks.includes('corestaff')?'CORESTAFF':(ranks.includes('network_admin')||ranks.includes('network_admin'))?'NETWORKSTAFF':'';
const named=kind=>Object.values(manifest).find(asset=>asset.role===kind&&asset.label?.toLowerCase()===account.username.toLowerCase())?.footer150||null;
if(role&&named(role))return named(role);
if(protectedStaffRanks(ranks)&&named('OWNER'))return named('OWNER');

View file

@ -3,11 +3,8 @@ import {existsSync} from 'node:fs';
import {syncNativeAgents} from './native-agents.mjs';
// One coalesced change event. Retrying this table never polls accounts or ranks.
export const NATIVE_SYNC_SCHEMA=`CREATE TABLE IF NOT EXISTS native_sync_outbox (
job_key VARCHAR(32) PRIMARY KEY, revision CHAR(36) NOT NULL, attempts INTEGER NOT NULL,
next_attempt_at BIGINT NOT NULL, lease_token CHAR(36) NOT NULL, lease_until BIGINT NOT NULL,
created_at BIGINT NOT NULL, last_error VARCHAR(80) NOT NULL
)`;
import {NATIVE_SYNC_SCHEMA} from './native-sync-schema.mjs';
export {NATIVE_SYNC_SCHEMA} from './native-sync-schema.mjs';
export async function initializeNativeSyncOutbox(db){await db.prepare(NATIVE_SYNC_SCHEMA).run();}
export function nativeSyncChange(db,now=Date.now()){
return db.prepare("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 CONFLICT(job_key) DO UPDATE SET revision=excluded.revision,attempts=0,next_attempt_at=0,created_at=excluded.created_at,last_error='' ").bind(randomUUID(),now);

View file

@ -0,0 +1,5 @@
export const NATIVE_SYNC_SCHEMA=`CREATE TABLE IF NOT EXISTS native_sync_outbox (
job_key VARCHAR(32) PRIMARY KEY, revision CHAR(36) NOT NULL, attempts INTEGER NOT NULL,
next_attempt_at BIGINT NOT NULL, lease_token CHAR(36) NOT NULL, lease_until BIGINT NOT NULL,
created_at BIGINT NOT NULL, last_error VARCHAR(80) NOT NULL
)`;

View file

@ -0,0 +1,22 @@
// Owner-approved migration roster. Names resolve existing identities; this catalogue grants nothing at request time.
export const MIGRATION_APPOINTMENTS=[
['unimatrix999','organisation','dunerealms','owner_ceo'],
...['grmacken','richwjr','mr_blueray'].map(user=>[user,'organisation','dunerealms','executive']),
['mr_blueray','department','community_operations','department_head'],
['richwjr','department','dunerealms_operations','department_head'],
['mr_blueray','branch','customer_support','branch_lead'],
['yooshi','branch','sales_accounts','branch_lead'],
['mr_blueray','branch','content_creative','branch_lead'],
['racoonvibz','branch','news_media','branch_lead'],
['richwjr','branch','trust_safety','branch_lead'],
['grmacken','branch','it_operations','branch_lead'],
['unimatrix999','branch','engineering','branch_lead'],
['grmacken','branch','people_operations','branch_lead'],
['unimatrix999','branch','legal_compliance','branch_lead'],
...['am_mk','larry7517'].map(user=>[user,'branch','customer_support','officer']),
['tyrario1703','branch','sales_accounts','officer'],
...['halobeau143','racoonvibz','the_game_lordyt'].map(user=>[user,'branch','content_creative','officer']),
['mustafaje','branch','news_media','officer'],
...['halobeau143','s_oio_s','bedrock_s73ffupk7hx','yooshi'].map(user=>[user,'branch','trust_safety','officer'])
].map(([username,scopeType,scopeKey,role])=>({username,scopeType,scopeKey,role}));
export const EXECUTIVE_TITLES={unimatrix999:'Owner & CEO',grmacken:'Chief Technology Officer',richwjr:'Chief Operating Officer',mr_blueray:'Chief Community Officer'};

View file

@ -33,7 +33,7 @@ export function defaultOrganisationPolicies(){
result.push({scopeType:'department',scopeKey:department.key,role:'department_head',nodes:unique(departmentNodes)});
}
// Enumerated catalogue snapshot, never '*' or OP. Native privilege editors stay Dev-only.
const executives=Object.keys(NODES).filter(n=>!['web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor'].includes(n)&&!/(^|\.)op($|\.)/.test(n));
const executives=Object.keys(NODES).filter(n=>!['web.forum.admin','web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor'].includes(n)&&!/(^|\.)op($|\.)/.test(n));
for(const role of ['owner_ceo','executive'])result.push({scopeType:'organisation',scopeKey:'dunerealms',role,nodes:unique(executives)});
for(const policy of result)validatePolicyNodes(policy.nodes,policy.scopeType,policy.role);
return result;

View file

@ -1,5 +1,5 @@
import {validStaffRole} from './organisation-model.mjs';
const nativeEditors=new Set(['web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor']);
const nativeEditors=new Set(['web.forum.admin','web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor']);
const officialBank=new Set(['web.bank.staff.manage','cp.bank.staff.manage','web.bank.staff.deposit','cp.bank.staff.deposit']);
// Pure preview: never changes legacy ranks or grants native product permissions.
export function effectiveOrganisationAccess({assignments,policies,registry,principalKind=null,now=Date.now()}){

View file

@ -19,7 +19,7 @@ export function canAssignRole(authority,scopeType,scopeKey,role){
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']);
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();
@ -58,11 +58,11 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c
if(!await authorize(db,actor,(policy||url.pathname.endsWith('/effective'))?'web.ranks.manage':'web.accounts.view'))return reply({message:'Central management permission required.'},403);
if(request.method==='GET'){
const auth=await readAuthority(actor.id);
if(url.pathname.endsWith('/authority'))return reply({editable:auth.editable,canEditPolicies:globalPrincipal(auth.principal),enforcement:'preparing'});
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:'preparing'});
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')){
@ -81,7 +81,7 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c
}
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'});
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);
@ -126,7 +126,8 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c
}
}
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'};
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);

View file

@ -1,3 +1,4 @@
import {NATIVE_SYNC_SCHEMA} from './native-sync-schema.mjs';
// Central assignment vocabulary. This catalogue never grants permissions by itself.
export const ORGANISATION = [
{key:'community_operations',label:'Community Operations',branches:[
@ -74,7 +75,7 @@ export const organisationSchema = [
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
];
export async function initializeOrganisation(db){
for(const sql of organisationSchema)await db.prepare(sql).run();
for(const sql of [...organisationSchema,NATIVE_SYNC_SCHEMA])await db.prepare(sql).run();
// No automatic appointments, account rewrites, rank resets or game grants.
}

View file

@ -1,4 +1,4 @@
const localPrivilegeEditors=new Set(['web.tickets.admin','web.luckperms.edit','cp.luckperms.edit']);
const localPrivilegeEditors=new Set(['web.forum.admin','web.tickets.admin','web.luckperms.edit','cp.luckperms.edit']);
export function nativeAgentIdentity(user,access){
const centralHuman=access.organisation?.mode==='active';
return {...user,role:access.rank,ranks:access.ranks,

View file

@ -0,0 +1,32 @@
import {ORGANISATION,assignmentLabel,validStaffRole} from './organisation-model.mjs';
import {EXECUTIVE_TITLES} from './organisation-appointments.mjs';
const weights={owner_ceo:100,executive:90,department_head:80,branch_lead:70,officer:50};
export function projectPublicOrganisation(rows,orderRows=[]){
const people=new Map();
for(const row of rows){
if(!validStaffRole(row.scope_type,row.scope_key,row.role_key)||row.game_link_exempt)continue;
let person=people.get(row.username);
if(!person){
const display=row.display_name||row.username;
const bedrock=typeof row.source_name==='string'&&row.source_name.startsWith('.')&&row.source_uuid===row.minecraft_uuid;
person={username:row.username,displayName:bedrock?display.replace(/^bedrock_/i,'').replace(/^\./,''):display,bio:row.bio||'',profile:'/people/'+encodeURIComponent(row.username),avatar:'https://cp.dunerealms.com/api/avatars/roster/'+encodeURIComponent(row.username),functions:[],seals:[],priority:0};people.set(row.username,person);
}
const f=assignmentLabel(row);
if(!person.functions.some(x=>x.scopeType===f.scopeType&&x.scopeKey===f.scopeKey&&x.role===f.role))person.functions.push({scopeType:f.scopeType,scopeKey:f.scopeKey,scopeLabel:f.scopeLabel,role:f.role,roleLabel:f.roleLabel});
person.priority=Math.max(person.priority,weights[row.role_key]||0);
if(row.scope_type==='organisation')person.title=EXECUTIVE_TITLES[row.username]||f.roleLabel;
}
const staff=[...people.values()].sort((a,b)=>b.priority-a.priority||a.displayName.localeCompare(b.displayName));
for(const p of staff){p.title||=p.functions.slice().sort((a,b)=>(weights[b.role]||0)-(weights[a.role]||0))[0].roleLabel;delete p.priority;}
const holders=(type,key,role)=>staff.filter(p=>p.functions.some(f=>f.scopeType===type&&f.scopeKey===key&&f.role===role)).map(p=>({username:p.username,displayName:p.displayName,title:p.title}));
const organisation=ORGANISATION.map(d=>({key:d.key,label:d.label,heads:holders('department',d.key,'department_head'),branches:d.branches.map(b=>({...b,leads:holders('branch',b.key,'branch_lead'),members:holders('branch',b.key,'officer')}))}));
const order=[...new Map(orderRows.map(r=>[r.username,{username:r.username,displayName:r.display_name||r.username,citation:r.citation||'',profile:r.slug?'/memorial/'+encodeURIComponent(r.slug):'/people/'+encodeURIComponent(r.username)}])).values()];
return {model:'organisation-v2',publishedOnly:true,executives:staff.filter(p=>p.functions.some(f=>f.scopeType==='organisation')).map(p=>({username:p.username,displayName:p.displayName,title:p.title})),organisation,staff,order};
}
export async function readPublicOrganisation(db){
return db.readSnapshot(async reader=>{
const rows=await reader.query("SELECT a.username,a.display_name,f.scope_type,f.scope_key,f.role_key,p.bio,g.minecraft_uuid,s.source_uuid,s.source_name,pol.game_link_exempt FROM staff_roster_publications r JOIN site_accounts a ON a.id=r.account_id JOIN org_assignments f ON f.user_id=a.id LEFT JOIN site_profiles p ON p.user_id=a.id LEFT JOIN site_game_links g ON g.user_id=a.id LEFT JOIN staff_source_members s ON s.user_id=a.id LEFT JOIN site_account_policies pol ON pol.user_id=a.id WHERE r.visible=1 AND a.password_hash NOT LIKE '!%' AND f.status='active' AND f.starts_at<=? AND (f.ends_at IS NULL OR f.ends_at>?) ORDER BY a.username,f.scope_type,f.scope_key LIMIT 2000",[Date.now(),Date.now()]);
const order=await reader.query("SELECT a.username,a.display_name,h.citation,m.slug FROM site_accounts a LEFT JOIN site_honours h ON h.user_id=a.id AND h.rank_key='crysknife' LEFT JOIN site_memorials m ON m.user_id=a.id WHERE (a.password_hash NOT LIKE '!%' OR a.password_hash='!memorial') AND a.role<>'official_account' AND (a.role='crysknife' OR EXISTS (SELECT 1 FROM cp_account_ranks r WHERE r.user_id=a.id AND r.rank_key='crysknife')) ORDER BY a.username LIMIT 250");
return projectPublicOrganisation(rows,order);
});
}

View file

@ -1,5 +1,6 @@
import {organisationRuntimeAccess} from './organisation-runtime.mjs';
export const NODES={
'web.forum.admin':'Native Forum administration (Dev service only after migration)',
'web.tickets.support':'Work Customer Support tickets',
'web.tickets.sales':'Work Sales and Account Services tickets',
'web.tickets.network':'Work IT Operations tickets',
@ -108,7 +109,7 @@ export async function can(db,user,node){
export async function publicUser(db,user){
if(!user)return null;
const access=await accessFor(db,user);
return {username:user.username,staff:!!access.organisation?.assignments.length||access.nodes.includes('cp.menu.administration')||access.nodes.includes('web.menu.administration'),rank:access.rank,ranks:access.ranks,rankLabel:access.label,rankLevel:access.level,permissions:access.nodes,...(access.organisation?{organisation:access.organisation}:{} )};
return {username:user.username,managementModel:db.organisationAccessEnabled?'organisation-v2':'legacy',staff:!!access.organisation?.assignments.length||access.nodes.includes('cp.menu.administration')||access.nodes.includes('web.menu.administration'),rank:access.rank,ranks:access.ranks,rankLabel:access.label,rankLevel:access.level,permissions:access.nodes,...(access.organisation?{organisation:access.organisation}:{} )};
}
export async function initializeRanks(db){
for(const rank of DEFAULT_RANKS)await db.prepare('INSERT INTO cp_ranks(rank_key,label,rank_level,kind,permissions_json,version) VALUES(?,?,?,?,?,1) ON CONFLICT(rank_key) DO UPDATE SET rank_key=excluded.rank_key').bind(rank.key,rank.label,rank.level,rank.kind,JSON.stringify(rank.nodes)).run();

View file

@ -1,3 +1,4 @@
import {readPublicOrganisation} from './organisation-public-roster.mjs';
// Public roster only includes explicitly published staff. No private staff directory leakage.
import {STAFF_SUBTEAMS} from './staff-bureau-subteams.mjs';
import {STAFF_DEPARTMENTS} from './staff-bureau-policy.mjs';
@ -7,4 +8,4 @@ import {badgesFor} from './community-badges.mjs';
import {AWARD_LABELS,AWARD_FILES} from './recognition.mjs';
export const PUBLIC_ROSTER_SCHEMA=`CREATE TABLE IF NOT EXISTS staff_roster_publications (account_id CHAR(36) PRIMARY KEY, visible TINYINT(1) NOT NULL DEFAULT 0, subteam_key VARCHAR(40) NULL, updated_at BIGINT NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
export async function initializePublicRoster(db){await db.prepare(PUBLIC_ROSTER_SCHEMA).run();}
export function createPublicStaffRoster(db){return async request=>{if(request.method!=='GET')return Response.json({message:'Read-only roster'},{status:405});const groups=Object.entries(STAFF_DEPARTMENTS).map(([key,label])=>({key,label,subteams:STAFF_SUBTEAMS[key],staff:[]}));try{const {results=[]}=await db.prepare(`SELECT a.id,a.username,a.display_name,p.department_key,p.staff_level,r.subteam_key FROM staff_roster_publications r JOIN staff_positions p ON p.account_id=r.account_id JOIN site_accounts a ON a.id=p.account_id WHERE r.visible=1 AND p.status='active' AND p.staff_level NOT IN ('player','trainee') ORDER BY p.department_key,p.staff_level DESC,a.username LIMIT 250`).all();const closureStats=await staffClosureStats(db);for(const item of results){const group=groups.find(g=>g.key===item.department_key);if(!group)continue;const subteam=group.subteams.find(t=>t.key===item.subteam_key);const access=await accessFor(db,{id:item.id,username:item.username});const ranks=Array.isArray(access.ranks)?access.ranks:[];const crysknife=ranks.includes('crysknife');const stats=statsForAccount(closureStats,item.id);const seals=[];const earned=await badgesFor(db,item.id);for(const key of earned){const file=AWARD_FILES[key];if(typeof file==='string'&&/^[a-z0-9_-]+\.png$/.test(file))seals.push({key,label:AWARD_LABELS[key]||key,file});}for(const key of Object.keys(stats?.departments||{})){if(departmentAwardEarned(stats,key)&&/^(support|ban-appeals|forum-support|legal|sales|network-staff|dev)$/.test(key))seals.push({key:'closure-'+key,label:key+' Ticket Closure Award',file:'award-'+key+'-150.png'});}group.staff.push({username:item.username,displayName:item.display_name,rank:item.staff_level,department:group.key,subteam:subteam?.name||null,subteamKey:subteam?.key||null,crysknife,seals});}}catch{return Response.json({message:'Roster temporarily unavailable'},{status:503,headers:{'Cache-Control':'no-store'}})}return Response.json({groups,mode:'published',publishedOnly:true},{headers:{'Cache-Control':'public,max-age=60'}})}}
export function createPublicStaffRoster(db){return async request=>{if(request.method!=='GET')return Response.json({message:'Read-only roster'},{status:405});if(db.organisationAccessEnabled){try{return Response.json(await readPublicOrganisation(db),{headers:{'Cache-Control':'public,max-age=30'}});}catch{return Response.json({message:'Roster temporarily unavailable'}, {status:503,headers:{'Cache-Control':'no-store'}});}}const groups=Object.entries(STAFF_DEPARTMENTS).map(([key,label])=>({key,label,subteams:STAFF_SUBTEAMS[key],staff:[]}));try{const {results=[]}=await db.prepare(`SELECT a.id,a.username,a.display_name,p.department_key,p.staff_level,r.subteam_key FROM staff_roster_publications r JOIN staff_positions p ON p.account_id=r.account_id JOIN site_accounts a ON a.id=p.account_id WHERE r.visible=1 AND p.status='active' AND p.staff_level NOT IN ('player','trainee') ORDER BY p.department_key,p.staff_level DESC,a.username LIMIT 250`).all();const closureStats=await staffClosureStats(db);for(const item of results){const group=groups.find(g=>g.key===item.department_key);if(!group)continue;const subteam=group.subteams.find(t=>t.key===item.subteam_key);const access=await accessFor(db,{id:item.id,username:item.username});const ranks=Array.isArray(access.ranks)?access.ranks:[];const crysknife=ranks.includes('crysknife');const stats=statsForAccount(closureStats,item.id);const seals=[];const earned=await badgesFor(db,item.id);for(const key of earned){const file=AWARD_FILES[key];if(typeof file==='string'&&/^[a-z0-9_-]+\.png$/.test(file))seals.push({key,label:AWARD_LABELS[key]||key,file});}for(const key of Object.keys(stats?.departments||{})){if(departmentAwardEarned(stats,key)&&/^(support|ban-appeals|forum-support|legal|sales|network-staff|dev)$/.test(key))seals.push({key:'closure-'+key,label:key+' Ticket Closure Award',file:'award-'+key+'-150.png'});}group.staff.push({username:item.username,displayName:item.display_name,rank:item.staff_level,department:group.key,subteam:subteam?.name||null,subteamKey:subteam?.key||null,crysknife,seals});}}catch{return Response.json({message:'Roster temporarily unavailable'},{status:503,headers:{'Cache-Control':'no-store'}})}return Response.json({groups,mode:'published',publishedOnly:true},{headers:{'Cache-Control':'public,max-age=60'}})}}

View file

@ -1,3 +1,4 @@
import {startNativeSyncRetryWorker} from './native-sync-outbox.mjs';
import {initializeOrganisation} from './organisation-model.mjs';
import {createGitIdentityRoute,initializeGitIdentities,gitProxyIdentity} from './git-identity.mjs';
import {createPublicExchange} from './exchange-public.mjs';
@ -94,6 +95,7 @@ export async function start(settings=process.env) {
const result=await handle(request),outgoing=new Headers(security);for(const [key,value]of result.headers)outgoing.set(key,value);outgoing.set('Content-Security-Policy',path.startsWith('/git/sso/')?(result.headers.get('Content-Security-Policy')||security['Content-Security-Policy']):security['Content-Security-Policy']);res.writeHead(result.status,Object.fromEntries(outgoing));res.end(Buffer.from(await result.arrayBuffer()));
}catch(error){console.error('Request failed:',error.code||error.name);if(!res.headersSent)res.writeHead(503,{'Content-Type':'application/json','Cache-Control':'no-store'});res.end(JSON.stringify({message:'The website is temporarily unavailable.'}));}
});
const stopOrganisationSync=db.organisationAccessEnabled?startNativeSyncRetryWorker(db):()=>{};server.once('close',stopOrganisationSync);
server.requestTimeout=300000;server.headersTimeout=10000;
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(Number(settings.PORT||3000),'127.0.0.1',resolve);});
console.log('DuneRealms website running on localhost:'+Number(settings.PORT||3000)+'; MySQL connected.');

View file

@ -0,0 +1,36 @@
import {randomUUID} from 'node:crypto';
import {fileURLToPath} from 'node:url';import {resolve} from 'node:path';
import {openDatabase} from '../node/mysql.mjs';
import {initializeOrganisation,validStaffRole} from '../node/organisation-model.mjs';
import {MIGRATION_APPOINTMENTS} from '../node/organisation-appointments.mjs';
const OWNER_ID='f3ffda37-01e4-41ea-b89d-fbeda82e453e';
export async function bootstrapAppointments(db,{actorId,apply=false,clock=Date.now}={}){
const names=[...new Set(MIGRATION_APPOINTMENTS.map(p=>p.username))];
const {results:accounts}=await db.prepare(`SELECT a.id,a.username,p.game_link_exempt FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.username IN (${names.map(()=>'?')}) AND a.password_hash NOT LIKE '!%'`).bind(...names).all();
if(accounts.length!==names.length||accounts.some(a=>a.game_link_exempt)||accounts.find(a=>a.username==='unimatrix999')?.id!==OWNER_ID)throw Error('Approved migration identities do not match the existing active accounts.');
const plan=MIGRATION_APPOINTMENTS.map(p=>({...p,userId:accounts.find(a=>a.username===p.username).id})).sort((a,b)=>(a.scopeType+':'+a.scopeKey+':'+a.role+':'+a.userId).localeCompare(b.scopeType+':'+b.scopeKey+':'+b.role+':'+b.userId));
if(plan.some(p=>!validStaffRole(p.scopeType,p.scopeKey,p.role)))throw Error('Invalid approved migration function.');
if(!apply)return {applied:false,accounts:accounts.length,assignments:plan,permissionsChanged:false};
return db.transaction(async tx=>{
const actor=await tx.first("SELECT p.principal_kind FROM org_control_principals p JOIN site_accounts a ON a.id=p.user_id WHERE a.id=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[actorId]);
if(!actor||!['owner','executive','service'].includes(actor.principal_kind))throw Error('Existing control actor required.');
let created=0,retained=0;
for(const p of plan){
await tx.query('INSERT IGNORE INTO org_scope_versions(scope_type,scope_key,version) VALUES(?,?,1)',[p.scopeType,p.scopeKey]);
await tx.first('SELECT version FROM org_scope_versions WHERE scope_type=? AND scope_key=? FOR UPDATE',[p.scopeType,p.scopeKey]);
const identity=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.username=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[p.userId,p.username]);
if(!identity||identity.game_link_exempt)throw Error('Migration identity changed.');
const now=clock(),current=await tx.query("SELECT 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",[p.scopeType,p.scopeKey,now,now]);
if(current.some(a=>a.user_id===p.userId&&a.role_key===p.role)){retained++;continue;}
if(['branch_lead','department_head','owner_ceo'].includes(p.role)&&current.some(a=>a.role_key===p.role))throw Error('A migration leadership position already has another holder.');
const id=randomUUID();
await tx.query('INSERT INTO org_assignments(id,user_id,scope_type,scope_key,role_key,source_kind,source_ref,status,starts_at,created_by,created_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,?,1)',[id,p.userId,p.scopeType,p.scopeKey,p.role,'manual','great-migration-owner-approved','active',now,actorId,now]);
await tx.query('UPDATE org_scope_versions SET version=version+1 WHERE scope_type=? AND scope_key=?',[p.scopeType,p.scopeKey]);
await tx.query('INSERT INTO org_assignment_events(id,user_id,assignment_id,actor_id,action,scope_type,scope_key,reason,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[randomUUID(),p.userId,id,actorId,'appointment-baseline',p.scopeType,p.scopeKey,'Owner-approved Great Migration appointment',JSON.stringify({...p,permissionsChanged:false}),now]);created++;
}
return {applied:true,created,retained,permissionsChanged: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 bootstrapAppointments(db,{actorId:process.argv.find(a=>a.startsWith('--actor='))?.slice(8),apply:process.argv.includes('--apply')})));}finally{await db.close();}
}

View file

@ -0,0 +1,12 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {bootstrapAppointments} from '../scripts/bootstrap-organisation-appointments.mjs';
import {MIGRATION_APPOINTMENTS} from '../node/organisation-appointments.mjs';
const owner='f3ffda37-01e4-41ea-b89d-fbeda82e453e';
function fixture({conflict=false,auditFail=false}={}){
const accounts=[...new Set(MIGRATION_APPOINTMENTS.map(p=>p.username))].map((username,i)=>({username,id:username==='unimatrix999'?owner:'id-'+i,game_link_exempt:0}));const assignments=[],events=[];
const tx={async first(sql,args){if(sql.includes('org_control_principals'))return {principal_kind:'owner'};if(sql.includes('org_scope_versions'))return {version:1};if(sql.includes('site_accounts'))return accounts.find(a=>a.id===args[0]&&a.username===args[1]);throw Error(sql);},async query(sql,args){if(sql.startsWith('SELECT user_id,role_key')){const list=assignments.filter(a=>a.type===args[0]&&a.scope===args[1]);return conflict?[...list,{user_id:'other',role_key:'branch_lead'}]:list;}if(sql.startsWith('INSERT INTO org_assignments'))assignments.push({user_id:args[1],type:args[2],scope:args[3],role_key:args[4]});if(sql.startsWith('INSERT INTO org_assignment_events')){if(auditFail)throw Error('audit failed');events.push(args);}}};
const db={prepare(){return {bind(){return {all:async()=>({results:accounts})};}};},async transaction(fn){const a=assignments.length,e=events.length;try{return await fn(tx);}catch(error){assignments.length=a;events.length=e;throw error;}}};return {db,accounts,assignments,events};
}
test('Approved roster resolves 14 existing people and 26 functions without changing access',async()=>{const f=fixture();const plan=await bootstrapAppointments(f.db);assert.equal(plan.accounts,14);assert.equal(plan.assignments.length,26);assert.equal(plan.permissionsChanged,false);assert.equal(f.assignments.length,0);});
test('Appointments are audited, idempotent and use the existing Owner identity',async()=>{const f=fixture();const result=await bootstrapAppointments(f.db,{actorId:owner,apply:true});assert.equal(result.created,26);assert.equal(f.events.length,26);const again=await bootstrapAppointments(f.db,{actorId:owner,apply:true});assert.equal(again.created,0);assert.equal(again.retained,26);assert.equal(f.events.length,26);});
test('A conflicting leader, identity mismatch or audit failure prevents a partial migration',async()=>{const f=fixture({conflict:true});await assert.rejects(bootstrapAppointments(f.db,{actorId:owner,apply:true}),/another holder/);assert.equal(f.assignments.length,0);const bad=fixture();bad.accounts[0].id='wrong';await assert.rejects(bootstrapAppointments(bad.db),/identities/);const fail=fixture({auditFail:true});await assert.rejects(bootstrapAppointments(fail.db,{actorId:owner,apply:true}),/audit/);assert.equal(fail.assignments.length,0);});

Some files were not shown because too many files have changed in this diff Show more