diff --git a/website/integrations/osticket/dev-policy.php b/website/integrations/osticket/dev-policy.php new file mode 100644 index 00000000..a431920b --- /dev/null +++ b/website/integrations/osticket/dev-policy.php @@ -0,0 +1,71 @@ +=$min&&mb_strlen(trim($value),'UTF-8')<=$max;} +function dune_dev_id($value){return is_string($value)&&preg_match('/^[1-9][0-9]*$/D',$value)&&filter_var($value,FILTER_VALIDATE_INT)!==false?(int)$value:false;} +function dune_dev_origin_valid($origin){return $origin===null||$origin==='https://support.dunerealms.com';} +// Central SSO identity only. Never accept ranks or actor IDs from submitted fields. +function dune_dev_team($identity) { + if (!is_array($identity)) return false; + if (($identity['nativePermissionManagement']??null)===false) return in_array('web.tickets.dev',$identity['permissions']??[],true); + return (bool)array_intersect($identity['ranks']??[], ['owners','official_account','corestaff','network_admin','web_net_admin','web_dev']); +} +function dune_dev_submitter($identity) { + if (!is_array($identity)) return false; + $staffRanks=['owners','official_account','corestaff','staff','network_admin','network_admin','web_net_admin','web_dev','web_streamer','web_news','web_forum','web_support','web_sales','web_legal','web_appeal','game_mod','game_admin','game_support','game_appeal','game_quests','game_restoration']; + return (bool)array_intersect($identity['ranks']??[],array_merge($staffRanks,['vip','council_member'])) || (bool)array_intersect($identity['permissions']??[], ['web.menu.staffmanual','web.tickets.staff','web.forum.moderate','web.posts.edit']); +} +function dune_dev_owner($identity) { + if(!is_array($identity))return false; + $ranks=$identity['ranks']??[];$nodes=$identity['permissions']??[]; + if (($identity['nativePermissionManagement']??null)===false) return (bool)array_intersect($ranks,['org_owner_ceo','org_executive']) && in_array('web.tickets.dev',$nodes,true) && in_array('web.ranks.manage',$nodes,true); + $name=strtolower($identity['username']??''); + return ($name==='unimatrix999'&&in_array('owners',$ranks,true))||($name==='grmacken'&&in_array('web_net_admin',$ranks,true)); +} +function dune_dev_transition($identity,$action,$state,$note) { + if(!dune_dev_team($identity)||($action!=='complete'&&!dune_dev_owner($identity)))throw new RuntimeException('Only unimatrix999 or grmacken can approve or deny tasks.'); + if(!dune_dev_text_valid($note,10,10000))throw new RuntimeException('Provide a decision reason or completion report of 10–10,000 characters.'); + if($action==='complete'&&$state==='approved')return 'completed'; + if($action==='approve'&&$state==='pending')return 'approved'; + if($action==='deny'&&$state==='pending')return 'denied'; + throw new RuntimeException('This action is not available for the current task state.'); +} +function dune_dev_priority_editor($identity) {return dune_dev_owner($identity)||(strtolower($identity['username']??'')==='dev'&&in_array('web_dev',$identity['ranks']??[],true));} +function dune_dev_fields() { + return [ + 'title'=>['Task title',true,160,'input','A short, specific outcome'], + 'type'=>['Request type',true,40,'select',['Feature','Bug','Design / artwork','Operations','Documentation','Release / verification']], + 'system'=>['System / component',true,120,'input','Website, Support, Shop, game plugin, world or server'], + 'objective'=>['Objective / full task prompt',true,12000,'textarea','What should be built or changed, and why?'], + 'current'=>['Current behaviour / context',true,6000,'textarea','What happens now? Add the relevant page, command or version.'], + 'expected'=>['Expected result',true,6000,'textarea','Describe the finished result from the user’s point of view.'], + 'acceptance'=>['Acceptance criteria',true,6000,'textarea','List the observable checks that must pass before this ticket can close.'], + 'scope'=>['Scope and exclusions',false,4000,'textarea','What is included? What must remain unchanged?'], + 'reproduction'=>['Reproduction steps / error messages',false,6000,'textarea','For bugs: steps, exact error, Java/Bedrock, client and server version.'], + 'testplan'=>['Suggested tests',false,4000,'textarea','Desktop/mobile, Java/Bedrock, permissions, failed and repeated requests.'], + 'references'=>['Links / design references',false,4000,'textarea','Relevant HTTPS pages, source paths or related ticket numbers. No credentials.'], + 'dependencies'=>['Dependencies / related tasks',false,3000,'textarea','What must be ready first? Who can clarify the request?'], + 'risk'=>['Data, rollout and rollback considerations',false,4000,'textarea','Mention sensitive data, paid receipts, migrations, backups or service interruptions.'], + 'priority'=>['Requested priority',true,40,'select',['Medium','Low','High']], + 'timing'=>['Desired timing / reason',false,500,'input','A request, not a guaranteed deadline'], + ]; +} +function dune_dev_validate($input) { + $values=[];$errors=[]; + foreach(dune_dev_fields() as$key=>[$label,$required,$max,$type,$hint]) { + $value=is_string($input[$key]??null)?trim($input[$key]):''; + if(($required&&$value==='')||!dune_dev_text_valid($value,0,$max)|| (isset($input[$key])&&!is_string($input[$key]))||($type==='select'&&!in_array($value,$hint,true)))$errors[]=$label.': enter a valid value (maximum '.$max.' characters).'; + $values[$key]=$value; + } + if(($input['privacy']??'')!=='1')$errors[]='Confirm that the request contains no passwords, tokens or unnecessary personal data.'; + return [$values,$errors]; +} +function dune_dev_prompt($values) { + $parts=['DuneRealms development task — submitted through the private Dev form.']; + foreach(dune_dev_fields() as$key=>[$label])if(($values[$key]??'')!=='')$parts[]=$label."\n".$values[$key]; + $parts[]='Workflow: Owner approval required before execution except explicit Owner submissions and the imported owner-approved backlog. Complete only with actual changes, checks, evidence and deployment/merge status. Scheduled morning/evening slots remain in effect.'; + return implode("\n\n",$parts); +} + +function dune_dev_execution_brief($values) { + return "## Approved objective\n".($values['objective']??'')."\n\n## Scope and exclusions\n".($values['scope']??'Keep the approved request scope.')."\n\n## Implementation plan\n1. Inspect the current implementation and linked original request.\n2. Make the smallest complete change within approved scope.\n3. Run focused positive, failure and permission checks.\n4. Review and merge through the Dev fork; back up and verify any authorised rollout.\n\n## Acceptance criteria\n".($values['acceptance']??'')."\n\n## Test plan\n".($values['testplan']??'')."\n\n## Dependencies\n".($values['dependencies']??'')."\n\n## Completion report required\nChanges, actual checks/results, evidence, fork/merge link, deployed versus staged, rollback and remaining limits. Do not silently enlarge the approved scope."; +} diff --git a/website/node/discord-news.mjs b/website/node/discord-news.mjs index bb5f21ae..dad76bf5 100644 --- a/website/node/discord-news.mjs +++ b/website/node/discord-news.mjs @@ -6,7 +6,7 @@ const categories=new Set(['world','news','maintenance','changelogs','events','co export function newsWebhookPayload(post,{test=false}={}){ const category=categories.has(post.category)?post.category:'news'; const summary=String(post.body||'').replace(/<[^>]*>/g,'').replace(/\[([^\]]+)\]\(https?:[^)]+\)/g,'$1').replace(/[#*_`]/g,'').replace(/\s+/g,' ').trim().slice(0,500); - return {username:'DuneRealms Dispatches',avatar_url:'https://cdn.discordapp.com/avatars/1567239700610285618/dc3ff7eb9f86481f52b4293affa3bbfd.png',allowed_mentions:{parse:[]},embeds:[{title:(test?'[TEST] ':'')+'['+({news:'NEWS',world:'World',maintenance:'Maintenance',changelogs:'Changelogs',events:'Events',community:'Community',unis_blog:'Uni’s Blog'}[post.category]||'NEWS')+'] '+String(post.title).slice(0,220),description:summary,url:ORIGIN+newsPath(post),color:0xc6a551,image:{url:ORIGIN+'/assets/news-'+(category==='unis_blog'?'news':category)+'.webp'},footer:{text:test?'Integration test — not a new published article':'Written by '+(post.author_name||'DuneRealms')+' • DuneRealms'},timestamp:new Date(Number(post.published_at)).toISOString()}]}; + return {username:'DuneRealms',avatar_url:'https://cdn.discordapp.com/avatars/1567239700610285618/dc3ff7eb9f86481f52b4293affa3bbfd.png',allowed_mentions:{parse:[]},embeds:[{title:(test?'[TEST] ':'')+'['+({news:'NEWS',world:'World',maintenance:'Maintenance',changelogs:'Changelogs',events:'Events',community:'Community',unis_blog:'Uni’s Blog'}[post.category]||'NEWS')+'] '+String(post.title).slice(0,220),description:summary,url:ORIGIN+newsPath(post),color:0xc6a551,image:{url:ORIGIN+'/assets/news-'+(category==='unis_blog'?'news':category)+'.webp'},footer:{text:test?'Integration test — not a new published article':'Written by '+(post.author_name||'DuneRealms')+' • DuneRealms'},timestamp:new Date(Number(post.published_at)).toISOString()}]}; } export function validateNewsWebhook(config){ const url=new URL(config.url);if(url.protocol!=='https:'||url.hostname!=='discord.com'||!/^\/api(?:\/v10)?\/webhooks\/\d+\/[A-Za-z0-9_.-]+$/.test(url.pathname)||url.search||url.hash||url.username||url.password||config.channelId!=='1567237542040834250'||config.guildId!=='1567229433033531462')throw Error('Invalid news webhook configuration'); diff --git a/website/node/member-profiles.mjs b/website/node/member-profiles.mjs index de2562f9..36f8267f 100644 --- a/website/node/member-profiles.mjs +++ b/website/node/member-profiles.mjs @@ -10,6 +10,7 @@ import{badgesFor,BADGES,communityBadgeVisible}from'./community-badges.mjs'; import {activeSealEntitlements} from './seal-entitlement-store.mjs'; import {isShowcaseSeal} from './seal-entitlements.mjs'; import {EXECUTIVE_TITLES} from './organisation-appointments.mjs'; +import {OFFICIAL_ACCOUNT} from './official-account.mjs'; import{staffSealFor,departmentsFor}from'./native-seals.mjs'; import{staffClosureStats,statsForAccount,departmentAwardEarned}from'./staff-closure-stats.mjs'; const origin='https://www.dunerealms.com',base=origin+'/assets/seals/'; @@ -34,12 +35,12 @@ export async function publicForumFor(db,id){ export async function memberProfileData(db,target,settings={}){ const access=await accessFor(db,target),publicProfile=await publicProfileFor(db,target.id),statsMap=await(settings.statsReader||staffClosureStats)(db),staff=access.nodes.includes('web.tickets.staff'),stats=staff?statsForAccount(statsMap,target.id):null; let manifest=settings.sealManifest||{};if(!settings.sealManifest){const file=settings.SEAL_MANIFEST_PATH||'/home/dunerealms/apps/integrations/seal-manifest.json';if(existsSync(file))manifest=JSON.parse(readFileSync(file,'utf8'));} - const showcase=target.username.toLowerCase()==='dunerealms'; + const showcase=target.id===OFFICIAL_ACCOUNT.id&&target.username===OFFICIAL_ACCOUNT.username; // Showcase never impersonates other people's personalized seals or the Crysknife Order. - const showcaseSealAllowed=(key,asset)=>!(/^(owner-|personal-staff-|network-staff-mr_|main-network-admin-|corestaff-)/i.test(key)||/crysknife/i.test(key+' '+(asset?.label||'')+' '+(asset?.footer150||''))); + const showcaseSealAllowed=(key,asset)=>isShowcaseSeal(key,{personal:asset?.category==='Personal'||asset?.personal===true})&&!/crysknife|crissknife/i.test((asset?.label||'')+' '+(asset?.footer150||'')); const ranks=[];for(const key of access.ranks){const functionRole=key.startsWith('org_')?access.organisation?.assignments.find(a=>'org_'+a.role===key):null;const r=functionRole?{key,label:functionRole.scopeType==='organisation'?(EXECUTIVE_TITLES[target.username]||functionRole.roleLabel):functionRole.roleLabel}:await rankFor(db,key);if(!ranks.some(x=>x.label===r.label))ranks.push({key:r.key,label:r.label});} const medals=[];const add=(key,label,url,group)=>{if(!medals.some(m=>m.key===key)&&typeof url==='string'&&/^https:\/\/(www|support|forums)\.dunerealms\.com\/assets\/seals\/[a-zA-Z0-9_./-]+\.png$/.test(url))medals.push({key,label,url:url.replace(/^https:\/\/(support|forums)\.dunerealms\.com\//,'https://www.dunerealms.com/'),group});}; - const personal=showcase?Object.values(manifest).find(a=>a.label?.toLowerCase()===target.username.toLowerCase()&&a.role==='OWNER')?.footer150||null:staffSealFor({...target,ranks:access.ranks},manifest);const namedPersonal=personal&&!personal.includes('/rank-network-staff-');if(personal)add('personal-role',namedPersonal?target.username+' · Personal seal':access.label,personal.startsWith('/')?(personal.includes('main-network')?'https://support.dunerealms.com':'https://www.dunerealms.com')+personal:personal,'Staff'); + const personal=showcase?null:staffSealFor({...target,ranks:access.ranks},manifest);const namedPersonal=personal&&!personal.includes('/rank-network-staff-');if(personal)add('personal-role',namedPersonal?target.username+' · Personal seal':access.label,personal.startsWith('/')?(personal.includes('main-network')?'https://support.dunerealms.com':'https://www.dunerealms.com')+personal:personal,'Staff'); for(const key of departmentsFor(access.nodes,access.ranks,target.username)){ const name=departments[key];if(!name)continue;let url=base+'department-'+key+(key==='legal'?'-v2':'')+'-150.png'; let label=name+' · Department';if(departmentAwardEarned(stats,key)){const file='personal-department-'+key+'-'+createHash('sha256').update(target.id+'|'+key+'|'+target.username).digest('hex').slice(0,20)+'.png';if(existsSync('/home/dunerealms/apps/integrations/osticket/assets/seals/earned/'+file)){url='https://support.dunerealms.com/assets/seals/earned/'+file;label=name+' · Personal department seal';}} @@ -56,6 +57,7 @@ export async function memberProfileData(db,target,settings={}){ const url=asset?.footer150?origin+asset.footer150:(BADGES.includes(key)?base+(AWARD_FILES[key]||key+'-150.png'):null); if(url)add(key,asset?.label||AWARD_LABELS[key]||badgeLabels[key]||key.replaceAll('-',' '),url,'Awards'); } + if(showcase)for(const [key,asset]of Object.entries(manifest))if(showcaseSealAllowed(key,asset)&&typeof asset.footer150==='string')add(key,asset.label||key,origin+asset.footer150,asset.category||'Seal catalogue'); for(const [key,asset]of Object.entries(manifest))if(asset.category==='Community'&&showcaseSealAllowed(key,asset)&&(showcase||asset.rank&&access.ranks.includes(asset.rank)))add(key,asset.label,origin+asset.footer150,'Community'); if(!showcase&&access.ranks.includes('crysknife'))add('rank-crysknife','Holy Order of The Crysknife',base+'order-crysknife-v1.png','Official'); if(access.ranks.includes('web_dev')||protectedStaffRanks(access.ranks))add('rank-dev','Development',base+'rank-dev-150.png','Official'); diff --git a/website/node/native-sync-outbox.mjs b/website/node/native-sync-outbox.mjs index 0a983b7c..bf9b24f6 100644 --- a/website/node/native-sync-outbox.mjs +++ b/website/node/native-sync-outbox.mjs @@ -6,8 +6,11 @@ import {syncNativeAgents} from './native-agents.mjs'; 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 nativeSyncMutation(now=Date.now()){ + return {sql:"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='' ",values:[randomUUID(),now]}; +} 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); + const change=nativeSyncMutation(now);return db.prepare(change.sql).bind(...change.values); } async function synchronize(db){ if(!['/home/dunerealms/apps/integrations/osticket/sync-agents.php','/home/dunerealms/apps/integrations/sync-staff-seals.php','/home/dunerealms/apps/integrations/seal-manifest.json'].every(existsSync))throw Error('Native adapters unavailable'); diff --git a/website/node/news.mjs b/website/node/news.mjs index d0549e8b..c4242882 100644 --- a/website/node/news.mjs +++ b/website/node/news.mjs @@ -2,6 +2,7 @@ import {nativeForumFeed} from './native-forum-feed.mjs'; import {randomUUID} from 'node:crypto'; import {readFile} from 'node:fs/promises'; import {json} from './game-link.mjs'; +import {OFFICIAL_ACCOUNT} from './official-account.mjs'; export const NEWS_CATEGORIES={world:'World',news:'NEWS',maintenance:'Maintenance',changelogs:'Changelogs',events:'Events',community:'Community',unis_blog:"Uni’s Blog"}; export function publicNewsExcerpt(body){return String(body||'').replace(/!\[[^\]]*\]\([^)]*\)/g,'').replace(/\[([^\]]+)\]\([^)]*\)/g,'$1').replace(/^\s*#{1,6}\s+/gm,'').replace(/[*_`]/g,'').replace(/\s+/g,' ').trim().slice(0,220);} export async function initializeNews(db){ @@ -12,7 +13,7 @@ export async function initializeNews(db){ const key='release:'+String(release.version).slice(0,100),existing=await db.prepare('SELECT id FROM website_posts WHERE source_key=?').bind(key).first();if(existing)continue; const date=Date.parse(release.date);if(!Number.isFinite(date)||date>Date.now())continue; const body=[release.synopsis,...(release.tasks||[]).flatMap(t=>[t.title,...(t.changes||[]).map(x=>'• '+x)])].filter(Boolean).join('\n\n').slice(0,12000); - await db.prepare('INSERT INTO website_posts(id,source_key,category,title,body,status,author_id,created_at,updated_at,published_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,1) ON CONFLICT(source_key) DO UPDATE SET source_key=excluded.source_key').bind(randomUUID(),key,'changelogs',String(release.title||release.version).slice(0,120),body,'published','release-register',date,date,date).run(); + await db.prepare('INSERT INTO website_posts(id,source_key,category,title,body,status,author_id,created_at,updated_at,published_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,1) ON CONFLICT(source_key) DO UPDATE SET source_key=excluded.source_key').bind(randomUUID(),key,'changelogs',String(release.title||release.version).slice(0,120),body,'published',OFFICIAL_ACCOUNT.id,date,date,date).run(); } } export async function forumLinks(db,posts){try{if(!posts.length)return posts;const{results}=await db.prepare('SELECT post_id,thread_id FROM forum_news_delivery WHERE post_id IN ('+posts.map(()=>'?').join(',')+") AND thread_id>0 AND state='sent'").bind(...posts.map(p=>p.id)).all();const links=new Map(results.filter(r=>Number.isSafeInteger(Number(r.thread_id))&&Number(r.thread_id)>0).map(r=>[r.post_id,'https://forums.dunerealms.com/showthread.php?tid='+Number(r.thread_id)]));return posts.map(p=>({...p,forum_url:links.get(p.id)||null}));}catch{return posts.map(p=>({...p,forum_url:null}));}} diff --git a/website/node/official-account.mjs b/website/node/official-account.mjs new file mode 100644 index 00000000..fa1fd1b4 --- /dev/null +++ b/website/node/official-account.mjs @@ -0,0 +1,11 @@ +// Existing verified identities. Display names and client input never establish this link. +export const OFFICIAL_ACCOUNT=Object.freeze({ + id:'2c281bc7-c352-4d9a-b94c-fa13eee1157d',username:'dunerealms', + ownerId:'f3ffda37-01e4-41ea-b89d-fbeda82e453e', + minecraftUuid:'00000000-0000-0000-0009-01f09764757f' +}); +export async function organisationSubject(reader,userId,{lock=false}={}){ + if(userId!==OFFICIAL_ACCOUNT.id)return {userId,alias:false}; + const rows=await reader.query("SELECT x.user_id FROM org_control_principals x JOIN site_accounts a ON a.id=x.user_id JOIN site_game_links l ON l.user_id=a.id JOIN org_control_principals p ON p.user_id=? JOIN site_accounts owner ON owner.id=p.user_id WHERE x.user_id=? AND x.principal_kind='owner_alias' AND x.created_by=? AND a.username='dunerealms' AND a.role='official_account' AND a.password_hash NOT LIKE '!%' AND l.minecraft_uuid=? AND p.principal_kind='owner' AND owner.username='unimatrix999' AND owner.password_hash NOT LIKE '!%'"+(lock?' FOR SHARE':''),[OFFICIAL_ACCOUNT.ownerId,userId,OFFICIAL_ACCOUNT.ownerId,OFFICIAL_ACCOUNT.minecraftUuid]); + return rows.length?{userId:OFFICIAL_ACCOUNT.ownerId,alias:true}:{userId,alias:false}; +} diff --git a/website/node/organisation-management.mjs b/website/node/organisation-management.mjs index e5273ad6..ccef8100 100644 --- a/website/node/organisation-management.mjs +++ b/website/node/organisation-management.mjs @@ -3,6 +3,7 @@ import {randomUUID} from 'node:crypto'; import {identity} from './auth.mjs'; import {can,NODES} from './permissions.mjs'; import {staffScopes,validStaffRole,assignmentLabel} from './organisation-model.mjs'; +import {organisationSubject} from './official-account.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}); @@ -35,6 +36,7 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c 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); + userId=(await organisationSubject(tx,userId,{lock:true})).userId; 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}; @@ -68,9 +70,10 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c if(url.pathname.endsWith('/effective')){ const now=clock(); const result=await db.transaction(async tx=>{ - const assignments=await tx.query('SELECT id,scope_type,scope_key,role_key,status,starts_at,ends_at FROM org_assignments WHERE user_id=?',[userId]); + const subject=await organisationSubject(tx,userId); + const assignments=await tx.query('SELECT id,scope_type,scope_key,role_key,status,starts_at,ends_at FROM org_assignments WHERE user_id=?',[subject.userId]); const policies=await tx.query('SELECT scope_type,scope_key,role_key,permissions_json,version FROM org_role_policies',[]); - const principal=await tx.first('SELECT principal_kind FROM org_control_principals WHERE user_id=?',[userId]); + const principal=await tx.first('SELECT principal_kind FROM org_control_principals WHERE user_id=?',[subject.userId]); return effectiveOrganisationAccess({assignments,policies,registry:NODES,principalKind:principal?.principal_kind,now}); });return reply({...result,enforcement:db.organisationAccessEnabled?'active':'preparing'}); } diff --git a/website/node/organisation-public-roster.mjs b/website/node/organisation-public-roster.mjs index d75d4eb4..352dab3e 100644 --- a/website/node/organisation-public-roster.mjs +++ b/website/node/organisation-public-roster.mjs @@ -1,7 +1,8 @@ import {ORGANISATION,assignmentLabel,validStaffRole} from './organisation-model.mjs'; import {EXECUTIVE_TITLES} from './organisation-appointments.mjs'; +import {OFFICIAL_ACCOUNT} from './official-account.mjs'; const weights={owner_ceo:100,executive:90,department_head:80,branch_lead:70,officer:50}; -export function projectPublicOrganisation(rows,orderRows=[]){ +export function projectPublicOrganisation(rows,orderRows=[],officialRows=[]){ 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; @@ -21,12 +22,14 @@ export function projectPublicOrganisation(rows,orderRows=[]){ 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}; + const officialAccounts=officialRows.filter(r=>r.id===OFFICIAL_ACCOUNT.id&&r.username===OFFICIAL_ACCOUNT.username&&r.role==='official_account').map(r=>({username:r.username,displayName:'DuneRealms',title:'Official DuneRealms Account',bio:r.bio||'Official account operated by the DuneRealms owner. Verify this profile through the staff directory.',profile:'/people/'+r.username,avatar:'https://cp.dunerealms.com/api/avatars/face/roster/'+r.username,official:true,functions:[],seals:[]})); + 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,officialAccounts}; } 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); + const official=await reader.query("SELECT a.id,a.username,a.role,p.bio FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id LEFT JOIN site_profiles p ON p.user_id=a.id WHERE a.id=? AND a.username=? AND a.role='official_account' AND a.password_hash NOT LIKE '!%' AND l.minecraft_uuid=?",[OFFICIAL_ACCOUNT.id,OFFICIAL_ACCOUNT.username,OFFICIAL_ACCOUNT.minecraftUuid]); + return projectPublicOrganisation(rows,order,official); }); } diff --git a/website/node/organisation-runtime.mjs b/website/node/organisation-runtime.mjs index 39f85b88..3ee8cbed 100644 --- a/website/node/organisation-runtime.mjs +++ b/website/node/organisation-runtime.mjs @@ -1,5 +1,6 @@ import {effectiveOrganisationAccess} from './organisation-effective.mjs'; import {assignmentLabel,validStaffRole} from './organisation-model.mjs'; +import {organisationSubject} from './official-account.mjs'; const SERVICE_ID='f7b88778-f0bc-41cc-9227-d8ef2f52264d'; const legacyStaff=new Set(['owners','owner','corestaff','staff','network_admin','web_net_admin','web_net_owner','web_network','official_account','admin','administrator','moderator','guardian','streamer','twitch','yt']); const privileged=node=>/^web\.(accounts\.|ranks\.|servers\.|luckperms\.|tickets\.(staff|admin|appeals)|bank\.staff\.|payroll\.|posts\.(edit|publish)|items\.manage|bans\.|forum\.moderate|git\.admin)/.test(node)||/^cp\.(accounts\.|ranks\.|servers\.|luckperms\.|bank\.staff\.|items\.manage)/.test(node)||/^dune\.(admin|staff\.|moderation\.|ban\.|unban\.)/.test(node)||node.startsWith('duneprotect.')||/^(?:web|cp)\.menu\.(?:administration|staffmanual|permissions|servers|luckperms|bans|forum|items|posts)$/.test(node)||/^web\.(?:shop\.support|bank\.projects\.approve|mail\.staff\.)/.test(node); @@ -7,15 +8,16 @@ const nativeEditor=node=>['web.luckperms.edit','cp.luckperms.edit','luckperms.ed export async function organisationRuntimeAccess(db,user,{registry,basicRank,legacyRanks,clock=Date.now}={}){ const now=clock(); const snapshot=await db.readSnapshot(async reader=>{ - const principal=(await reader.query('SELECT principal_kind FROM org_control_principals WHERE user_id=?',[user.id]))[0]; + const subject=await organisationSubject(reader,user.id); + const principal=(await reader.query('SELECT principal_kind FROM org_control_principals WHERE user_id=?',[subject.userId]))[0]; if(principal?.principal_kind==='service'){ const service=(await reader.query('SELECT service_uuid,game_link_exempt FROM site_account_policies WHERE user_id=?',[user.id]))[0]; if(user.id!==SERVICE_ID||!service?.game_link_exempt||service.service_uuid!=='00000000-0000-4000-8000-00000000de01')throw Error('Invalid service control identity.'); return {service:true}; } - const assignments=await reader.query("SELECT id,scope_type,scope_key,role_key,status,starts_at,ends_at 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>?)",[user.id,now,now]); + const assignments=await reader.query("SELECT id,scope_type,scope_key,role_key,status,starts_at,ends_at 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>?)",[subject.userId,now,now]); const policies=await reader.query('SELECT scope_type,scope_key,role_key,permissions_json,version FROM org_role_policies',[]); - return {assignments,access:effectiveOrganisationAccess({assignments,policies,registry,principalKind:principal?.principal_kind,now})}; + return {subject,assignments,access:effectiveOrganisationAccess({assignments,policies,registry,principalKind:principal?.principal_kind,now})}; }); if(snapshot.service)return null; // Preserve the existing verified Dev service access, including native tools. const citizenRanks=legacyRanks.filter(r=>!legacyStaff.has(r.key)&&!r.key.startsWith('web_')&&!r.key.startsWith('game_')); @@ -27,5 +29,5 @@ export async function organisationRuntimeAccess(db,user,{registry,basicRank,lega const precedence={owner_ceo:100,executive:90,department_head:80,branch_lead:70,officer:50}; active.sort((a,b)=>(precedence[b.role_key]||0)-(precedence[a.role_key]||0)||a.scope_key.localeCompare(b.scope_key)); const primary=active[0],citizen=ranks.reduce((a,b)=>a.level>=b.level?a:b,basicRank); - return {rank:primary?'org_'+primary.role_key:citizen.key,ranks:[...new Set([...ranks.map(r=>r.key),...active.map(a=>'org_'+a.role_key)])],label:primary?assignmentLabel(primary).roleLabel:citizen.label,level:primary?precedence[primary.role_key]||0:citizen.level,nodes:[...nodes].sort(),organisation:{mode:'active',assignments:active.map(assignmentLabel),missingPolicies:snapshot.access.missingPolicies,blocked:snapshot.access.blocked.length}}; + return {rank:primary?'org_'+primary.role_key:citizen.key,ranks:[...new Set([...ranks.map(r=>r.key),...active.map(a=>'org_'+a.role_key)])],label:primary?assignmentLabel(primary).roleLabel:citizen.label,level:primary?precedence[primary.role_key]||0:citizen.level,nodes:[...nodes].sort(),organisation:{mode:'active',permissionPrincipalId:snapshot.subject.userId,officialOwnerAlias:snapshot.subject.alias,assignments:active.map(assignmentLabel),missingPolicies:snapshot.access.missingPolicies,blocked:snapshot.access.blocked.length}}; } diff --git a/website/node/public/passport.html b/website/node/public/passport.html index 01275fb3..9e8f8a81 100644 --- a/website/node/public/passport.html +++ b/website/node/public/passport.html @@ -5,6 +5,6 @@
THE PERSON BEHIND THE NAME
No public biography added yet.
CURRENT RESPONSIBILITIES
PERSONAL RECOGNITION
Issued in this member’s name.

SERVICE BEYOND OFFICE
Order membership recognises service to DuneRealms and is separate from staff authority.
SERVICE & RECOGNITION
Current function seals and recorded community achievements.
SERVICE & RECOGNITION
Current function seals and recorded community achievements.
AROUND THE REALMS