diff --git a/website/control-panel/public/cp-v2/citizen-directory.css b/website/control-panel/public/cp-v2/citizen-directory.css new file mode 100644 index 00000000..79651c18 --- /dev/null +++ b/website/control-panel/public/cp-v2/citizen-directory.css @@ -0,0 +1,7 @@ +.migration-directory{--md-gold:#dfc17a;--md-line:#66846b;--md-muted:#bacbbb;--md-bg:#102b22;--md-panel:#17382b;color:#f2e7c8;font:14px/1.5 system-ui,sans-serif;display:grid;gap:18px} +.migration-directory [hidden]{display:none!important}.migration-directory h2,.migration-directory h3{margin:0;color:var(--md-gold);font-family:Georgia,serif}.migration-directory h2{font-size:24px}.migration-directory h3{font-size:19px}.migration-directory p{margin:0}.migration-directory button,.migration-directory input,.migration-directory select{font:inherit}.migration-directory button,.migration-directory a{color:var(--md-gold)} +.migration-directory button{padding:9px 14px;background:#102b22;border:1px solid #a98b4c;border-radius:8px;cursor:pointer}.migration-directory button:hover{background:#284a34}.migration-directory button:disabled{opacity:.45;cursor:default}.migration-directory button:focus-visible,.migration-directory input:focus-visible,.migration-directory select:focus-visible{outline:2px solid var(--md-gold);outline-offset:3px} +.migration-directory .md-tabs{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 18px}.migration-directory .md-tabs button[aria-current=true]{background:#d5b867;color:#14271b;border-color:#f0db9d}.migration-directory .md-muted,.migration-directory small{color:var(--md-muted)}.migration-directory small{display:block} +.migration-directory .md-tools{display:flex;align-items:end;flex-wrap:wrap;gap:12px;margin-bottom:18px}.migration-directory input,.migration-directory select{background:var(--md-bg);color:#f2e7c8;border:1px solid var(--md-line);border-radius:8px;padding:11px;min-width:0;max-width:100%;box-sizing:border-box}.migration-directory input[type=search]{flex:1 1 260px}.migration-directory .md-field{display:grid;gap:4px;flex:1 1 150px;color:var(--md-muted)} +.migration-directory .md-table-wrap{overflow:auto;border:1px solid var(--md-line);border-radius:12px}.migration-directory .md-table{border-collapse:collapse;width:100%;table-layout:auto;background:var(--md-bg)}.migration-directory .md-table th{padding:12px;text-align:left;color:var(--md-gold);background:#244b39;font-size:12px;text-transform:uppercase;letter-spacing:.04em}.migration-directory .md-table td{padding:12px;border-top:1px solid #355741;vertical-align:middle;overflow-wrap:anywhere}.migration-directory .md-table tr:nth-child(even){background:#153528}.migration-directory .md-table td:first-child button{background:transparent;border:0;padding:0;text-align:left;font-weight:600}.migration-directory .md-table td:last-child{white-space:nowrap}.migration-directory .md-badge{display:inline-block;border:1px solid #778b61;border-radius:20px;padding:3px 10px;font-size:12px;color:#d7e9c9} +.migration-directory .md-pager{display:flex;justify-content:end;align-items:center;gap:14px;margin-top:16px}.migration-directory .md-identity{display:flex;align-items:center;flex-wrap:wrap;gap:16px;margin:18px 0 22px;padding-bottom:20px;border-bottom:1px solid var(--md-line)}.migration-directory .md-identity img{object-fit:contain;border-radius:9px}.migration-directory .md-identity a{margin-left:auto}.migration-directory .md-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.migration-directory .md-box{border:1px solid var(--md-line);border-radius:12px;background:linear-gradient(130deg,#1d4230,#102b22);padding:20px;display:grid;gap:14px;margin-bottom:18px}.migration-directory .md-detail{display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px;padding:9px 0;border-bottom:1px solid #355741}.migration-directory .md-detail span{color:var(--md-muted)}.migration-directory .md-detail strong{overflow-wrap:anywhere}.migration-directory .md-assignment{border-left:3px solid #c7ad62;padding:8px 12px;background:#153326}.migration-directory .md-assignment strong{color:var(--md-gold)}.migration-directory .md-note{color:var(--md-muted);padding-top:12px}.migration-directory details{margin-top:12px}.migration-directory summary{color:var(--md-gold);cursor:pointer}.migration-directory .md-diagnostics{border-top:1px solid #476046;padding-top:16px}.migration-directory .md-diagnostics p{margin:12px 0}.migration-directory .md-status:empty{display:none}@media(max-width:850px){.migration-directory .md-grid{grid-template-columns:1fr}.migration-directory .md-table{min-width:650px}} diff --git a/website/control-panel/public/cp-v2/citizen-directory.mjs b/website/control-panel/public/cp-v2/citizen-directory.mjs new file mode 100644 index 00000000..6a6744ee --- /dev/null +++ b/website/control-panel/public/cp-v2/citizen-directory.mjs @@ -0,0 +1,64 @@ +import {applyShellHeading} from './cp-v2-page-template.mjs'; + +const API='/api/admin/citizens'; +const element=(tag,value,cls)=>{const e=document.createElement(tag);if(value!==undefined)e.textContent=value;if(cls)e.className=cls;return e;}; +const button=(label,action)=>{const b=element('button',label);b.type='button';b.onclick=action;return b;}; +const date=value=>value?new Date(Number(value)).toLocaleDateString('en-GB'):'Not recorded'; +const roleDescription=a=>a.assignments.map(x=>x.scopeLabel+' · '+x.roleLabel).join(' / '); +async function request(path,signal){const r=await fetch(path,{credentials:'same-origin',cache:'no-store',signal});const data=await r.json().catch(()=>({}));if(!r.ok)throw Error(data.message||'Directory unavailable.');return data;} + +export function mountCitizenDirectory(host){ + const root=element('section',undefined,'migration-directory'); + const css=document.createElement('link');css.rel='stylesheet';css.href='/v2/citizen-directory.css';root.append(css); + const view=element('div');const status=element('p','Loading directory…','md-status');status.setAttribute('role','status'); + const diagnostics=element('details',undefined,'md-diagnostics');diagnostics.append(element('summary','+ Workspace details'),element('p','Central account directory. Assignment catalogue preparation does not change existing permissions.'),button('Reload workspace',()=>load())); + root.append(status,view,diagnostics);host.replaceChildren(root); + let context='users',page=1,query='',filter='',department='',branch='',selected=null,tab='overview',disposed=false,controller,sequence=0,catalogue={departments:[]}; + let searchTimer; + function heading(){applyShellHeading(host,{title:selected?(context==='staff'?'Manage Staff':'Manage User'):'Citizen Directory',description:selected?selected.displayName+' · '+selected.username:'Find a citizen, then manage their account or staff responsibilities.',artwork:context==='staff'?'nav-staff-v2.webp':'nav-account-v2.webp'});} + function box(title){const section=element('section',undefined,'md-box');section.append(element('h3',title));return section;} + function detail(label,value){const row=element('div',undefined,'md-detail');row.append(element('span',label),element('strong',String(value??'Not recorded')));return row;} + function choices(label,items,value,onChange){const field=element('label',label,'md-field'),s=element('select');for(const [key,title]of items){const o=element('option',title);o.value=key;s.append(o);}s.value=value;s.onchange=()=>onChange(s.value);field.append(s);return field;} + function badge(label){return element('span',label,'md-badge');} + function assignments(){const panel=box(context==='staff'?'Staff assignments':'Memberships & offices'); + if(selected.assignments.length){for(const a of selected.assignments){const card=element('div',undefined,'md-assignment');card.append(element('strong',a.roleLabel),element('p',a.scopeLabel),badge(a.source||'Recorded assignment'));if(a.endsAt)card.append(element('small','Until '+date(a.endsAt)));panel.append(card);}} + else panel.append(element('p',context==='staff'?'No new-model staff assignments have been activated for this account.':'No memberships or offices have been registered in the new assignment model yet. Existing memberships remain in their source systems.','md-muted')); + panel.append(element('p','Assignment editing and automatic source integration are the next migration batch. Existing rights have not been replaced.','md-note')); + return panel; + } + function renderAccount(){ + view.replaceChildren();heading();const back=button('← '+(context==='staff'?'Staff Directory':'User Directory'),()=>{selected=null;void load();});view.append(back); + const hero=element('header',undefined,'md-identity');const avatar=element('img');avatar.alt='';avatar.width=56;avatar.height=56;avatar.src=selected.minecraftUuid?'/api/avatars/minecraft/'+encodeURIComponent(selected.minecraftUuid):'https://www.dunerealms.com/assets/nav-account-v2.webp'; + const names=element('div');names.append(element('h2',selected.displayName),element('p',selected.username,'md-muted'));const publicLink=element('a','View public profile →');publicLink.href='https://www.dunerealms.com/people/'+encodeURIComponent(selected.username);hero.append(avatar,names,badge(selected.status),publicLink);view.append(hero); + const tabs=context==='staff'?[['overview','Overview'],['account','Account'],['assignments','Staff assignments'],['honours','Seals & honours'],['activity','Activity']]:[['overview','Overview'],['account','Account'],['assignments','Memberships & offices'],['honours','Seals & honours'],['activity','Activity']]; + const nav=element('nav',undefined,'md-tabs');nav.setAttribute('aria-label','Manage '+(context==='staff'?'staff':'user'));for(const[key,label]of tabs){const b=button(label,()=>{tab=key;renderAccount();});b.setAttribute('aria-current',String(tab===key));nav.append(b);}view.append(nav); + if(tab==='overview'){ + const grid=element('div',undefined,'md-grid'),identity=box('Account summary');identity.append(detail('Minecraft',selected.minecraftName||'Not linked'),detail('Joined',date(selected.createdAt)),detail('Status',selected.status));grid.append(identity,assignments());view.append(grid); + if(context==='staff'&&selected.staffSources?.length){const source=box('Imported staff record');for(const row of selected.staffSources)source.append(detail('Source account',row.name),detail('Imported',date(row.importedAt)));source.append(element('p','Imported identity is evidence of the staff cohort, not a new permission grant.','md-muted'));view.append(source);} + }else if(tab==='account'){ + const identity=box('Linked identity');identity.append(detail('Username',selected.username),detail('Display name',selected.displayName),detail('Minecraft',selected.minecraftName||'Not linked'),detail('Status',selected.status));const advanced=element('details');advanced.append(element('summary','+ Advanced account details'),detail('Account ID',selected.id),detail('Minecraft UUID',selected.minecraftUuid||'Not linked'));identity.append(advanced);view.append(identity); + }else if(tab==='assignments')view.append(assignments()); + else if(tab==='honours'){const panel=box('Seals & honours');panel.append(element('p','Existing awards are preserved. The new seal ledger and compact award controls follow in the recognition batch.','md-muted'));panel.append(publicLink.cloneNode(true));view.append(panel);} + else{const panel=box('Account activity');panel.append(element('p','The audited assignment timeline will be connected with assignment editing. No historical account records have been removed.','md-muted'));view.append(panel);} + } + function renderList(data){ + const restoreSearch=document.activeElement===view.querySelector('input[type="search"]'); + view.replaceChildren();heading();const nav=element('nav',undefined,'md-tabs');nav.setAttribute('aria-label','Directory type');for(const[key,label]of [['users','Users'],['staff','Staff']]){const b=button(label,()=>{if(context===key)return;context=key;page=1;department='';branch='';void load();});b.setAttribute('aria-current',String(context===key));nav.append(b);}view.append(nav); + const toolbar=element('form',undefined,'md-tools');const search=element('input');search.type='search';search.value=query;search.placeholder='Name, Minecraft UUID or account ID';search.setAttribute('aria-label','Search all directory records');search.oninput=()=>{query=search.value;clearTimeout(searchTimer);searchTimer=setTimeout(()=>{page=1;void load();},350);}; + toolbar.onsubmit=e=>{e.preventDefault();clearTimeout(searchTimer);page=1;void load();};toolbar.append(search,choices('Status',[['','All statuses'],['active','Active'],['banned','Banned'],['deleted','Deleted']],filter,value=>{filter=value;page=1;void load();})); + if(context==='staff'){ + toolbar.append(choices('Department',[['','All departments'],...catalogue.departments.map(d=>[d.key,d.label])],department,value=>{department=value;branch='';page=1;void load();})); + const branches=catalogue.departments.filter(d=>!department||d.key===department).flatMap(d=>d.branches); + toolbar.append(choices('Branch',[['','All branches'],...branches.map(b=>[b.key,b.label])],branch,value=>{branch=value;page=1;void load();})); + }view.append(toolbar);if(restoreSearch){search.focus({preventScroll:true});search.setSelectionRange(search.value.length,search.value.length);} + const wrap=element('div',undefined,'md-table-wrap'),table=element('table',undefined,'md-table'),head=element('thead'),tr=element('tr'); + for(const label of ['Citizen','Status',context==='staff'?'Functions':'Memberships & offices','Minecraft',''])tr.append(element('th',label));head.append(tr);table.append(head);const body=element('tbody'); + for(const a of data.accounts){const row=element('tr');const name=element('td');name.append(button(a.displayName,()=>open(a.id)),element('small',a.username));const state=element('td');state.append(badge(a.status));row.append(name,state,element('td',roleDescription(a)||(context==='staff'?'Awaiting migration':'Source integration pending'),'md-muted'),element('td',a.minecraftName||'Not linked'));const action=element('td');action.append(button('Manage →',()=>open(a.id)));row.append(action);body.append(row);} + if(!data.accounts.length){const row=element('tr'),cell=element('td','No matching '+(context==='staff'?'staff accounts.':'users.'));cell.colSpan=5;row.append(cell);body.append(row);}table.append(body);wrap.append(table);view.append(wrap); + const pager=element('div',undefined,'md-pager'),previous=button('Previous',()=>{page--;void load();}),next=button('Next',()=>{page++;void load();});previous.disabled=page===1;next.disabled=!data.hasMore;pager.append(previous,element('span','Page '+page),next);view.append(pager); + if(context==='staff'&&(department||branch))view.append(element('p','Department and branch filters use new-model assignments. Imported accounts appear in All staff until their assignments are migrated.','md-note')); + } + async function open(id){controller?.abort();controller=new AbortController();const current=++sequence;status.textContent='Loading account…';try{const data=await request(API+'/'+encodeURIComponent(id)+'?context='+context,controller.signal);if(disposed||current!==sequence)return;selected=data.account;tab='overview';renderAccount();status.textContent='';}catch(e){if(!disposed&&e.name!=='AbortError')status.textContent=e.message;}} + async function load(){controller?.abort();controller=new AbortController();const current=++sequence;status.textContent='Loading '+context+'…';try{if(context==='staff'&&!catalogue.departments.length)catalogue=await request(API+'/catalogue?context=staff',controller.signal);const params=new URLSearchParams({context,page:String(page),q:query,status:filter,department,branch});const data=await request(API+'?'+params,controller.signal);if(disposed||current!==sequence)return;selected=null;renderList(data);status.textContent=data.accounts.length+' records on this page · search covers the complete directory.';}catch(e){if(!disposed&&e.name!=='AbortError'){view.replaceChildren();status.textContent=e.message;}}} + void load();return()=>{disposed=true;sequence++;clearTimeout(searchTimer);controller?.abort();root.remove();}; +} diff --git a/website/control-panel/public/cp-v2/v2.js b/website/control-panel/public/cp-v2/v2.js index 2507d69e..dc1bb1b9 100644 --- a/website/control-panel/public/cp-v2/v2.js +++ b/website/control-panel/public/cp-v2/v2.js @@ -199,8 +199,9 @@ overview.append(el('p','hint',descriptor.description)); if(w.id==='bureau'&&item.id==='user-management'){ const host=el('div','citizen-live-host');overview.append(host); const state=el('p','alpha-muted','Loading the authorized Citizens Registry…');host.append(state); - import('/v2/citizens-registry.mjs?v=cpalpha-20261112c').then(({mountCitizensRegistry})=>{ - if(host.isConnected)mountCitizensRegistry(host) + const migrationPreview=new URL(location.href).searchParams.get('migration')==='1'; + import(migrationPreview?'/v2/citizen-directory.mjs':'/v2/citizens-registry.mjs?v=cpalpha-20261112c').then(module=>{ + if(host.isConnected)disposePage=migrationPreview?module.mountCitizenDirectory(host):module.mountCitizensRegistry(host) }).catch(error=>{if(host.isConnected)state.textContent='Citizens Registry could not load: '+error.message}); history.replaceState(null,'','#'+w.id+'/'+item.id); return; diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 26a4967a..cc8b7ef7 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -68,6 +68,8 @@ import {sharedErrorResponse} from '../node/shared-errors.mjs'; import {initializeNews} from '../node/news.mjs'; import {initializeStaffBureau} from '../node/staff-bureau-schema.mjs'; import {createStaffBureauReadApi} from '../node/staff-bureau-read-api.mjs'; +import {initializeOrganisation} from '../node/organisation-model.mjs'; +import {createCitizenDirectory} from '../node/citizen-directory.mjs'; import {initializeRanks,initializeCommunityAccess,initializeQuestAccess,initializeBankAccess,can,accessFor} from '../node/permissions.mjs'; import {createServer} from 'node:http'; import {createV1PersonalBank} from './api-v1-personal-bank.mjs'; @@ -105,6 +107,7 @@ export function createPanel(db,settings={},dependencies={}){ const honours=createHonourRoute(db,origin);const ranks=createRankAdmin(db,settings,origin);const badges=createBadgeAdmin(db,origin);const manualSeals=createManualSealRoute(db,origin);const sealCatalog=createSealCatalogAdmin(db,origin);const companyAdmin=createCompanyAdmin(db,origin); const manual=createStaffManual(db); const staffBureauRead=createStaffBureauReadApi(db); + const citizenDirectory=createCitizenDirectory(db); const luckperms=createLuckPerms(db,settings,dependencies.luckperms); const servers=createServerControl(db,settings,dependencies.serverControl); const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}}; @@ -155,6 +158,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/politics/applications')return electionApplications(request); if(path==='/api/politics/preview')return politicsPreview(request); if(path==='/api/admin/register-user')return adminRegistration(request); + if(path==='/api/admin/citizens'||path.startsWith('/api/admin/citizens/'))return citizenDirectory(request); if(path==='/api/account/email')return contactEmail(request); if(path.startsWith('/api/people/'))return memberProfiles(request); if(path==='/profile-login'&&request.method==='GET'){ @@ -244,6 +248,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});} if(path==='/federal-reserve'||path==='/federal-reserve/')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/reserve-ledger.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); // V2 shell is public; private data and writes retain their authenticated API gates. + if(['/v2/citizen-directory.mjs','/v2/citizen-directory.css'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice('/v2/'.length),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-authorisations.mjs','/v2/cp-v2-tax-treasury.mjs','/v2/cp-v2-reserve-ledger.mjs','/v2/cp-v2-reserve-entry.mjs','/v2/cp-v2-postbank-credit.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){ const moduleFile=path.endsWith('.mjs')||path.endsWith('.js'); const file=path.endsWith('.mjs')?path.slice('/v2/'.length):path.endsWith('.js')?'v2.js':path.endsWith('.css')?'v2.css':'index.html'; @@ -262,7 +267,7 @@ export async function startPanel(settings=process.env){ inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); } const bankDatabase=await openPostbankDatabase(settings); - const db=await openDatabase(settings);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool,bankDatabase}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const db=await openDatabase(settings);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);const handle=createPanel(db,settings,{inventoryPool,bankDatabase}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db); const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db),stopPostbankQueue=startPostbankQueue(db,bankDatabase,settings); const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com"}; diff --git a/website/docs/great-migration.md b/website/docs/great-migration.md new file mode 100644 index 00000000..d82ea09d --- /dev/null +++ b/website/docs/great-migration.md @@ -0,0 +1,57 @@ +# Alpha 1.0.0.7 — The Great Migration + +## Batch 1: central directory and contextual account views + +The existing CP account tool mixes staff access, user memberships and recognition. +The new directory separates Users and Staff while keeping one underlying account. + +Review URL after this batch is deployed: +`https://cp.dunerealms.com/?migration=1#bureau/user-management`. +The regular URL continues to use the existing editor during this incremental batch. + +Included: + +- Central organisation vocabulary: two departments, nine branches, contextual roles. +- Additive `org_assignments` storage, indexed by account and scope. +- Read-only `/api/admin/citizens`, `/catalogue`, and `/:accountId` endpoints. +- Server-side whole-directory search by account name, Minecraft name/UUID or ID, + contextual staff filtering and 25-record pagination with an extra sentinel row. +- Users, Manage User and Manage Staff views. User responses exclude staff scopes + and staff provenance. Staff views retain imported source identity for review. +- Existing account administration and all live permissions remain unchanged. + +Not claimed complete: assignment writes, permission activation/projection, native +integration migration, the recognition editor and the audit timeline. Their UI +states are explicitly marked as subsequent batches. Existing memberships have not +yet been imported into `org_assignments`; an empty new-model list is not a claim +that the citizen has no memberships in existing systems. + +Validation: contextual disclosure, authentication and authorisation denials, +SQL parameterisation/literal wildcard search, filter validation, schema no-grant +behaviour, and pagination are covered by executable tests. No financial actions, +player identities or live staff appointments are changed by this batch. + +## Migration rules + +Reuse the existing API, database adapter and integration adapters. Do not rewrite +osTicket, MyBB or LuckPerms. Human ranks lose native user/group/permission editing +capabilities; those writes originate centrally. Do not remove or lock the native +modules. Dev retains existing service access, separate from the human organigram. + +Official bank account management is reserved for the Big Four and Department Heads. +Existing system-account restrictions remain. Staff ranks contain explicit job +nodes, without wildcard or OP grants. Assignments may overlap and expire; their +derived rights/seals must follow their lifecycle. Earned honours remain intact. + +## Subsequent batches + +1. Contextual assignment editor, audited changes and central policy matrix. +2. Map current rights to the approved hierarchy and existing native adapters; + synchronisation/revocation, visible failures and retry. +3. Recognition, personal and function seals, signatures across connected systems. +4. Public staff organigram + ordered bio cards; separate Crysknife Order gallery. +5. Full public profile template preserving current features; verified Bedrock-name + normalisation; Picard memorial restyle/link and Big-Four-only Deceased workflow. +6. Access/lifecycle/privacy verification, release and combined .6/.7 announcement. + +Do not change the public version banner or publish release news before .7 is done. diff --git a/website/node/citizen-directory.mjs b/website/node/citizen-directory.mjs new file mode 100644 index 00000000..18bb2059 --- /dev/null +++ b/website/node/citizen-directory.mjs @@ -0,0 +1,75 @@ +import {identity} from './auth.mjs'; +import {can} from './permissions.mjs'; +import {ORGANISATION,ASSIGNMENT_ROLES,STAFF_SCOPE_TYPES,assignmentLabel} from './organisation-model.mjs'; + +const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}}); +const LEGACY_STAFF=['staff','corestaff','owners','official_account','web_net_admin','web_net_owner','web_network','network_admin','web_dev']; +const STATUS_SQL="CASE WHEN a.password_hash='!deleted' THEN 'deleted' WHEN a.password_hash='!banned' THEN 'banned' ELSE 'active' END"; +const fields=`a.id,a.username,a.display_name,a.created_at,${STATUS_SQL} AS account_status, + (SELECT l.minecraft_name FROM site_game_links l WHERE l.user_id=a.id LIMIT 1) AS minecraft_name, + (SELECT l.minecraft_uuid FROM site_game_links l WHERE l.user_id=a.id LIMIT 1) AS minecraft_uuid`; +const placeholders=LEGACY_STAFF.map(()=>'?').join(','); +const activeStaff=`EXISTS (SELECT 1 FROM org_assignments o WHERE o.user_id=a.id AND o.scope_type IN ('organisation','department','branch') AND o.status='active' AND o.starts_at<=? AND (o.ends_at IS NULL OR o.ends_at>?))`; +const importedStaff='EXISTS (SELECT 1 FROM staff_source_members s WHERE s.user_id=a.id)'; +const legacyStaff=`(a.role IN (${placeholders}) OR EXISTS (SELECT 1 FROM cp_account_ranks cr WHERE cr.user_id=a.id AND cr.rank_key IN (${placeholders})))`; + +export function directoryFilters(url,now=Date.now()){ + const context=url.searchParams.get('context')||'users'; + if(!['users','staff'].includes(context))throw new Error('Invalid directory context.'); + const query=(url.searchParams.get('q')||'').trim(); + if(query.length>80)throw new Error('Search must be at most 80 characters.'); + const pageText=url.searchParams.get('page')||'1'; + if(!/^[1-9]\d{0,3}$/.test(pageText))throw new Error('Invalid page.'); + const status=url.searchParams.get('status')||''; + if(status&&!['active','banned','deleted'].includes(status))throw new Error('Invalid status.'); + const department=url.searchParams.get('department')||'',branch=url.searchParams.get('branch')||''; + if(context==='users'&&(department||branch))throw new Error('Staff filters require Staff context.'); + const dept=ORGANISATION.find(d=>d.key===department); + if(department&&!dept)throw new Error('Invalid department.'); + if(branch&&!(dept?dept.branches:ORGANISATION.flatMap(d=>d.branches)).some(b=>b.key===branch))throw new Error('Invalid branch.'); + const where=[],values=[]; + if(context==='staff'){where.push(`(${activeStaff} OR ${importedStaff} OR ${legacyStaff})`);values.push(now,now,...LEGACY_STAFF,...LEGACY_STAFF);where.push('NOT EXISTS (SELECT 1 FROM site_account_policies service WHERE service.user_id=a.id AND service.game_link_exempt=1)');} + if(query){where.push('(a.username LIKE ? OR a.id=? OR EXISTS (SELECT 1 FROM site_game_links gl WHERE gl.user_id=a.id AND (gl.minecraft_uuid=? OR gl.minecraft_name LIKE ?)))');const term='%'+query.replace(/[=%_]/g,c=>'='+c)+'%';values.push(term,query,query,term);where[where.length-1]=where.at(-1).replaceAll('LIKE ?',"LIKE ? ESCAPE '='");} + if(status){where.push(STATUS_SQL+'=?');values.push(status);} + if(department||branch){ + const keys=branch?[branch]:[department,...dept.branches.map(b=>b.key)]; + where.push(`EXISTS (SELECT 1 FROM org_assignments f WHERE f.user_id=a.id AND f.scope_type IN ('department','branch') AND f.scope_key IN (${keys.map(()=>'?')}) AND f.status='active' AND f.starts_at<=? AND (f.ends_at IS NULL OR f.ends_at>?))`);values.push(...keys,now,now); + } + return {context,page:Number(pageText),where:where.length?' WHERE '+where.join(' AND '):'',values}; +} +function project(row){return {id:row.id,username:row.username,displayName:row.display_name||row.username, + status:row.account_status,createdAt:Number(row.created_at),minecraftName:row.minecraft_name||null,minecraftUuid:row.minecraft_uuid||null};} + +export function createCitizenDirectory(db,{authenticate=identity,authorize=can,clock=Date.now}={}){ + async function assignments(ids,context){ + if(!ids.length)return []; + const scopeClause=context==='users'?"NOT IN ('organisation','department','branch')":"IN ('organisation','department','branch')"; + const now=clock(); + const {results}=await db.prepare(`SELECT id,user_id,scope_type,scope_key,role_key,source_kind,starts_at,ends_at,version FROM org_assignments WHERE user_id IN (${ids.map(()=>'?')}) AND scope_type ${scopeClause} AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) ORDER BY scope_type,scope_key,role_key`).bind(...ids,now,now).all(); + return results; + } + return async request=>{ + if(request.method!=='GET')return reply({message:'This directory endpoint is read-only.'},405); + const actor=await authenticate(request,db);if(!actor)return reply({message:'Sign in first.'},401); + if(!await authorize(db,actor,'web.accounts.view'))return reply({message:'Account directory permission required.'},403); + const url=new URL(request.url);let filter;try{filter=directoryFilters(url,clock());}catch(e){return reply({message:e.message},400);} + if(url.pathname==='/api/admin/citizens/catalogue')return reply({departments:filter.context==='staff'?ORGANISATION:[],roles:Object.fromEntries(Object.entries(ASSIGNMENT_ROLES).filter(([key])=>STAFF_SCOPE_TYPES.includes(key)===(filter.context==='staff'))),assignmentMode:'preparing',permissionsChanged:false}); + const match=url.pathname.match(/^\/api\/admin\/citizens\/([0-9a-f-]{36})$/i); + if(match){ + const row=await db.prepare(`SELECT ${fields} FROM site_accounts a WHERE a.id=?${filter.where?' AND '+filter.where.slice(7):''}`).bind(match[1],...filter.values).first(); + if(!row)return reply({message:'Account not found.'},404); + const current=await assignments([row.id],filter.context); + const account={...project(row),assignments:current.map(assignmentLabel)}; + // Staff provenance and legacy staff ranks never leave the Staff view. + if(filter.context==='staff'){ + const {results}=await db.prepare('SELECT source_name,source_ref,imported_at FROM staff_source_members WHERE user_id=? ORDER BY source_key').bind(row.id).all(); + account.staffSources=results.map(s=>({name:s.source_name,reference:s.source_ref,importedAt:Number(s.imported_at)})); + } + return reply({account,context:filter.context,assignmentMode:'preparing',permissionsChanged:false}); + } + if(url.pathname!=='/api/admin/citizens')return reply({message:'Not found.'},404); + const {results}=await db.prepare(`SELECT ${fields} FROM site_accounts a${filter.where} ORDER BY a.username,a.id LIMIT ? OFFSET ?`).bind(...filter.values,26,(filter.page-1)*25).all(); + const rows=results.slice(0,25),current=await assignments(rows.map(a=>a.id),filter.context); + return reply({accounts:rows.map(row=>({...project(row),assignments:current.filter(a=>a.user_id===row.id).map(assignmentLabel)})),page:filter.page,pageSize:25,hasMore:results.length>25,context:filter.context,assignmentMode:'preparing'}); + }; +} diff --git a/website/node/organisation-model.mjs b/website/node/organisation-model.mjs new file mode 100644 index 00000000..451b119a --- /dev/null +++ b/website/node/organisation-model.mjs @@ -0,0 +1,56 @@ +// Central assignment vocabulary. This catalogue never grants permissions by itself. +export const ORGANISATION = [ + {key:'community_operations',label:'Community Operations',branches:[ + {key:'customer_support',label:'Customer Support'}, + {key:'sales_accounts',label:'Sales & Account Services'}, + {key:'content_creative',label:'Content & Creative'}, + {key:'news_media',label:'News & Media'}]}, + {key:'dunerealms_operations',label:'DuneRealms Operations',branches:[ + {key:'trust_safety',label:'Trust & Safety'}, + {key:'it_operations',label:'IT Operations'}, + {key:'engineering',label:'Engineering'}, + {key:'people_operations',label:'People Operations'}, + {key:'legal_compliance',label:'Legal & Compliance'}]} +]; +export const STAFF_SCOPE_TYPES = ['organisation','department','branch']; +export const ASSIGNMENT_ROLES = { + organisation:[{key:'owner_ceo',label:'Owner & CEO'},{key:'executive',label:'Executive'}], + department:[{key:'department_head',label:'Department Head'}], + branch:[{key:'branch_lead',label:'Branch Lead'},{key:'officer',label:'Officer'}], + clan:[{key:'leader',label:'Clan Leader'},{key:'officer',label:'Clan Officer'},{key:'member',label:'Clan Member'}], + house:[{key:'member',label:'House Member'},{key:'leader',label:'House Leader'},{key:'mentat',label:'Mentat'}], + office:[{key:'emperor',label:'Emperor'},{key:'water_rights',label:'Water Rights'},{key:'spice_rights',label:'Spice Rights'}], + company:[{key:'owner',label:'Company Owner'},{key:'director',label:'Company Director'},{key:'delegate',label:'Company Delegate'}], + order:[{key:'member',label:'Order Member'}], + service:[{key:'officeholder',label:'Service Officeholder'}] +}; +export function assignmentLabel(row){ + const scopeType=row.scope_type??row.scopeType,scopeKey=row.scope_key??row.scopeKey,roleKey=row.role_key??row.roleKey; + const scopes=ORGANISATION.flatMap(d=>[d,...d.branches]); + return {scopeType,scopeKey,scopeLabel:scopeType==='organisation'?'DuneRealms':scopes.find(s=>s.key===scopeKey)?.label||scopeKey, + role:roleKey,roleLabel:ASSIGNMENT_ROLES[scopeType]?.find(r=>r.key===roleKey)?.label||roleKey, + source:row.source_kind??row.source,startsAt:row.starts_at??row.startsAt,endsAt:row.ends_at??row.endsAt, + id:row.id,version:Number(row.version||1)}; +} +export const organisationSchema = [ + `CREATE TABLE IF NOT EXISTS org_assignments ( + id CHAR(36) PRIMARY KEY, user_id CHAR(36) NOT NULL, + scope_type VARCHAR(24) NOT NULL, scope_key VARCHAR(80) NOT NULL, role_key VARCHAR(40) NOT NULL, + source_kind VARCHAR(24) NOT NULL, source_ref VARCHAR(160) NULL, + status VARCHAR(16) NOT NULL DEFAULT 'active', starts_at BIGINT NOT NULL, ends_at BIGINT NULL, + created_by CHAR(36) NOT NULL, created_at BIGINT NOT NULL, version INT NOT NULL DEFAULT 1, + INDEX org_user_status(user_id,status), INDEX org_scope_role(scope_type,scope_key,role_key,status), + FOREIGN KEY(user_id) REFERENCES site_accounts(id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS staff_source_members ( + user_id CHAR(36) NOT NULL, source_key VARCHAR(40) NOT NULL, source_name VARCHAR(80) NOT NULL, + source_uuid CHAR(36) NOT NULL, source_ranks_json TEXT NOT NULL, source_ref VARCHAR(255) NOT NULL, + imported_at BIGINT NOT NULL, imported_by CHAR(36) NOT NULL, + PRIMARY KEY(user_id,source_key), UNIQUE KEY staff_source_uuid(source_key,source_uuid), + FOREIGN KEY(user_id) REFERENCES site_accounts(id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4` +]; +export async function initializeOrganisation(db){ + for(const sql of organisationSchema)await db.prepare(sql).run(); + // No automatic appointments, account rewrites, rank resets or game grants. +} diff --git a/website/tests/citizen-directory.test.mjs b/website/tests/citizen-directory.test.mjs new file mode 100644 index 00000000..83a8c172 --- /dev/null +++ b/website/tests/citizen-directory.test.mjs @@ -0,0 +1,64 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {createCitizenDirectory,directoryFilters} from '../node/citizen-directory.mjs'; +import {ORGANISATION,initializeOrganisation} from '../node/organisation-model.mjs'; + +const id='49d2fe76-7977-4d49-bd39-e48fc8c648b8'; +const row={id,username:'example',display_name:'Example',created_at:100,account_status:'active',minecraft_name:'Example',minecraft_uuid:id}; +const assignment=(type,key,role)=>({id:'assignment',user_id:id,scope_type:type,scope_key:key,role_key:role,source_kind:'appointment',starts_at:1,ends_at:null}); +function fixture({rows=[row],grants=[assignment('clan','clan-example','member'),assignment('branch','trust_safety','officer')],authenticated=true,allowed=true}={}){ + const queries=[]; + const db={prepare(sql){let args=[];queries.push({sql,get args(){return args;}});return {bind(...v){args=v;return this;},async first(){return rows.find(r=>r.id===args[0])||null;},async all(){ + if(sql.includes('FROM org_assignments WHERE'))return {results:grants.filter(g=>sql.includes("scope_type NOT IN")?!['organisation','department','branch'].includes(g.scope_type):['organisation','department','branch'].includes(g.scope_type))}; + if(sql.includes('FROM staff_source_members WHERE'))return {results:[{source_name:'.bedrock',source_ref:'private-staff-source',imported_at:10}]}; + return {results:rows}; + }}}}; + return {queries,api:createCitizenDirectory(db,{authenticate:async()=>authenticated?{id,role:'user'}:null,authorize:async()=>allowed,clock:()=>50})}; +} +const req=(path='?context=users',method='GET')=>new Request('https://cp.dunerealms.com/api/admin/citizens'+path,{method}); +test('directory rejects guests and unprivileged users before database reads',async()=>{ + for(const [options,status]of [[{authenticated:false},401],[{allowed:false},403]]){const f=fixture(options);assert.equal((await f.api(req())).status,status);assert.equal(f.queries.length,0);} +}); +test('directory is read-only; catalog registration never seeds appointments or grants',async()=>{ + assert.equal((await fixture().api(req('','POST'))).status,405); + const statements=[];await initializeOrganisation({prepare(sql){statements.push(sql);return{run:async()=>{}};}}); + assert.ok(statements.every(sql=>sql.startsWith('CREATE TABLE IF NOT EXISTS'))); + assert.equal(ORGANISATION.length,2);assert.equal(ORGANISATION.flatMap(d=>d.branches).length,9); +}); +test('user detail never contains staff sources, legacy staff rank or staff assignments',async()=>{ + const f=fixture();const response=await f.api(req('/'+id+'?context=users'));const data=await response.json(); + assert.equal(response.status,200);assert.equal(data.account.assignments.length,1);assert.equal(data.account.assignments[0].scopeType,'clan'); + assert.equal(data.account.staffSources,undefined);assert.equal(data.account.primaryRank,undefined); + assert.equal(f.queries.some(q=>q.sql.includes('FROM staff_source_members WHERE')),false); +}); +test('staff detail only contains staff scopes and includes imported provenance',async()=>{ + const response=await fixture().api(req('/'+id+'?context=staff'));const data=await response.json(); + assert.equal(data.account.assignments.length,1);assert.equal(data.account.assignments[0].scopeLabel,'Trust & Safety');assert.equal(data.account.assignments[0].roleLabel,'Officer'); + assert.equal(data.account.staffSources[0].name,'.bedrock');assert.equal(data.permissionsChanged,false); +}); +test('invalid contexts and incompatible department/branch filters fail before SQL',async()=>{ + for(const suffix of ['?context=owner','?context=users&branch=engineering','?context=staff&department=community_operations&branch=engineering','?page=0','?page=1;DROP','?q='+('x'.repeat(81))]){ + const f=fixture();assert.equal((await f.api(req(suffix))).status,400,suffix);assert.equal(f.queries.length,0); + } +}); +test('SQL search is parameterised and treats wildcard characters literally',()=>{ + const f=directoryFilters(new URL("https://cp.dunerealms.com/?q=%25_%3D'%20OR%201%3D1")); + assert.ok(!f.where.includes("OR 1=1"));assert.ok(f.where.includes("ESCAPE '='"));assert.ok(f.values[0].includes('=%=_=='));assert.equal(f.values.length,4); +}); +test('staff cohort and scoped filters use parameterised fresh active assignment checks',()=>{ + const f=directoryFilters(new URL('https://cp.dunerealms.com/?context=staff&department=dunerealms_operations&branch=engineering'),500); + assert.ok(f.where.includes('staff_source_members'));assert.ok(f.where.includes('cp_account_ranks'));assert.ok(f.where.includes('starts_at<=?'));assert.ok(f.where.includes('service.game_link_exempt=1')); + assert.deepEqual(f.values.slice(-3),['engineering',500,500]);assert.ok(!f.where.includes("scope_key IN ('engineering')")); +}); +test('directory pagination uses an extra sentinel record, not row count guessing',async()=>{ + const rows=Array.from({length:26},(_,i)=>({...row,id:String(i)}));const f=fixture({rows,grants:[]});const data=await (await f.api(req('?page=2'))).json(); + assert.equal(data.accounts.length,25);assert.equal(data.hasMore,true);assert.equal(data.page,2);assert.deepEqual(f.queries[0].args.slice(-2),[26,25]); +}); +test('empty and missing accounts are handled explicitly',async()=>{ + const f=fixture({rows:[]});assert.equal((await (await f.api(req())).json()).hasMore,false);assert.equal((await f.api(req('/'+id))).status,404); +}); +test('catalogue respects the same user/staff context split',async()=>{ + const api=fixture().api; + const users=await (await api(req('/catalogue?context=users'))).json();assert.equal(users.departments.length,0);assert.equal(users.roles.branch,undefined);assert.ok(users.roles.clan); + const staff=await (await api(req('/catalogue?context=staff'))).json();assert.equal(staff.departments.length,2);assert.equal(staff.roles.clan,undefined);assert.ok(staff.roles.branch); +});