forked from unimatrix/web
Build the new public staff directory and audited Great Migration appointments
This commit is contained in:
parent
04532cb7ec
commit
fc9549ee71
15 changed files with 181 additions and 29 deletions
|
|
@ -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))));}
|
||||
|
|
|
|||
|
|
@ -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});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
5
website/node/native-sync-schema.mjs
Normal file
5
website/node/native-sync-schema.mjs
Normal 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
|
||||
)`;
|
||||
22
website/node/organisation-appointments.mjs
Normal file
22
website/node/organisation-appointments.mjs
Normal 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'};
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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()}){
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
32
website/node/organisation-public-roster.mjs
Normal file
32
website/node/organisation-public-roster.mjs
Normal 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);
|
||||
});
|
||||
}
|
||||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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'}})}}
|
||||
|
|
|
|||
|
|
@ -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.');
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff