From ee6018a6537f20d0f393f0edaa1ba05632e0ca6e Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:42:55 +0100 Subject: [PATCH 01/16] Keep production and two rollback releases after promotion --- website/ops/dunerealms-release-retention.conf | 3 + website/ops/prune-deployment-releases.py | 68 +++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 website/ops/dunerealms-release-retention.conf create mode 100644 website/ops/prune-deployment-releases.py diff --git a/website/ops/dunerealms-release-retention.conf b/website/ops/dunerealms-release-retention.conf new file mode 100644 index 00000000..401085a4 --- /dev/null +++ b/website/ops/dunerealms-release-retention.conf @@ -0,0 +1,3 @@ +[Service] +# Runs after the existing CP sync. Shared promoter lock prevents races. +ExecStartPost=/usr/local/sbin/dunerealms-prune-releases --apply diff --git a/website/ops/prune-deployment-releases.py b/website/ops/prune-deployment-releases.py new file mode 100644 index 00000000..23ef2ca6 --- /dev/null +++ b/website/ops/prune-deployment-releases.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Retain production and two rollback releases; preserve live dependencies.""" +import argparse +import fcntl +import json +import pathlib +import re +import shutil + + +def candidates(app): + releases = (app / 'releases').resolve(strict=True) + current = (app / 'current').resolve(strict=True) + if current.parent != releases: + raise RuntimeError('Current release is outside the release directory') + versions = [p for p in releases.iterdir() + if not p.is_symlink() and p.is_dir() + and re.fullmatch(r'ci-[0-9a-f]{40}', p.name)] + keep = {current} + keep.update(sorted((p for p in versions if p != current), + key=lambda p: p.stat().st_mtime, reverse=True)[:2]) + # Explicit rollback links and shared node_modules must remain usable. + keep.update(p.resolve(strict=True) for p in app.iterdir() if p.is_symlink()) + for proc in pathlib.Path('/proc').glob('[0-9]*/cwd'): + try: + location = proc.resolve(strict=True) + if location.parent == releases: + keep.add(location) + except (OSError, RuntimeError): + pass + pending = list(keep) + while pending: + directory = pending.pop() + if directory.parent != releases or not directory.is_dir(): + continue + for link in directory.rglob('*'): + if not link.is_symlink(): + continue + target = link.resolve(strict=True) + if target.is_relative_to(releases): + owner = releases / target.relative_to(releases).parts[0] + if owner not in keep: + keep.add(owner) + pending.append(owner) + return releases, [p for p in versions if p not in keep], keep + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--apply', action='store_true') + args = parser.parse_args() + app = pathlib.Path('/home/dunerealms/apps/dunerealms') + # Share the promoter lock: never remove a candidate during traffic switch. + with open('/var/lib/dunerealms-ci-promote/safe-lock', 'a') as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + releases, obsolete, keep = candidates(app) + for release in obsolete: + if release.is_symlink() or release.resolve().parent != releases: + raise RuntimeError('Unsafe deletion target') + if args.apply: + shutil.rmtree(release) + print(json.dumps({'applied': args.apply, + 'obsolete': [p.name for p in obsolete], + 'protected': sorted(p.name for p in keep)})) + + +if __name__ == '__main__': + main() From 95b18e8279d6946707e2273d1ea7a3aef44b962d Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:42:03 +0100 Subject: [PATCH 02/16] Add central citizen directory with separate user and staff previews --- .../public/cp-v2/citizen-directory.css | 7 ++ .../public/cp-v2/citizen-directory.mjs | 64 ++++++++++++++++ website/control-panel/public/cp-v2/v2.js | 5 +- website/control-panel/server.mjs | 7 +- website/docs/great-migration.md | 57 ++++++++++++++ website/node/citizen-directory.mjs | 75 +++++++++++++++++++ website/node/organisation-model.mjs | 56 ++++++++++++++ website/tests/citizen-directory.test.mjs | 64 ++++++++++++++++ 8 files changed, 332 insertions(+), 3 deletions(-) create mode 100644 website/control-panel/public/cp-v2/citizen-directory.css create mode 100644 website/control-panel/public/cp-v2/citizen-directory.mjs create mode 100644 website/docs/great-migration.md create mode 100644 website/node/citizen-directory.mjs create mode 100644 website/node/organisation-model.mjs create mode 100644 website/tests/citizen-directory.test.mjs 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); +}); From 396d2f3e2e7f8f2ae668d1b32fe6654bf277add8 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:41:54 +0100 Subject: [PATCH 03/16] Add audited staff assignments and central policy mapping editor --- .../public/cp-v2/citizen-directory.css | 1 + .../public/cp-v2/citizen-directory.mjs | 55 +++++++- .../public/cp-v2/organisation-permissions.mjs | 33 +++++ website/control-panel/public/cp-v2/v2.js | 1 + website/control-panel/server.mjs | 5 +- website/docs/great-migration.md | 45 ++++++- website/node/citizen-directory.mjs | 5 +- website/node/organisation-management.mjs | 126 ++++++++++++++++++ website/node/organisation-model.mjs | 32 +++++ .../bootstrap-organisation-control.mjs | 28 ++++ .../tests/organisation-management.test.mjs | 86 ++++++++++++ 11 files changed, 408 insertions(+), 9 deletions(-) create mode 100644 website/control-panel/public/cp-v2/organisation-permissions.mjs create mode 100644 website/node/organisation-management.mjs create mode 100644 website/scripts/bootstrap-organisation-control.mjs create mode 100644 website/tests/organisation-management.test.mjs diff --git a/website/control-panel/public/cp-v2/citizen-directory.css b/website/control-panel/public/cp-v2/citizen-directory.css index 79651c18..7de19620 100644 --- a/website/control-panel/public/cp-v2/citizen-directory.css +++ b/website/control-panel/public/cp-v2/citizen-directory.css @@ -5,3 +5,4 @@ .migration-directory .md-tools{display:flex;align-items:end;flex-wrap:wrap;gap:12px;margin-bottom:18px}.migration-directory input,.migration-directory select{background:var(--md-bg);color:#f2e7c8;border:1px solid var(--md-line);border-radius:8px;padding:11px;min-width:0;max-width:100%;box-sizing:border-box}.migration-directory input[type=search]{flex:1 1 260px}.migration-directory .md-field{display:grid;gap:4px;flex:1 1 150px;color:var(--md-muted)} .migration-directory .md-table-wrap{overflow:auto;border:1px solid var(--md-line);border-radius:12px}.migration-directory .md-table{border-collapse:collapse;width:100%;table-layout:auto;background:var(--md-bg)}.migration-directory .md-table th{padding:12px;text-align:left;color:var(--md-gold);background:#244b39;font-size:12px;text-transform:uppercase;letter-spacing:.04em}.migration-directory .md-table td{padding:12px;border-top:1px solid #355741;vertical-align:middle;overflow-wrap:anywhere}.migration-directory .md-table tr:nth-child(even){background:#153528}.migration-directory .md-table td:first-child button{background:transparent;border:0;padding:0;text-align:left;font-weight:600}.migration-directory .md-table td:last-child{white-space:nowrap}.migration-directory .md-badge{display:inline-block;border:1px solid #778b61;border-radius:20px;padding:3px 10px;font-size:12px;color:#d7e9c9} .migration-directory .md-pager{display:flex;justify-content:end;align-items:center;gap:14px;margin-top:16px}.migration-directory .md-identity{display:flex;align-items:center;flex-wrap:wrap;gap:16px;margin:18px 0 22px;padding-bottom:20px;border-bottom:1px solid var(--md-line)}.migration-directory .md-identity img{object-fit:contain;border-radius:9px}.migration-directory .md-identity a{margin-left:auto}.migration-directory .md-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.migration-directory .md-box{border:1px solid var(--md-line);border-radius:12px;background:linear-gradient(130deg,#1d4230,#102b22);padding:20px;display:grid;gap:14px;margin-bottom:18px}.migration-directory .md-detail{display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px;padding:9px 0;border-bottom:1px solid #355741}.migration-directory .md-detail span{color:var(--md-muted)}.migration-directory .md-detail strong{overflow-wrap:anywhere}.migration-directory .md-assignment{border-left:3px solid #c7ad62;padding:8px 12px;background:#153326}.migration-directory .md-assignment strong{color:var(--md-gold)}.migration-directory .md-note{color:var(--md-muted);padding-top:12px}.migration-directory details{margin-top:12px}.migration-directory summary{color:var(--md-gold);cursor:pointer}.migration-directory .md-diagnostics{border-top:1px solid #476046;padding-top:16px}.migration-directory .md-diagnostics p{margin:12px 0}.migration-directory .md-status:empty{display:none}@media(max-width:850px){.migration-directory .md-grid{grid-template-columns:1fr}.migration-directory .md-table{min-width:650px}} +.migration-directory .md-assignment-form{display:grid;gap:12px;margin-top:18px}.migration-directory textarea{font:inherit;background:#102b22;color:#f2e7c8;border:1px solid #66846b;border-radius:8px;padding:11px;box-sizing:border-box;width:100%}.migration-directory .md-policy-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px;margin-top:14px}.migration-directory .md-permission{display:flex;align-items:start;gap:10px;padding:10px;background:#153528;border-radius:8px;overflow-wrap:anywhere}.migration-directory .md-permission input{margin-top:5px}.migration-directory .md-permission strong{font-weight:500}.migration-directory .md-permission small{display:block}.migration-directory .md-permission[hidden]{display:none}@media(max-width:850px){.migration-directory .md-policy-grid{grid-template-columns:1fr}} diff --git a/website/control-panel/public/cp-v2/citizen-directory.mjs b/website/control-panel/public/cp-v2/citizen-directory.mjs index 6a6744ee..6b4c9be1 100644 --- a/website/control-panel/public/cp-v2/citizen-directory.mjs +++ b/website/control-panel/public/cp-v2/citizen-directory.mjs @@ -6,6 +6,7 @@ const button=(label,action)=>{const b=element('button',label);b.type='button';b. const date=value=>value?new Date(Number(value)).toLocaleDateString('en-GB'):'Not recorded'; const roleDescription=a=>a.assignments.map(x=>x.scopeLabel+' · '+x.roleLabel).join(' / '); async function request(path,signal){const r=await fetch(path,{credentials:'same-origin',cache:'no-store',signal});const data=await r.json().catch(()=>({}));if(!r.ok)throw Error(data.message||'Directory unavailable.');return data;} +async function send(body){const r=await fetch('/api/admin/organisation/assignments',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const data=await r.json().catch(()=>({}));if(!r.ok)throw Error(data.message||'Assignment could not be saved.');return data;} export function mountCitizenDirectory(host){ const root=element('section',undefined,'migration-directory'); @@ -13,7 +14,7 @@ export function mountCitizenDirectory(host){ const view=element('div');const status=element('p','Loading directory…','md-status');status.setAttribute('role','status'); const diagnostics=element('details',undefined,'md-diagnostics');diagnostics.append(element('summary','+ Workspace details'),element('p','Central account directory. Assignment catalogue preparation does not change existing permissions.'),button('Reload workspace',()=>load())); root.append(status,view,diagnostics);host.replaceChildren(root); - let context='users',page=1,query='',filter='',department='',branch='',selected=null,tab='overview',disposed=false,controller,sequence=0,catalogue={departments:[]}; + let context='users',page=1,query='',filter='',department='',branch='',selected=null,tab='overview',disposed=false,controller,sequence=0,catalogue={departments:[]},assignmentData=null; let searchTimer; function heading(){applyShellHeading(host,{title:selected?(context==='staff'?'Manage Staff':'Manage User'):'Citizen Directory',description:selected?selected.displayName+' · '+selected.username:'Find a citizen, then manage their account or staff responsibilities.',artwork:context==='staff'?'nav-staff-v2.webp':'nav-account-v2.webp'});} function box(title){const section=element('section',undefined,'md-box');section.append(element('h3',title));return section;} @@ -23,9 +24,47 @@ export function mountCitizenDirectory(host){ function assignments(){const panel=box(context==='staff'?'Staff assignments':'Memberships & offices'); if(selected.assignments.length){for(const a of selected.assignments){const card=element('div',undefined,'md-assignment');card.append(element('strong',a.roleLabel),element('p',a.scopeLabel),badge(a.source||'Recorded assignment'));if(a.endsAt)card.append(element('small','Until '+date(a.endsAt)));panel.append(card);}} else panel.append(element('p',context==='staff'?'No new-model staff assignments have been activated for this account.':'No memberships or offices have been registered in the new assignment model yet. Existing memberships remain in their source systems.','md-muted')); - panel.append(element('p','Assignment editing and automatic source integration are the next migration batch. Existing rights have not been replaced.','md-note')); + panel.append(element('p','The new assignment register is being prepared. Recorded changes do not replace existing permissions until migration activation.','md-note')); return panel; } + function scopeVersion(a){return Number(assignmentData.versions.find(v=>v.scope_type===a.scopeType&&v.scope_key===a.scopeKey)?.version||1);} + async function loadAssignments(panel){ + const target=selected.id;panel.append(element('p','Loading assignment controls…','md-muted')); + try{ + const data=await request('/api/admin/organisation/assignments?userId='+encodeURIComponent(target),controller?.signal); + if(disposed||selected?.id!==target||context!=='staff'||tab!=='assignments'||!panel.isConnected)return; + assignmentData=data;selected.assignments=data.assignments;panel.replaceChildren(element('h3','Staff assignments'),element('p','Changes are audited in the new register. Live permission activation follows after the mapping is verified.','md-note')); + const message=element('p','');message.setAttribute('role','status'); + for(const a of data.assignments){ + const row=element('div',undefined,'md-assignment');row.append(element('strong',a.roleLabel),element('p',a.scopeLabel),badge(a.source)); + if(a.editable){const revoke=button('Remove assignment',async()=>{ + const reason=prompt('Reason for removing '+a.roleLabel+' from '+selected.username+' (3–500 characters):');if(reason===null)return; + if(!confirm('Remove '+a.roleLabel+' in '+a.scopeLabel+'?'))return;revoke.disabled=true; + try{await send({action:'revoke',userId:target,assignmentId:a.id,version:a.version,scopeType:a.scopeType,scopeKey:a.scopeKey,role:a.role,scopeVersion:scopeVersion(a),reason});message.textContent='Assignment removal recorded.';await loadAssignments(panel);}catch(e){message.textContent=e.message;revoke.disabled=false;} + });row.append(revoke);}else row.append(element('small',a.source==='manual'?'Outside your management scope.':'Automatic assignment — manage at its source.'));panel.append(row); + } + if(!data.assignments.length)panel.append(element('p','No new-model staff assignments recorded.','md-muted')); + if(data.editable.length){ + const form=element('form',undefined,'md-assignment-form');const scope=element('select');scope.setAttribute('aria-label','Assignment scope');const role=element('select');role.setAttribute('aria-label','Role within scope'); + const unique=[...new Map(data.editable.map(s=>[s.type+':'+s.key,s])).values()];for(const s of unique){const o=element('option',s.label+' · '+s.type);o.value=s.type+':'+s.key;scope.append(o);} + const updateRoles=()=>{role.replaceChildren();const[type,key]=scope.value.split(':');for(const s of data.editable.filter(s=>s.type===type&&s.key===key)){const o=element('option',s.role.replaceAll('_',' '));o.value=s.role;role.append(o);}};scope.onchange=updateRoles;updateRoles(); + const reason=element('textarea');reason.required=true;reason.minLength=3;reason.maxLength=500;reason.rows=2;reason.placeholder='Reason for the appointment';reason.setAttribute('aria-label','Reason for appointment'); + const save=button('Save assignment',()=>{});save.type='submit'; + for(const[label,input]of [['Department or branch',scope],['Role',role],['Reason',reason]]){const wrap=element('label',label,'md-field');wrap.append(input);form.append(wrap);}form.append(save); + form.onsubmit=async e=>{e.preventDefault();if(!form.reportValidity())return;const[type,key]=scope.value.split(':');if(!confirm('Record '+role.selectedOptions[0].textContent+' for '+selected.username+'?'))return;save.disabled=true; + try{await send({action:'assign',userId:target,scopeType:type,scopeKey:key,role:role.value,scopeVersion:scopeVersion({scopeType:type,scopeKey:key}),reason:reason.value});await loadAssignments(panel);status.textContent='Assignment recorded; current live permissions remain unchanged.';}catch(error){message.textContent=error.message;save.disabled=false;} + };panel.append(form); + }else panel.append(element('p','You have no assignment-management authority in this register.','md-muted')); + panel.append(message); + }catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.append(element('p',e.message,'md-note'));} + } + async function loadActivity(panel){ + const target=selected.id,currentContext=context; + try{const data=await request('/api/admin/organisation/activity?userId='+encodeURIComponent(target)+'&context='+context,controller?.signal);if(disposed||selected?.id!==target||context!==currentContext||tab!=='activity'||!panel.isConnected)return; + if(!data.events.length)panel.append(element('p','No changes recorded in the new management register. Older account history remains preserved.','md-muted')); + for(const event of data.events){const row=element('div',undefined,'md-assignment');row.append(element('strong',event.action+' · '+event.scope_key.replaceAll('_',' ')),element('p',event.reason),element('small',(event.actor||'System')+' · '+new Date(Number(event.created_at)).toLocaleString('en-GB')));panel.append(row);} + }catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.append(element('p',e.message,'md-note'));} + } function renderAccount(){ view.replaceChildren();heading();const back=button('← '+(context==='staff'?'Staff Directory':'User Directory'),()=>{selected=null;void load();});view.append(back); const hero=element('header',undefined,'md-identity');const avatar=element('img');avatar.alt='';avatar.width=56;avatar.height=56;avatar.src=selected.minecraftUuid?'/api/avatars/minecraft/'+encodeURIComponent(selected.minecraftUuid):'https://www.dunerealms.com/assets/nav-account-v2.webp'; @@ -37,13 +76,14 @@ export function mountCitizenDirectory(host){ if(context==='staff'&&selected.staffSources?.length){const source=box('Imported staff record');for(const row of selected.staffSources)source.append(detail('Source account',row.name),detail('Imported',date(row.importedAt)));source.append(element('p','Imported identity is evidence of the staff cohort, not a new permission grant.','md-muted'));view.append(source);} }else if(tab==='account'){ const identity=box('Linked identity');identity.append(detail('Username',selected.username),detail('Display name',selected.displayName),detail('Minecraft',selected.minecraftName||'Not linked'),detail('Status',selected.status));const advanced=element('details');advanced.append(element('summary','+ Advanced account details'),detail('Account ID',selected.id),detail('Minecraft UUID',selected.minecraftUuid||'Not linked'));identity.append(advanced);view.append(identity); - }else if(tab==='assignments')view.append(assignments()); + }else if(tab==='assignments'){const panel=assignments();view.append(panel);if(context==='staff')void loadAssignments(panel);} else if(tab==='honours'){const panel=box('Seals & honours');panel.append(element('p','Existing awards are preserved. The new seal ledger and compact award controls follow in the recognition batch.','md-muted'));panel.append(publicLink.cloneNode(true));view.append(panel);} - else{const panel=box('Account activity');panel.append(element('p','The audited assignment timeline will be connected with assignment editing. No historical account records have been removed.','md-muted'));view.append(panel);} + else{const panel=box('Account activity');view.append(panel);void loadActivity(panel);} } function renderList(data){ const restoreSearch=document.activeElement===view.querySelector('input[type="search"]'); view.replaceChildren();heading();const nav=element('nav',undefined,'md-tabs');nav.setAttribute('aria-label','Directory type');for(const[key,label]of [['users','Users'],['staff','Staff']]){const b=button(label,()=>{if(context===key)return;context=key;page=1;department='';branch='';void load();});b.setAttribute('aria-current',String(context===key));nav.append(b);}view.append(nav); + if(context==='staff')nav.append(button('Add staff member',()=>pickCandidate())); const toolbar=element('form',undefined,'md-tools');const search=element('input');search.type='search';search.value=query;search.placeholder='Name, Minecraft UUID or account ID';search.setAttribute('aria-label','Search all directory records');search.oninput=()=>{query=search.value;clearTimeout(searchTimer);searchTimer=setTimeout(()=>{page=1;void load();},350);}; toolbar.onsubmit=e=>{e.preventDefault();clearTimeout(searchTimer);page=1;void load();};toolbar.append(search,choices('Status',[['','All statuses'],['active','Active'],['banned','Banned'],['deleted','Deleted']],filter,value=>{filter=value;page=1;void load();})); if(context==='staff'){ @@ -58,6 +98,13 @@ export function mountCitizenDirectory(host){ const pager=element('div',undefined,'md-pager'),previous=button('Previous',()=>{page--;void load();}),next=button('Next',()=>{page++;void load();});previous.disabled=page===1;next.disabled=!data.hasMore;pager.append(previous,element('span','Page '+page),next);view.append(pager); if(context==='staff'&&(department||branch))view.append(element('p','Department and branch filters use new-model assignments. Imported accounts appear in All staff until their assignments are migrated.','md-note')); } + function pickCandidate(){ + view.replaceChildren(button('← Staff Directory',()=>load()));const panel=box('Find a citizen to appoint'),form=element('form',undefined,'md-tools'),input=element('input'),find=button('Find citizen',()=>{}),results=element('div');input.type='search';input.required=true;input.minLength=3;input.maxLength=80;input.placeholder='Username or Minecraft identity';input.setAttribute('aria-label','Find a staff candidate');find.type='submit';form.append(input,find);panel.append(form,results);view.append(panel); + form.onsubmit=async e=>{e.preventDefault();if(!form.reportValidity())return;find.disabled=true;results.replaceChildren(element('p','Finding citizens…')); + try{const data=await request(API+'?context=users&q='+encodeURIComponent(input.value),controller?.signal);if(!panel.isConnected||disposed)return;results.replaceChildren();for(const account of data.accounts.filter(a=>a.status==='active')){const row=element('div',undefined,'md-detail');row.append(element('span',account.displayName+' · '+account.username),button('Manage staff assignments',async()=>{await open(account.id);if(selected?.id===account.id){tab='assignments';renderAccount();}}));results.append(row);}if(!results.children.length)results.append(element('p','No active citizens found.'));if(data.hasMore)results.append(element('p','Refine the name to narrow the results.','md-note'));} + catch(error){if(panel.isConnected)results.replaceChildren(element('p',error.message));}finally{find.disabled=false;} + }; + } async function open(id){controller?.abort();controller=new AbortController();const current=++sequence;status.textContent='Loading account…';try{const data=await request(API+'/'+encodeURIComponent(id)+'?context='+context,controller.signal);if(disposed||current!==sequence)return;selected=data.account;tab='overview';renderAccount();status.textContent='';}catch(e){if(!disposed&&e.name!=='AbortError')status.textContent=e.message;}} async function load(){controller?.abort();controller=new AbortController();const current=++sequence;status.textContent='Loading '+context+'…';try{if(context==='staff'&&!catalogue.departments.length)catalogue=await request(API+'/catalogue?context=staff',controller.signal);const params=new URLSearchParams({context,page:String(page),q:query,status:filter,department,branch});const data=await request(API+'?'+params,controller.signal);if(disposed||current!==sequence)return;selected=null;renderList(data);status.textContent=data.accounts.length+' records on this page · search covers the complete directory.';}catch(e){if(!disposed&&e.name!=='AbortError'){view.replaceChildren();status.textContent=e.message;}}} void load();return()=>{disposed=true;sequence++;clearTimeout(searchTimer);controller?.abort();root.remove();}; diff --git a/website/control-panel/public/cp-v2/organisation-permissions.mjs b/website/control-panel/public/cp-v2/organisation-permissions.mjs new file mode 100644 index 00000000..dd3ca14a --- /dev/null +++ b/website/control-panel/public/cp-v2/organisation-permissions.mjs @@ -0,0 +1,33 @@ +import {applyShellHeading} from './cp-v2-page-template.mjs'; +const el=(tag,value,cls)=>{const e=document.createElement(tag);if(value!==undefined)e.textContent=value;if(cls)e.className=cls;return e;}; +const roleNames={owner_ceo:'Owner & CEO',executive:'Executive',department_head:'Department Head',branch_lead:'Branch Lead',officer:'Officer'}; +const roles={organisation:['owner_ceo','executive'],department:['department_head'],branch:['branch_lead','officer']}; +const API='/api/admin/organisation/policies'; +export function mountOrganisationPermissions(host){ + let disposed=false,data,selection='branch:news_media',role='officer',dirty=false,busy=false;const controller=new AbortController(); + const root=el('section',undefined,'migration-directory');const css=el('link');css.rel='stylesheet';css.href='/v2/citizen-directory.css'; + const status=el('p','Loading the central permission matrix…');status.setAttribute('role','status');const content=el('div');root.append(css,status,content);host.replaceChildren(root); + applyShellHeading(host,{title:'Imperial Permissions',description:'Map existing permissions to departments, branches and functions.',artwork:'nav-staff-v2.webp'}); + async function api(body){const r=await fetch(API,{credentials:'same-origin',cache:'no-store',signal:controller.signal,...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});const d=await r.json().catch(()=>({}));if(!r.ok)throw Error(d.message||'Policy service unavailable.');return d;} + function render(){ + content.replaceChildren();content.append(el('p','Preparation mode: saved mappings are versioned and audited. Current live permissions remain unchanged until the migration is activated.','md-note')); + const tools=el('div',undefined,'md-tools'),scopes=el('select'),ranks=el('select');scopes.setAttribute('aria-label','Department or branch');ranks.setAttribute('aria-label','Function'); + for(const s of data.scopes){const o=el('option',s.label+' · '+s.type);o.value=s.type+':'+s.key;scopes.append(o);}scopes.value=selection; + const [type,key]=selection.split(':');for(const value of roles[type]){const o=el('option',roleNames[value]);o.value=value;ranks.append(o);}if(!roles[type].includes(role))role=roles[type][0];ranks.value=role; + const choose=callback=>{if(busy)return;if(dirty&&!confirm('Discard unsaved mapping changes?'))return;dirty=false;callback();render();};scopes.onchange=()=>choose(()=>{selection=scopes.value;});ranks.onchange=()=>choose(()=>{role=ranks.value;});tools.append(scopes,ranks);content.append(tools); + const policy=data.policies.find(p=>p.scope_type===type&&p.scope_key===key&&p.role_key===role),chosen=new Set(policy?.nodes||[]); + const heading=el('h3',roleNames[role]+' · '+data.scopes.find(s=>s.type===type&&s.key===key).label);content.append(heading); + const search=el('input');search.type='search';search.placeholder='Find existing permission';search.setAttribute('aria-label','Filter permission catalogue');const assignedOnly=el('input');assignedOnly.type='checkbox';const assignedLabel=el('label','Show assigned only');assignedLabel.prepend(assignedOnly);const filters=el('div',undefined,'md-tools');filters.append(search,assignedLabel);content.append(filters); + const matrix=el('div',undefined,'md-policy-grid'); + for(const item of data.catalogue){const option=el('label',undefined,'md-permission');const check=el('input');check.type='checkbox';check.checked=chosen.has(item.node);check.disabled=!data.canEdit;const label=el('span');label.append(el('strong',item.label),el('small',item.node));option.append(check,label);option.dataset.search=(item.node+' '+item.label).toLowerCase();check.onchange=()=>{dirty=true;check.checked?chosen.add(item.node):chosen.delete(item.node);count.textContent=chosen.size+' mapped permissions';filter();};matrix.append(option);} + const filter=()=>{for(const row of matrix.children)row.hidden=!!search.value&&!row.dataset.search.includes(search.value.toLowerCase())||assignedOnly.checked&&!row.querySelector('input').checked;};search.oninput=filter;assignedOnly.onchange=filter;content.append(matrix); + const count=el('p',chosen.size+' mapped permissions','md-note');const reason=el('textarea');reason.rows=2;reason.required=true;reason.minLength=3;reason.maxLength=500;reason.placeholder='Reason for this policy change';reason.setAttribute('aria-label','Reason for policy change');const save=el('button','Save policy mapping');save.type='submit';save.disabled=!data.canEdit;const form=el('form',undefined,'md-assignment-form');form.append(count,reason,save);content.append(form); + form.onsubmit=async e=>{e.preventDefault();if(busy||!data.canEdit||!form.reportValidity()||!confirm('Save this mapping? Live activation is a separate migration step.'))return;busy=true;save.disabled=true; + try{const version=Number(data.versions.find(v=>v.scope_type===type&&v.scope_key===key)?.version||1);await api({scopeType:type,scopeKey:key,role,nodes:[...chosen],scopeVersion:version,reason:reason.value});dirty=false;await load();status.textContent='Policy mapping saved and audited. Live permissions unchanged.';}catch(error){if(!disposed)status.textContent=error.message;}finally{busy=false;if(save.isConnected)save.disabled=!data.canEdit;} + }; + if(!data.canEdit)content.append(el('p','Read-only mapping. Editing requires Executive or Dev service authority.','md-note')); + const advanced=el('details');advanced.append(el('summary','+ Workspace details'),el('p','Central policy register · version '+(policy?.version||0)+' · no native rank editor or wildcard grants'));content.append(advanced); + } + async function load(){try{data=await api();if(disposed)return;render();status.textContent='';}catch(e){if(!disposed&&e.name!=='AbortError')status.textContent=e.message;}} + void load();return()=>{disposed=true;controller.abort();root.remove();}; +} diff --git a/website/control-panel/public/cp-v2/v2.js b/website/control-panel/public/cp-v2/v2.js index dc1bb1b9..d6284a3b 100644 --- a/website/control-panel/public/cp-v2/v2.js +++ b/website/control-panel/public/cp-v2/v2.js @@ -206,6 +206,7 @@ if(w.id==='bureau'&&item.id==='user-management'){ history.replaceState(null,'','#'+w.id+'/'+item.id); return; } +if(w.id==='bureau'&&item.id==='permissions'&&new URL(location.href).searchParams.get('migration')==='1'){const host=el('div','citizen-live-host');overview.append(host);import('/v2/organisation-permissions.mjs').then(({mountOrganisationPermissions})=>{if(host.isConnected)disposePage=mountOrganisationPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent=error.message});history.replaceState(null,'','#bureau/permissions');return;} if(w.id==='bureau'&&item.id==='permissions'){const host=el('div','citizen-live-host');overview.append(host);host.append(el('p','alpha-muted','Loading Imperial Permissions…'));import('/v2/imperial-permissions.mjs?v=rankdelete-20261112a').then(({mountImperialPermissions})=>{if(host.isConnected)mountImperialPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent='Imperial Permissions unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} if(w.id==='bureau'&&item.id==='manual-seals'){const host=el('div','citizen-live-host');overview.append(host);host.append(el('p','alpha-muted','Loading Honours & Seals…'));import('/v2/honours-seals.mjs?v=sealupload-20261112a').then(({mountHonoursSeals})=>{if(host.isConnected)mountHonoursSeals(host)}).catch(error=>{if(host.isConnected)host.textContent='Honours & Seals unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} if(w.id==='bureau'&&['company-management','company-management-v2','company-audit','staff-bank','server-kits','kit-publishing','kit-claims','exchange-admin','shop-admin','items','website-posts','staff-tickets','bans','ban-evidence','forum-admin','quests-admin','community-goals','support-management','server-operations','hosting-control','dev-approvals'].includes(item.id)){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-bureau-pages.mjs?v=bureau-registers-20261112c').then(({mountBureauPlaceholder})=>{if(host.isConnected)disposePage=mountBureauPlaceholder(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Bureau page unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index cc8b7ef7..e23a9d3c 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -70,6 +70,7 @@ import {initializeStaffBureau} from '../node/staff-bureau-schema.mjs'; import {createStaffBureauReadApi} from '../node/staff-bureau-read-api.mjs'; import {initializeOrganisation} from '../node/organisation-model.mjs'; import {createCitizenDirectory} from '../node/citizen-directory.mjs'; +import {createOrganisationManagement} from '../node/organisation-management.mjs'; import {initializeRanks,initializeCommunityAccess,initializeQuestAccess,initializeBankAccess,can,accessFor} from '../node/permissions.mjs'; import {createServer} from 'node:http'; import {createV1PersonalBank} from './api-v1-personal-bank.mjs'; @@ -108,6 +109,7 @@ export function createPanel(db,settings={},dependencies={}){ const manual=createStaffManual(db); const staffBureauRead=createStaffBureauReadApi(db); const citizenDirectory=createCitizenDirectory(db); + const organisationManagement=createOrganisationManagement(db,{origin}); const luckperms=createLuckPerms(db,settings,dependencies.luckperms); const servers=createServerControl(db,settings,dependencies.serverControl); const pool=dependencies.inventoryPool||{async query(){throw Error('Inventory database is not configured');}}; @@ -159,6 +161,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/politics/preview')return politicsPreview(request); if(path==='/api/admin/register-user')return adminRegistration(request); if(path==='/api/admin/citizens'||path.startsWith('/api/admin/citizens/'))return citizenDirectory(request); + if(path.startsWith('/api/admin/organisation/'))return organisationManagement(request); if(path==='/api/account/email')return contactEmail(request); if(path.startsWith('/api/people/'))return memberProfiles(request); if(path==='/profile-login'&&request.method==='GET'){ @@ -248,7 +251,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});} if(path==='/federal-reserve'||path==='/federal-reserve/')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/reserve-ledger.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}}); // V2 shell is public; private data and writes retain their authenticated API gates. - if(['/v2/citizen-directory.mjs','/v2/citizen-directory.css'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice('/v2/'.length),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); + if(['/v2/citizen-directory.mjs','/v2/citizen-directory.css','/v2/organisation-permissions.mjs'].includes(path))return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+path.slice('/v2/'.length),import.meta.url)),{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-authorisations.mjs','/v2/cp-v2-tax-treasury.mjs','/v2/cp-v2-reserve-ledger.mjs','/v2/cp-v2-reserve-entry.mjs','/v2/cp-v2-postbank-credit.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){ const moduleFile=path.endsWith('.mjs')||path.endsWith('.js'); const file=path.endsWith('.mjs')?path.slice('/v2/'.length):path.endsWith('.js')?'v2.js':path.endsWith('.css')?'v2.css':'index.html'; diff --git a/website/docs/great-migration.md b/website/docs/great-migration.md index d82ea09d..42e9581e 100644 --- a/website/docs/great-migration.md +++ b/website/docs/great-migration.md @@ -20,9 +20,8 @@ Included: and staff provenance. Staff views retain imported source identity for review. - Existing account administration and all live permissions remain unchanged. -Not claimed complete: assignment writes, permission activation/projection, native -integration migration, the recognition editor and the audit timeline. Their UI -states are explicitly marked as subsequent batches. Existing memberships have not +Not claimed complete in batch 1: assignment writes, permission activation/projection, +native integration migration, the recognition editor and the audit timeline. Existing memberships have not yet been imported into `org_assignments`; an empty new-model list is not a claim that the citizen has no memberships in existing systems. @@ -55,3 +54,43 @@ derived rights/seals must follow their lifecycle. Earned honours remain intact. 6. Access/lifecycle/privacy verification, release and combined .6/.7 announcement. Do not change the public version banner or publish release news before .7 is done. + +## Batch 2: audited assignment editor and policy preparation + +Staff assignments can be recorded and revoked within the manager's scope. One +lead per branch/department is enforced under a shared scope lock. A scope version +prevents stale forms from overwriting another manager's work. Automatic records +must be changed at their source. Service accounts stay outside human appointments. + +The permission matrix at `?migration=1#bureau/permissions` maps registered existing +nodes to each function. It rejects wildcard/OP/native-editor nodes and official +bank management on ordinary branch roles. Policy writes and assignments share +atomic audit and version checks. These are preparatory records: they do not yet +replace live roles. No native backend code is rewritten. + +An explicit operator-run `scripts/bootstrap-organisation-control.mjs --apply` +pins the existing Big Four and Dev service by account ID for management authority. +It is idempotent, checks the established Owner/Dev identities, refuses conflicting +existing principals and does not run at application startup. Its audit clearly +states that it does not activate live permission projection. + +## Additional Owner-approved bank work + +After the current management batch, add a staff Client Management context reusing +Accounts & Payments components without generic Wire Transfers. + +Add immediate Service Compensation from Payment Control, linked to the original +posted payment, with reason, consent, actual actor and a distinct purple type +badge in staff/customer histories and statements. Recover funds from the original +recipient when possible; otherwise the bank bears the cost. Never erase the +original payment or compensate its value more than once across retries/partials. + +The shared budget is the available balance of a dedicated Compensation Reserve. +A monthly standing instruction funds it from Website Bank Treasury, initially +25,000 DM; unspent funds roll forward. Big Four and the bank CEO may change that +standing instruction and transfer reserve funds in/out through Treasury Accounts. +No extra Officer cap/counter, CEO override system, support ticket, approval flow, +or four-hour compensation queue. Reuse existing posting/audit infrastructure. + +Cash conversion is reserved for the future in-game GUI + central API in both +directions. No cash web page, redeem code flow or game changes in this batch. diff --git a/website/node/citizen-directory.mjs b/website/node/citizen-directory.mjs index 18bb2059..28c8339c 100644 --- a/website/node/citizen-directory.mjs +++ b/website/node/citizen-directory.mjs @@ -56,7 +56,10 @@ export function createCitizenDirectory(db,{authenticate=identity,authorize=can,c if(url.pathname==='/api/admin/citizens/catalogue')return reply({departments:filter.context==='staff'?ORGANISATION:[],roles:Object.fromEntries(Object.entries(ASSIGNMENT_ROLES).filter(([key])=>STAFF_SCOPE_TYPES.includes(key)===(filter.context==='staff'))),assignmentMode:'preparing',permissionsChanged:false}); const match=url.pathname.match(/^\/api\/admin\/citizens\/([0-9a-f-]{36})$/i); if(match){ - const row=await db.prepare(`SELECT ${fields} FROM site_accounts a WHERE a.id=?${filter.where?' AND '+filter.where.slice(7):''}`).bind(match[1],...filter.values).first(); + // Staff managers may open a human candidate before their first appointment. + // The directory list remains staff-only; service accounts are never candidates. + const candidateGuard=filter.context==='staff'?' AND NOT EXISTS (SELECT 1 FROM site_account_policies service WHERE service.user_id=a.id AND service.game_link_exempt=1)':''; + const row=await db.prepare(`SELECT ${fields} FROM site_accounts a WHERE a.id=?${candidateGuard}`).bind(match[1]).first(); if(!row)return reply({message:'Account not found.'},404); const current=await assignments([row.id],filter.context); const account={...project(row),assignments:current.map(assignmentLabel)}; diff --git a/website/node/organisation-management.mjs b/website/node/organisation-management.mjs new file mode 100644 index 00000000..54198017 --- /dev/null +++ b/website/node/organisation-management.mjs @@ -0,0 +1,126 @@ +import {randomUUID} from 'node:crypto'; +import {identity} from './auth.mjs'; +import {can,NODES} from './permissions.mjs'; +import {staffScopes,validStaffRole,assignmentLabel} from './organisation-model.mjs'; + +const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}}); +const fault=(message,status=409)=>Object.assign(new Error(message),{status}); +const identifier=value=>typeof value==='string'&&/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value); +const globalPrincipal=kind=>['owner','executive','service'].includes(kind); +const active=row=>row.status==='active'; +export function canAssignRole(authority,scopeType,scopeKey,role){ + if(!validStaffRole(scopeType,scopeKey,role)||role==='owner_ceo')return false; + if(scopeType==='organisation')return globalPrincipal(authority.principal); + if(globalPrincipal(authority.principal))return true; + const scope=staffScopes().find(s=>s.type===scopeType&&s.key===scopeKey); + return authority.assignments.some(a=>active(a)&&( + a.scope_type==='department'&&a.role_key==='department_head'&&scopeType==='branch'&&scope.department===a.scope_key|| + a.scope_type==='branch'&&a.role_key==='branch_lead'&&scopeType==='branch'&&scopeKey===a.scope_key&&role==='officer' + )); +} +const nativeEditorNodes=new Set(['web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor']); +export function validatePolicyNodes(nodes,scopeType,role){ + if(!Array.isArray(nodes)||nodes.length>500||nodes.some(n=>typeof n!=='string'))throw fault('Choose registered permission nodes.',400); + const unique=[...new Set(nodes)].sort(); + for(const n of unique){ + if(!Object.hasOwn(NODES,n)||n.includes('*')||/(^|\.)op($|\.)/.test(n))throw fault('Unregistered or unrestricted permission: '+n,400); + if(nativeEditorNodes.has(n))throw fault('Native permission editors remain reserved for the Dev service.',400); + if(['web.bank.staff.manage','cp.bank.staff.manage','web.bank.staff.deposit','cp.bank.staff.deposit'].includes(n)&&!((scopeType==='organisation'&&['owner_ceo','executive'].includes(role))||(scopeType==='department'&&role==='department_head')))throw fault('Official banking management is reserved for executives and department heads.',400); + } + return unique; +} +export function createOrganisationManagement(db,{origin='https://cp.dunerealms.com',authenticate=identity,authorize=can,clock=Date.now}={}){ + async function authority(tx,userId){ + const actor=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' FOR SHARE",[userId]); + if(!actor)throw fault('Account authority changed.',403); + const principal=await tx.first('SELECT principal_kind FROM org_control_principals WHERE user_id=? FOR SHARE',[userId]); + const assignments=await tx.query("SELECT scope_type,scope_key,role_key,status FROM org_assignments WHERE user_id=? AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) FOR SHARE",[userId,clock(),clock()]); + return {principal:principal?.principal_kind||null,assignments}; + } + async function readAuthority(id){ + const result=await db.transaction(tx=>authority(tx,id)); + return {...result,editable:staffScopes().flatMap(scope=>['executive','department_head','branch_lead','officer'].filter(role=>canAssignRole(result,scope.type,scope.key,role)).map(role=>({...scope,role})))}; + } + async function scopeLock(tx,b){ + await tx.query('INSERT IGNORE INTO org_scope_versions(scope_type,scope_key,version) VALUES(?,?,1)',[b.scopeType,b.scopeKey]); + const current=await tx.first('SELECT version FROM org_scope_versions WHERE scope_type=? AND scope_key=? FOR UPDATE',[b.scopeType,b.scopeKey]); + if(Number(current.version)!==b.scopeVersion)throw fault('This scope changed. Refresh before saving.'); + } + async function audit(tx,actor,b,action,before,after,assignmentId=null){ + await tx.query('INSERT INTO org_assignment_events(id,user_id,assignment_id,actor_id,action,scope_type,scope_key,reason,before_json,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)',[randomUUID(),b.userId||null,assignmentId,actor.id,action,b.scopeType,b.scopeKey,b.reason,before?JSON.stringify(before):null,JSON.stringify(after),clock()]); + } + return async request=>{ + const actor=await authenticate(request,db);if(!actor)return reply({message:'Sign in first.'},401); + const url=new URL(request.url),policy=url.pathname==='/api/admin/organisation/policies'; + if(!['/api/admin/organisation/assignments','/api/admin/organisation/policies','/api/admin/organisation/activity','/api/admin/organisation/authority'].includes(url.pathname))return reply({message:'Not found.'},404); + if(!await authorize(db,actor,policy?'web.ranks.manage':'web.accounts.view'))return reply({message:'Central management permission required.'},403); + if(request.method==='GET'){ + const auth=await readAuthority(actor.id); + if(url.pathname.endsWith('/authority'))return reply({editable:auth.editable,canEditPolicies:globalPrincipal(auth.principal),enforcement:'preparing'}); + if(policy){ + const {results:policies}=await db.prepare('SELECT scope_type,scope_key,role_key,permissions_json,version,updated_at FROM org_role_policies ORDER BY scope_type,scope_key,role_key').all(); + const {results:versions}=await db.prepare('SELECT scope_type,scope_key,version FROM org_scope_versions').all(); + return reply({scopes:staffScopes(),versions,policies:policies.map(p=>({...p,nodes:JSON.parse(p.permissions_json),permissions_json:undefined})),catalogue:Object.entries(NODES).filter(([n])=>!n.includes('*')).map(([node,label])=>({node,label})),canEdit:globalPrincipal(auth.principal),enforcement:'preparing'}); + } + const userId=url.searchParams.get('userId');if(!identifier(userId))return reply({message:'Select a registered account.'},400); + if(url.pathname.endsWith('/activity')){ + const context=url.searchParams.get('context')||'users';if(!['users','staff'].includes(context))return reply({message:'Invalid context.'},400); + const clause=context==='staff'?"IN ('organisation','department','branch')":"NOT IN ('organisation','department','branch')"; + const {results}=await db.prepare(`SELECT e.id,e.action,e.scope_type,e.scope_key,e.reason,e.created_at,a.username AS actor FROM org_assignment_events e LEFT JOIN site_accounts a ON a.id=e.actor_id WHERE e.user_id=? AND e.scope_type ${clause} ORDER BY e.created_at DESC,e.id DESC LIMIT 50`).bind(userId).all();return reply({events:results}); + } + const {results:assignments}=await db.prepare("SELECT id,user_id,scope_type,scope_key,role_key,source_kind,status,starts_at,ends_at,version FROM org_assignments WHERE user_id=? AND scope_type IN ('organisation','department','branch') AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) ORDER BY scope_type,scope_key,role_key").bind(userId,clock(),clock()).all(); + const {results:versions}=await db.prepare('SELECT scope_type,scope_key,version FROM org_scope_versions').all(); + return reply({assignments:assignments.map(a=>({...assignmentLabel(a),editable:a.source_kind==='manual'&&canAssignRole(auth,a.scope_type,a.scope_key,a.role_key)})),editable:auth.editable,versions,permissionsChanged:false,enforcement:'preparing'}); + } + if(request.method!=='POST'||!['/api/admin/organisation/assignments','/api/admin/organisation/policies'].includes(url.pathname))return reply({message:'Method not allowed.'},405); + if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403); + if(!request.headers.get('content-type')?.startsWith('application/json'))return reply({message:'Send JSON.'},415); + if(!await authorize(db,actor,policy?'web.ranks.manage':'web.accounts.assign'))return reply({message:'Assignment permission required.'},403); + let b;try{const raw=await request.text();if(Buffer.byteLength(raw)>32000)throw Error();b=JSON.parse(raw);}catch{return reply({message:'Invalid request.'},400);} + if(!b||typeof b!=='object'||Array.isArray(b)||typeof b.reason!=='string'||b.reason.trim().length<3||b.reason.length>500||!validStaffRole(b.scopeType,b.scopeKey,b.role)||!Number.isSafeInteger(b.scopeVersion)||b.scopeVersion<1)return reply({message:'Choose a scope, role and a reason of 3–500 characters.'},400); + const allowed=policy?['scopeType','scopeKey','role','reason','scopeVersion','nodes']:['scopeType','scopeKey','role','reason','scopeVersion','userId','action','assignmentId','version']; + if(Object.keys(b).some(key=>!allowed.includes(key)))return reply({message:'Unexpected request fields.'},400); + b.reason=b.reason.trim(); + try{ + const result=await db.transaction(async tx=>{ + // Fresh authority and version checks are in the same transaction as the change. + const auth=await authority(tx,actor.id); + if(policy){ + if(!globalPrincipal(auth.principal))throw fault('Policy changes require Executive or Dev service authority.',403); + const nodes=validatePolicyNodes(b.nodes,b.scopeType,b.role);await scopeLock(tx,b); + const before=await tx.first('SELECT permissions_json,version FROM org_role_policies WHERE scope_type=? AND scope_key=? AND role_key=? FOR UPDATE',[b.scopeType,b.scopeKey,b.role]); + const after={nodes,version:Number(before?.version||0)+1}; + await tx.query('INSERT INTO org_role_policies(scope_type,scope_key,role_key,permissions_json,version,updated_by,updated_at) VALUES(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE permissions_json=VALUES(permissions_json),version=VALUES(version),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)',[b.scopeType,b.scopeKey,b.role,JSON.stringify(nodes),after.version,actor.id,clock()]); + await audit(tx,actor,b,'policy',before,after); + }else{ + if(!identifier(b.userId)||!['assign','revoke'].includes(b.action))throw fault('Invalid assignment request.',400); + if(!canAssignRole(auth,b.scopeType,b.scopeKey,b.role))throw fault('This role is outside your management scope.',403); + const target=await tx.first("SELECT a.id,p.game_link_exempt FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.id=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[b.userId]); + if(!target)throw fault('Account not found.',404);if(target.game_link_exempt)throw fault('Service accounts are outside the human staff structure.',403); + await scopeLock(tx,b); + if(b.action==='assign'){ + const current=await tx.query("SELECT id,user_id,role_key FROM org_assignments WHERE scope_type=? AND scope_key=? AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) FOR UPDATE",[b.scopeType,b.scopeKey,clock(),clock()]); + if(current.some(a=>a.user_id===b.userId&&a.role_key===b.role))throw fault('This assignment already exists.'); + if(['branch_lead','department_head'].includes(b.role)&¤t.some(a=>a.role_key===b.role))throw fault('This scope already has an accountable lead. Revoke that assignment before appointing another.'); + const id=randomUUID(),after={userId:b.userId,scopeType:b.scopeType,scopeKey:b.scopeKey,role:b.role,source:'manual'}; + await tx.query("INSERT INTO org_assignments(id,user_id,scope_type,scope_key,role_key,source_kind,starts_at,created_by,created_at) VALUES(?,?,?,?,?,'manual',?,?,?)",[id,b.userId,b.scopeType,b.scopeKey,b.role,clock(),actor.id,clock()]); + await audit(tx,actor,b,'assign',null,after,id); + }else{ + if(!identifier(b.assignmentId)||!Number.isSafeInteger(b.version)||b.version<1)throw fault('Select the current assignment version.',400); + const before=await tx.first('SELECT * FROM org_assignments WHERE id=? FOR UPDATE',[b.assignmentId]); + if(!before||before.user_id!==b.userId||before.scope_type!==b.scopeType||before.scope_key!==b.scopeKey||before.role_key!==b.role)throw fault('Assignment not found.',404); + if(before.source_kind!=='manual')throw fault('Automatic assignments must be changed at their source.',403); + if(before.status!=='active'||Number(before.version)!==b.version)throw fault('Assignment changed. Refresh before retrying.'); + await tx.query("UPDATE org_assignments SET status='revoked',version=version+1 WHERE id=?",[b.assignmentId]);await audit(tx,actor,b,'revoke',before,{status:'revoked'},b.assignmentId); + } + } + await tx.query('UPDATE org_scope_versions SET version=version+1 WHERE scope_type=? AND scope_key=?',[b.scopeType,b.scopeKey]); + return {ok:true,scopeVersion:b.scopeVersion+1,permissionsChanged:false,enforcement:'preparing'}; + });return reply(result); + }catch(e){ + if(e.status)return reply({message:e.message},e.status); + if(['ER_LOCK_DEADLOCK','ER_LOCK_WAIT_TIMEOUT'].includes(e.code))return reply({message:'A concurrent management change was detected. Refresh before retrying.'},409); + throw e; + } + }; +} diff --git a/website/node/organisation-model.mjs b/website/node/organisation-model.mjs index 451b119a..5a5a5ada 100644 --- a/website/node/organisation-model.mjs +++ b/website/node/organisation-model.mjs @@ -33,6 +33,29 @@ export function assignmentLabel(row){ id:row.id,version:Number(row.version||1)}; } export const organisationSchema = [ + `CREATE TABLE IF NOT EXISTS org_control_principals ( + user_id CHAR(36) PRIMARY KEY, principal_kind VARCHAR(24) NOT NULL, + created_by CHAR(36) NOT NULL, created_at BIGINT NOT NULL, + FOREIGN KEY(user_id) REFERENCES site_accounts(id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS org_scope_versions ( + scope_type VARCHAR(24) NOT NULL, scope_key VARCHAR(80) NOT NULL, + version INT NOT NULL DEFAULT 1, PRIMARY KEY(scope_type,scope_key) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS org_role_policies ( + scope_type VARCHAR(24) NOT NULL, scope_key VARCHAR(80) NOT NULL, + role_key VARCHAR(40) NOT NULL, permissions_json TEXT NOT NULL, + version INT NOT NULL DEFAULT 1, updated_by CHAR(36) NOT NULL, updated_at BIGINT NOT NULL, + PRIMARY KEY(scope_type,scope_key,role_key) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS org_assignment_events ( + id CHAR(36) PRIMARY KEY, user_id CHAR(36) NULL, assignment_id CHAR(36) NULL, + actor_id CHAR(36) NOT NULL, action VARCHAR(24) NOT NULL, + scope_type VARCHAR(24) NOT NULL, scope_key VARCHAR(80) NOT NULL, + reason VARCHAR(500) NOT NULL, before_json TEXT NULL, after_json TEXT NOT NULL, + created_at BIGINT NOT NULL, + INDEX org_events_target(user_id,created_at), INDEX org_events_scope(scope_type,scope_key,created_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, `CREATE TABLE IF NOT EXISTS org_assignments ( id CHAR(36) PRIMARY KEY, user_id CHAR(36) NOT NULL, scope_type VARCHAR(24) NOT NULL, scope_key VARCHAR(80) NOT NULL, role_key VARCHAR(40) NOT NULL, @@ -54,3 +77,12 @@ export async function initializeOrganisation(db){ for(const sql of organisationSchema)await db.prepare(sql).run(); // No automatic appointments, account rewrites, rank resets or game grants. } + +export function staffScopes(){ + return [{type:'organisation',key:'dunerealms',label:'DuneRealms'},...ORGANISATION.flatMap(d=>[ + {type:'department',key:d.key,label:d.label},...d.branches.map(b=>({type:'branch',key:b.key,label:b.label,department:d.key})) + ])]; +} +export function validStaffRole(type,key,role){ + return staffScopes().some(s=>s.type===type&&s.key===key)&&ASSIGNMENT_ROLES[type]?.some(r=>r.key===role); +} diff --git a/website/scripts/bootstrap-organisation-control.mjs b/website/scripts/bootstrap-organisation-control.mjs new file mode 100644 index 00000000..714f00d8 --- /dev/null +++ b/website/scripts/bootstrap-organisation-control.mjs @@ -0,0 +1,28 @@ +// One-time, explicit Owner-authorised control baseline. Does not activate role grants. +import {randomUUID} from 'node:crypto'; +import {fileURLToPath} from 'node:url'; +import {resolve} from 'node:path'; +import {openDatabase} from '../node/mysql.mjs'; +import {initializeOrganisation} from '../node/organisation-model.mjs'; +const OWNER_ID='f3ffda37-01e4-41ea-b89d-fbeda82e453e'; +const SERVICE_ID='f7b88778-f0bc-41cc-9227-d8ef2f52264d'; +const desired={unimatrix999:'owner',grmacken:'executive',richwjr:'executive',mr_blueray:'executive',dev:'service'}; +export async function bootstrapControl(db,{apply=false}={}){ + const rows=(await db.prepare(`SELECT id,username,role FROM site_accounts WHERE username IN (${Object.keys(desired).map(()=>'?')}) AND password_hash NOT LIKE '!%'`).bind(...Object.keys(desired)).all()).results; + if(rows.length!==5||new Set(rows.map(r=>r.username)).size!==5||rows.find(r=>r.username==='unimatrix999')?.id!==OWNER_ID||rows.find(r=>r.username==='dev')?.id!==SERVICE_ID)throw Error('Expected existing control identities do not match.'); + const policy=await db.prepare('SELECT service_uuid,game_link_exempt FROM site_account_policies WHERE user_id=?').bind(SERVICE_ID).first(); + if(!policy?.game_link_exempt||policy.service_uuid!=='00000000-0000-4000-8000-00000000de01')throw Error('Dev service exemption mismatch.'); + const plan=rows.map(r=>({id:r.id,username:r.username,kind:desired[r.username]}));if(!apply)return {applied:false,principals:plan}; + await db.transaction(async tx=>{ + for(const p of plan){ + const existing=await tx.first('SELECT principal_kind FROM org_control_principals WHERE user_id=? FOR UPDATE',[p.id]); + if(existing){if(existing.principal_kind!==p.kind)throw Error('Existing control assignment differs; never overwrite automatically.');continue;} + const account=await tx.first("SELECT id,username FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' FOR SHARE",[p.id]);if(account?.username!==p.username)throw Error('Identity changed during bootstrap.'); + const now=Date.now();await tx.query('INSERT INTO org_control_principals(user_id,principal_kind,created_by,created_at) VALUES(?,?,?,?)',[p.id,p.kind,OWNER_ID,now]); + await tx.query('INSERT INTO org_assignment_events(id,user_id,actor_id,action,scope_type,scope_key,reason,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[randomUUID(),p.id,OWNER_ID,'control-baseline','organisation','dunerealms','Owner-approved existing Big Four and Dev service control baseline',JSON.stringify({principal:p.kind,livePermissionsChanged:false}),now]); + } + });return {applied:true,principals:plan,livePermissionsChanged:false}; +} +if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){ + const db=await openDatabase(process.env);try{await initializeOrganisation(db);console.log(JSON.stringify(await bootstrapControl(db,{apply:process.argv.includes('--apply')})));}finally{await db.close();} +} diff --git a/website/tests/organisation-management.test.mjs b/website/tests/organisation-management.test.mjs new file mode 100644 index 00000000..f7b2dbf7 --- /dev/null +++ b/website/tests/organisation-management.test.mjs @@ -0,0 +1,86 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {canAssignRole,validatePolicyNodes,createOrganisationManagement} from '../node/organisation-management.mjs'; +import {bootstrapControl} from '../scripts/bootstrap-organisation-control.mjs'; +const owner='11111111-1111-4111-8111-111111111111',target='22222222-2222-4222-8222-222222222222'; +const position=(scope_type,scope_key,role_key)=>({scope_type,scope_key,role_key,status:'active'}); +test('branch and department managers cannot escalate outside their own scope',()=>{ + const head={assignments:[position('department','community_operations','department_head')]}; + assert.equal(canAssignRole(head,'branch','customer_support','branch_lead'),true); + assert.equal(canAssignRole(head,'branch','engineering','officer'),false); + assert.equal(canAssignRole(head,'department','community_operations','department_head'),false); + const lead={assignments:[position('branch','news_media','branch_lead')]}; + assert.equal(canAssignRole(lead,'branch','news_media','officer'),true);assert.equal(canAssignRole(lead,'branch','news_media','branch_lead'),false);assert.equal(canAssignRole(lead,'branch','customer_support','officer'),false); + assert.equal(canAssignRole({assignments:[position('branch','news_media','officer')]},'branch','news_media','officer'),false); +}); +test('Big Four and service control are organisation-wide; Owner office stays protected',()=>{ + for(const principal of ['owner','executive','service']){const auth={principal,assignments:[]};assert.equal(canAssignRole(auth,'organisation','dunerealms','executive'),true);assert.equal(canAssignRole(auth,'branch','engineering','branch_lead'),true);assert.equal(canAssignRole(auth,'organisation','dunerealms','owner_ceo'),false);assert.equal(canAssignRole(auth,'branch','invented','officer'),false);} +}); +test('policy mapping rejects native editors, unregistered permissions and excessive bank power',()=>{ + assert.throws(()=>validatePolicyNodes(['*'],'organisation','executive')); + assert.throws(()=>validatePolicyNodes(['web.luckperms.edit'],'organisation','executive')); + assert.throws(()=>validatePolicyNodes(['web.bank.staff.manage'],'branch','officer')); + assert.deepEqual(validatePolicyNodes(['web.bank.staff.manage'],'department','department_head'),['web.bank.staff.manage']); + assert.deepEqual(validatePolicyNodes(['web.posts.view','web.posts.view'],'branch','officer'),['web.posts.view']); +}); +function fixture({principal='owner',positions=[],scopeVersion=1,current=[],existing=null,service=false,authenticated=true,allowed=true,auditFail=false,dbError=null}={}){ + const writes=[]; + const tx={async first(sql,args){ + if(sql.includes('SELECT a.id,p.game_link_exempt'))return {id:target,game_link_exempt:service?1:0}; + if(sql.includes('FROM site_accounts'))return {id:owner}; + if(sql.includes('FROM org_control_principals'))return principal?{principal_kind:principal}:null; + if(sql.includes('FROM org_scope_versions'))return {version:scopeVersion}; + if(sql.includes('SELECT * FROM org_assignments'))return existing; + if(sql.includes('FROM org_role_policies'))return null; + throw Error('Unexpected SQL: '+sql); + },async query(sql,args){ + if(sql.startsWith('SELECT scope_type'))return positions; + if(sql.startsWith('SELECT id,user_id,role_key'))return current; + if(auditFail&&sql.includes('INSERT INTO org_assignment_events'))throw Error('audit unavailable'); + writes.push({sql,args});return []; + }}; + const db={async transaction(fn){if(dbError)throw Object.assign(new Error('Concurrent transaction'),{code:dbError});const start=writes.length;try{return await fn(tx);}catch(e){writes.splice(start);throw e;}},prepare(){return {bind(){return this;},all:async()=>({results:[]})};}}; + const api=createOrganisationManagement(db,{authenticate:async()=>authenticated?{id:owner}:null,authorize:async()=>allowed,clock:()=>100});return {api,writes}; +} +const body=(extra={})=>({action:'assign',userId:target,scopeType:'branch',scopeKey:'news_media',role:'officer',scopeVersion:1,reason:'Approved appointment',...extra}); +const request=(data,options={})=>new Request('https://cp.dunerealms.com/api/admin/organisation/'+(options.policy?'policies':'assignments'),{method:'POST',headers:{'Origin':options.origin||'https://cp.dunerealms.com','Content-Type':'application/json'},body:JSON.stringify(data)}); +test('assignment creates an audited register record without activating live permissions',async()=>{ + const f=fixture();const r=await f.api(request(body()));assert.equal(r.status,200);const result=await r.json();assert.equal(result.permissionsChanged,false);assert.equal(result.scopeVersion,2); + assert.ok(f.writes.some(w=>w.sql.startsWith('INSERT INTO org_assignments')));assert.ok(f.writes.some(w=>w.sql.startsWith('INSERT INTO org_assignment_events')));assert.ok(f.writes.every(w=>!w.sql.includes('cp_account_ranks')&&!w.sql.includes('UPDATE site_accounts'))); +}); +test('fresh transaction authority defeats stale or missing scope grants',async()=>{ + const f=fixture({principal:null});assert.equal((await f.api(request(body()))).status,403);assert.equal(f.writes.length,0); + const scoped=fixture({principal:null,positions:[position('branch','customer_support','branch_lead')]});assert.equal((await scoped.api(request(body()))).status,403); +}); +test('stale versions, duplicates and a second lead roll back completely',async()=>{ + for(const [options,b]of [[{scopeVersion:2},body()],[{current:[{user_id:target,role_key:'officer'}]},body()],[{current:[{user_id:owner,role_key:'branch_lead'}]},body({role:'branch_lead'})]]){const f=fixture(options);assert.equal((await f.api(request(b))).status,409);assert.equal(f.writes.length,0);} +}); +test('automatic assignments cannot be revoked from the manual editor',async()=>{ + const id='33333333-3333-4333-8333-333333333333';const f=fixture({existing:{id,user_id:target,scope_type:'branch',scope_key:'news_media',role_key:'officer',source_kind:'system',status:'active',version:1}}); + assert.equal((await f.api(request(body({action:'revoke',assignmentId:id,version:1})))).status,403);assert.equal(f.writes.length,0); +}); +test('service identities stay outside staff appointments and cross-origin writes are denied',async()=>{ + const f=fixture({service:true});assert.equal((await f.api(request(body()))).status,403);assert.equal(f.writes.length,0); + const g=fixture();assert.equal((await g.api(request(body(),{origin:'https://evil.example'}))).status,403);assert.equal(g.writes.length,0); +}); +test('denials and forged request metadata never write to the register',async()=>{ + for(const [options,status]of [[{authenticated:false},401],[{allowed:false},403]]){const f=fixture(options);assert.equal((await f.api(request(body()))).status,status);assert.equal(f.writes.length,0);} + for(const b of [body({source:'election'}),body({reason:' '}),body({userId:'wrong'}),body({scopeVersion:0})]){const f=fixture();assert.equal((await f.api(request(b))).status,400);assert.equal(f.writes.length,0);} +}); +test('audit failure prevents a partial assignment commit',async()=>{ + const f=fixture({auditFail:true});await assert.rejects(()=>f.api(request(body())),/audit unavailable/);assert.equal(f.writes.length,0); +}); +test('policy changes share the scope version and record their exact node set',async()=>{ + const f=fixture({principal:'executive'});const {action,userId,...b}=body({nodes:['web.posts.view']});const r=await f.api(request(b,{policy:true}));assert.equal(r.status,200);assert.ok(f.writes.some(w=>w.sql.includes('INSERT INTO org_role_policies')));assert.ok(f.writes.some(w=>w.sql.includes('INSERT INTO org_assignment_events'))); +}); +test('database lock races are reported as refreshable conflicts, never partial success',async()=>{ + for(const dbError of ['ER_LOCK_DEADLOCK','ER_LOCK_WAIT_TIMEOUT']){const f=fixture({dbError});const r=await f.api(request(body()));assert.equal(r.status,409);assert.equal(f.writes.length,0);assert.match((await r.json()).message,/Refresh/);} +}); +test('control bootstrap pins existing identities, is idempotent and rejects conflicting principals',async()=>{ + const rows=[['unimatrix999','f3ffda37-01e4-41ea-b89d-fbeda82e453e'],['dev','f7b88778-f0bc-41cc-9227-d8ef2f52264d'],['grmacken',owner],['richwjr',target],['mr_blueray','33333333-3333-4333-8333-333333333333']].map(([username,id])=>({username,id})); + let commits=0;const principals=new Map(); + const db={prepare(sql){return{bind(){return this;},async all(){return{results:rows};},async first(){return{game_link_exempt:1,service_uuid:'00000000-0000-4000-8000-00000000de01'};}};},async transaction(work){return work({async first(sql,args){if(sql.includes('org_control_principals'))return principals.has(args[0])?{principal_kind:principals.get(args[0])}:null;return rows.find(r=>r.id===args[0]);},async query(sql,args){if(sql.startsWith('INSERT INTO org_control_principals')){principals.set(args[0],args[1]);commits++;}}});}}; + assert.equal((await bootstrapControl(db)).applied,false);assert.equal(commits,0); + await bootstrapControl(db,{apply:true});await bootstrapControl(db,{apply:true});assert.equal(commits,5); + principals.set(owner,'owner');await assert.rejects(()=>bootstrapControl(db,{apply:true}),/differs/); + rows[0].id=target;await assert.rejects(()=>bootstrapControl(db),/identities/); +}); From 7bc4121c9f2f424584813ecca68597b1292ae2d6 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:50:24 +0100 Subject: [PATCH 04/16] Route legacy citizen clan and political banking views to Postbank --- website/control-panel/public/clan-shop.mjs | 2 +- website/control-panel/public/cp-v2/cp-v2-bureau-pages.mjs | 4 ++-- website/control-panel/public/cp-v2/cp-v2-user-pages.mjs | 5 +++-- website/control-panel/public/politics.mjs | 4 ++-- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/website/control-panel/public/clan-shop.mjs b/website/control-panel/public/clan-shop.mjs index a7146283..ec6f4548 100644 --- a/website/control-panel/public/clan-shop.mjs +++ b/website/control-panel/public/clan-shop.mjs @@ -17,7 +17,7 @@ function refresh(view){const b=el('button','Refresh');b.type='button';b.onclick= function priceEditor(view){if(!data.canSetPrice)return;const form=el('form');form.className='clan-form';const label=el('label','Full clan kit price · Dunemarks'),price=el('input');price.type='number';price.min=1;price.max=1000000;price.required=true;price.value=data.priceDunemarks;label.append(price);const save=el('button','Set kit price');save.type='submit';save.dataset.duneAction='admin';form.append(label,save);form.onsubmit=async e=>{e.preventDefault();const g=generation;save.disabled=true;try{const r=await fetch('/api/clans/shop/price',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({priceDunemarks:Number(price.value)})});const d=await r.json();if(!r.ok)throw Error(d.message);if(g===generation)await load();}catch(e){if(g===generation)view.status.textContent=e.message;}finally{if(g===generation)save.disabled=false;}};view.body.append(form);} function renderShop(v){header(v,'shops','Clan shops','Equipment commissioned under your clan banner.','nav-exchange-full-v2.webp');const card=el('article');card.className='clan-shop-card';const image=el('img');image.src='https://www.dunerealms.com/assets/clan-atelier-v1.webp';image.alt='Illustrated desert stillsuit armour display';const copy=el('div');copy.append(el('span','UNCOMMON · FOUR-PIECE SET'),el('h3',data.blueprint?.name||'Clan stillsuit'),el('strong',data.priceDunemarks+' Dunemarks'),el('p','Paid from the buyer’s Dunemarks wallet. Physical spice is not used.'));if(data.blueprint){for(const line of data.blueprint.lore)copy.append(el('p',line));const swatch=el('span',data.blueprint.color);swatch.className='clan-kit-swatch';swatch.style.backgroundColor=data.blueprint.color;copy.append(swatch,el('p','Open the Clan Shop in game to confirm payment and receive your four armour pieces.'));}else copy.append(el('p','Your clan owner or an officer must save a kit design before members can purchase it.'));card.append(image,copy);v.body.append(card);priceEditor(v);} function renderKits(v){header(v,'kits','House Tailor','Commission your clan’s colours and write the lore carried into the desert.','items/office_water.png');const g=generation,mount=createHouseTailor({data,save:api,isCurrent:()=>g===generation&&mount.element.isConnected});v.body.append(mount.element);} -function renderBank(v){header(v,'bank','Clan Treasury','Your clan’s Dunemarks treasury and recorded transactions.','dunemark-icon-64.png');v.body.classList.add('imperial-bank-view');const brand=el('img');brand.src='/assets/imperial-postbank-v2.png';brand.alt='Imperial Postbank · Part of Corrino Group';brand.className='imperial-bank-brand';brand.width=480;v.body.append(brand);refresh(v);if(!data.bankAvailable){v.body.append(el('p','The Dunemarks bank connection is temporarily unavailable.'));return;}const stats=el('div');stats.className='clan-stat-grid';const total=el('article');total.append(el('small','CLAN BALANCE · DUNEMARKS'),el('strong',data.bank.balanceDunemarks+' DM'));const access=el('article');access.append(el('small','YOUR BANK ACCESS'),el('strong',['owner','officer'].includes(data.clan.role)?'Officer':'Member'));stats.append(total,access);const account=el('article');account.className='imperial-account-card';account.append(el('small','CLAN ACCOUNT NUMBER'),el('strong',data.bank.accountNumber),el('p',data.clan.name));v.body.append(account,stats,el('p','Deposit and withdraw Dunemarks in game. Bank withdrawals require the clan owner or an officer. No physical spice is used.'),el('h3','Transaction ledger'));const scroll=el('div');scroll.className='clan-table-scroll';const table=el('table');table.className='clan-table';const head=el('tr');for(const t of ['Date','Entry','From account','To account','Dunemarks','Balance after'])head.append(el('th',t));table.append(head);for(const row of data.bank.ledger){const tr=el('tr');tr.append(el('td',new Date(Number(row.createdAt)).toLocaleString()),el('td',row.kind),el('td',row.amountDunemarks.startsWith('-')?data.bank.accountNumber:'Not recorded'),el('td',row.amountDunemarks.startsWith('-')?'Not recorded':data.bank.accountNumber),el('td',row.amountDunemarks),el('td',row.balanceDunemarks));table.append(tr);}scroll.append(table);v.body.append(scroll);if(!data.bank.ledger.length)v.body.append(el('p','No bank transactions recorded yet.'));} +function renderBank(v){header(v,'bank','Clan Banking','Manage your authorised clan accounts in Imperial Postbank.','imperial-postbank-v2.png');const link=el('a','Open Imperial Postbank');link.href='https://cp.dunerealms.com/#bank/bank-overview';link.target='_top';v.body.append(link);} function questMenu(v,current){const nav=el('nav');nav.className='quest-submenu';nav.setAttribute('aria-label','Quest categories');for(const[id,label]of [['player','Player Quests'],['clan','Clan Quests'],['guild','Spacing Guild Quests']]){const a=el('a',label);if(data.member||id==='player')a.href='#clan-quests-'+id;else{a.setAttribute('aria-disabled','true');a.title='Join a clan to unlock this section.';}if(current===id)a.setAttribute('aria-current','page');nav.append(a);}v.body.append(nav);} function placeholders(v,kind){const labels={player:['Personal quest journal','Track your own objectives and plan your next crossing.'],clan:['Clan expedition ledger','Coordinate shared objectives and clan contributions.'],guild:['Spacing Guild contracts','Personal assignments and contracts undertaken by your clan.']};header(v,'quests',...labels[kind],'nav-manual-full-v2.webp');questMenu(v,kind);if(kind==='player'){const host=el('div');v.body.append(host);mountPersonalKitArc(host);return;}const banner=el('aside');banner.className='quest-preview-notice';banner.append(el('strong','LAYOUT PREVIEW'),el('p','Example planning material only. These entries are not active quests and grant no rewards.'));v.body.append(banner);if(kind==='player'){const live=el('a','Open your live quest journal');live.href='#quests';v.body.append(live);}const stats=el('div');stats.className='clan-stat-grid';for(const label of ['Active objectives','Completed journeys','Rewards ready']){const c=el('article');c.append(el('small',label),el('strong','—'));stats.append(c);}v.body.append(stats);const tools=el('nav');tools.className='quest-preview-filters';for(const label of ['Overview','In progress','Completed','Archived']){const b=el('button',label);b.type='button';b.disabled=true;tools.append(b);}v.body.append(tools);const cards=el('div');cards.className='quest-plan-grid';const examples=kind==='player'?[['Desert field training','Prepare a stillsuit, learn the safe routes and record a first expedition.','Personal objectives'],['A traveller’s provisions','Organise supplies before your next planetary crossing.','Personal checklist']]:kind==='clan'?[['Raise the clan banner','Plan a shared expedition and assign contributions to clan members.','Clan objectives'],['Caravan provisions','Review collective supplies and coordinate your clan’s next journey.','Member contributions']]:[['Personal Guild contract','A reserved place for individual travel and courier assignments.','Player contracts'],['Clan Guild charter','A reserved place for coordinated contracts undertaken under your clan banner.','Clan contracts']];for(const[title,description,scope]of examples){const card=el('article'),img=el('img');img.src='https://www.dunerealms.com/assets/'+(kind==='guild'?'guild.webp':'nav-manual-full-v2.webp');img.alt='';card.append(img,el('small','PLANNED · '+scope),el('h3',title),el('p',description),el('p','Objectives · — Progress · — Reward · Not configured'));const button=el('button','Details coming soon');button.type='button';button.disabled=true;card.append(button);cards.append(card);}v.body.append(cards);} async function render(id){const v=views[id];if(!v||!data)return;v.status.textContent='';if(!data.member&&!id.startsWith('clan-quests')){header(v,id.slice(5),'Join a clan','A verified clan membership is required for this page.');v.body.append(el('p','Your personal quest journal is available without a clan.'));const a=el('a','Open Player Quests');a.href='#clan-quests-player';v.body.append(a);return;}if(id==='clan-shops')renderShop(v);else if(id==='clan-kits')renderKits(v);else if(id==='clan-bank')renderBank(v);else if(id==='clan-settings'){header(v,'settings','Clan settings','Manage your banner, membership and leadership.');const mount=el('div');v.body.append(mount);if(!await mountOwnClanManagement(mount))mount.append(el('p','Clan management could not be loaded. Refresh to retry.'));}else if(id==='clan-portal'){header(v,'portal','Clan portal','Your clan’s operations, colours and shared journeys.');const cards=el('div');cards.className='clan-portal-grid';for(const[key,label,art]of entries.filter(x=>x[0]!=='portal')){const a=el('a');a.href='#clan-'+key;const image=el('img');image.src='https://www.dunerealms.com/assets/'+art;image.alt='';a.append(image,el('h3',label),el('p',{shops:'Commission a full clan stillsuit.',kits:'Design your clan colours and lore.',bank:'Inspect the Dunemarks balance and ledger.',settings:'Manage members and your banner.',quests:'Plan personal and clan journeys.'}[key]));cards.append(a);}v.body.append(cards);}else{let kind=id.split('-').at(-1);if(!['player','clan','guild'].includes(kind))kind='player';if(!data.member&&kind!=='player'){header(v,'quests','Clan membership required','Only Player Quests are available without a clan.','nav-manual-full-v2.webp');questMenu(v,'player');return;}placeholders(v,kind);}} diff --git a/website/control-panel/public/cp-v2/cp-v2-bureau-pages.mjs b/website/control-panel/public/cp-v2/cp-v2-bureau-pages.mjs index 8d20c033..cbbeece2 100644 --- a/website/control-panel/public/cp-v2/cp-v2-bureau-pages.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-bureau-pages.mjs @@ -12,7 +12,7 @@ import {createCPV2Page,element as el} from './cp-v2-page-template.mjs'; import {mountReadRegister} from './cp-v2-read-register.mjs'; import {BUREAU_READS} from './cp-v2-bureau-data.mjs'; import {mountCompanyActions} from './cp-v2-company-actions.mjs'; -import {mountImperialRevenue} from './cp-v2-imperial-revenue.mjs'; +import {mountPostbankAdmin} from './cp-v2-postbank-admin.mjs'; // Imperial Bureau pages not yet backed by verified V2 APIs. Never expose fake writes. const PAGES={"company-management":{"title":"Company Directorate","tabs":["Enterprise registry","Corporate governance","Company permissions"]},"company-management-v2":{"title":"Corporate Administration","tabs":["Company administration","Officer assignments","Corporate settings"]},"company-audit":{"title":"Corporate Audit","tabs":["Audit register","Corporate changes","Compliance reports"]},"staff-bank":{"title":"Imperial Revenue","tabs":["Revenue overview","Collections","Allocation controls"]},"server-kits":{"title":"Kit Directorate","tabs":["Kit catalogue","Kit administration","In-game delivery"]},"kit-publishing":{"title":"Kit Publications","tabs":["Publication queue","Published kits","Version history"]},"kit-claims":{"title":"Claim Registry","tabs":["Claim requests","Claim history","Delivery reconciliation"]},"exchange-admin":{"title":"Exchange Authority","tabs":["Exchange operations","Listing moderation","Trade oversight"]},"shop-admin":{"title":"Merchant Directorate","tabs":["Merchant directory","Shop approvals","Sales administration"]},"items":{"title":"Item Registry","tabs":["Item catalogue","Item definitions","Publishing queue"]},"website-posts":{"title":"Imperial Newsroom","tabs":["Newsroom drafts","Publication schedule","Published announcements"]},"staff-tickets":{"title":"Petition Office","tabs":["Incoming petitions","Assigned cases","Resolution history"]},"bans":{"title":"Tribunal","tabs":["Tribunal cases","Sanctions register","Appeal reviews"]},"ban-evidence":{"title":"Evidence Registry","tabs":["Evidence register","Case attachments","Chain of custody"]},"forum-admin":{"title":"Forum Wardens","tabs":["Forum reports","Moderation queue","Community rules"]},"quests-admin":{"title":"Campaign Directorate","tabs":["Campaign catalogue","Quest publishing","Participation reports"]},"community-goals":{"title":"Community Treasury","tabs":["Treasury goals","Contribution records","Funding oversight"]},"support-management":{"title":"Petition Administration","tabs":["Support queue","Staff assignments","Service reports"]},"server-operations":{"title":"Network Command","tabs":["Network overview","Server operations","Incident register"]},"hosting-control":{"title":"Hosting Command","tabs":["Infrastructure status","Hosting controls","Change approvals"]},"dev-approvals":{"title":"Development Approvals","tabs":["Approval queue","Change proposals","Decision history"]}}; const artFor=id=>/kit|item|dev/.test(id)?'nav-manual-v2.webp':/bank|exchange|shop|revenue|treasury/.test(id)?'nav-exchange-v2.webp':'nav-staff-v2.webp'; @@ -101,6 +101,6 @@ export function mountBureauPlaceholder(host,id){ if(id==='website-posts')return mountNewsroom(host); if(SERVICE_PAGES[id])return mountBureauServicePage(host,id); if(id==='company-management')return mountCompanyDirectorate(host); - if(id==='staff-bank')return mountImperialRevenue(host); + if(id==='staff-bank')return mountPostbankAdmin(host,'staff-bank'); if(BUREAU_READS[id]){const spec=PAGES[id];return mountReadRegister(host,{title:spec.title,description:'Imperial Bureau · '+spec.title+' · Read-only preview',artwork:artFor(id),tabs:spec.tabs.map((label,index)=>({id:'area-'+(index+1),label,...BUREAU_READS[id][index]}))});} const spec=PAGES[id];if(!spec)throw Error('Unknown Bureau page');const artwork=artFor(id);const tabs=spec.tabs.map((label,index)=>{const content=el('section',undefined,'cp-v2-bank-placeholder');const image=el('img');image.src='https://www.dunerealms.com/assets/'+artwork;image.alt='';image.width=82;image.height=82;content.append(image,el('h4',label),el('p',label+' will be connected to its verified authorization and data service during V2 integration.'),el('p','V2 · PLANNED — no live data or administrative changes are available here.','cp-v2-bank-status'));return{id:'area-'+(index+1),label,artwork,content}});const {root}=createCPV2Page({title:spec.title,description:'Imperial Bureau · '+spec.title+' workspace.',artwork,tabs});host.replaceChildren(root);return()=>root.remove()} diff --git a/website/control-panel/public/cp-v2/cp-v2-user-pages.mjs b/website/control-panel/public/cp-v2/cp-v2-user-pages.mjs index 721db98f..8b1df7bc 100644 --- a/website/control-panel/public/cp-v2/cp-v2-user-pages.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-user-pages.mjs @@ -12,7 +12,8 @@ export function mountUserPage(host,id,{fetcher=fetch,initialTab,listingId}={}){ async function mount(){ const loaders={game:['./cp-v2-passport.mjs','mountPassport'],'site-profile':['./cp-v2-personal-records.mjs','mountPersonalRecords'],security:['./cp-v2-security.mjs','mountSecurity'],'rewards-codes':['./cp-v2-rewards.mjs','mountRewards']}; if(loaders[id]){const [path,key]=loaders[id],module=await import(path);if(active)dispose=module[key](host,{fetcher,initialTab});return;} - if(['tickets','clans','shared-inbox','kits-exchange','personal-bank'].includes(id)){const {mountNativeService}=await import('./cp-v2-native-services.mjs');if(active)dispose=mountNativeService(host,id,{fetcher,singleHeading:true,initialTab,listingId});return;} + if(['personal-bank','transactions'].includes(id)){const {mountBankPage}=await import('./cp-v2-bank-pages.mjs');if(active)dispose=mountBankPage(host,id==='transactions'?'bank-statements':'personal-bank',{fetcher});return;} + if(['tickets','clans','shared-inbox','kits-exchange'].includes(id)){const {mountNativeService}=await import('./cp-v2-native-services.mjs');if(active)dispose=mountNativeService(host,id,{fetcher,singleHeading:true,initialTab,listingId});return;} if(id==='planetary-inventory'){ const {mountInventory}=await import('/inventory/inventory-view.mjs');if(!active)return; if(!document.querySelector('link[data-v2-inventory]')){const css=el('link');css.rel='stylesheet';css.href='/inventory/inventory.css';css.dataset.v2Inventory='true';document.head.append(css);} @@ -20,7 +21,7 @@ export function mountUserPage(host,id,{fetcher=fetch,initialTab,listingId}={}){ const {root}=createCPV2Page({shellHost:host,title:'My Inventory',description:'Your saved planetary equipment and exchange history, connected to the existing game inventory service.',artwork:'nav-account-v2.webp',tabs:[{id:'inventory-record',label:'Equipment & ledger',content:inventory}]});host.replaceChildren(root); const view=mountInventory(inventory,{request:api.request,visibleTabs:['inventory','history'],title:'Saved inventory'});dispose=()=>{view.clear();root.remove();};return; } - if(['transactions','shop-settings','exchange-settings'].includes(id)){const {mountUserCommerce}=await import('./cp-v2-user-commerce.mjs');if(active)dispose=mountUserCommerce(host,id,{fetcher});return;} + if(['shop-settings','exchange-settings'].includes(id)){const {mountUserCommerce}=await import('./cp-v2-user-commerce.mjs');if(active)dispose=mountUserCommerce(host,id,{fetcher});return;} if(id==='quests'){mountQuests();return;} if(id==='discord-link'){ const box=el('section',undefined,'cp-v2-personal-box'),{root}=createCPV2Page({shellHost:host,title:'Discord Link',description:'Your Discord community presence and account-linking availability.',artwork:'nav-discord-v2.webp',tabs:[{id:'discord-identity',label:'Discord identity',content:box}]});host.replaceChildren(root); diff --git a/website/control-panel/public/politics.mjs b/website/control-panel/public/politics.mjs index 518f8e62..7945127b 100644 --- a/website/control-panel/public/politics.mjs +++ b/website/control-panel/public/politics.mjs @@ -118,8 +118,8 @@ function render(){ const house=views['house-elections'].content; if(context?.faction){const name=context.faction[0].toUpperCase()+context.faction.slice(1);house.append(card(name+' · House chamber','Your faction was confirmed from your linked Minecraft account. The register below contains real candidatures for this chamber.','seals/office-house_leader.png'),renderVoting('house'));} else{const title=context?.linked===false?'Link your Minecraft account':context?'House not confirmed':'Checking your linked House';const box=card(title,context?.linked===false?'Link your Minecraft identity to enter the chamber belonging to the faction you chose in game.':'Your House has not been confirmed. Other House elections remain hidden.','seals/office-house_leader.png');box.append(artLink('Minecraft account','game','nav-clan-v2.webp'));house.append(box);} - const council=views['formal-council'].content;if(context?.factionAccount){const treasury=card('House Treasury',context.factionAccount,'dunemark-icon-64.png');treasury.classList.add('imperial-account-card');const brand=el('img');brand.src='/assets/imperial-postbank-v2.png';brand.alt='Imperial Postbank · Part of Corrino Group';brand.className='imperial-bank-brand';brand.width=480;treasury.prepend(brand);council.append(treasury);}council.append(councilPreview(),rallyPreview(),revoltPreview(),warPreview(),inboxPreview());if(views['shared-inbox'].section.dataset.internalMail!=='true')views['shared-inbox'].content.append(el('p','Loading your private inbox…')); - const councilLink=card('Faction Council','Banking, appointments, rallies, war requests and your shared inbox.','seals/office-house_leader.png');councilLink.append(artLink('Enter the council','formal-council','seals/office-house_leader.png'));landing.append(councilLink); + const council=views['formal-council'].content;{const treasury=card('House Treasury','Manage your authorised House and office accounts in Imperial Postbank.','imperial-postbank-v2.png');const link=el('a','Open Imperial Postbank');link.href='https://cp.dunerealms.com/#bank/bank-overview';link.target='_top';treasury.append(link);council.append(treasury);}council.append(councilPreview(),rallyPreview(),revoltPreview(),warPreview(),inboxPreview());if(views['shared-inbox'].section.dataset.internalMail!=='true')views['shared-inbox'].content.append(el('p','Loading your private inbox…')); + const councilLink=card('Faction Council','Appointments, rallies, war requests, your shared inbox and Imperial Postbank access.','seals/office-house_leader.png');councilLink.append(artLink('Enter the council','formal-council','seals/office-house_leader.png'));landing.append(councilLink); const lore=card('The Veiled Concord · Caitain','In the quiet courts of Caitain, the Concord keeps the promises that crowns forget. Its scholars train in memory, diplomacy and patient observation. Three woven paths surround a guiding star upon their seal: knowledge, restraint and accord. Their elected Reverent Mother speaks with the standing of a House leader, while an appointed Concord Sister tends the treasury. They may counsel another House toward war, but never declare it themselves.','seals/veiled-concord-v1.png');lore.classList.add('politics-concord');landing.append(lore); for(const key of ['house-elections','imperial-elections']){const note=views[key].section.querySelector('.politics-preview-note');if(note)note.textContent='ELECTION CHAMBER · Real candidates and definitive votes. Voting opens at the scheduled time.';} const imperial=views['imperial-elections'].content;imperial.append(renderVoting('imperial')); From f21824b268706d7bcef5f6fd11f83c58222b813c Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:52:10 +0100 Subject: [PATCH 05/16] Expose tax allocations from treasury account management --- website/control-panel/public/cp-v2/cp-v2-postbank-admin.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/website/control-panel/public/cp-v2/cp-v2-postbank-admin.mjs b/website/control-panel/public/cp-v2/cp-v2-postbank-admin.mjs index 8021375c..0ceaf7f6 100644 --- a/website/control-panel/public/cp-v2/cp-v2-postbank-admin.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-postbank-admin.mjs @@ -21,6 +21,7 @@ export function mountPostbankAdmin(host,id,{fetcher=fetch}={}){ const nav=el('nav',undefined,'pb-ledger-pagination'),previous=el('button','Previous'),next=el('button','Next');previous.type=next.type='button';previous.disabled=page===1;next.disabled=!data.hasMore;previous.onclick=()=>{page--;void load();};next.onclick=()=>{page++;void load();};nav.append(previous,el('span','Page '+page),next);frame.content.append(nav);frame.status.hidden=true;frame.diagnostics.textContent='Central API · Bank administration permission confirmed · '+new Date().toLocaleString('en-GB'); }catch(error){if(active)message(error.message);}finally{busy=false;if(active)frame.reloadButton.disabled=false;}} function renderTreasuries(data,canManage,canIssueReserve){ + if(canManage){const allocations=el('a','Tax Treasury Payments');allocations.href='#bureau/tax-treasury';allocations.className='pb-primary-link';frame.content.append(allocations);} const managed=data.records.filter(a=>!a.system||a.canTransfer),automated=data.records.filter(a=>a.system&&!a.canTransfer),priority=a=>a.name==='Website Bank Treasury'?0:a.name==='In-game Bank Treasury'?1:a.name==='I.D. Taxes'?2:3; managed.sort((a,b)=>priority(a)-priority(b)||a.name.localeCompare(b.name));automated.sort((a,b)=>a.name.localeCompare(b.name)); for(const [title,records,type,description]of [['Managed Accounts',managed,'managed','Bank reserves, the combined web/game tax treasury and staff accounts. Manual treasury transfers are limited to the website bank, in-game reserve and tax treasury.'],['System Accounts',automated,'system','Automated service accounts. Federal Imperial Reserve records capital issuance; P&O is a fictitious payroll issuer. Neither can make manual payments here.']]){ From 458125d04db4fc47301613ab4c566c1eb97f63df Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:11:42 +0100 Subject: [PATCH 06/16] Add public branded Postbank rates guide and footer link --- website/scripts/bank-rates-page.mjs | 9 +++++++++ website/scripts/build.mjs | 2 ++ website/web/bank-rates.css | 1 + website/web/portal-navigation.js | 2 ++ website/web/rates-and-charges.html | 1 + 5 files changed, 15 insertions(+) create mode 100644 website/scripts/bank-rates-page.mjs create mode 100644 website/web/bank-rates.css create mode 100644 website/web/rates-and-charges.html diff --git a/website/scripts/bank-rates-page.mjs b/website/scripts/bank-rates-page.mjs new file mode 100644 index 00000000..7f601540 --- /dev/null +++ b/website/scripts/bank-rates-page.mjs @@ -0,0 +1,9 @@ +import {PACKAGES,BANK_VERSION} from '../node/postbank-catalogue.mjs'; +import {CREDIT_PRODUCTS,CREDIT_VERSION} from '../node/postbank-credit-model.mjs'; +import {createHash} from 'node:crypto'; +export function bankRatesPage(){ +const version=createHash('sha256').update(JSON.stringify([PACKAGES,CREDIT_PRODUCTS])).digest('hex').slice(0,10); +const packages=PACKAGES.map(p=>`${p.name}${p.kinds.join(' / ')}${(p.monthly/100).toFixed(2)} DM${p.extra}${p.extra?(p.extraFee/100).toFixed(2)+' DM':'—'}${p.instant}`).join(''); +const credit=CREDIT_PRODUCTS.filter(p=>!p.revolving).map(p=>`${p.name}${(p.annualBps/100).toFixed(2)}%${p.min}–${p.max} DM${p.terms?p.terms.join(', '):'Up to '+p.maxMonths} months`).join(''); +return `Rates & Charges | Imperial Postbank
DuneRealms
Imperial Postbank

YOUR MONEY. CLEAR TERMS.

Rates & Charges

A clear guide to your banking costs.

PUBLIC TARIFF GUIDE · ${version}
01 / EVERYDAY BANKING

Accounts & packages

One current account is included in each package.

${packages}
PackageClientMonthly priceExtra current accounts¹Each / month¹Instant quota / month

¹ Published additional-account limits and prices, subject to feature availability. Flow includes a savings account. Start has no instant payments. Instant quotas are server usage limits.

02 / BORROWING

Credit rates

Annual rates for new applications. Your accepted contract and repayment schedule govern your loan.

${credit}
ProductAnnual ratePrincipal rangeAvailable terms

Launch grants are repayable at 0% interest. Ordinary loans require review and 25% blocked DM collateral. Eligibility, available funding and refinancing conditions apply. Existing fixed-rate contracts retain their agreed rate. Revolving credit is not available.

03 / TRANSPARENCY

Services & taxes

Monthly statements

Free

Automatically archived PDF statements after month-end.

Balance Guard

1.00 DM / month

Published optional price per eligible account. Preference saving is available; protection and charging are not active yet.

Tax policy

Not yet published

VAT and account-tax rates await central configuration. No unconfirmed rate is presented as active.

Your tariff guide

Generated from the bank catalogues on each build. Version ${version}. Package terms: ${BANK_VERSION}. Credit terms: ${CREDIT_VERSION}.

Catalogue references identify source terms, not a new effective date. Administrative rate editing and automatic downloadable PDF publication are planned. You can print or save this guide as PDF now.

No private account or transaction data is published here.

`; +} diff --git a/website/scripts/build.mjs b/website/scripts/build.mjs index 4a77092d..b15c2022 100644 --- a/website/scripts/build.mjs +++ b/website/scripts/build.mjs @@ -1,3 +1,4 @@ +import {bankRatesPage} from './bank-rates-page.mjs'; import{withCanonicalMenu,MAIN_MENU}from'./main-menu.mjs'; import{recordPageUpdates,withMenuBadges}from'./menu-updates.mjs'; import{updatePortalNavigation}from'./portal-navigation.mjs'; @@ -28,6 +29,7 @@ function preparePublicHtml(html){ } return result; } +writeFileSync(path.join(web,'rates-and-charges.html'),bankRatesPage()); let assetCount=0;let assetWriter=null;const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.mp4':'video/mp4','.zip':'application/zip','.svg':'image/svg+xml'}; function collect(directory){for(const entry of readdirSync(directory).sort()){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const relative=path.relative(web,p).split(path.sep).join('/');if(/^assets\/seals\/[^/]+-provenance\.txt$/.test(relative))continue;const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);const bytes=readFileSync(p);const payload=relative.endsWith('.html')?Buffer.from(preparePublicHtml(bytes.toString('utf8'))):relative==='portal-navigation.js'?Buffer.from(withCanonicalMenu(withMenuBadges(bytes.toString('utf8')))):bytes;writeSync(assetWriter,JSON.stringify('/'+relative)+':['+JSON.stringify(type)+','+JSON.stringify(payload.toString('base64'))+'],');assetCount++}}}if(existsSync(dist)){const resolved=path.resolve(dist);if(resolved!==path.join(root,'dist'))throw Error('Invalid dist directory');rmSync(resolved,{recursive:true,force:true})} mkdirSync(path.join(dist,'server'),{recursive:true});mkdirSync(path.join(dist,'.openai'),{recursive:true});assetWriter=openSync(path.join(dist,'server/index.js'),'w');writeSync(assetWriter,'const ASSET_DATA={');collect(web);writeSync(assetWriter,'};\n'); diff --git a/website/web/bank-rates.css b/website/web/bank-rates.css new file mode 100644 index 00000000..8623290d --- /dev/null +++ b/website/web/bank-rates.css @@ -0,0 +1 @@ +*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:#091f18;color:#e9eadb;font:16px/1.6 Arial,sans-serif}body>header,footer{padding:22px 5%;border-bottom:1px solid #756337}a{color:#e7cc88}main{max-width:1240px;margin:48px auto;padding:0 28px}.hero{display:flex;gap:48px;align-items:center;padding:54px;border:1px solid #b99a53;border-radius:24px;background:radial-gradient(at top left,#355540,#102e24 70%)}.hero img{width:260px;height:160px;object-fit:contain}.eyebrow{font-size:11px;letter-spacing:.2em;color:#c8af70}h1{font:54px/1.12 Georgia,serif;color:#f2da9d;margin:12px 0}h2{font:32px/1.3 Georgia,serif;color:#f2da9d;margin:10px 0}h3{font-size:18px;color:#ecd79e}.stamp{display:inline-block;border:1px solid #8c8158;border-radius:40px;padding:6px 14px;font-size:11px}.sections{display:flex;gap:12px;margin:24px 0}.sections a,button{border:1px solid #9f874f;border-radius:9px;padding:12px 20px;text-decoration:none;background:#19382c;color:#efdaa3;font-weight:bold}.notice{border-left:4px solid #c5aa64;background:#203c30;border-radius:8px;padding:20px 26px;margin:32px 0}.notice p{margin:5px 0}section[id]{margin:48px 0}.table-wrap{overflow:auto;border:1px solid #55765a;border-radius:14px}table{width:100%;border-collapse:collapse;font-size:14px;text-align:left}thead{background:#294e3d;color:#e2c77d}th,td{padding:17px 20px;border-bottom:1px solid #365342}tbody tr:last-child>*{border:0}tbody th{color:#f2e0b4}tbody tr:nth-child(even){background:#112e23}.fine{font-size:12px;color:#b6c9bc}.service-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.service-grid article{border:1px solid #597659;border-radius:14px;padding:24px;background:#153328}.service-grid strong{font:26px Georgia,serif;color:#abd8c4}.service-grid p{font-size:14px;color:#c2d0c4}.document{display:flex;align-items:center;gap:35px;padding:28px;border:1px solid #9f874f;border-radius:14px}.document p{font-size:13px}.document button{white-space:nowrap;cursor:pointer}footer{display:flex;gap:26px;margin-top:55px}@media print{body{background:white;color:#182d23}body>header,.sections,button,footer{display:none}main{margin:0;max-width:none}.hero{padding:20px}.hero img{width:170px;height:90px}h1{font-size:32px}h1,h2,h3,.fine{color:#263c2c}section[id]{margin:24px 0}th,td{padding:9px}section,article{break-inside:avoid}.service-grid{display:block}.service-grid article,.notice{background:white}.service-grid article{padding:8px}.document{padding:12px}} diff --git a/website/web/portal-navigation.js b/website/web/portal-navigation.js index e0f5033e..d3e90ac8 100644 --- a/website/web/portal-navigation.js +++ b/website/web/portal-navigation.js @@ -61,3 +61,5 @@ /* Public developer API portal link in the shared footer */ (()=>{function sync(){const nav=document.querySelector('.dune-shared-footer nav');if(!nav)return;let a=nav.querySelector('[data-dune-api-footer]');if(!a){a=document.createElement('a');a.dataset.duneApiFooter='1';nav.append(a);}a.href='https://www.dunerealms.com/api.html';a.textContent='Developer API';}sync();new MutationObserver(sync).observe(document.body,{childList:true});})(); + +(()=>{function sync(){const nav=document.querySelector('.dune-shared-footer nav');if(!nav||nav.querySelector('[data-bank-rates]'))return;const a=document.createElement('a');a.dataset.bankRates='1';a.href='https://www.dunerealms.com/rates-and-charges.html';a.textContent='Rates & Charges';nav.append(a);}sync();new MutationObserver(sync).observe(document.body,{childList:true,subtree:true});})(); diff --git a/website/web/rates-and-charges.html b/website/web/rates-and-charges.html new file mode 100644 index 00000000..fb3bd457 --- /dev/null +++ b/website/web/rates-and-charges.html @@ -0,0 +1 @@ +Rates & Charges | Imperial Postbank
DuneRealms
Imperial Postbank

YOUR MONEY. CLEAR TERMS.

Rates & Charges

A clear guide to your banking costs.

PUBLIC TARIFF GUIDE · d290bf6cb0
01 / EVERYDAY BANKING

Accounts & packages

One current account is included in each package.

PackageClientMonthly priceExtra current accounts¹Each / month¹Instant quota / month
Startperson0.00 DM0—0
Flowperson5.00 DM13.00 DM5
Connectclan / company10.00 DM23.00 DM15
Scaleclan / company25.00 DM92.00 DM40
Civichouse / office0.00 DM0—10
Publicstaff0.00 DM0—25

¹ Published additional-account limits and prices, subject to feature availability. Flow includes a savings account. Start has no instant payments. Instant quotas are server usage limits.

02 / BORROWING

Credit rates

Annual rates for new applications. Your accepted contract and repayment schedule govern your loan.

ProductAnnual ratePrincipal rangeAvailable terms
Launch Start0.00%2500.00–2500.00 DMUp to 12 months
Launch Build0.00%5000.00–5000.00 DMUp to 12 months
Launch Advance0.00%10000.00–10000.00 DMUp to 12 months
Personal Loan8.39%1000.00–25000.00 DM3, 6, 9, 12 months
One-Month Advance10.39%250.00–2500.00 DM1 months
Business Loan4.50%5000.00–100000.00 DM3, 6, 12, 18, 24 months
Civic Loan3.50%5000.00–100000.00 DM3, 6, 12 months
Personal Refinancing12.00%0.01–100000.00 DM3, 6, 9, 12, 18, 24 months
Business Refinancing6.50%0.01–500000.00 DM3, 6, 12, 18, 24 months
Civic Refinancing5.50%0.01–500000.00 DM3, 6, 12 months

Launch grants are repayable at 0% interest. Ordinary loans require review and 25% blocked DM collateral. Eligibility, available funding and refinancing conditions apply. Existing fixed-rate contracts retain their agreed rate. Revolving credit is not available.

03 / TRANSPARENCY

Services & taxes

Monthly statements

Free

Automatically archived PDF statements after month-end.

Balance Guard

1.00 DM / month

Published optional price per eligible account. Preference saving is available; protection and charging are not active yet.

Tax policy

Not yet published

VAT and account-tax rates await central configuration. No unconfirmed rate is presented as active.

Your tariff guide

Generated from the bank catalogues on each build. Version d290bf6cb0. Package terms: postbank-foundation-2026-11-13. Credit terms: postbank-credit-2026-11-14.

Catalogue references identify source terms, not a new effective date. Administrative rate editing and automatic downloadable PDF publication are planned. You can print or save this guide as PDF now.

No private account or transaction data is published here.

\ No newline at end of file From ee6e8be908bd7a1578a9c4d13402298de74cb977 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:38:46 +0100 Subject: [PATCH 07/16] Unify shared chrome and add colour-coded V2 workspace publication badges --- website/node/server.mjs | 2 +- website/scripts/bank-rates-page.mjs | 3 +- website/scripts/build-portal-navigation.mjs | 3 +- website/scripts/install-shared-header.mjs | 4 +++ website/scripts/menu-updates.mjs | 2 +- website/scripts/shared-chrome-style.mjs | 1 + website/tests/menu-updates.test.mjs | 2 ++ website/web/menu-new-items.json | 40 +++++++++++++++++++++ website/web/portal-navigation.css | 11 ++++++ website/web/portal-navigation.js | 6 ++-- website/web/rates-and-charges.html | 2 +- 11 files changed, 68 insertions(+), 8 deletions(-) create mode 100644 website/scripts/shared-chrome-style.mjs diff --git a/website/node/server.mjs b/website/node/server.mjs index d547df0d..e1219f7f 100644 --- a/website/node/server.mjs +++ b/website/node/server.mjs @@ -18,7 +18,7 @@ import {initializeCompanyRegistry,listPublicCompanies} from './company-registry. import {initializeShareLedger} from './share-ledger.mjs'; import {createPublicNews} from './news.mjs'; const root=new URL('./public/',import.meta.url); -const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin','Content-Security-Policy':"default-src 'self'; frame-src https://cp.dunerealms.com; img-src 'self' https://cp.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com data:; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self' https://cp.dunerealms.com; base-uri 'self'; object-src 'none'; frame-ancestors 'self'"}; +const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin','Content-Security-Policy':"default-src 'self'; frame-src https://cp.dunerealms.com; img-src 'self' https://www.dunerealms.com https://cp.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com data:; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self' https://cp.dunerealms.com; base-uri 'self'; object-src 'none'; frame-ancestors 'self'"}; export function createApplication(db,settings={}) { const origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin; const auth=createAuth(db,origin); diff --git a/website/scripts/bank-rates-page.mjs b/website/scripts/bank-rates-page.mjs index 7f601540..fcffd8a9 100644 --- a/website/scripts/bank-rates-page.mjs +++ b/website/scripts/bank-rates-page.mjs @@ -1,3 +1,4 @@ +import {SHARED_HEADER} from './portal-navigation.mjs'; import {PACKAGES,BANK_VERSION} from '../node/postbank-catalogue.mjs'; import {CREDIT_PRODUCTS,CREDIT_VERSION} from '../node/postbank-credit-model.mjs'; import {createHash} from 'node:crypto'; @@ -5,5 +6,5 @@ export function bankRatesPage(){ const version=createHash('sha256').update(JSON.stringify([PACKAGES,CREDIT_PRODUCTS])).digest('hex').slice(0,10); const packages=PACKAGES.map(p=>`${p.name}${p.kinds.join(' / ')}${(p.monthly/100).toFixed(2)} DM${p.extra}${p.extra?(p.extraFee/100).toFixed(2)+' DM':'—'}${p.instant}`).join(''); const credit=CREDIT_PRODUCTS.filter(p=>!p.revolving).map(p=>`${p.name}${(p.annualBps/100).toFixed(2)}%${p.min}–${p.max} DM${p.terms?p.terms.join(', '):'Up to '+p.maxMonths} months`).join(''); -return `Rates & Charges | Imperial Postbank
DuneRealms
Imperial Postbank

YOUR MONEY. CLEAR TERMS.

Rates & Charges

A clear guide to your banking costs.

PUBLIC TARIFF GUIDE · ${version}
01 / EVERYDAY BANKING

Accounts & packages

One current account is included in each package.

${packages}
PackageClientMonthly priceExtra current accounts¹Each / month¹Instant quota / month

¹ Published additional-account limits and prices, subject to feature availability. Flow includes a savings account. Start has no instant payments. Instant quotas are server usage limits.

02 / BORROWING

Credit rates

Annual rates for new applications. Your accepted contract and repayment schedule govern your loan.

${credit}
ProductAnnual ratePrincipal rangeAvailable terms

Launch grants are repayable at 0% interest. Ordinary loans require review and 25% blocked DM collateral. Eligibility, available funding and refinancing conditions apply. Existing fixed-rate contracts retain their agreed rate. Revolving credit is not available.

03 / TRANSPARENCY

Services & taxes

Monthly statements

Free

Automatically archived PDF statements after month-end.

Balance Guard

1.00 DM / month

Published optional price per eligible account. Preference saving is available; protection and charging are not active yet.

Tax policy

Not yet published

VAT and account-tax rates await central configuration. No unconfirmed rate is presented as active.

Your tariff guide

Generated from the bank catalogues on each build. Version ${version}. Package terms: ${BANK_VERSION}. Credit terms: ${CREDIT_VERSION}.

Catalogue references identify source terms, not a new effective date. Administrative rate editing and automatic downloadable PDF publication are planned. You can print or save this guide as PDF now.

No private account or transaction data is published here.

`; +return `Rates & Charges | Imperial Postbank${SHARED_HEADER}
Imperial Postbank

YOUR MONEY. CLEAR TERMS.

Rates & Charges

A clear guide to your banking costs.

PUBLIC TARIFF GUIDE · ${version}
01 / EVERYDAY BANKING

Accounts & packages

One current account is included in each package.

${packages}
PackageClientMonthly priceExtra current accounts¹Each / month¹Instant quota / month

¹ Published additional-account limits and prices, subject to feature availability. Flow includes a savings account. Start has no instant payments. Instant quotas are server usage limits.

02 / BORROWING

Credit rates

Annual rates for new applications. Your accepted contract and repayment schedule govern your loan.

${credit}
ProductAnnual ratePrincipal rangeAvailable terms

Launch grants are repayable at 0% interest. Ordinary loans require review and 25% blocked DM collateral. Eligibility, available funding and refinancing conditions apply. Existing fixed-rate contracts retain their agreed rate. Revolving credit is not available.

03 / TRANSPARENCY

Services & taxes

Monthly statements

Free

Automatically archived PDF statements after month-end.

Balance Guard

1.00 DM / month

Published optional price per eligible account. Preference saving is available; protection and charging are not active yet.

Tax policy

Not yet published

VAT and account-tax rates await central configuration. No unconfirmed rate is presented as active.

Your tariff guide

Generated from the bank catalogues on each build. Version ${version}. Package terms: ${BANK_VERSION}. Credit terms: ${CREDIT_VERSION}.

Catalogue references identify source terms, not a new effective date. Administrative rate editing and automatic downloadable PDF publication are planned. You can print or save this guide as PDF now.

No private account or transaction data is published here.

`; } diff --git a/website/scripts/build-portal-navigation.mjs b/website/scripts/build-portal-navigation.mjs index 6b0f1308..60eedec0 100644 --- a/website/scripts/build-portal-navigation.mjs +++ b/website/scripts/build-portal-navigation.mjs @@ -1,3 +1,4 @@ +import {SHARED_CHROME_STYLE} from './shared-chrome-style.mjs'; import{CANONICAL_MENU_SCRIPT}from'./main-menu.mjs'; import{recordPageUpdates,menuBadgeScript}from'./menu-updates.mjs'; import {RELEASE_SCRIPT,RELEASE_CSS} from './release-branding.mjs'; @@ -5,7 +6,7 @@ import {BUTTON_CSS,BUTTON_SCRIPT} from './dune-buttons.mjs'; import {readFileSync,writeFileSync,readdirSync} from 'node:fs'; import {updatePortalNavigation,PORTAL_CSS,PORTAL_SCRIPT,CONTEXT_SCRIPT,CONTEXT_CSS} from './portal-navigation.mjs'; const web=new URL('../web/',import.meta.url); -writeFileSync(new URL('portal-navigation.css',web),PORTAL_CSS+CONTEXT_CSS+BUTTON_CSS+RELEASE_CSS); +writeFileSync(new URL('portal-navigation.css',web),PORTAL_CSS+CONTEXT_CSS+BUTTON_CSS+RELEASE_CSS+SHARED_CHROME_STYLE); recordPageUpdates(); writeFileSync(new URL('portal-navigation.js',web),PORTAL_SCRIPT+CONTEXT_SCRIPT+BUTTON_SCRIPT+RELEASE_SCRIPT+menuBadgeScript()+CANONICAL_MENU_SCRIPT); writeFileSync(new URL('dune-actions.css',web),BUTTON_CSS); diff --git a/website/scripts/install-shared-header.mjs b/website/scripts/install-shared-header.mjs index e7f79f40..299e3d3e 100644 --- a/website/scripts/install-shared-header.mjs +++ b/website/scripts/install-shared-header.mjs @@ -27,3 +27,7 @@ console.log('Shared header installed in CP and native integration templates'); // The Clan center serves local copies to retain the same masthead styles. const clans='/home/dunerealms/htdocs/clans.dunerealms.com'; if(existsSync(clans+'/index.html')){writeFileSync(clans+'/dune-navigation.css',PORTAL_CSS+CONTEXT_CSS+BUTTON_CSS+RELEASE_CSS);writeFileSync(clans+'/dune-navigation.js',PORTAL_SCRIPT+CONTEXT_SCRIPT+BUTTON_SCRIPT+RELEASE_SCRIPT);} + +// Persistent shared nginx aliases read these exact files on every site. +const chrome='/var/lib/dunerealms-public-rates'; +if(existsSync(chrome)){for(const file of ['portal-navigation.js','portal-navigation.css','menu-new-items.json'])copyFileSync(release+'/web/'+file,chrome+'/'+file);} diff --git a/website/scripts/menu-updates.mjs b/website/scripts/menu-updates.mjs index b7eb626e..f4afbd8d 100644 --- a/website/scripts/menu-updates.mjs +++ b/website/scripts/menu-updates.mjs @@ -1,7 +1,7 @@ import{readFileSync,writeFileSync}from'node:fs';import{execFileSync}from'node:child_process';import{fileURLToPath}from'node:url';import path from'node:path';import{RELEASE_VERSION}from'./release-branding.mjs'; export function pagesForChanges(paths){const pages=new Set();for(let p of paths){p=p.replaceAll('\\','/');if(/website\/node\/staff-roster\.mjs$/.test(p))pages.add('https://www.dunerealms.com/staff.html');if(/website\/node\/memorials\.mjs$|website\/node\/public\/memorial\./.test(p))pages.add('https://www.dunerealms.com/');if(/website\/control-panel\//.test(p)||/website\/node\/(auth|permissions|account-admin|account-archive|honours|profile)\.mjs$/.test(p))pages.add('https://cp.dunerealms.com/');if(/website\/integrations\/azuriom\//.test(p))pages.add('https://www.dunerealms.com/shop.html');if(/website\/integrations\/osticket\//.test(p))pages.add('https://support.dunerealms.com/');if(/website\/web\/([a-z-]+)\.html$/.test(p)){const name=p.match(/([^/]+)\.html$/)[1];pages.add('https://www.dunerealms.com/'+(['index','portal'].includes(name)?'':name+'.html'));}}return[...pages].sort();} export function recordPageUpdates({root=fileURLToPath(new URL('../',import.meta.url)),paths,version=RELEASE_VERSION}={}){if(!/^\d+(?:\.\d+){3}$/.test(version))throw Error('Invalid release');const repo=path.resolve(root,'..');if(paths===undefined){let changed='';try{const gitRoot=execFileSync('git',['rev-parse','--show-toplevel'],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();if(path.resolve(gitRoot)===repo)changed=execFileSync('git',['diff','--name-only','HEAD'],{cwd:repo,encoding:'utf8'}).trim();}catch(error){if(error?.status!==128&&error?.status!==129&&error?.code!=='ENOENT')throw error;}paths=changed?changed.split('\n'):[];}const file=path.join(root,'web/menu-new-items.json'),data=JSON.parse(readFileSync(file,'utf8'));const pages=pagesForChanges(paths);for(const href of pages){let entry=data.items.find(x=>x.href===href);if(!entry){entry={href};data.items.push(entry);}entry.updatedIn=version;entry.badge=entry.introducedIn===version?'NEW':'UPDATE';}writeFileSync(file,JSON.stringify(data,null,2)+'\n');return pages;} -export function menuBadgeScript(){const data=JSON.parse(readFileSync(new URL('../web/menu-new-items.json',import.meta.url),'utf8'));return `\n/* Central automatic release menu badges */\n(()=>{let items=${JSON.stringify(data.items)};function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\\d+(?:\\.\\d+){3}/)?.[0];if(!release)return;for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a')){const item=items.find(x=>x.href===a.href),label=item?.introducedIn===release?'NEW':item?.updatedIn===release?'UPDATE':null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://www.dunerealms.com/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})();\n`;} +export function menuBadgeScript(){const data=JSON.parse(readFileSync(new URL('../web/menu-new-items.json',import.meta.url),'utf8'));return `\n/* Central automatic release menu badges */\n(()=>{let items=${JSON.stringify(data.items)};function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\\d+(?:\\.\\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:item?.introducedIn===release?'NEW':item?.updatedIn===release?'UPDATE':null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://www.dunerealms.com/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})();\n`;} export function withMenuBadges(s){return s.replace(/\n?\/\* Central automatic release menu badges \*\/[\s\S]*?(?=\n\/\*|$)/,'').replace(/\(\(\)=>\{const items=\[[\s\S]*?new MutationObserver\(mark\)\.observe\(document.body,\{childList:true,subtree:true,characterData:true\}\);\}\)\(\);/,'')+menuBadgeScript();} export function patchMenuBadges(root=fileURLToPath(new URL('../',import.meta.url))){const file=path.join(root,'web/portal-navigation.js');writeFileSync(file,withMenuBadges(readFileSync(file,'utf8')));} if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){const pages=recordPageUpdates();patchMenuBadges();console.log('Central release badges updated for '+pages.length+' changed pages.');} diff --git a/website/scripts/shared-chrome-style.mjs b/website/scripts/shared-chrome-style.mjs new file mode 100644 index 00000000..e6b6a97c --- /dev/null +++ b/website/scripts/shared-chrome-style.mjs @@ -0,0 +1 @@ +export const SHARED_CHROME_STYLE="\n/* Shared chrome must not inherit native forum/support link decorations. */\nheader.dune-site-header nav[aria-label=\"Main navigation\"] a,header.dune-site-header .wordmark,.dune-shared-footer a{text-decoration:none!important}header.dune-site-header nav[aria-label=\"Main navigation\"] a{font-family:Arial,sans-serif!important;line-height:1.35!important}.dune-shared-footer{font-family:Arial,sans-serif!important}.dune-shared-footer a:hover{text-decoration:underline!important}\n\n#portals .portal{position:relative}#portals .portal>.dune-new-overlay{position:absolute;top:9px;right:10px;padding:3px 8px;border:1px solid #c7a65c;border-radius:12px;background:#bba05c;color:#10251f;font:700 10px/1.2 Arial,sans-serif;letter-spacing:.06em}#portals .portal>.dune-update-overlay{background:#1b4d43;color:#bfe4d3;border-color:#6ba58e}\n\n/* One V2 banking-style surface, seven recognisable workspace accents. */\n#portals .portal{--workspace-accent:#d2b66d;isolation:isolate;overflow:hidden;background:linear-gradient(145deg,color-mix(in srgb,var(--workspace-accent) 15%,#142e24),#10251f)!important;border-color:color-mix(in srgb,var(--workspace-accent) 70%,#475841)!important;box-shadow:inset 0 1px 0 #ffffff0b,0 4px 12px #0002}\n#portals .portal::before{content:'';position:absolute;inset:0;z-index:-1;background:radial-gradient(ellipse at 85% 0%,color-mix(in srgb,var(--workspace-accent) 17%,transparent),transparent 65%);pointer-events:none}\n#portals .portal[data-id=\"realm\"]{--workspace-accent:#8dcbb1}#portals .portal[data-id=\"bureau\"]{--workspace-accent:#cbb680}#portals .portal[data-id=\"forge\"]{--workspace-accent:#a9a1d6}#portals .portal[data-id=\"politics\"]{--workspace-accent:#d0a56b}#portals .portal[data-id=\"post\"]{--workspace-accent:#86bacd}#portals .portal[data-id=\"bank\"]{--workspace-accent:#e1c66c}#portals .portal[data-id=\"market\"]{--workspace-accent:#cb9b7d}\n#portals .portal>span:not(.dune-new-overlay){color:var(--workspace-accent)}#portals .portal.active,#portals .portal[aria-current=\"page\"]{outline:2px solid var(--workspace-accent);outline-offset:-2px}#portals .portal:focus-visible{outline:3px solid #fff1c1;outline-offset:3px}\n"; diff --git a/website/tests/menu-updates.test.mjs b/website/tests/menu-updates.test.mjs index bb916f56..1f85e0de 100644 --- a/website/tests/menu-updates.test.mjs +++ b/website/tests/menu-updates.test.mjs @@ -21,3 +21,5 @@ test('Explicit changed paths still update menu badges without Git metadata',()=> const data=JSON.parse(readFileSync(manifest,'utf8'));assert.equal(data.items[0].updatedIn,'1.0.0.4'); }finally{rmSync(repo,{recursive:true,force:true});} }); + +test('V2 workspace tiles use the shared manifest even with the simple Alpha header',()=>{const s=menuBadgeScript();assert(s.includes('#portals .portal[data-id]'));assert(s.includes("'https://cp.dunerealms.com/#'+a.dataset.id"));assert(!s.includes('if(!release)return'));new Function(s);}); diff --git a/website/web/menu-new-items.json b/website/web/menu-new-items.json index 1b58d32a..b39b0c31 100644 --- a/website/web/menu-new-items.json +++ b/website/web/menu-new-items.json @@ -56,6 +56,46 @@ "href": "https://cp.dunerealms.com/#kits-exchange", "introducedIn": "1.0.0.5", "badge": "NEW" + }, + { + "href": "https://cp.dunerealms.com/#realm", + "badge": "NEW", + "introducedIn": "v2-api" + }, + { + "href": "https://cp.dunerealms.com/#bureau", + "badge": "NEW", + "introducedIn": "v2-api" + }, + { + "href": "https://cp.dunerealms.com/#forge", + "badge": "NEW", + "introducedIn": "v2-api" + }, + { + "href": "https://cp.dunerealms.com/#politics", + "badge": "NEW", + "introducedIn": "v2-api" + }, + { + "href": "https://cp.dunerealms.com/#post", + "badge": "NEW", + "introducedIn": "v2-api" + }, + { + "href": "https://cp.dunerealms.com/#bank", + "badge": "NEW", + "introducedIn": "v2-api" + }, + { + "href": "https://cp.dunerealms.com/#market", + "badge": "NEW", + "introducedIn": "v2-api" + }, + { + "href": "https://www.dunerealms.com/rates-and-charges.html", + "updatedIn": "1.0.1.0", + "badge": "UPDATE" } ] } diff --git a/website/web/portal-navigation.css b/website/web/portal-navigation.css index 2fe745c9..8eef22e2 100644 --- a/website/web/portal-navigation.css +++ b/website/web/portal-navigation.css @@ -116,3 +116,14 @@ header.dune-site-header .dune-memorial .dune-memorial-dedication blockquote{back /* Native applications must use the same link spacing as the public header. */ header.dune-site-header>nav[aria-label="Main navigation"]>a{display:inline-flex!important;align-items:center!important;gap:8px!important}@media(min-width:1241px){header.dune-site-header>button.menu-toggle{display:none!important}} + +/* Shared chrome must not inherit native forum/support link decorations. */ +header.dune-site-header nav[aria-label="Main navigation"] a,header.dune-site-header .wordmark,.dune-shared-footer a{text-decoration:none!important}header.dune-site-header nav[aria-label="Main navigation"] a{font-family:Arial,sans-serif!important;line-height:1.35!important}.dune-shared-footer{font-family:Arial,sans-serif!important}.dune-shared-footer a:hover{text-decoration:underline!important} + +#portals .portal{position:relative}#portals .portal>.dune-new-overlay{position:absolute;top:9px;right:10px;padding:3px 8px;border:1px solid #c7a65c;border-radius:12px;background:#bba05c;color:#10251f;font:700 10px/1.2 Arial,sans-serif;letter-spacing:.06em}#portals .portal>.dune-update-overlay{background:#1b4d43;color:#bfe4d3;border-color:#6ba58e} + +/* One V2 banking-style surface, seven recognisable workspace accents. */ +#portals .portal{--workspace-accent:#d2b66d;isolation:isolate;overflow:hidden;background:linear-gradient(145deg,color-mix(in srgb,var(--workspace-accent) 15%,#142e24),#10251f)!important;border-color:color-mix(in srgb,var(--workspace-accent) 70%,#475841)!important;box-shadow:inset 0 1px 0 #ffffff0b,0 4px 12px #0002} +#portals .portal::before{content:'';position:absolute;inset:0;z-index:-1;background:radial-gradient(ellipse at 85% 0%,color-mix(in srgb,var(--workspace-accent) 17%,transparent),transparent 65%);pointer-events:none} +#portals .portal[data-id="realm"]{--workspace-accent:#8dcbb1}#portals .portal[data-id="bureau"]{--workspace-accent:#cbb680}#portals .portal[data-id="forge"]{--workspace-accent:#a9a1d6}#portals .portal[data-id="politics"]{--workspace-accent:#d0a56b}#portals .portal[data-id="post"]{--workspace-accent:#86bacd}#portals .portal[data-id="bank"]{--workspace-accent:#e1c66c}#portals .portal[data-id="market"]{--workspace-accent:#cb9b7d} +#portals .portal>span:not(.dune-new-overlay){color:var(--workspace-accent)}#portals .portal.active,#portals .portal[aria-current="page"]{outline:2px solid var(--workspace-accent);outline-offset:-2px}#portals .portal:focus-visible{outline:3px solid #fff1c1;outline-offset:3px} diff --git a/website/web/portal-navigation.js b/website/web/portal-navigation.js index d3e90ac8..97b57d3e 100644 --- a/website/web/portal-navigation.js +++ b/website/web/portal-navigation.js @@ -48,9 +48,6 @@ /* DuneGit repository footer link */ (()=>{function link(){const foot=document.querySelector('.dune-shared-footer');if(!foot)return;const nav=foot.querySelector('nav');if(!nav)return;let a=nav.querySelector('[data-dune-git-footer]');if(!a){a=document.createElement('a');a.dataset.duneGitFooter='1';nav.append(a);}a.href='https://www.dunerealms.com/git/unimatrix/MC';a.textContent='DuneGit';}link();new MutationObserver(link).observe(document.body,{childList:true});addEventListener('hashchange',link);})(); -/* Central automatic release menu badges */ -(()=>{let items=[{"href":"https://cp.dunerealms.com/#shop","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://wiki.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://clans.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://cp.dunerealms.com/","badge":"NEW","introducedIn":"1.0.0.3"},{"href":"https://cp.dunerealms.com/#exchange","updatedIn":"1.0.0.2","badge":"UPDATE"},{"href":"https://support.dunerealms.com/","updatedIn":"1.0.0.3","badge":"UPDATE"},{"href":"https://www.dunerealms.com/staff.html","updatedIn":"1.0.0.3","badge":"UPDATE"},{"href":"https://www.dunerealms.com/","badge":"NEW","introducedIn":"1.0.0.3","updatedIn":"1.0.0.3"},{"href":"https://www.dunerealms.com/shop.html","updatedIn":"1.0.0.3","badge":"UPDATE"}];function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\d+(?:\.\d+){3}/)?.[0];if(!release)return;for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a')){const item=items.find(x=>x.href===a.href),label=item?.introducedIn===release?'NEW':item?.updatedIn===release?'UPDATE':null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://www.dunerealms.com/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})(); - /* Dune canonical menu begin */ (()=>{if(window.top!==window.self)return;const MAIN_MENU=[["Home","https://www.dunerealms.com/","nav-home-v2.webp"],["Shop","https://www.dunerealms.com/shop.html","nav-exchange-full-v2.webp"],["Boards","https://forums.dunerealms.com/","nav-boards-v2.webp"],["Staff roster","https://www.dunerealms.com/staff.html","nav-staff-v2.webp"],["Discord","https://www.dunerealms.com/discord.html","nav-discord-v2.webp"],["Exchange","https://www.dunerealms.com/exchange.html","nav-exchange-v2.webp"],["Kit Exchange","https://www.dunerealms.com/kits.html","items/office_water.png"],["Support center","https://support.dunerealms.com/","nav-support-v2.webp"],["Account center","https://cp.dunerealms.com/","nav-account-v2.webp"],["Clan center","https://clans.dunerealms.com/","nav-clan-v2.webp"],["Dunopedia","https://wiki.dunerealms.com/","nav-manual-v2.webp"]];const canonicalMenuHref=function canonicalMenuHref(value){const u=new URL(value,'https://www.dunerealms.com');if(u.hostname==='dunerealms.com')u.hostname='www.dunerealms.com';if(u.hostname==='www.dunerealms.com'&&/^\/(manual|wiki)\.html$/.test(u.pathname))return'https://wiki.dunerealms.com/';if(u.hostname==='cp.dunerealms.com'&&u.pathname==='/'){if(u.hash==='#shop')return'https://www.dunerealms.com/shop.html';if(u.hash==='#exchange')return'https://www.dunerealms.com/exchange.html';}if(['forums','support','cp','clans','wiki'].some(h=>u.hostname===h+'.dunerealms.com'))return u.origin+'/';return u.origin+(u.pathname==='/index.html'?'/':u.pathname);};const normalizeMainMenus=function normalizeMainMenus(doc,currentUrl,links=MAIN_MENU){let changes=0;const set=(node,key,value)=>{if(node.getAttribute(key)!==value){node.setAttribute(key,value);changes++;}}; for(const nav of doc.querySelectorAll('header nav[aria-label="Main navigation"]')){const old=[...nav.querySelectorAll('a')],ordered=[];for(const[name,href,icon]of links){let a=old.find(x=>!ordered.includes(x)&&canonicalMenuHref(x.href)===href);if(!a){a=doc.createElement('a');changes++;}set(a,'href',href);let image=a.querySelector('img');if(!image){image=doc.createElement('img');a.insertBefore(image,a.firstChild);changes++;}set(image,'src','https://www.dunerealms.com/assets/'+icon);set(image,'alt','');set(image,'width','34');set(image,'height','34');let label=[...a.children].find(x=>x.tagName==='SPAN'&&!x.classList.contains('dune-new-overlay')&&!x.classList.contains('dune-sales-overlay'));if(!label){label=doc.createElement('span');a.append(label);changes++;}set(label,'data-dune-nav-label','1');if(label.textContent!==name){label.textContent=name;changes++;}for(const n of [...a.childNodes])if(n.nodeType===3){n.remove();changes++;}const active=canonicalMenuHref(currentUrl)===href;if(active)set(a,'aria-current','page');else if(a.hasAttribute('aria-current')){a.removeAttribute('aria-current');changes++;}ordered.push(a);} @@ -63,3 +60,6 @@ (()=>{function sync(){const nav=document.querySelector('.dune-shared-footer nav');if(!nav)return;let a=nav.querySelector('[data-dune-api-footer]');if(!a){a=document.createElement('a');a.dataset.duneApiFooter='1';nav.append(a);}a.href='https://www.dunerealms.com/api.html';a.textContent='Developer API';}sync();new MutationObserver(sync).observe(document.body,{childList:true});})(); (()=>{function sync(){const nav=document.querySelector('.dune-shared-footer nav');if(!nav||nav.querySelector('[data-bank-rates]'))return;const a=document.createElement('a');a.dataset.bankRates='1';a.href='https://www.dunerealms.com/rates-and-charges.html';a.textContent='Rates & Charges';nav.append(a);}sync();new MutationObserver(sync).observe(document.body,{childList:true,subtree:true});})(); + +/* Central automatic release menu badges */ +(()=>{let items=[{"href":"https://cp.dunerealms.com/#shop","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://wiki.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://clans.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://cp.dunerealms.com/","badge":"NEW","updatedIn":"1.0.1.0","introducedIn":"1.0.1.0"},{"href":"https://cp.dunerealms.com/#exchange","updatedIn":"1.0.0.2","badge":"UPDATE"},{"href":"https://support.dunerealms.com/","updatedIn":"1.0.0.3","badge":"UPDATE"},{"href":"https://www.dunerealms.com/staff.html","updatedIn":"1.0.0.5","badge":"UPDATE"},{"href":"https://www.dunerealms.com/","badge":"NEW","introducedIn":"1.0.0.3","updatedIn":"1.0.0.3"},{"href":"https://www.dunerealms.com/shop.html","updatedIn":"1.0.0.5","badge":"UPDATE"},{"href":"https://www.dunerealms.com/kits.html","introducedIn":"1.0.0.5","badge":"NEW"},{"href":"https://cp.dunerealms.com/#kits-exchange","introducedIn":"1.0.0.5","badge":"NEW"},{"href":"https://cp.dunerealms.com/#realm","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#bureau","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#forge","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#politics","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#post","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#bank","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#market","badge":"NEW","introducedIn":"v2-api"},{"href":"https://www.dunerealms.com/rates-and-charges.html","updatedIn":"1.0.1.0","badge":"UPDATE"}];function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\d+(?:\.\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:item?.introducedIn===release?'NEW':item?.updatedIn===release?'UPDATE':null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://www.dunerealms.com/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})(); diff --git a/website/web/rates-and-charges.html b/website/web/rates-and-charges.html index fb3bd457..371cd788 100644 --- a/website/web/rates-and-charges.html +++ b/website/web/rates-and-charges.html @@ -1 +1 @@ -Rates & Charges | Imperial Postbank
DuneRealms
Imperial Postbank

YOUR MONEY. CLEAR TERMS.

Rates & Charges

A clear guide to your banking costs.

PUBLIC TARIFF GUIDE · d290bf6cb0
01 / EVERYDAY BANKING

Accounts & packages

One current account is included in each package.

PackageClientMonthly priceExtra current accounts¹Each / month¹Instant quota / month
Startperson0.00 DM0—0
Flowperson5.00 DM13.00 DM5
Connectclan / company10.00 DM23.00 DM15
Scaleclan / company25.00 DM92.00 DM40
Civichouse / office0.00 DM0—10
Publicstaff0.00 DM0—25

¹ Published additional-account limits and prices, subject to feature availability. Flow includes a savings account. Start has no instant payments. Instant quotas are server usage limits.

02 / BORROWING

Credit rates

Annual rates for new applications. Your accepted contract and repayment schedule govern your loan.

ProductAnnual ratePrincipal rangeAvailable terms
Launch Start0.00%2500.00–2500.00 DMUp to 12 months
Launch Build0.00%5000.00–5000.00 DMUp to 12 months
Launch Advance0.00%10000.00–10000.00 DMUp to 12 months
Personal Loan8.39%1000.00–25000.00 DM3, 6, 9, 12 months
One-Month Advance10.39%250.00–2500.00 DM1 months
Business Loan4.50%5000.00–100000.00 DM3, 6, 12, 18, 24 months
Civic Loan3.50%5000.00–100000.00 DM3, 6, 12 months
Personal Refinancing12.00%0.01–100000.00 DM3, 6, 9, 12, 18, 24 months
Business Refinancing6.50%0.01–500000.00 DM3, 6, 12, 18, 24 months
Civic Refinancing5.50%0.01–500000.00 DM3, 6, 12 months

Launch grants are repayable at 0% interest. Ordinary loans require review and 25% blocked DM collateral. Eligibility, available funding and refinancing conditions apply. Existing fixed-rate contracts retain their agreed rate. Revolving credit is not available.

03 / TRANSPARENCY

Services & taxes

Monthly statements

Free

Automatically archived PDF statements after month-end.

Balance Guard

1.00 DM / month

Published optional price per eligible account. Preference saving is available; protection and charging are not active yet.

Tax policy

Not yet published

VAT and account-tax rates await central configuration. No unconfirmed rate is presented as active.

Your tariff guide

Generated from the bank catalogues on each build. Version d290bf6cb0. Package terms: postbank-foundation-2026-11-13. Credit terms: postbank-credit-2026-11-14.

Catalogue references identify source terms, not a new effective date. Administrative rate editing and automatic downloadable PDF publication are planned. You can print or save this guide as PDF now.

No private account or transaction data is published here.

\ No newline at end of file +Rates & Charges | Imperial Postbank
Imperial Postbank

YOUR MONEY. CLEAR TERMS.

Rates & Charges

A clear guide to your banking costs.

PUBLIC TARIFF GUIDE · d290bf6cb0
01 / EVERYDAY BANKING

Accounts & packages

One current account is included in each package.

PackageClientMonthly priceExtra current accounts¹Each / month¹Instant quota / month
Startperson0.00 DM0—0
Flowperson5.00 DM13.00 DM5
Connectclan / company10.00 DM23.00 DM15
Scaleclan / company25.00 DM92.00 DM40
Civichouse / office0.00 DM0—10
Publicstaff0.00 DM0—25

¹ Published additional-account limits and prices, subject to feature availability. Flow includes a savings account. Start has no instant payments. Instant quotas are server usage limits.

02 / BORROWING

Credit rates

Annual rates for new applications. Your accepted contract and repayment schedule govern your loan.

ProductAnnual ratePrincipal rangeAvailable terms
Launch Start0.00%2500.00–2500.00 DMUp to 12 months
Launch Build0.00%5000.00–5000.00 DMUp to 12 months
Launch Advance0.00%10000.00–10000.00 DMUp to 12 months
Personal Loan8.39%1000.00–25000.00 DM3, 6, 9, 12 months
One-Month Advance10.39%250.00–2500.00 DM1 months
Business Loan4.50%5000.00–100000.00 DM3, 6, 12, 18, 24 months
Civic Loan3.50%5000.00–100000.00 DM3, 6, 12 months
Personal Refinancing12.00%0.01–100000.00 DM3, 6, 9, 12, 18, 24 months
Business Refinancing6.50%0.01–500000.00 DM3, 6, 12, 18, 24 months
Civic Refinancing5.50%0.01–500000.00 DM3, 6, 12 months

Launch grants are repayable at 0% interest. Ordinary loans require review and 25% blocked DM collateral. Eligibility, available funding and refinancing conditions apply. Existing fixed-rate contracts retain their agreed rate. Revolving credit is not available.

03 / TRANSPARENCY

Services & taxes

Monthly statements

Free

Automatically archived PDF statements after month-end.

Balance Guard

1.00 DM / month

Published optional price per eligible account. Preference saving is available; protection and charging are not active yet.

Tax policy

Not yet published

VAT and account-tax rates await central configuration. No unconfirmed rate is presented as active.

Your tariff guide

Generated from the bank catalogues on each build. Version d290bf6cb0. Package terms: postbank-foundation-2026-11-13. Credit terms: postbank-credit-2026-11-14.

Catalogue references identify source terms, not a new effective date. Administrative rate editing and automatic downloadable PDF publication are planned. You can print or save this guide as PDF now.

No private account or transaction data is published here.

\ No newline at end of file From 1e38bb31aeb057b48b0b48cd3ae0942a2106944f Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:39:45 +0100 Subject: [PATCH 08/16] Expire unchanged publication badges instead of keeping NEW for a whole release --- website/scripts/menu-updates.mjs | 4 ++-- website/tests/menu-updates.test.mjs | 4 +++- website/web/portal-navigation.js | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/website/scripts/menu-updates.mjs b/website/scripts/menu-updates.mjs index f4afbd8d..e3cfd1a2 100644 --- a/website/scripts/menu-updates.mjs +++ b/website/scripts/menu-updates.mjs @@ -1,7 +1,7 @@ import{readFileSync,writeFileSync}from'node:fs';import{execFileSync}from'node:child_process';import{fileURLToPath}from'node:url';import path from'node:path';import{RELEASE_VERSION}from'./release-branding.mjs'; export function pagesForChanges(paths){const pages=new Set();for(let p of paths){p=p.replaceAll('\\','/');if(/website\/node\/staff-roster\.mjs$/.test(p))pages.add('https://www.dunerealms.com/staff.html');if(/website\/node\/memorials\.mjs$|website\/node\/public\/memorial\./.test(p))pages.add('https://www.dunerealms.com/');if(/website\/control-panel\//.test(p)||/website\/node\/(auth|permissions|account-admin|account-archive|honours|profile)\.mjs$/.test(p))pages.add('https://cp.dunerealms.com/');if(/website\/integrations\/azuriom\//.test(p))pages.add('https://www.dunerealms.com/shop.html');if(/website\/integrations\/osticket\//.test(p))pages.add('https://support.dunerealms.com/');if(/website\/web\/([a-z-]+)\.html$/.test(p)){const name=p.match(/([^/]+)\.html$/)[1];pages.add('https://www.dunerealms.com/'+(['index','portal'].includes(name)?'':name+'.html'));}}return[...pages].sort();} -export function recordPageUpdates({root=fileURLToPath(new URL('../',import.meta.url)),paths,version=RELEASE_VERSION}={}){if(!/^\d+(?:\.\d+){3}$/.test(version))throw Error('Invalid release');const repo=path.resolve(root,'..');if(paths===undefined){let changed='';try{const gitRoot=execFileSync('git',['rev-parse','--show-toplevel'],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();if(path.resolve(gitRoot)===repo)changed=execFileSync('git',['diff','--name-only','HEAD'],{cwd:repo,encoding:'utf8'}).trim();}catch(error){if(error?.status!==128&&error?.status!==129&&error?.code!=='ENOENT')throw error;}paths=changed?changed.split('\n'):[];}const file=path.join(root,'web/menu-new-items.json'),data=JSON.parse(readFileSync(file,'utf8'));const pages=pagesForChanges(paths);for(const href of pages){let entry=data.items.find(x=>x.href===href);if(!entry){entry={href};data.items.push(entry);}entry.updatedIn=version;entry.badge=entry.introducedIn===version?'NEW':'UPDATE';}writeFileSync(file,JSON.stringify(data,null,2)+'\n');return pages;} -export function menuBadgeScript(){const data=JSON.parse(readFileSync(new URL('../web/menu-new-items.json',import.meta.url),'utf8'));return `\n/* Central automatic release menu badges */\n(()=>{let items=${JSON.stringify(data.items)};function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\\d+(?:\\.\\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:item?.introducedIn===release?'NEW':item?.updatedIn===release?'UPDATE':null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://www.dunerealms.com/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})();\n`;} +export function recordPageUpdates({root=fileURLToPath(new URL('../',import.meta.url)),paths,newPages=[],version=RELEASE_VERSION}={}){if(!/^\d+(?:\.\d+){3}$/.test(version))throw Error('Invalid release');const repo=path.resolve(root,'..');if(paths===undefined){let changed='';try{const gitRoot=execFileSync('git',['rev-parse','--show-toplevel'],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();if(path.resolve(gitRoot)===repo)changed=execFileSync('git',['diff','--name-only','HEAD'],{cwd:repo,encoding:'utf8'}).trim();}catch(error){if(error?.status!==128&&error?.status!==129&&error?.code!=='ENOENT')throw error;}paths=changed?changed.split('\n'):[];}const file=path.join(root,'web/menu-new-items.json'),data=JSON.parse(readFileSync(file,'utf8'));const pages=pagesForChanges(paths);if(paths.length){for(const item of data.items)delete item.badge;}for(const href of pages){let entry=data.items.find(x=>x.href===href);if(!entry){entry={href};data.items.push(entry);}entry.updatedIn=version;entry.badge=newPages.includes(href)?'NEW':'UPDATE';}writeFileSync(file,JSON.stringify(data,null,2)+'\n');return pages;} +export function menuBadgeScript(){const data=JSON.parse(readFileSync(new URL('../web/menu-new-items.json',import.meta.url),'utf8'));return `\n/* Central automatic release menu badges */\n(()=>{let items=${JSON.stringify(data.items)};function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\\d+(?:\\.\\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://www.dunerealms.com/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})();\n`;} export function withMenuBadges(s){return s.replace(/\n?\/\* Central automatic release menu badges \*\/[\s\S]*?(?=\n\/\*|$)/,'').replace(/\(\(\)=>\{const items=\[[\s\S]*?new MutationObserver\(mark\)\.observe\(document.body,\{childList:true,subtree:true,characterData:true\}\);\}\)\(\);/,'')+menuBadgeScript();} export function patchMenuBadges(root=fileURLToPath(new URL('../',import.meta.url))){const file=path.join(root,'web/portal-navigation.js');writeFileSync(file,withMenuBadges(readFileSync(file,'utf8')));} if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){const pages=recordPageUpdates();patchMenuBadges();console.log('Central release badges updated for '+pages.length+' changed pages.');} diff --git a/website/tests/menu-updates.test.mjs b/website/tests/menu-updates.test.mjs index 1f85e0de..a90f1912 100644 --- a/website/tests/menu-updates.test.mjs +++ b/website/tests/menu-updates.test.mjs @@ -1,6 +1,6 @@ import test from'node:test';import assert from'node:assert/strict';import{mkdtempSync,mkdirSync,writeFileSync,readFileSync,rmSync}from'node:fs';import{tmpdir}from'node:os';import path from'node:path';import{pagesForChanges,menuBadgeScript,recordPageUpdates}from'../scripts/menu-updates.mjs'; test('Release badge mapping follows deployed page scopes and ignores tests and unrelated game changes',()=>{assert.deepEqual(pagesForChanges(['website/node/staff-roster.mjs','website/node/staff-roster.mjs']),['https://www.dunerealms.com/staff.html']);assert.deepEqual(pagesForChanges(['website/tests/staff-roster.test.mjs','DuneCore/src/Main.java']),[]);assert.deepEqual(pagesForChanges(['website/node/memorials.mjs','website/control-panel/public/panel.js']),['https://cp.dunerealms.com/','https://www.dunerealms.com/']);assert(pagesForChanges(['website/integrations/azuriom/DuneShopRanks.php']).includes('https://www.dunerealms.com/shop.html'));}); -test('Shared badge script reads the one central manifest and changes labels only when needed',()=>{const s=menuBadgeScript();assert(s.includes('/menu-new-items.json'));assert(s.includes("cache:'no-store'"));assert(s.includes("if(tag.textContent!==label)"));assert(s.includes('updatedIn===release'));assert(s.includes('https://www.dunerealms.com/staff.html'));new Function(s);}); +test('Shared badge script reads the one central manifest and changes labels only when needed',()=>{const s=menuBadgeScript();assert(s.includes('/menu-new-items.json'));assert(s.includes("cache:'no-store'"));assert(s.includes("if(tag.textContent!==label)"));assert(s.includes("includes(item?.badge)"));assert(s.includes('https://www.dunerealms.com/staff.html'));new Function(s);}); test('Immutable CI artifact without .git builds release badge manifest without crashing',()=>{ const repo=mkdtempSync(path.join(tmpdir(),'dune-gitless-build-')); @@ -23,3 +23,5 @@ test('Explicit changed paths still update menu badges without Git metadata',()=> }); test('V2 workspace tiles use the shared manifest even with the simple Alpha header',()=>{const s=menuBadgeScript();assert(s.includes('#portals .portal[data-id]'));assert(s.includes("'https://cp.dunerealms.com/#'+a.dataset.id"));assert(!s.includes('if(!release)return'));new Function(s);}); + +test('New publication clears untouched badges and distinguishes a new page from an update',()=>{const repo=mkdtempSync(path.join(tmpdir(),'dune-badge-expiry-'));try{const root=path.join(repo,'website');mkdirSync(path.join(root,'web'),{recursive:true});const file=path.join(root,'web/menu-new-items.json');writeFileSync(file,JSON.stringify({items:[{href:'https://clans.dunerealms.com/',badge:'NEW'},{href:'https://www.dunerealms.com/staff.html',badge:'NEW',introducedIn:'1.0.0.4'}]}));recordPageUpdates({root,version:'1.0.0.4',paths:['website/node/staff-roster.mjs','website/web/rates-and-charges.html'],newPages:['https://www.dunerealms.com/rates-and-charges.html']});const items=JSON.parse(readFileSync(file)).items;assert.equal(items.find(x=>x.href==='https://clans.dunerealms.com/').badge,undefined);assert.equal(items.find(x=>x.href.endsWith('/staff.html')).badge,'UPDATE');assert.equal(items.find(x=>x.href.endsWith('/rates-and-charges.html')).badge,'NEW');}finally{rmSync(repo,{recursive:true,force:true});}}); diff --git a/website/web/portal-navigation.js b/website/web/portal-navigation.js index 97b57d3e..9d4fcead 100644 --- a/website/web/portal-navigation.js +++ b/website/web/portal-navigation.js @@ -62,4 +62,4 @@ (()=>{function sync(){const nav=document.querySelector('.dune-shared-footer nav');if(!nav||nav.querySelector('[data-bank-rates]'))return;const a=document.createElement('a');a.dataset.bankRates='1';a.href='https://www.dunerealms.com/rates-and-charges.html';a.textContent='Rates & Charges';nav.append(a);}sync();new MutationObserver(sync).observe(document.body,{childList:true,subtree:true});})(); /* Central automatic release menu badges */ -(()=>{let items=[{"href":"https://cp.dunerealms.com/#shop","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://wiki.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://clans.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://cp.dunerealms.com/","badge":"NEW","updatedIn":"1.0.1.0","introducedIn":"1.0.1.0"},{"href":"https://cp.dunerealms.com/#exchange","updatedIn":"1.0.0.2","badge":"UPDATE"},{"href":"https://support.dunerealms.com/","updatedIn":"1.0.0.3","badge":"UPDATE"},{"href":"https://www.dunerealms.com/staff.html","updatedIn":"1.0.0.5","badge":"UPDATE"},{"href":"https://www.dunerealms.com/","badge":"NEW","introducedIn":"1.0.0.3","updatedIn":"1.0.0.3"},{"href":"https://www.dunerealms.com/shop.html","updatedIn":"1.0.0.5","badge":"UPDATE"},{"href":"https://www.dunerealms.com/kits.html","introducedIn":"1.0.0.5","badge":"NEW"},{"href":"https://cp.dunerealms.com/#kits-exchange","introducedIn":"1.0.0.5","badge":"NEW"},{"href":"https://cp.dunerealms.com/#realm","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#bureau","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#forge","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#politics","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#post","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#bank","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#market","badge":"NEW","introducedIn":"v2-api"},{"href":"https://www.dunerealms.com/rates-and-charges.html","updatedIn":"1.0.1.0","badge":"UPDATE"}];function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\d+(?:\.\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:item?.introducedIn===release?'NEW':item?.updatedIn===release?'UPDATE':null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://www.dunerealms.com/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})(); +(()=>{let items=[{"href":"https://cp.dunerealms.com/#shop","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://wiki.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://clans.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://cp.dunerealms.com/","badge":"NEW","updatedIn":"1.0.1.0","introducedIn":"1.0.1.0"},{"href":"https://cp.dunerealms.com/#exchange","updatedIn":"1.0.0.2","badge":"UPDATE"},{"href":"https://support.dunerealms.com/","updatedIn":"1.0.0.3","badge":"UPDATE"},{"href":"https://www.dunerealms.com/staff.html","updatedIn":"1.0.0.5","badge":"UPDATE"},{"href":"https://www.dunerealms.com/","badge":"NEW","introducedIn":"1.0.0.3","updatedIn":"1.0.0.3"},{"href":"https://www.dunerealms.com/shop.html","updatedIn":"1.0.0.5","badge":"UPDATE"},{"href":"https://www.dunerealms.com/kits.html","introducedIn":"1.0.0.5","badge":"NEW"},{"href":"https://cp.dunerealms.com/#kits-exchange","introducedIn":"1.0.0.5","badge":"NEW"},{"href":"https://cp.dunerealms.com/#realm","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#bureau","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#forge","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#politics","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#post","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#bank","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#market","badge":"NEW","introducedIn":"v2-api"},{"href":"https://www.dunerealms.com/rates-and-charges.html","updatedIn":"1.0.1.0","badge":"UPDATE"}];function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\d+(?:\.\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://www.dunerealms.com/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})(); From 316aee8ba7aac538f0d71e59a74554f1573c8501 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:45:41 +0100 Subject: [PATCH 09/16] Read published Alpha and world status through shared same-origin routes --- website/scripts/install-shared-header.mjs | 2 +- website/scripts/menu-updates.mjs | 2 +- website/scripts/portal-navigation.mjs | 2 +- website/scripts/release-branding.mjs | 4 ++-- website/web/portal-navigation.js | 6 +++--- website/web/release.json | 4 ++-- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/website/scripts/install-shared-header.mjs b/website/scripts/install-shared-header.mjs index 299e3d3e..61e3e9cf 100644 --- a/website/scripts/install-shared-header.mjs +++ b/website/scripts/install-shared-header.mjs @@ -30,4 +30,4 @@ if(existsSync(clans+'/index.html')){writeFileSync(clans+'/dune-navigation.css',P // Persistent shared nginx aliases read these exact files on every site. const chrome='/var/lib/dunerealms-public-rates'; -if(existsSync(chrome)){for(const file of ['portal-navigation.js','portal-navigation.css','menu-new-items.json'])copyFileSync(release+'/web/'+file,chrome+'/'+file);} +if(existsSync(chrome)){for(const file of ['portal-navigation.js','portal-navigation.css','menu-new-items.json','release.json'])copyFileSync(release+'/web/'+file,chrome+'/'+file);} diff --git a/website/scripts/menu-updates.mjs b/website/scripts/menu-updates.mjs index e3cfd1a2..c127501f 100644 --- a/website/scripts/menu-updates.mjs +++ b/website/scripts/menu-updates.mjs @@ -1,7 +1,7 @@ import{readFileSync,writeFileSync}from'node:fs';import{execFileSync}from'node:child_process';import{fileURLToPath}from'node:url';import path from'node:path';import{RELEASE_VERSION}from'./release-branding.mjs'; export function pagesForChanges(paths){const pages=new Set();for(let p of paths){p=p.replaceAll('\\','/');if(/website\/node\/staff-roster\.mjs$/.test(p))pages.add('https://www.dunerealms.com/staff.html');if(/website\/node\/memorials\.mjs$|website\/node\/public\/memorial\./.test(p))pages.add('https://www.dunerealms.com/');if(/website\/control-panel\//.test(p)||/website\/node\/(auth|permissions|account-admin|account-archive|honours|profile)\.mjs$/.test(p))pages.add('https://cp.dunerealms.com/');if(/website\/integrations\/azuriom\//.test(p))pages.add('https://www.dunerealms.com/shop.html');if(/website\/integrations\/osticket\//.test(p))pages.add('https://support.dunerealms.com/');if(/website\/web\/([a-z-]+)\.html$/.test(p)){const name=p.match(/([^/]+)\.html$/)[1];pages.add('https://www.dunerealms.com/'+(['index','portal'].includes(name)?'':name+'.html'));}}return[...pages].sort();} export function recordPageUpdates({root=fileURLToPath(new URL('../',import.meta.url)),paths,newPages=[],version=RELEASE_VERSION}={}){if(!/^\d+(?:\.\d+){3}$/.test(version))throw Error('Invalid release');const repo=path.resolve(root,'..');if(paths===undefined){let changed='';try{const gitRoot=execFileSync('git',['rev-parse','--show-toplevel'],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();if(path.resolve(gitRoot)===repo)changed=execFileSync('git',['diff','--name-only','HEAD'],{cwd:repo,encoding:'utf8'}).trim();}catch(error){if(error?.status!==128&&error?.status!==129&&error?.code!=='ENOENT')throw error;}paths=changed?changed.split('\n'):[];}const file=path.join(root,'web/menu-new-items.json'),data=JSON.parse(readFileSync(file,'utf8'));const pages=pagesForChanges(paths);if(paths.length){for(const item of data.items)delete item.badge;}for(const href of pages){let entry=data.items.find(x=>x.href===href);if(!entry){entry={href};data.items.push(entry);}entry.updatedIn=version;entry.badge=newPages.includes(href)?'NEW':'UPDATE';}writeFileSync(file,JSON.stringify(data,null,2)+'\n');return pages;} -export function menuBadgeScript(){const data=JSON.parse(readFileSync(new URL('../web/menu-new-items.json',import.meta.url),'utf8'));return `\n/* Central automatic release menu badges */\n(()=>{let items=${JSON.stringify(data.items)};function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\\d+(?:\\.\\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://www.dunerealms.com/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})();\n`;} +export function menuBadgeScript(){const data=JSON.parse(readFileSync(new URL('../web/menu-new-items.json',import.meta.url),'utf8'));return `\n/* Central automatic release menu badges */\n(()=>{let items=${JSON.stringify(data.items)};function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\\d+(?:\\.\\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})();\n`;} export function withMenuBadges(s){return s.replace(/\n?\/\* Central automatic release menu badges \*\/[\s\S]*?(?=\n\/\*|$)/,'').replace(/\(\(\)=>\{const items=\[[\s\S]*?new MutationObserver\(mark\)\.observe\(document.body,\{childList:true,subtree:true,characterData:true\}\);\}\)\(\);/,'')+menuBadgeScript();} export function patchMenuBadges(root=fileURLToPath(new URL('../',import.meta.url))){const file=path.join(root,'web/portal-navigation.js');writeFileSync(file,withMenuBadges(readFileSync(file,'utf8')));} if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){const pages=recordPageUpdates();patchMenuBadges();console.log('Central release badges updated for '+pages.length+' changed pages.');} diff --git a/website/scripts/portal-navigation.mjs b/website/scripts/portal-navigation.mjs index d94f6cdb..88c7ad0e 100644 --- a/website/scripts/portal-navigation.mjs +++ b/website/scripts/portal-navigation.mjs @@ -36,7 +36,7 @@ export function pageContextFor(value,links=PORTAL_LINKS){ const link=links.find(x=>x[0]===name); return !link?{label:typeof document!=='undefined'?(document.querySelector('h1')?.textContent.trim()||'Field guide'):'Field guide',icon:'nav-manual-full-v2.webp'}:{label:link[0],icon:link[2].replace('-v2.webp','-full-v2.webp')}; } -export const CONTEXT_SCRIPT=`(()=>{if(window.top!==window.self){document.documentElement.classList.add('dune-embedded');return;}const links=${JSON.stringify(PORTAL_LINKS)},choose=${pageContextFor.toString()};let welcomeName='traveller';fetch('https://cp.dunerealms.com/api/welcome',{credentials:'include',cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(typeof data?.username==='string'&&data.username.length<=32){welcomeName=data.username;render();}}).catch(()=>{});function render(){if(location.hostname==='support.dunerealms.com')document.body.classList.add('dune-support');const item=choose(location.href,links);let worlds=document.querySelector('.world-status');if(!worlds){worlds=document.createElement('aside');worlds.className='world-status';worlds.setAttribute('aria-label','Live server status');const heading=document.createElement('h2');heading.textContent='Worlds online';const list=document.createElement('ul');list.className='world-status-list';const note=document.createElement('p');note.className='world-status-note';note.textContent='Checking the caravan network…';worlds.append(heading,list,note);}worlds.remove();document.querySelector('.dune-page-marker')?.remove();if(!item)return;const header=document.querySelector('.dune-site-header');if(!header)return;const panel=document.createElement('section');panel.className='dune-page-marker';panel.setAttribute('aria-label','Welcome to '+item.label);const image=document.createElement('img');image.src='https://www.dunerealms.com/assets/'+item.icon;image.alt='';image.width=160;image.height=160;const text=document.createElement('div'),small=document.createElement('small'),title=document.createElement('p');small.textContent='THE CARAVAN GUIDE';title.textContent='Welcome, '+welcomeName+', to the '+item.label+'.';const lore=document.createElement('small');const quotes={DuneGit:['Every invention begins with a mark in the caravan ledger.','Share your craft; a good idea can travel beyond the dunes.','Build with care, and leave a trail others can follow.'],Webmail:['A sealed message carries your voice across the dunes.'],Home:['The caravan gathers here; the latest word travels with the wind.','Rest beneath our banners and hear what stirs beyond the dunes.','Every journey begins with news from the road.'],Boards:['A shared tale can light the way for another traveller.','Trade your stories beneath the awning; every voice has a place.','Listen well: the quietest traveller may know the safest passage.'],Exchange:['Weigh your Dunemarks carefully; a fair bargain outlasts a fortune.','Count the coin, inspect the wares, and leave with honour.','Even in a sea of sand, a good bargain is worth finding.'],Discord:['Tune to the caravan frequency; familiar voices shorten the crossing.','Across the dunes, a friendly voice is its own shelter.','The signal is clear. Join the conversation beyond the horizon.'],'Manual/wiki':['A well-read field guide saves more water than a hurried journey.','Learn the trail before you challenge the dunes.','Turn the page; knowledge is the lightest provision you can carry.'],'Staff roster':['A watchful crew keeps the caravan moving.','Every banner is stronger with a trusted hand behind it.','Meet the keepers of the caravan and the worlds beyond.'],'Support center':['Set down your burden; the caravan clerks are here to help.','A troubled journey deserves a patient listener.','Bring us the details, and we will help find the next step.'],'Account center':['Your journey has a place in the caravan ledger.','Keep your records in order and your next crossing within reach.','Behind every banner stands a traveller with a story of their own.'],'Clan center':['Raise your banner; the strongest caravan travels together.','Choose your companions well, and no horizon is too distant.','A shared purpose binds a clan more firmly than any crest.']};const choices=quotes[item.label]||['May your water last and your journey bring good fortune.'];const key=location.hostname+location.pathname+location.hash;let seed=0;for(const character of key)seed=(seed*31+character.charCodeAt(0))>>>0;lore.textContent=choices[seed%choices.length];text.append(lore);const npc=document.createElement('img');npc.src='https://www.dunerealms.com/assets/nav-account-v2.webp';npc.alt='Caravan guide';npc.style.cssText='width:48px;height:48px;object-fit:contain';text.prepend(npc);text.append(small,title);if(worlds&&!worlds.querySelector('.dune-join-box')){const join=document.createElement('div');join.className='dune-join-box';const address=document.createElement('code');address.textContent='play.dunerealms.com';const button=document.createElement('button');button.type='button';button.textContent='Join now';button.setAttribute('aria-label','Join now: copy Minecraft server address');const help=document.createElement('p');help.className='dune-join-help';help.textContent='Java & Bedrock · copy the server address';help.setAttribute('role','status');button.addEventListener('click',async()=>{try{await navigator.clipboard.writeText('play.dunerealms.com');button.textContent='Copied ✓';help.textContent='Address copied · choose Add Server in Java or Bedrock.';}catch{help.textContent='In Minecraft Java, add a server with address play.dunerealms.com.';}});const ports=document.createElement('div');ports.className='dune-join-ports';for(const [edition,port]of [['Bedrock','19132'],['Java','25565']]){const box=document.createElement('span'),label=document.createElement('small'),value=document.createElement('code');label.textContent=edition+' port';value.textContent=port;const icon=document.createElement('img');icon.className='edition-icon';icon.alt='';icon.width=12;icon.height=12;icon.src='https://www.dunerealms.com/assets/edition-'+(edition==='Java'?'java':'bedrock')+'.svg';box.append(icon,label,value);ports.append(box);}join.append(address,button,ports,help);worlds.append(join);}if(worlds&&!worlds.querySelector('.world-network-art')){worlds.querySelector('.eyebrow')?.remove();const plate=document.createElement('img');plate.className='world-network-art';plate.src='https://www.dunerealms.com/assets/vaerkring-network-title-v1.webp';plate.alt='Vaerkring Network';plate.width=280;plate.height=80;worlds.prepend(plate);}panel.append(image,text);if(worlds)panel.append(worlds);header.after(panel);if(!document.querySelector('.dune-shared-footer')){const old=document.querySelector('body>footer,.site-footer'),foot=old||document.createElement('footer');foot.className='dune-shared-footer';foot.replaceChildren();const brand=document.createElement('a');brand.href='https://www.dunerealms.com/';brand.textContent='✦ dunerealms.com';brand.className='dune-footer-brand';const links=document.createElement('nav');links.setAttribute('aria-label','Footer navigation');for(const [label,href]of [['Manual/wiki','https://wiki.dunerealms.com/'],['Support','https://support.dunerealms.com/'],['Account','https://cp.dunerealms.com/'],['DuneGit','https://www.dunerealms.com/git/unimatrix/MC'],['Disclaimer & contact','https://www.dunerealms.com/wiki.html']]){const a=document.createElement('a');a.textContent=label;a.href=href;links.append(a);}const note=document.createElement('small');note.textContent='Independent fan project · Not affiliated with Dune rights holders, Mojang or Microsoft.';foot.append(brand,links);const host=document.createElement('a');host.className='dune-hosting-badge';host.href='https://www.hetzner.com/';host.target='_blank';host.rel='noopener noreferrer';host.setAttribute('aria-label','Powered by Hetzner — visit Hetzner');const server=document.createElement('span');server.className='dune-hosting-art';server.textContent='▤';server.setAttribute('aria-hidden','true');const hostText=document.createElement('span');const powered=document.createElement('span');powered.textContent='POWERED BY';const hostLogo=document.createElement('img');hostLogo.src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODEuNDIgMjIuMjQiPjxkZWZzPjxzdHlsZT4uY2xzLTF7ZmlsbDojZDUwYzJkO308L3N0eWxlPjwvZGVmcz48dGl0bGU+RWxlbWVudCAxPC90aXRsZT48ZyBpZD0iRWJlbmVfMiIgZGF0YS1uYW1lPSJFYmVuZSAyIj48ZyBpZD0iTG9nb19QdXIiIGRhdGEtbmFtZT0iTG9nbyBQdXIiPjxnIGlkPSJMb2dvIj48ZyBpZD0iSEVUWk5FUiI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTc0LjA1LDE0LjEyYTEwLjIyLDEwLjIyLDAsMCwwLDQuNTMtMmwwLDBhNi4xNSw2LjE1LDAsMCwwLDEuNjgtNC43OCw3LjcxLDcuNzEsMCwwLDAtMS4xNC00LjA2QTYuNDcsNi40NywwLDAsMCwxNzMuODQuMDlsLTEuMDksMEwxNzAuMiwwLDE1OC42NiwwYy0uNywwLTEsLjI5LTEsMVYyMS4yMmMwLC43LjI5LDEsMSwxaDNjLjcsMCwxLS4yOSwxLTF2LTYuN2gzLjY3YTMuNDgsMy40OCwwLDAsMSwyLjE3LjkxbDUuODIsNS44NWEzLjA4LDMuMDgsMCwwLDAsMiwuOTJoNC40N2MuNywwLC44Ny0uNDEuMzgtLjkxWm0tLjc2LTQuM0gxNjIuNjRWNC43MmgxMC42NWEyLjEzLDIuMTMsMCwwLDEsMS44NywyLjE1di43OUEyLjE0LDIuMTQsMCwwLDEsMTczLjI5LDkuODJaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTUzLDE3LjUySDEzNi40N1YxMy4zNWgxMy4xOWMuNywwLDEtLjI5LDEtMVY5LjkyYzAtLjctLjI5LTEtMS0xaC0xMy4yVjQuNzZIMTUzYy43LDAsMS0uMjksMS0xVjFjMC0uNy0uMjktMS0xLTFIMTMyLjM4Yy0uNywwLTEsLjI5LTEsMVYyMS4yNGMwLC43LjI5LDEsMSwxSDE1M2MuNywwLDEtLjI5LDEtMVYxOC41MUMxNTQsMTcuODEsMTUzLjY3LDE3LjUyLDE1MywxNy41MloiLz48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik0xMjcuNzMsNy4zYTcuMjUsNy4yNSwwLDAsMC0xLjEzLTRBNi42MSw2LjYxLDAsMCwwLDEyMS4yNCwwTDEwNi4wOCwwYy0uNzEsMC0xLC4yOS0xLDFWMjEuMjJjMCwuNy4yOSwxLDEsMWgzLjI2Yy43LDAsMS0uMjgsMS0xVjQuNzNsOC43OCwwYzEuODcsMCwzLjY5LDEuMjQsMy42OSwzLjExVjIxLjI0YzAsLjcuMjksMSwxLDFoMi45NWMuNzEsMCwxLS4yOSwxLTFaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTAwLjQ3LDE3LjM5bC0xNC4yNSwwTDEwMC41LDQuODRhMi41NywyLjU3LDAsMCwwLDEtMS44NFYxYzAtLjctLjMtMS0xLTFINzkuODNjLS43LDAtMSwuMjktMSwxVjMuNzdjMCwuNy4yOSwxLDEsMUg5My4wOEw3OS43OSwxNy4yNGEyLjYyLDIuNjIsMCwwLDAtMSwxLjg0djIuMTdjMCwuNy4yOSwxLDEsMWwyMC42NSwwYy43LDAsMS0uMjksMS0xVjE4LjM4QzEwMS40NiwxNy42OCwxMDEuMTcsMTcuMzksMTAwLjQ3LDE3LjM5WiIvPjxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTc0LjE5LDBINTMuNTVjLS43MSwwLTEsLjI4LTEsMVYzLjc2YzAsLjcuMjgsMSwxLDFoNy43OFYyMS4yNGMwLC43LjI5LDEsMSwxaDMuM2MuNywwLDEtLjI5LDEtMVY0Ljc1aDcuNTdjLjcsMCwxLS4yOSwxLTFWMUM3NS4xOC4zMiw3NC44OSwwLDc0LjE5LDBaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDcuOTEsMTcuNTJIMzEuNDFWMTMuMzVINDQuNmMuNywwLDEtLjI5LDEtMVY5LjkyYzAtLjctLjI4LTEtMS0xSDMxLjQxVjQuNzZoMTYuNWMuNywwLDEtLjI5LDEtMVYxYzAtLjctLjI5LTEtMS0xSDI3LjMzYy0uNywwLTEsLjI5LTEsMVYyMS4yNGMwLC43LjI5LDEsMSwxSDQ3LjkxYy43LDAsMS0uMjksMS0xVjE4LjUxQzQ4LjksMTcuODEsNDguNjEsMTcuNTIsNDcuOTEsMTcuNTJaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMjEuNjMsMEgxOC41MmMtLjcsMC0xLC4yOS0xLDFWOC44N0g1LjEzVjFjMC0uNy0uMjktMS0xLTFIMUMuMjksMCwwLC4yOSwwLDFWMjEuMjVjMCwuNzEuMjksMSwxLDFINC4xM2MuNywwLDEtLjI4LDEtMXYtOGgxMi40djhjMCwuNy4yOSwxLDEsMWgzLjExYy43LDAsMS0uMjksMS0xVjFDMjIuNjIuMzIsMjIuMzMsMCwyMS42MywwWiIvPjwvZz48L2c+PC9nPjwvZz48L3N2Zz4=";hostLogo.alt='Hetzner';hostLogo.width=120;hostLogo.height=20;hostText.append(powered,hostLogo);host.append(server,hostText);host.title='Hosting infrastructure · Logo: Hetzner Online GmbH';foot.append(host);foot.append(note);const legal=document.querySelector('.legal-notice');if(legal){const details=document.createElement('details'),summary=document.createElement('summary');summary.textContent='Unofficial fan project';details.className='dune-footer-legal';details.append(summary,legal);foot.append(details);}if(['www.dunerealms.com','dunerealms.com'].includes(location.hostname)&&['/','/index.html'].includes(location.pathname)){const box=document.createElement('div');box.className='dune-footer-parental';const heading=document.createElement('strong');heading.textContent='Parents & guardians';const copy=document.createElement('span');copy.textContent='Parental consent or a child’s account-data request? Contact our support team.';const link=document.createElement('a');link.href='https://support.dunerealms.com/open.php';link.textContent='Parental help →';box.append(heading,copy,link);foot.append(box);}if(!old)document.body.append(foot);}const pin=()=>document.documentElement.style.setProperty('--dune-nav-height',header.getBoundingClientRect().height+'px');pin();if(!header.dataset.pinObserved){new ResizeObserver(pin).observe(header);header.dataset.pinObserved='1';}}render();async function refreshWorlds(){try{const response=await fetch('https://www.dunerealms.com/api/worlds',{cache:'no-store',credentials:'omit',signal:AbortSignal.timeout(7000)});if(!response.ok)throw Error();const data=await response.json(),panel=document.querySelector('.dune-page-marker .world-status');if(!panel)return;const list=panel.querySelector('.world-status-list');list.replaceChildren();const glyphs={Arrakduin:'serevan',Kaladam:'pelareth',Giedermark:'varkesh',Kaiterhof:'orivane','Sigmadraken IV':'nivareth'};list.setAttribute('role','table');list.setAttribute('aria-label','World and connection status');for(const server of data.servers){const row=document.createElement('li'),name=document.createElement('span'),state=document.createElement('span'),icon=document.createElement('img');const display=server.name==='Velocity'?'Proxi':server.name;row.setAttribute('role','row');name.setAttribute('role','cell');name.className='world-name';name.title=display;icon.alt='';icon.width=14;icon.height=14;icon.src=glyphs[server.name]?'https://www.dunerealms.com/assets/planet-glyphs/'+glyphs[server.name]+'.svg':server.name==='Velocity'?'https://www.dunerealms.com/assets/network-proxy.svg':'https://www.dunerealms.com/assets/nav-home-v2.webp';name.append(icon,document.createTextNode(display));const status=server.state==='online'?'Online':server.state==='offline'?'Offline':'Unknown';state.setAttribute('role','cell');state.setAttribute('aria-label',status);state.title=status;state.className='world-state traffic-light '+server.state;for(const color of ['red','amber','green']){const lamp=document.createElement('i');lamp.className='lamp-'+color;lamp.setAttribute('aria-hidden','true');state.append(lamp);}row.append(name,state);list.append(row);}panel.querySelector('.world-status-note').textContent=data.available?'Live check · updates every 30s':'Status check unavailable';}catch{const note=document.querySelector('.dune-page-marker .world-status-note');if(note)note.textContent='Status check unavailable · retrying';}}refreshWorlds();setInterval(()=>{if(!document.hidden)refreshWorlds();},30000);addEventListener('hashchange',()=>{render();refreshWorlds();});})();`; +export const CONTEXT_SCRIPT=`(()=>{if(window.top!==window.self){document.documentElement.classList.add('dune-embedded');return;}const links=${JSON.stringify(PORTAL_LINKS)},choose=${pageContextFor.toString()};let welcomeName='traveller';fetch('https://cp.dunerealms.com/api/welcome',{credentials:'include',cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(typeof data?.username==='string'&&data.username.length<=32){welcomeName=data.username;render();}}).catch(()=>{});function render(){if(location.hostname==='support.dunerealms.com')document.body.classList.add('dune-support');const item=choose(location.href,links);let worlds=document.querySelector('.world-status');if(!worlds){worlds=document.createElement('aside');worlds.className='world-status';worlds.setAttribute('aria-label','Live server status');const heading=document.createElement('h2');heading.textContent='Worlds online';const list=document.createElement('ul');list.className='world-status-list';const note=document.createElement('p');note.className='world-status-note';note.textContent='Checking the caravan network…';worlds.append(heading,list,note);}worlds.remove();document.querySelector('.dune-page-marker')?.remove();if(!item)return;const header=document.querySelector('.dune-site-header');if(!header)return;const panel=document.createElement('section');panel.className='dune-page-marker';panel.setAttribute('aria-label','Welcome to '+item.label);const image=document.createElement('img');image.src='https://www.dunerealms.com/assets/'+item.icon;image.alt='';image.width=160;image.height=160;const text=document.createElement('div'),small=document.createElement('small'),title=document.createElement('p');small.textContent='THE CARAVAN GUIDE';title.textContent='Welcome, '+welcomeName+', to the '+item.label+'.';const lore=document.createElement('small');const quotes={DuneGit:['Every invention begins with a mark in the caravan ledger.','Share your craft; a good idea can travel beyond the dunes.','Build with care, and leave a trail others can follow.'],Webmail:['A sealed message carries your voice across the dunes.'],Home:['The caravan gathers here; the latest word travels with the wind.','Rest beneath our banners and hear what stirs beyond the dunes.','Every journey begins with news from the road.'],Boards:['A shared tale can light the way for another traveller.','Trade your stories beneath the awning; every voice has a place.','Listen well: the quietest traveller may know the safest passage.'],Exchange:['Weigh your Dunemarks carefully; a fair bargain outlasts a fortune.','Count the coin, inspect the wares, and leave with honour.','Even in a sea of sand, a good bargain is worth finding.'],Discord:['Tune to the caravan frequency; familiar voices shorten the crossing.','Across the dunes, a friendly voice is its own shelter.','The signal is clear. Join the conversation beyond the horizon.'],'Manual/wiki':['A well-read field guide saves more water than a hurried journey.','Learn the trail before you challenge the dunes.','Turn the page; knowledge is the lightest provision you can carry.'],'Staff roster':['A watchful crew keeps the caravan moving.','Every banner is stronger with a trusted hand behind it.','Meet the keepers of the caravan and the worlds beyond.'],'Support center':['Set down your burden; the caravan clerks are here to help.','A troubled journey deserves a patient listener.','Bring us the details, and we will help find the next step.'],'Account center':['Your journey has a place in the caravan ledger.','Keep your records in order and your next crossing within reach.','Behind every banner stands a traveller with a story of their own.'],'Clan center':['Raise your banner; the strongest caravan travels together.','Choose your companions well, and no horizon is too distant.','A shared purpose binds a clan more firmly than any crest.']};const choices=quotes[item.label]||['May your water last and your journey bring good fortune.'];const key=location.hostname+location.pathname+location.hash;let seed=0;for(const character of key)seed=(seed*31+character.charCodeAt(0))>>>0;lore.textContent=choices[seed%choices.length];text.append(lore);const npc=document.createElement('img');npc.src='https://www.dunerealms.com/assets/nav-account-v2.webp';npc.alt='Caravan guide';npc.style.cssText='width:48px;height:48px;object-fit:contain';text.prepend(npc);text.append(small,title);if(worlds&&!worlds.querySelector('.dune-join-box')){const join=document.createElement('div');join.className='dune-join-box';const address=document.createElement('code');address.textContent='play.dunerealms.com';const button=document.createElement('button');button.type='button';button.textContent='Join now';button.setAttribute('aria-label','Join now: copy Minecraft server address');const help=document.createElement('p');help.className='dune-join-help';help.textContent='Java & Bedrock · copy the server address';help.setAttribute('role','status');button.addEventListener('click',async()=>{try{await navigator.clipboard.writeText('play.dunerealms.com');button.textContent='Copied ✓';help.textContent='Address copied · choose Add Server in Java or Bedrock.';}catch{help.textContent='In Minecraft Java, add a server with address play.dunerealms.com.';}});const ports=document.createElement('div');ports.className='dune-join-ports';for(const [edition,port]of [['Bedrock','19132'],['Java','25565']]){const box=document.createElement('span'),label=document.createElement('small'),value=document.createElement('code');label.textContent=edition+' port';value.textContent=port;const icon=document.createElement('img');icon.className='edition-icon';icon.alt='';icon.width=12;icon.height=12;icon.src='https://www.dunerealms.com/assets/edition-'+(edition==='Java'?'java':'bedrock')+'.svg';box.append(icon,label,value);ports.append(box);}join.append(address,button,ports,help);worlds.append(join);}if(worlds&&!worlds.querySelector('.world-network-art')){worlds.querySelector('.eyebrow')?.remove();const plate=document.createElement('img');plate.className='world-network-art';plate.src='https://www.dunerealms.com/assets/vaerkring-network-title-v1.webp';plate.alt='Vaerkring Network';plate.width=280;plate.height=80;worlds.prepend(plate);}panel.append(image,text);if(worlds)panel.append(worlds);header.after(panel);if(!document.querySelector('.dune-shared-footer')){const old=document.querySelector('body>footer,.site-footer'),foot=old||document.createElement('footer');foot.className='dune-shared-footer';foot.replaceChildren();const brand=document.createElement('a');brand.href='https://www.dunerealms.com/';brand.textContent='✦ dunerealms.com';brand.className='dune-footer-brand';const links=document.createElement('nav');links.setAttribute('aria-label','Footer navigation');for(const [label,href]of [['Manual/wiki','https://wiki.dunerealms.com/'],['Support','https://support.dunerealms.com/'],['Account','https://cp.dunerealms.com/'],['DuneGit','https://www.dunerealms.com/git/unimatrix/MC'],['Disclaimer & contact','https://www.dunerealms.com/wiki.html']]){const a=document.createElement('a');a.textContent=label;a.href=href;links.append(a);}const note=document.createElement('small');note.textContent='Independent fan project · Not affiliated with Dune rights holders, Mojang or Microsoft.';foot.append(brand,links);const host=document.createElement('a');host.className='dune-hosting-badge';host.href='https://www.hetzner.com/';host.target='_blank';host.rel='noopener noreferrer';host.setAttribute('aria-label','Powered by Hetzner — visit Hetzner');const server=document.createElement('span');server.className='dune-hosting-art';server.textContent='▤';server.setAttribute('aria-hidden','true');const hostText=document.createElement('span');const powered=document.createElement('span');powered.textContent='POWERED BY';const hostLogo=document.createElement('img');hostLogo.src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODEuNDIgMjIuMjQiPjxkZWZzPjxzdHlsZT4uY2xzLTF7ZmlsbDojZDUwYzJkO308L3N0eWxlPjwvZGVmcz48dGl0bGU+RWxlbWVudCAxPC90aXRsZT48ZyBpZD0iRWJlbmVfMiIgZGF0YS1uYW1lPSJFYmVuZSAyIj48ZyBpZD0iTG9nb19QdXIiIGRhdGEtbmFtZT0iTG9nbyBQdXIiPjxnIGlkPSJMb2dvIj48ZyBpZD0iSEVUWk5FUiI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTc0LjA1LDE0LjEyYTEwLjIyLDEwLjIyLDAsMCwwLDQuNTMtMmwwLDBhNi4xNSw2LjE1LDAsMCwwLDEuNjgtNC43OCw3LjcxLDcuNzEsMCwwLDAtMS4xNC00LjA2QTYuNDcsNi40NywwLDAsMCwxNzMuODQuMDlsLTEuMDksMEwxNzAuMiwwLDE1OC42NiwwYy0uNywwLTEsLjI5LTEsMVYyMS4yMmMwLC43LjI5LDEsMSwxaDNjLjcsMCwxLS4yOSwxLTF2LTYuN2gzLjY3YTMuNDgsMy40OCwwLDAsMSwyLjE3LjkxbDUuODIsNS44NWEzLjA4LDMuMDgsMCwwLDAsMiwuOTJoNC40N2MuNywwLC44Ny0uNDEuMzgtLjkxWm0tLjc2LTQuM0gxNjIuNjRWNC43MmgxMC42NWEyLjEzLDIuMTMsMCwwLDEsMS44NywyLjE1di43OUEyLjE0LDIuMTQsMCwwLDEsMTczLjI5LDkuODJaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTUzLDE3LjUySDEzNi40N1YxMy4zNWgxMy4xOWMuNywwLDEtLjI5LDEtMVY5LjkyYzAtLjctLjI5LTEtMS0xaC0xMy4yVjQuNzZIMTUzYy43LDAsMS0uMjksMS0xVjFjMC0uNy0uMjktMS0xLTFIMTMyLjM4Yy0uNywwLTEsLjI5LTEsMVYyMS4yNGMwLC43LjI5LDEsMSwxSDE1M2MuNywwLDEtLjI5LDEtMVYxOC41MUMxNTQsMTcuODEsMTUzLjY3LDE3LjUyLDE1MywxNy41MloiLz48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik0xMjcuNzMsNy4zYTcuMjUsNy4yNSwwLDAsMC0xLjEzLTRBNi42MSw2LjYxLDAsMCwwLDEyMS4yNCwwTDEwNi4wOCwwYy0uNzEsMC0xLC4yOS0xLDFWMjEuMjJjMCwuNy4yOSwxLDEsMWgzLjI2Yy43LDAsMS0uMjgsMS0xVjQuNzNsOC43OCwwYzEuODcsMCwzLjY5LDEuMjQsMy42OSwzLjExVjIxLjI0YzAsLjcuMjksMSwxLDFoMi45NWMuNzEsMCwxLS4yOSwxLTFaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTAwLjQ3LDE3LjM5bC0xNC4yNSwwTDEwMC41LDQuODRhMi41NywyLjU3LDAsMCwwLDEtMS44NFYxYzAtLjctLjMtMS0xLTFINzkuODNjLS43LDAtMSwuMjktMSwxVjMuNzdjMCwuNy4yOSwxLDEsMUg5My4wOEw3OS43OSwxNy4yNGEyLjYyLDIuNjIsMCwwLDAtMSwxLjg0djIuMTdjMCwuNy4yOSwxLDEsMWwyMC42NSwwYy43LDAsMS0uMjksMS0xVjE4LjM4QzEwMS40NiwxNy42OCwxMDEuMTcsMTcuMzksMTAwLjQ3LDE3LjM5WiIvPjxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTc0LjE5LDBINTMuNTVjLS43MSwwLTEsLjI4LTEsMVYzLjc2YzAsLjcuMjgsMSwxLDFoNy43OFYyMS4yNGMwLC43LjI5LDEsMSwxaDMuM2MuNywwLDEtLjI5LDEtMVY0Ljc1aDcuNTdjLjcsMCwxLS4yOSwxLTFWMUM3NS4xOC4zMiw3NC44OSwwLDc0LjE5LDBaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDcuOTEsMTcuNTJIMzEuNDFWMTMuMzVINDQuNmMuNywwLDEtLjI5LDEtMVY5LjkyYzAtLjctLjI4LTEtMS0xSDMxLjQxVjQuNzZoMTYuNWMuNywwLDEtLjI5LDEtMVYxYzAtLjctLjI5LTEtMS0xSDI3LjMzYy0uNywwLTEsLjI5LTEsMVYyMS4yNGMwLC43LjI5LDEsMSwxSDQ3LjkxYy43LDAsMS0uMjksMS0xVjE4LjUxQzQ4LjksMTcuODEsNDguNjEsMTcuNTIsNDcuOTEsMTcuNTJaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMjEuNjMsMEgxOC41MmMtLjcsMC0xLC4yOS0xLDFWOC44N0g1LjEzVjFjMC0uNy0uMjktMS0xLTFIMUMuMjksMCwwLC4yOSwwLDFWMjEuMjVjMCwuNzEuMjksMSwxLDFINC4xM2MuNywwLDEtLjI4LDEtMXYtOGgxMi40djhjMCwuNy4yOSwxLDEsMWgzLjExYy43LDAsMS0uMjksMS0xVjFDMjIuNjIuMzIsMjIuMzMsMCwyMS42MywwWiIvPjwvZz48L2c+PC9nPjwvZz48L3N2Zz4=";hostLogo.alt='Hetzner';hostLogo.width=120;hostLogo.height=20;hostText.append(powered,hostLogo);host.append(server,hostText);host.title='Hosting infrastructure · Logo: Hetzner Online GmbH';foot.append(host);foot.append(note);const legal=document.querySelector('.legal-notice');if(legal){const details=document.createElement('details'),summary=document.createElement('summary');summary.textContent='Unofficial fan project';details.className='dune-footer-legal';details.append(summary,legal);foot.append(details);}if(['www.dunerealms.com','dunerealms.com'].includes(location.hostname)&&['/','/index.html'].includes(location.pathname)){const box=document.createElement('div');box.className='dune-footer-parental';const heading=document.createElement('strong');heading.textContent='Parents & guardians';const copy=document.createElement('span');copy.textContent='Parental consent or a child’s account-data request? Contact our support team.';const link=document.createElement('a');link.href='https://support.dunerealms.com/open.php';link.textContent='Parental help →';box.append(heading,copy,link);foot.append(box);}if(!old)document.body.append(foot);}const pin=()=>document.documentElement.style.setProperty('--dune-nav-height',header.getBoundingClientRect().height+'px');pin();if(!header.dataset.pinObserved){new ResizeObserver(pin).observe(header);header.dataset.pinObserved='1';}}render();async function refreshWorlds(){try{const response=await fetch('/api/worlds',{cache:'no-store',credentials:'omit',signal:AbortSignal.timeout(7000)});if(!response.ok)throw Error();const data=await response.json(),panel=document.querySelector('.dune-page-marker .world-status');if(!panel)return;const list=panel.querySelector('.world-status-list');list.replaceChildren();const glyphs={Arrakduin:'serevan',Kaladam:'pelareth',Giedermark:'varkesh',Kaiterhof:'orivane','Sigmadraken IV':'nivareth'};list.setAttribute('role','table');list.setAttribute('aria-label','World and connection status');for(const server of data.servers){const row=document.createElement('li'),name=document.createElement('span'),state=document.createElement('span'),icon=document.createElement('img');const display=server.name==='Velocity'?'Proxi':server.name;row.setAttribute('role','row');name.setAttribute('role','cell');name.className='world-name';name.title=display;icon.alt='';icon.width=14;icon.height=14;icon.src=glyphs[server.name]?'https://www.dunerealms.com/assets/planet-glyphs/'+glyphs[server.name]+'.svg':server.name==='Velocity'?'https://www.dunerealms.com/assets/network-proxy.svg':'https://www.dunerealms.com/assets/nav-home-v2.webp';name.append(icon,document.createTextNode(display));const status=server.state==='online'?'Online':server.state==='offline'?'Offline':'Unknown';state.setAttribute('role','cell');state.setAttribute('aria-label',status);state.title=status;state.className='world-state traffic-light '+server.state;for(const color of ['red','amber','green']){const lamp=document.createElement('i');lamp.className='lamp-'+color;lamp.setAttribute('aria-hidden','true');state.append(lamp);}row.append(name,state);list.append(row);}panel.querySelector('.world-status-note').textContent=data.available?'Live check · updates every 30s':'Status check unavailable';}catch{const note=document.querySelector('.dune-page-marker .world-status-note');if(note)note.textContent='Status check unavailable · retrying';}}refreshWorlds();setInterval(()=>{if(!document.hidden)refreshWorlds();},30000);addEventListener('hashchange',()=>{render();refreshWorlds();});})();`; export const CONTEXT_CSS=`.dune-page-marker>.world-status{max-width:325px!important;min-width:245px!important;flex-basis:245px!important;padding:8px 12px!important;border:1px solid #8a7845!important;border-radius:4px;box-shadow:inset 0 0 0 3px #0b2117,0 3px 9px #0003}.dune-page-marker .world-status h2{font:600 16px/1.25 system-ui!important;margin:3px 0 7px!important;color:#ead399}.dune-page-marker .world-status .eyebrow{font:700 8px/1.4 system-ui!important;letter-spacing:.12em!important;margin:0 0 3px!important;color:#b6c5aa}.dune-page-marker .world-status-list{gap:1px 8px!important}.dune-page-marker .world-status-list li{font:10px/1.35 system-ui!important;padding:2px 0!important;border-bottom:1px solid #58654444}.dune-page-marker .world-state{font-size:9px!important;white-space:nowrap}.dune-page-marker .world-status-note{font:8px/1.4 system-ui!important;margin:5px 0 0!important}.dune-join-box{padding:6px 7px!important;margin-top:7px!important;gap:5px 7px!important}.dune-join-box>code{font-size:10px!important}.dune-join-box button{padding:5px 8px!important;font-size:10px!important}.dune-join-ports{gap:5px!important}.dune-join-ports>span{padding:3px 4px!important}.dune-join-ports small{font-size:8px!important}.dune-join-ports code{font-size:9px!important}.dune-page-marker .dune-join-help{font-size:8px!important;line-height:1.35!important}@media(max-width:1000px){.dune-page-marker>.world-status{max-width:none!important;flex-basis:100%!important}}.dune-join-ports{grid-column:1/-1;display:grid;grid-template-columns:1fr 1fr;gap:6px}.dune-join-ports>span{display:flex;align-items:center;justify-content:space-between;gap:7px;padding:4px 6px;background:#10251b;border:1px solid #62704a;border-radius:2px}.dune-join-ports small{font:9px/1.4 system-ui!important;color:#bcc8ae!important}.dune-join-ports code{font-size:11px;color:#ead49a}.dune-join-box{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:7px 10px;margin-top:10px;padding:9px 10px;background:#1f3728;border:1px solid #98854e;border-radius:3px}.dune-join-box code{font:600 12px/1.5 ui-monospace,monospace;color:#f0dfad;background:none;padding:0;overflow-wrap:anywhere}.dune-join-box button{border:1px solid #dfc479;background:linear-gradient(#d9bd74,#b9974c);color:#12241a;padding:7px 12px;border-radius:2px;font:700 11px/1.3 system-ui;cursor:pointer;white-space:nowrap}.dune-join-box button:hover{filter:brightness(1.1)}.dune-join-box button:focus-visible{outline:2px solid #c5e4b8;outline-offset:3px}.dune-page-marker .dune-join-help{grid-column:1/-1;font:10px/1.4 system-ui!important;color:#bdcbb4!important;margin:0!important;letter-spacing:normal!important}.dune-embedded .dune-page-marker,.dune-embedded .dune-shared-footer,.dune-embedded #footer,.dune-embedded footer{display:none!important}.dune-page-marker .world-status .eyebrow,.dune-page-marker .world-status-note{font:11px/1.5 system-ui!important;letter-spacing:normal!important}.dune-footer-legal,.dune-footer-parental{flex-basis:100%;font:12px/1.6 system-ui}.dune-footer-legal summary{cursor:pointer;color:#d6ba76}.dune-footer-legal .legal-notice{max-width:none!important;margin:10px 0 0!important;padding:12px 0!important;background:none!important;border:0!important;font:11px/1.6 system-ui}.dune-footer-parental{display:flex;flex-wrap:wrap;align-items:center;gap:8px 16px;border-top:1px solid #425a45;padding-top:10px;color:#bdc7b8}.dune-footer-parental strong,.dune-footer-parental a{color:#dfc17c}.dune-shared-footer{display:flex!important;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px 24px!important;padding:18px max(24px,4%)!important;background:#10271f!important;border-top:1px solid #74663f!important;border-bottom:0!important;margin-top:20px;box-sizing:border-box}.dune-hosting-badge{display:inline-flex!important;align-items:center;gap:12px;padding:9px 15px!important;border:1px solid #a88e4b!important;border-radius:7px;background:linear-gradient(135deg,#294636,#0d241b)!important;box-shadow:inset 0 0 0 3px #d1b66b12,0 3px 8px #0003;text-decoration:none!important}.dune-hosting-badge>span:last-child{display:grid;gap:5px}.dune-hosting-badge span span{font:9px/1.2 system-ui;letter-spacing:.2em;color:#e4c77f}.dune-hosting-badge img{display:block;width:120px!important;height:20px!important;object-fit:contain;background:#fff;border-radius:3px;padding:6px 8px}.dune-hosting-art{font-size:38px;line-height:1;color:#d5b66b;text-shadow:2px 2px #081c14;border:1px solid #857847;padding:2px 7px;border-radius:4px}.dune-hosting-badge:hover{border-color:#f0d488!important;box-shadow:0 0 15px #dfbb4c22}.dune-shared-footer .dune-footer-brand{font:700 19px/1.4 system-ui;letter-spacing:0;color:#dfbe78}.dune-shared-footer nav{display:flex!important;position:static!important;flex-direction:row!important;flex-wrap:wrap;gap:10px 20px!important;padding:0!important;background:none!important;border:0!important;font:12px/1.5 system-ui}.dune-shared-footer nav a{color:#dfc17c!important;text-decoration:none!important;padding:0!important;min-height:0!important;background:none!important;border:0!important}.dune-shared-footer small{flex-basis:100%;border:0!important;padding:0!important;font:10px/1.5 system-ui;letter-spacing:0!important;text-align:left!important;color:#b7c3b5}.dune-page-marker{gap:20px!important;min-height:165px!important;padding-top:10px!important;padding-bottom:10px!important}.dune-page-marker>img{width:130px!important;height:140px!important;flex-basis:130px!important}.dune-page-marker p{margin:8px 0!important;font-size:21px!important}.dune-page-marker>.world-status{padding:10px 16px!important}.dune-page-marker .world-status-list{gap:3px 12px!important}#footer:not(footer){padding-top:12px!important;padding-bottom:12px!important}@media(max-width:650px){.dune-page-marker>img{width:80px!important;height:90px!important;flex-basis:80px!important}.dune-shared-footer{gap:8px!important;padding:15px 20px!important}}footer,.site-footer{background-repeat:no-repeat!important;background-size:cover!important;background-position:center!important}html,body{background-color:#0d211b!important;background-image:none!important}header.dune-site-header::after{display:none!important;content:none!important}header.dune-site-header{position:static!important;top:auto!important}.dune-page-marker{position:static!important;top:auto!important;border-bottom:3px double #b49a5c!important;box-shadow:0 5px 10px #0005}html{scroll-padding-top:0}@media(max-height:650px){.dune-page-marker{min-height:120px!important;padding-top:6px!important;padding-bottom:6px!important}.dune-page-marker>img{height:90px!important;width:90px!important;flex-basis:90px!important}.dune-page-marker p{font-size:17px!important}.dune-page-marker .world-status-list{gap:0 12px!important}.dune-page-marker>.world-status{padding:6px 12px!important}}.dune-page-marker>.world-status{position:static!important;transform:none!important;inset:auto!important;flex:1 1 320px;max-width:430px;width:auto!important;min-width:260px;margin:0 0 0 auto!important;padding:14px 20px!important;box-sizing:border-box;background:#0d211b;border:1px solid #586844;border-radius:6px}.dune-page-marker .world-status h2{font:600 20px/1.3 system-ui;margin:4px 0 10px}.dune-page-marker .world-status .eyebrow{font-size:10px;margin:0}.dune-page-marker .world-status-list{display:grid;grid-template-columns:1fr 1fr;gap:5px 16px;margin:0;padding:0;list-style:none}.dune-page-marker .world-status-list li{display:flex;justify-content:space-between;gap:8px;font:12px/1.5 system-ui;padding:2px 0}.dune-page-marker .world-status>p:last-child{font:11px/1.5 system-ui;margin:8px 0 0}@media(max-width:1000px){.dune-page-marker{flex-wrap:wrap}.dune-page-marker>.world-status{flex-basis:100%;max-width:none;margin:8px 0 0!important}}body.dune-support #landing_page .main-content,body.dune-support #content .main-content{background:#142d26!important;color:#e6dfca!important;padding:20px;box-sizing:border-box;border:1px solid #50624d}body.dune-support #content p,body.dune-support #content h1,body.dune-support #content h2{color:#e6dfca}body.dune-support #content input,body.dune-support #content select,body.dune-support #content textarea{background:#10261f;color:#eee3c7;border:1px solid #718266}header.dune-site-header[hidden]{display:none!important}.dune-page-marker{display:flex;align-items:center;gap:26px;width:100%;min-height:206px;margin:0;padding:14px max(5%,24px);background:#122c23;border-top:1px solid #596345;border-bottom:1px solid #596345;color:#e9d5aa;box-sizing:border-box;text-align:left}.dune-page-marker>img{display:block;width:164px;height:178px;object-fit:contain;flex:0 0 164px}.dune-page-marker>div{max-width:470px;text-align:center}.dune-page-marker div>img{display:inline-block;width:48px;height:48px;object-fit:contain}.dune-page-marker small{display:block;font:12px/1.5 system-ui;letter-spacing:normal;color:#cbb978}.dune-page-marker p{font:600 25px/1.35 system-ui;margin:10px 0;color:#eee3c7}@media(max-width:650px){.dune-page-marker{padding:14px 5%;min-height:160px;gap:14px}.dune-page-marker>img{width:90px;height:120px;flex-basis:90px}.dune-page-marker p{font-size:18px}.dune-page-marker small{font-size:11px}.dune-page-marker div>img{width:40px;height:40px}} .dune-page-marker .world-network-art{display:block;width:100%!important;height:62px!important;object-fit:contain;margin:0 auto 3px} .dune-page-marker .world-status h2{font:700 10px/1.4 system-ui!important;text-transform:uppercase;letter-spacing:.14em;margin:2px 0 5px!important;color:#cbb37a} diff --git a/website/scripts/release-branding.mjs b/website/scripts/release-branding.mjs index d81ad489..cfbeae6e 100644 --- a/website/scripts/release-branding.mjs +++ b/website/scripts/release-branding.mjs @@ -1,3 +1,3 @@ -export const RELEASE_VERSION='1.0.1.0'; +export const RELEASE_VERSION='1.0.0.5'; export const RELEASE_CSS=`\n.dune-release-badge{display:block;width:max-content;max-width:100%;margin:5px auto 0;padding:4px 12px;border:1px solid #ba9952;border-radius:20px;background:linear-gradient(120deg,#102d25,#263c2a);color:#ead190;font:600 11px/1.4 system-ui,sans-serif;letter-spacing:.09em;text-align:center;white-space:nowrap;box-shadow:0 2px 8px #0003}.dune-release-badge::before{content:'✦';margin-right:6px;color:#cda64f}\n`; -export const RELEASE_SCRIPT=`\n(()=>{const stamp=()=>{const brand=document.querySelector('.dune-site-header .wordmark');if(!brand)return false;if(!brand.querySelector('.dune-release-badge')){const badge=document.createElement('span');badge.className='dune-release-badge';badge.textContent='Alpha 1.0.1.0';brand.append(badge);}return true;};if(!stamp()){const observer=new MutationObserver(()=>{if(stamp())observer.disconnect();});observer.observe(document.documentElement,{childList:true,subtree:true});}})();\n`; +export const RELEASE_SCRIPT=`\n(()=>{const stamp=()=>{const brand=document.querySelector('.dune-site-header .wordmark');if(!brand)return false;if(!brand.querySelector('.dune-release-badge')){const badge=document.createElement('span');badge.className='dune-release-badge';badge.textContent='Alpha';brand.append(badge);fetch('/release.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(release=>{if(release&&release.stage==='alpha'&&/^\\d+(?:\\.\\d+){3}$/.test(release.version))badge.textContent='Alpha '+release.version;}).catch(()=>{});}return true;};if(!stamp()){const observer=new MutationObserver(()=>{if(stamp())observer.disconnect();});observer.observe(document.documentElement,{childList:true,subtree:true});}})();\n`; diff --git a/website/web/portal-navigation.js b/website/web/portal-navigation.js index 9d4fcead..fdb89dea 100644 --- a/website/web/portal-navigation.js +++ b/website/web/portal-navigation.js @@ -7,7 +7,7 @@ const name=host==='forums.dunerealms.com'?'Boards':host==='support.dunerealms.com'?'Support center':host==='clans.dunerealms.com'?'Clan center':host==='cp.dunerealms.com'?(url.hash==='#exchange'?'Exchange':url.hash==='#tickets'?'Support center':url.hash==='#forum-admin'?'Boards':'Account center'):/\/(manual|wiki)\.html$/.test(url.pathname)?'Manual/wiki':/\/staff\.html$/.test(url.pathname)?'Staff roster':/\/discord\.html$/.test(url.pathname)?'Discord':/\/exchange\.html$/.test(url.pathname)?'Exchange':['/','/index.html'].includes(url.pathname)?'Home':null; const link=links.find(x=>x[0]===name); return !link?{label:typeof document!=='undefined'?(document.querySelector('h1')?.textContent.trim()||'Field guide'):'Field guide',icon:'nav-manual-full-v2.webp'}:{label:link[0],icon:link[2].replace('-v2.webp','-full-v2.webp')}; -};let welcomeName='traveller';fetch('https://cp.dunerealms.com/api/welcome',{credentials:'include',cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(typeof data?.username==='string'&&data.username.length<=32){welcomeName=data.username;render();}}).catch(()=>{});function render(){if(location.hostname==='support.dunerealms.com')document.body.classList.add('dune-support');const item=choose(location.href,links);let worlds=document.querySelector('.world-status');if(!worlds){worlds=document.createElement('aside');worlds.className='world-status';worlds.setAttribute('aria-label','Live server status');const heading=document.createElement('h2');heading.textContent='Worlds online';const list=document.createElement('ul');list.className='world-status-list';const note=document.createElement('p');note.className='world-status-note';note.textContent='Checking the caravan network…';worlds.append(heading,list,note);}worlds.remove();document.querySelector('.dune-page-marker')?.remove();if(!item)return;const header=document.querySelector('.dune-site-header');if(!header)return;const panel=document.createElement('section');panel.className='dune-page-marker';panel.setAttribute('aria-label','Welcome to '+item.label);const image=document.createElement('img');image.src='https://www.dunerealms.com/assets/'+item.icon;image.alt='';image.width=160;image.height=160;const text=document.createElement('div'),small=document.createElement('small'),title=document.createElement('p');small.textContent='THE CARAVAN GUIDE';title.textContent='Welcome, '+welcomeName+', to the '+item.label+'.';const lore=document.createElement('small');const quotes={Home:['The caravan gathers here; the latest word travels with the wind.','Rest beneath our banners and hear what stirs beyond the dunes.','Every journey begins with news from the road.'],Boards:['A shared tale can light the way for another traveller.','Trade your stories beneath the awning; every voice has a place.','Listen well: the quietest traveller may know the safest passage.'],Exchange:['Weigh your Dunemarks carefully; a fair bargain outlasts a fortune.','Count the coin, inspect the wares, and leave with honour.','Even in a sea of sand, a good bargain is worth finding.'],Discord:['Tune to the caravan frequency; familiar voices shorten the crossing.','Across the dunes, a friendly voice is its own shelter.','The signal is clear. Join the conversation beyond the horizon.'],'Manual/wiki':['A well-read field guide saves more water than a hurried journey.','Learn the trail before you challenge the dunes.','Turn the page; knowledge is the lightest provision you can carry.'],'Staff roster':['A watchful crew keeps the caravan moving.','Every banner is stronger with a trusted hand behind it.','Meet the keepers of the caravan and the worlds beyond.'],'Support center':['Set down your burden; the caravan clerks are here to help.','A troubled journey deserves a patient listener.','Bring us the details, and we will help find the next step.'],'Account center':['Your journey has a place in the caravan ledger.','Keep your records in order and your next crossing within reach.','Behind every banner stands a traveller with a story of their own.'],'Clan center':['Raise your banner; the strongest caravan travels together.','Choose your companions well, and no horizon is too distant.','A shared purpose binds a clan more firmly than any crest.']};const choices=quotes[item.label]||['May your water last and your journey bring good fortune.'];const key=location.hostname+location.pathname+location.hash;let seed=0;for(const character of key)seed=(seed*31+character.charCodeAt(0))>>>0;lore.textContent=choices[seed%choices.length];text.append(lore);const npc=document.createElement('img');npc.src='https://www.dunerealms.com/assets/nav-account-v2.webp';npc.alt='Caravan guide';npc.style.cssText='width:48px;height:48px;object-fit:contain';text.prepend(npc);text.append(small,title);if(worlds&&!worlds.querySelector('.dune-join-box')){const join=document.createElement('div');join.className='dune-join-box';const address=document.createElement('code');address.textContent='play.dunerealms.com';const button=document.createElement('button');button.type='button';button.textContent='Join now';button.setAttribute('aria-label','Join now: copy Minecraft server address');const help=document.createElement('p');help.className='dune-join-help';help.textContent='Java & Bedrock · copy the server address';help.setAttribute('role','status');button.addEventListener('click',async()=>{try{await navigator.clipboard.writeText('play.dunerealms.com');button.textContent='Copied ✓';help.textContent='Address copied · choose Add Server in Java or Bedrock.';}catch{help.textContent='In Minecraft Java, add a server with address play.dunerealms.com.';}});const ports=document.createElement('div');ports.className='dune-join-ports';for(const [edition,port]of [['Bedrock','19132'],['Java','25565']]){const box=document.createElement('span'),label=document.createElement('small'),value=document.createElement('code');label.textContent=edition+' port';value.textContent=port;const icon=document.createElement('img');icon.className='edition-icon';icon.alt='';icon.width=12;icon.height=12;icon.src='https://www.dunerealms.com/assets/edition-'+(edition==='Java'?'java':'bedrock')+'.svg';box.append(icon,label,value);ports.append(box);}join.append(address,button,ports,help);worlds.append(join);}if(worlds&&!worlds.querySelector('.world-network-art')){worlds.querySelector('.eyebrow')?.remove();const plate=document.createElement('img');plate.className='world-network-art';plate.src='https://www.dunerealms.com/assets/vaerkring-network-title-v1.webp';plate.alt='Vaerkring Network';plate.width=280;plate.height=80;worlds.prepend(plate);}panel.append(image,text);if(worlds)panel.append(worlds);header.after(panel);if(!document.querySelector('.dune-shared-footer')){const old=document.querySelector('body>footer,.site-footer'),foot=old||document.createElement('footer');foot.className='dune-shared-footer';foot.replaceChildren();const brand=document.createElement('a');brand.href='https://www.dunerealms.com/';brand.textContent='✦ dunerealms.com';brand.className='dune-footer-brand';const links=document.createElement('nav');links.setAttribute('aria-label','Footer navigation');for(const [label,href]of [['Manual/wiki','https://wiki.dunerealms.com/'],['Support','https://support.dunerealms.com/'],['Account','https://cp.dunerealms.com/'],['Disclaimer & contact','https://www.dunerealms.com/wiki.html']]){const a=document.createElement('a');a.textContent=label;a.href=href;links.append(a);}const note=document.createElement('small');note.textContent='Independent fan project · Not affiliated with Dune rights holders, Mojang or Microsoft.';foot.append(brand,links);const host=document.createElement('a');host.className='dune-hosting-badge';host.href='https://www.hetzner.com/';host.target='_blank';host.rel='noopener noreferrer';host.setAttribute('aria-label','Powered by Hetzner — visit Hetzner');const server=document.createElement('span');server.className='dune-hosting-art';server.textContent='▤';server.setAttribute('aria-hidden','true');const hostText=document.createElement('span');const powered=document.createElement('span');powered.textContent='POWERED BY';const hostLogo=document.createElement('img');hostLogo.src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODEuNDIgMjIuMjQiPjxkZWZzPjxzdHlsZT4uY2xzLTF7ZmlsbDojZDUwYzJkO308L3N0eWxlPjwvZGVmcz48dGl0bGU+RWxlbWVudCAxPC90aXRsZT48ZyBpZD0iRWJlbmVfMiIgZGF0YS1uYW1lPSJFYmVuZSAyIj48ZyBpZD0iTG9nb19QdXIiIGRhdGEtbmFtZT0iTG9nbyBQdXIiPjxnIGlkPSJMb2dvIj48ZyBpZD0iSEVUWk5FUiI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTc0LjA1LDE0LjEyYTEwLjIyLDEwLjIyLDAsMCwwLDQuNTMtMmwwLDBhNi4xNSw2LjE1LDAsMCwwLDEuNjgtNC43OCw3LjcxLDcuNzEsMCwwLDAtMS4xNC00LjA2QTYuNDcsNi40NywwLDAsMCwxNzMuODQuMDlsLTEuMDksMEwxNzAuMiwwLDE1OC42NiwwYy0uNywwLTEsLjI5LTEsMVYyMS4yMmMwLC43LjI5LDEsMSwxaDNjLjcsMCwxLS4yOSwxLTF2LTYuN2gzLjY3YTMuNDgsMy40OCwwLDAsMSwyLjE3LjkxbDUuODIsNS44NWEzLjA4LDMuMDgsMCwwLDAsMiwuOTJoNC40N2MuNywwLC44Ny0uNDEuMzgtLjkxWm0tLjc2LTQuM0gxNjIuNjRWNC43MmgxMC42NWEyLjEzLDIuMTMsMCwwLDEsMS44NywyLjE1di43OUEyLjE0LDIuMTQsMCwwLDEsMTczLjI5LDkuODJaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTUzLDE3LjUySDEzNi40N1YxMy4zNWgxMy4xOWMuNywwLDEtLjI5LDEtMVY5LjkyYzAtLjctLjI5LTEtMS0xaC0xMy4yVjQuNzZIMTUzYy43LDAsMS0uMjksMS0xVjFjMC0uNy0uMjktMS0xLTFIMTMyLjM4Yy0uNywwLTEsLjI5LTEsMVYyMS4yNGMwLC43LjI5LDEsMSwxSDE1M2MuNywwLDEtLjI5LDEtMVYxOC41MUMxNTQsMTcuODEsMTUzLjY3LDE3LjUyLDE1MywxNy41MloiLz48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik0xMjcuNzMsNy4zYTcuMjUsNy4yNSwwLDAsMC0xLjEzLTRBNi42MSw2LjYxLDAsMCwwLDEyMS4yNCwwTDEwNi4wOCwwYy0uNzEsMC0xLC4yOS0xLDFWMjEuMjJjMCwuNy4yOSwxLDEsMWgzLjI2Yy43LDAsMS0uMjgsMS0xVjQuNzNsOC43OCwwYzEuODcsMCwzLjY5LDEuMjQsMy42OSwzLjExVjIxLjI0YzAsLjcuMjksMSwxLDFoMi45NWMuNzEsMCwxLS4yOSwxLTFaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTAwLjQ3LDE3LjM5bC0xNC4yNSwwTDEwMC41LDQuODRhMi41NywyLjU3LDAsMCwwLDEtMS44NFYxYzAtLjctLjMtMS0xLTFINzkuODNjLS43LDAtMSwuMjktMSwxVjMuNzdjMCwuNy4yOSwxLDEsMUg5My4wOEw3OS43OSwxNy4yNGEyLjYyLDIuNjIsMCwwLDAtMSwxLjg0djIuMTdjMCwuNy4yOSwxLDEsMWwyMC42NSwwYy43LDAsMS0uMjksMS0xVjE4LjM4QzEwMS40NiwxNy42OCwxMDEuMTcsMTcuMzksMTAwLjQ3LDE3LjM5WiIvPjxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTc0LjE5LDBINTMuNTVjLS43MSwwLTEsLjI4LTEsMVYzLjc2YzAsLjcuMjgsMSwxLDFoNy43OFYyMS4yNGMwLC43LjI5LDEsMSwxaDMuM2MuNywwLDEtLjI5LDEtMVY0Ljc1aDcuNTdjLjcsMCwxLS4yOSwxLTFWMUM3NS4xOC4zMiw3NC44OSwwLDc0LjE5LDBaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDcuOTEsMTcuNTJIMzEuNDFWMTMuMzVINDQuNmMuNywwLDEtLjI5LDEtMVY5LjkyYzAtLjctLjI4LTEtMS0xSDMxLjQxVjQuNzZoMTYuNWMuNywwLDEtLjI5LDEtMVYxYzAtLjctLjI5LTEtMS0xSDI3LjMzYy0uNywwLTEsLjI5LTEsMVYyMS4yNGMwLC43LjI5LDEsMSwxSDQ3LjkxYy43LDAsMS0uMjksMS0xVjE4LjUxQzQ4LjksMTcuODEsNDguNjEsMTcuNTIsNDcuOTEsMTcuNTJaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMjEuNjMsMEgxOC41MmMtLjcsMC0xLC4yOS0xLDFWOC44N0g1LjEzVjFjMC0uNy0uMjktMS0xLTFIMUMuMjksMCwwLC4yOSwwLDFWMjEuMjVjMCwuNzEuMjksMSwxLDFINC4xM2MuNywwLDEtLjI4LDEtMXYtOGgxMi40djhjMCwuNy4yOSwxLDEsMWgzLjExYy43LDAsMS0uMjksMS0xVjFDMjIuNjIuMzIsMjIuMzMsMCwyMS42MywwWiIvPjwvZz48L2c+PC9nPjwvZz48L3N2Zz4=";hostLogo.alt='Hetzner';hostLogo.width=120;hostLogo.height=20;hostText.append(powered,hostLogo);host.append(server,hostText);host.title='Hosting infrastructure · Logo: Hetzner Online GmbH';foot.append(host);foot.append(note);const legal=document.querySelector('.legal-notice');if(legal){const details=document.createElement('details'),summary=document.createElement('summary');summary.textContent='Unofficial fan project';details.className='dune-footer-legal';details.append(summary,legal);foot.append(details);}if(['www.dunerealms.com','dunerealms.com'].includes(location.hostname)&&['/','/index.html'].includes(location.pathname)){const box=document.createElement('div');box.className='dune-footer-parental';const heading=document.createElement('strong');heading.textContent='Parents & guardians';const copy=document.createElement('span');copy.textContent='Parental consent or a child’s account-data request? Contact our support team.';const link=document.createElement('a');link.href='https://support.dunerealms.com/open.php';link.textContent='Parental help →';box.append(heading,copy,link);foot.append(box);}if(!old)document.body.append(foot);}const pin=()=>document.documentElement.style.setProperty('--dune-nav-height',header.getBoundingClientRect().height+'px');pin();if(!header.dataset.pinObserved){new ResizeObserver(pin).observe(header);header.dataset.pinObserved='1';}}render();async function refreshWorlds(){try{const response=await fetch('https://www.dunerealms.com/api/worlds',{cache:'no-store',credentials:'omit',signal:AbortSignal.timeout(7000)});if(!response.ok)throw Error();const data=await response.json(),panel=document.querySelector('.dune-page-marker .world-status');if(!panel)return;const list=panel.querySelector('.world-status-list');list.replaceChildren();const glyphs={Arrakduin:'serevan',Kaladam:'pelareth',Giedermark:'varkesh',Kaiterhof:'orivane','Sigmadraken IV':'nivareth'};list.setAttribute('role','table');list.setAttribute('aria-label','World and connection status');for(const server of data.servers){const row=document.createElement('li'),name=document.createElement('span'),state=document.createElement('span'),icon=document.createElement('img');const display=server.name==='Velocity'?'Proxi':server.name;row.setAttribute('role','row');name.setAttribute('role','cell');name.className='world-name';name.title=display;icon.alt='';icon.width=14;icon.height=14;icon.src=glyphs[server.name]?'https://www.dunerealms.com/assets/planet-glyphs/'+glyphs[server.name]+'.svg':server.name==='Velocity'?'https://www.dunerealms.com/assets/network-proxy.svg':'https://www.dunerealms.com/assets/nav-home-v2.webp';name.append(icon,document.createTextNode(display));const status=server.state==='online'?'Online':server.state==='offline'?'Offline':'Unknown';state.setAttribute('role','cell');state.setAttribute('aria-label',status);state.title=status;state.className='world-state traffic-light '+server.state;for(const color of ['red','amber','green']){const lamp=document.createElement('i');lamp.className='lamp-'+color;lamp.setAttribute('aria-hidden','true');state.append(lamp);}row.append(name,state);list.append(row);}panel.querySelector('.world-status-note').textContent=data.available?'Live check · updates every 30s':'Status check unavailable';}catch{const note=document.querySelector('.dune-page-marker .world-status-note');if(note)note.textContent='Status check unavailable · retrying';}}refreshWorlds();setInterval(()=>{if(!document.hidden)refreshWorlds();},30000);addEventListener('hashchange',()=>{render();refreshWorlds();});})(); +};let welcomeName='traveller';fetch('https://cp.dunerealms.com/api/welcome',{credentials:'include',cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(typeof data?.username==='string'&&data.username.length<=32){welcomeName=data.username;render();}}).catch(()=>{});function render(){if(location.hostname==='support.dunerealms.com')document.body.classList.add('dune-support');const item=choose(location.href,links);let worlds=document.querySelector('.world-status');if(!worlds){worlds=document.createElement('aside');worlds.className='world-status';worlds.setAttribute('aria-label','Live server status');const heading=document.createElement('h2');heading.textContent='Worlds online';const list=document.createElement('ul');list.className='world-status-list';const note=document.createElement('p');note.className='world-status-note';note.textContent='Checking the caravan network…';worlds.append(heading,list,note);}worlds.remove();document.querySelector('.dune-page-marker')?.remove();if(!item)return;const header=document.querySelector('.dune-site-header');if(!header)return;const panel=document.createElement('section');panel.className='dune-page-marker';panel.setAttribute('aria-label','Welcome to '+item.label);const image=document.createElement('img');image.src='https://www.dunerealms.com/assets/'+item.icon;image.alt='';image.width=160;image.height=160;const text=document.createElement('div'),small=document.createElement('small'),title=document.createElement('p');small.textContent='THE CARAVAN GUIDE';title.textContent='Welcome, '+welcomeName+', to the '+item.label+'.';const lore=document.createElement('small');const quotes={Home:['The caravan gathers here; the latest word travels with the wind.','Rest beneath our banners and hear what stirs beyond the dunes.','Every journey begins with news from the road.'],Boards:['A shared tale can light the way for another traveller.','Trade your stories beneath the awning; every voice has a place.','Listen well: the quietest traveller may know the safest passage.'],Exchange:['Weigh your Dunemarks carefully; a fair bargain outlasts a fortune.','Count the coin, inspect the wares, and leave with honour.','Even in a sea of sand, a good bargain is worth finding.'],Discord:['Tune to the caravan frequency; familiar voices shorten the crossing.','Across the dunes, a friendly voice is its own shelter.','The signal is clear. Join the conversation beyond the horizon.'],'Manual/wiki':['A well-read field guide saves more water than a hurried journey.','Learn the trail before you challenge the dunes.','Turn the page; knowledge is the lightest provision you can carry.'],'Staff roster':['A watchful crew keeps the caravan moving.','Every banner is stronger with a trusted hand behind it.','Meet the keepers of the caravan and the worlds beyond.'],'Support center':['Set down your burden; the caravan clerks are here to help.','A troubled journey deserves a patient listener.','Bring us the details, and we will help find the next step.'],'Account center':['Your journey has a place in the caravan ledger.','Keep your records in order and your next crossing within reach.','Behind every banner stands a traveller with a story of their own.'],'Clan center':['Raise your banner; the strongest caravan travels together.','Choose your companions well, and no horizon is too distant.','A shared purpose binds a clan more firmly than any crest.']};const choices=quotes[item.label]||['May your water last and your journey bring good fortune.'];const key=location.hostname+location.pathname+location.hash;let seed=0;for(const character of key)seed=(seed*31+character.charCodeAt(0))>>>0;lore.textContent=choices[seed%choices.length];text.append(lore);const npc=document.createElement('img');npc.src='https://www.dunerealms.com/assets/nav-account-v2.webp';npc.alt='Caravan guide';npc.style.cssText='width:48px;height:48px;object-fit:contain';text.prepend(npc);text.append(small,title);if(worlds&&!worlds.querySelector('.dune-join-box')){const join=document.createElement('div');join.className='dune-join-box';const address=document.createElement('code');address.textContent='play.dunerealms.com';const button=document.createElement('button');button.type='button';button.textContent='Join now';button.setAttribute('aria-label','Join now: copy Minecraft server address');const help=document.createElement('p');help.className='dune-join-help';help.textContent='Java & Bedrock · copy the server address';help.setAttribute('role','status');button.addEventListener('click',async()=>{try{await navigator.clipboard.writeText('play.dunerealms.com');button.textContent='Copied ✓';help.textContent='Address copied · choose Add Server in Java or Bedrock.';}catch{help.textContent='In Minecraft Java, add a server with address play.dunerealms.com.';}});const ports=document.createElement('div');ports.className='dune-join-ports';for(const [edition,port]of [['Bedrock','19132'],['Java','25565']]){const box=document.createElement('span'),label=document.createElement('small'),value=document.createElement('code');label.textContent=edition+' port';value.textContent=port;const icon=document.createElement('img');icon.className='edition-icon';icon.alt='';icon.width=12;icon.height=12;icon.src='https://www.dunerealms.com/assets/edition-'+(edition==='Java'?'java':'bedrock')+'.svg';box.append(icon,label,value);ports.append(box);}join.append(address,button,ports,help);worlds.append(join);}if(worlds&&!worlds.querySelector('.world-network-art')){worlds.querySelector('.eyebrow')?.remove();const plate=document.createElement('img');plate.className='world-network-art';plate.src='https://www.dunerealms.com/assets/vaerkring-network-title-v1.webp';plate.alt='Vaerkring Network';plate.width=280;plate.height=80;worlds.prepend(plate);}panel.append(image,text);if(worlds)panel.append(worlds);header.after(panel);if(!document.querySelector('.dune-shared-footer')){const old=document.querySelector('body>footer,.site-footer'),foot=old||document.createElement('footer');foot.className='dune-shared-footer';foot.replaceChildren();const brand=document.createElement('a');brand.href='https://www.dunerealms.com/';brand.textContent='✦ dunerealms.com';brand.className='dune-footer-brand';const links=document.createElement('nav');links.setAttribute('aria-label','Footer navigation');for(const [label,href]of [['Manual/wiki','https://wiki.dunerealms.com/'],['Support','https://support.dunerealms.com/'],['Account','https://cp.dunerealms.com/'],['Disclaimer & contact','https://www.dunerealms.com/wiki.html']]){const a=document.createElement('a');a.textContent=label;a.href=href;links.append(a);}const note=document.createElement('small');note.textContent='Independent fan project · Not affiliated with Dune rights holders, Mojang or Microsoft.';foot.append(brand,links);const host=document.createElement('a');host.className='dune-hosting-badge';host.href='https://www.hetzner.com/';host.target='_blank';host.rel='noopener noreferrer';host.setAttribute('aria-label','Powered by Hetzner — visit Hetzner');const server=document.createElement('span');server.className='dune-hosting-art';server.textContent='▤';server.setAttribute('aria-hidden','true');const hostText=document.createElement('span');const powered=document.createElement('span');powered.textContent='POWERED BY';const hostLogo=document.createElement('img');hostLogo.src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODEuNDIgMjIuMjQiPjxkZWZzPjxzdHlsZT4uY2xzLTF7ZmlsbDojZDUwYzJkO308L3N0eWxlPjwvZGVmcz48dGl0bGU+RWxlbWVudCAxPC90aXRsZT48ZyBpZD0iRWJlbmVfMiIgZGF0YS1uYW1lPSJFYmVuZSAyIj48ZyBpZD0iTG9nb19QdXIiIGRhdGEtbmFtZT0iTG9nbyBQdXIiPjxnIGlkPSJMb2dvIj48ZyBpZD0iSEVUWk5FUiI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTc0LjA1LDE0LjEyYTEwLjIyLDEwLjIyLDAsMCwwLDQuNTMtMmwwLDBhNi4xNSw2LjE1LDAsMCwwLDEuNjgtNC43OCw3LjcxLDcuNzEsMCwwLDAtMS4xNC00LjA2QTYuNDcsNi40NywwLDAsMCwxNzMuODQuMDlsLTEuMDksMEwxNzAuMiwwLDE1OC42NiwwYy0uNywwLTEsLjI5LTEsMVYyMS4yMmMwLC43LjI5LDEsMSwxaDNjLjcsMCwxLS4yOSwxLTF2LTYuN2gzLjY3YTMuNDgsMy40OCwwLDAsMSwyLjE3LjkxbDUuODIsNS44NWEzLjA4LDMuMDgsMCwwLDAsMiwuOTJoNC40N2MuNywwLC44Ny0uNDEuMzgtLjkxWm0tLjc2LTQuM0gxNjIuNjRWNC43MmgxMC42NWEyLjEzLDIuMTMsMCwwLDEsMS44NywyLjE1di43OUEyLjE0LDIuMTQsMCwwLDEsMTczLjI5LDkuODJaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTUzLDE3LjUySDEzNi40N1YxMy4zNWgxMy4xOWMuNywwLDEtLjI5LDEtMVY5LjkyYzAtLjctLjI5LTEtMS0xaC0xMy4yVjQuNzZIMTUzYy43LDAsMS0uMjksMS0xVjFjMC0uNy0uMjktMS0xLTFIMTMyLjM4Yy0uNywwLTEsLjI5LTEsMVYyMS4yNGMwLC43LjI5LDEsMSwxSDE1M2MuNywwLDEtLjI5LDEtMVYxOC41MUMxNTQsMTcuODEsMTUzLjY3LDE3LjUyLDE1MywxNy41MloiLz48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik0xMjcuNzMsNy4zYTcuMjUsNy4yNSwwLDAsMC0xLjEzLTRBNi42MSw2LjYxLDAsMCwwLDEyMS4yNCwwTDEwNi4wOCwwYy0uNzEsMC0xLC4yOS0xLDFWMjEuMjJjMCwuNy4yOSwxLDEsMWgzLjI2Yy43LDAsMS0uMjgsMS0xVjQuNzNsOC43OCwwYzEuODcsMCwzLjY5LDEuMjQsMy42OSwzLjExVjIxLjI0YzAsLjcuMjksMSwxLDFoMi45NWMuNzEsMCwxLS4yOSwxLTFaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTAwLjQ3LDE3LjM5bC0xNC4yNSwwTDEwMC41LDQuODRhMi41NywyLjU3LDAsMCwwLDEtMS44NFYxYzAtLjctLjMtMS0xLTFINzkuODNjLS43LDAtMSwuMjktMSwxVjMuNzdjMCwuNy4yOSwxLDEsMUg5My4wOEw3OS43OSwxNy4yNGEyLjYyLDIuNjIsMCwwLDAtMSwxLjg0djIuMTdjMCwuNy4yOSwxLDEsMWwyMC42NSwwYy43LDAsMS0uMjksMS0xVjE4LjM4QzEwMS40NiwxNy42OCwxMDEuMTcsMTcuMzksMTAwLjQ3LDE3LjM5WiIvPjxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTc0LjE5LDBINTMuNTVjLS43MSwwLTEsLjI4LTEsMVYzLjc2YzAsLjcuMjgsMSwxLDFoNy43OFYyMS4yNGMwLC43LjI5LDEsMSwxaDMuM2MuNywwLDEtLjI5LDEtMVY0Ljc1aDcuNTdjLjcsMCwxLS4yOSwxLTFWMUM3NS4xOC4zMiw3NC44OSwwLDc0LjE5LDBaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDcuOTEsMTcuNTJIMzEuNDFWMTMuMzVINDQuNmMuNywwLDEtLjI5LDEtMVY5LjkyYzAtLjctLjI4LTEtMS0xSDMxLjQxVjQuNzZoMTYuNWMuNywwLDEtLjI5LDEtMVYxYzAtLjctLjI5LTEtMS0xSDI3LjMzYy0uNywwLTEsLjI5LTEsMVYyMS4yNGMwLC43LjI5LDEsMSwxSDQ3LjkxYy43LDAsMS0uMjksMS0xVjE4LjUxQzQ4LjksMTcuODEsNDguNjEsMTcuNTIsNDcuOTEsMTcuNTJaIi8+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMjEuNjMsMEgxOC41MmMtLjcsMC0xLC4yOS0xLDFWOC44N0g1LjEzVjFjMC0uNy0uMjktMS0xLTFIMUMuMjksMCwwLC4yOSwwLDFWMjEuMjVjMCwuNzEuMjksMSwxLDFINC4xM2MuNywwLDEtLjI4LDEtMXYtOGgxMi40djhjMCwuNy4yOSwxLDEsMWgzLjExYy43LDAsMS0uMjksMS0xVjFDMjIuNjIuMzIsMjIuMzMsMCwyMS42MywwWiIvPjwvZz48L2c+PC9nPjwvZz48L3N2Zz4=";hostLogo.alt='Hetzner';hostLogo.width=120;hostLogo.height=20;hostText.append(powered,hostLogo);host.append(server,hostText);host.title='Hosting infrastructure · Logo: Hetzner Online GmbH';foot.append(host);foot.append(note);const legal=document.querySelector('.legal-notice');if(legal){const details=document.createElement('details'),summary=document.createElement('summary');summary.textContent='Unofficial fan project';details.className='dune-footer-legal';details.append(summary,legal);foot.append(details);}if(['www.dunerealms.com','dunerealms.com'].includes(location.hostname)&&['/','/index.html'].includes(location.pathname)){const box=document.createElement('div');box.className='dune-footer-parental';const heading=document.createElement('strong');heading.textContent='Parents & guardians';const copy=document.createElement('span');copy.textContent='Parental consent or a child’s account-data request? Contact our support team.';const link=document.createElement('a');link.href='https://support.dunerealms.com/open.php';link.textContent='Parental help →';box.append(heading,copy,link);foot.append(box);}if(!old)document.body.append(foot);}const pin=()=>document.documentElement.style.setProperty('--dune-nav-height',header.getBoundingClientRect().height+'px');pin();if(!header.dataset.pinObserved){new ResizeObserver(pin).observe(header);header.dataset.pinObserved='1';}}render();async function refreshWorlds(){try{const response=await fetch('/api/worlds',{cache:'no-store',credentials:'omit',signal:AbortSignal.timeout(7000)});if(!response.ok)throw Error();const data=await response.json(),panel=document.querySelector('.dune-page-marker .world-status');if(!panel)return;const list=panel.querySelector('.world-status-list');list.replaceChildren();const glyphs={Arrakduin:'serevan',Kaladam:'pelareth',Giedermark:'varkesh',Kaiterhof:'orivane','Sigmadraken IV':'nivareth'};list.setAttribute('role','table');list.setAttribute('aria-label','World and connection status');for(const server of data.servers){const row=document.createElement('li'),name=document.createElement('span'),state=document.createElement('span'),icon=document.createElement('img');const display=server.name==='Velocity'?'Proxi':server.name;row.setAttribute('role','row');name.setAttribute('role','cell');name.className='world-name';name.title=display;icon.alt='';icon.width=14;icon.height=14;icon.src=glyphs[server.name]?'https://www.dunerealms.com/assets/planet-glyphs/'+glyphs[server.name]+'.svg':server.name==='Velocity'?'https://www.dunerealms.com/assets/network-proxy.svg':'https://www.dunerealms.com/assets/nav-home-v2.webp';name.append(icon,document.createTextNode(display));const status=server.state==='online'?'Online':server.state==='offline'?'Offline':'Unknown';state.setAttribute('role','cell');state.setAttribute('aria-label',status);state.title=status;state.className='world-state traffic-light '+server.state;for(const color of ['red','amber','green']){const lamp=document.createElement('i');lamp.className='lamp-'+color;lamp.setAttribute('aria-hidden','true');state.append(lamp);}row.append(name,state);list.append(row);}panel.querySelector('.world-status-note').textContent=data.available?'Live check · updates every 30s':'Status check unavailable';}catch{const note=document.querySelector('.dune-page-marker .world-status-note');if(note)note.textContent='Status check unavailable · retrying';}}refreshWorlds();setInterval(()=>{if(!document.hidden)refreshWorlds();},30000);addEventListener('hashchange',()=>{render();refreshWorlds();});})(); /* DuneRealms action system v1 */ (()=>{ const selector='button,input[type=submit],input[type=button],input[type=reset],a.button,a.btn,a.action-button,[role=button],.ui.button,.cp-area-tabs>button,.tabs>a,.git-control-actions>a,.exchange-actions>a'; @@ -28,7 +28,7 @@ window.addEventListener('hashchange',()=>scan(document)); })(); -(()=>{const stamp=()=>{const brand=document.querySelector('.dune-site-header .wordmark');if(!brand)return false;if(!brand.querySelector('.dune-release-badge')){const badge=document.createElement('span');badge.className='dune-release-badge';badge.textContent='Alpha';brand.append(badge);fetch('https://www.dunerealms.com/release.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(release=>{if(release&&release.stage==='alpha'&&/^\d+(?:\.\d+){3}$/.test(release.version))badge.textContent='Alpha '+release.version;}).catch(()=>{});}return true;};if(!stamp()){const observer=new MutationObserver(()=>{if(stamp())observer.disconnect();});observer.observe(document.documentElement,{childList:true,subtree:true});}})(); +(()=>{const stamp=()=>{const brand=document.querySelector('.dune-site-header .wordmark');if(!brand)return false;if(!brand.querySelector('.dune-release-badge')){const badge=document.createElement('span');badge.className='dune-release-badge';badge.textContent='Alpha';brand.append(badge);fetch('/release.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(release=>{if(release&&release.stage==='alpha'&&/^\d+(?:\.\d+){3}$/.test(release.version))badge.textContent='Alpha '+release.version;}).catch(()=>{});}return true;};if(!stamp()){const observer=new MutationObserver(()=>{if(stamp())observer.disconnect();});observer.observe(document.documentElement,{childList:true,subtree:true});}})(); /* Unified main menu Shop v1 */ (()=>{const update=()=>{for(const nav of document.querySelectorAll('header nav[aria-label="Main navigation"]')){if(nav.querySelector('a[data-dune-shop],a[href="https://www.dunerealms.com/shop.html"]'))continue;const a=document.createElement('a');a.href='https://www.dunerealms.com/shop.html';a.dataset.duneShop='1';const i=document.createElement('img');i.src='https://www.dunerealms.com/assets/nav-exchange-v2.webp';i.alt='';i.width=34;i.height=34;const t=document.createElement('span');t.textContent='Shop';a.append(i,t);const exchange=[...nav.querySelectorAll('a')].find(a=>a.textContent.trim()==='Exchange'||a.textContent.trim()==='Exchange');if(exchange)exchange.after(a);else nav.append(a);}};update();new MutationObserver(update).observe(document.body,{childList:true,subtree:true});})(); @@ -62,4 +62,4 @@ (()=>{function sync(){const nav=document.querySelector('.dune-shared-footer nav');if(!nav||nav.querySelector('[data-bank-rates]'))return;const a=document.createElement('a');a.dataset.bankRates='1';a.href='https://www.dunerealms.com/rates-and-charges.html';a.textContent='Rates & Charges';nav.append(a);}sync();new MutationObserver(sync).observe(document.body,{childList:true,subtree:true});})(); /* Central automatic release menu badges */ -(()=>{let items=[{"href":"https://cp.dunerealms.com/#shop","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://wiki.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://clans.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://cp.dunerealms.com/","badge":"NEW","updatedIn":"1.0.1.0","introducedIn":"1.0.1.0"},{"href":"https://cp.dunerealms.com/#exchange","updatedIn":"1.0.0.2","badge":"UPDATE"},{"href":"https://support.dunerealms.com/","updatedIn":"1.0.0.3","badge":"UPDATE"},{"href":"https://www.dunerealms.com/staff.html","updatedIn":"1.0.0.5","badge":"UPDATE"},{"href":"https://www.dunerealms.com/","badge":"NEW","introducedIn":"1.0.0.3","updatedIn":"1.0.0.3"},{"href":"https://www.dunerealms.com/shop.html","updatedIn":"1.0.0.5","badge":"UPDATE"},{"href":"https://www.dunerealms.com/kits.html","introducedIn":"1.0.0.5","badge":"NEW"},{"href":"https://cp.dunerealms.com/#kits-exchange","introducedIn":"1.0.0.5","badge":"NEW"},{"href":"https://cp.dunerealms.com/#realm","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#bureau","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#forge","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#politics","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#post","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#bank","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#market","badge":"NEW","introducedIn":"v2-api"},{"href":"https://www.dunerealms.com/rates-and-charges.html","updatedIn":"1.0.1.0","badge":"UPDATE"}];function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\d+(?:\.\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://www.dunerealms.com/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})(); +(()=>{let items=[{"href":"https://cp.dunerealms.com/#shop","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://wiki.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://clans.dunerealms.com/","introducedIn":"1.0.0.2","badge":"NEW"},{"href":"https://cp.dunerealms.com/","badge":"NEW","updatedIn":"1.0.1.0","introducedIn":"1.0.1.0"},{"href":"https://cp.dunerealms.com/#exchange","updatedIn":"1.0.0.2","badge":"UPDATE"},{"href":"https://support.dunerealms.com/","updatedIn":"1.0.0.3","badge":"UPDATE"},{"href":"https://www.dunerealms.com/staff.html","updatedIn":"1.0.0.5","badge":"UPDATE"},{"href":"https://www.dunerealms.com/","badge":"NEW","introducedIn":"1.0.0.3","updatedIn":"1.0.0.3"},{"href":"https://www.dunerealms.com/shop.html","updatedIn":"1.0.0.5","badge":"UPDATE"},{"href":"https://www.dunerealms.com/kits.html","introducedIn":"1.0.0.5","badge":"NEW"},{"href":"https://cp.dunerealms.com/#kits-exchange","introducedIn":"1.0.0.5","badge":"NEW"},{"href":"https://cp.dunerealms.com/#realm","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#bureau","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#forge","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#politics","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#post","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#bank","badge":"NEW","introducedIn":"v2-api"},{"href":"https://cp.dunerealms.com/#market","badge":"NEW","introducedIn":"v2-api"},{"href":"https://www.dunerealms.com/rates-and-charges.html","updatedIn":"1.0.1.0","badge":"UPDATE"}];function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\d+(?:\.\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})(); diff --git a/website/web/release.json b/website/web/release.json index b8d692cb..859bb370 100644 --- a/website/web/release.json +++ b/website/web/release.json @@ -1,6 +1,6 @@ { - "version": "1.0.1.0", + "version": "1.0.0.5", "stage": "alpha", "updatedAt": "2026-11-13T00:06:04.014493+00:00", - "scope": "Control Panel V2. Existing services connected; unconnected services remain labelled as planned." + "scope": "Latest published Alpha release. Development batches are not a new published release." } From 9e400357b7de728fc804dbd740fe2809d68fbfc1 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:52:00 +0100 Subject: [PATCH 10/16] Generate publication badges from exact pushed commits in CI --- .forgejo/workflows/web-deploy.yml | 14 ++++++++++++++ website/scripts/menu-updates.mjs | 6 +++--- website/scripts/publication-changes.mjs | 17 +++++++++++++++++ website/tests/menu-updates.test.mjs | 2 ++ website/tests/publication-changes.test.mjs | 21 +++++++++++++++++++++ 5 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 website/scripts/publication-changes.mjs create mode 100644 website/tests/publication-changes.test.mjs diff --git a/.forgejo/workflows/web-deploy.yml b/.forgejo/workflows/web-deploy.yml index e4504d99..eb8f3e04 100644 --- a/.forgejo/workflows/web-deploy.yml +++ b/.forgejo/workflows/web-deploy.yml @@ -27,6 +27,20 @@ jobs: with: node-version: '22' + - name: Prepare publication comparison + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + BEFORE=$(node -e 'const fs=require("fs");const p=process.env.GITHUB_EVENT_PATH;const e=p&&fs.existsSync(p)?JSON.parse(fs.readFileSync(p)):{};process.stdout.write(e.before||"");') + if [[ ! "$BEFORE" =~ ^[0-9a-f]{40}$ || "$BEFORE" =~ ^0+$ ]]; then + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --deepen=1 https://www.dunerealms.com/git/unimatrix/MC.git "$GITHUB_SHA" + BEFORE=$(git rev-parse HEAD^) + else + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/MC.git "$BEFORE" + fi + node website/scripts/publication-changes.mjs "$BEFORE" "$GITHUB_SHA" + - name: Verify deployment policy run: node --test .forgejo/tests/web-deploy.test.mjs diff --git a/website/scripts/menu-updates.mjs b/website/scripts/menu-updates.mjs index c127501f..4452037f 100644 --- a/website/scripts/menu-updates.mjs +++ b/website/scripts/menu-updates.mjs @@ -1,6 +1,6 @@ -import{readFileSync,writeFileSync}from'node:fs';import{execFileSync}from'node:child_process';import{fileURLToPath}from'node:url';import path from'node:path';import{RELEASE_VERSION}from'./release-branding.mjs'; -export function pagesForChanges(paths){const pages=new Set();for(let p of paths){p=p.replaceAll('\\','/');if(/website\/node\/staff-roster\.mjs$/.test(p))pages.add('https://www.dunerealms.com/staff.html');if(/website\/node\/memorials\.mjs$|website\/node\/public\/memorial\./.test(p))pages.add('https://www.dunerealms.com/');if(/website\/control-panel\//.test(p)||/website\/node\/(auth|permissions|account-admin|account-archive|honours|profile)\.mjs$/.test(p))pages.add('https://cp.dunerealms.com/');if(/website\/integrations\/azuriom\//.test(p))pages.add('https://www.dunerealms.com/shop.html');if(/website\/integrations\/osticket\//.test(p))pages.add('https://support.dunerealms.com/');if(/website\/web\/([a-z-]+)\.html$/.test(p)){const name=p.match(/([^/]+)\.html$/)[1];pages.add('https://www.dunerealms.com/'+(['index','portal'].includes(name)?'':name+'.html'));}}return[...pages].sort();} -export function recordPageUpdates({root=fileURLToPath(new URL('../',import.meta.url)),paths,newPages=[],version=RELEASE_VERSION}={}){if(!/^\d+(?:\.\d+){3}$/.test(version))throw Error('Invalid release');const repo=path.resolve(root,'..');if(paths===undefined){let changed='';try{const gitRoot=execFileSync('git',['rev-parse','--show-toplevel'],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();if(path.resolve(gitRoot)===repo)changed=execFileSync('git',['diff','--name-only','HEAD'],{cwd:repo,encoding:'utf8'}).trim();}catch(error){if(error?.status!==128&&error?.status!==129&&error?.code!=='ENOENT')throw error;}paths=changed?changed.split('\n'):[];}const file=path.join(root,'web/menu-new-items.json'),data=JSON.parse(readFileSync(file,'utf8'));const pages=pagesForChanges(paths);if(paths.length){for(const item of data.items)delete item.badge;}for(const href of pages){let entry=data.items.find(x=>x.href===href);if(!entry){entry={href};data.items.push(entry);}entry.updatedIn=version;entry.badge=newPages.includes(href)?'NEW':'UPDATE';}writeFileSync(file,JSON.stringify(data,null,2)+'\n');return pages;} +import{existsSync,readFileSync,writeFileSync}from'node:fs';import{execFileSync}from'node:child_process';import{fileURLToPath}from'node:url';import path from'node:path';import{RELEASE_VERSION}from'./release-branding.mjs'; +export function pagesForChanges(paths){const pages=new Set();for(let p of paths){p=p.replaceAll('\\','/');if(!p.includes('/tests/')){const scopes=[[/postbank|bank-rates/,'bank'],[/politic|election|charter/,'politics'],[/internal-mail|mail-service|post-pages/,'post'],[/organisation-|citizen-directory|account-admin|honours|permissions/,'bureau'],[/forge-pages|dev-request|git-identity/,'forge'],[/exchange-public|commodity/,'market'],[/passport|personal-records|user-pages/,'realm']];for(const [pattern,scope]of scopes)if(pattern.test(p)){pages.add('https://cp.dunerealms.com/');pages.add('https://cp.dunerealms.com/#'+scope);}}if(/website\/node\/staff-roster\.mjs$/.test(p))pages.add('https://www.dunerealms.com/staff.html');if(/website\/node\/memorials\.mjs$|website\/node\/public\/memorial\./.test(p))pages.add('https://www.dunerealms.com/');if(/website\/control-panel\//.test(p)||/website\/node\/(auth|permissions|account-admin|account-archive|honours|profile)\.mjs$/.test(p))pages.add('https://cp.dunerealms.com/');if(/website\/integrations\/azuriom\//.test(p))pages.add('https://www.dunerealms.com/shop.html');if(/website\/integrations\/osticket\//.test(p))pages.add('https://support.dunerealms.com/');if(/website\/web\/([a-z-]+)\.html$/.test(p)){const name=p.match(/([^/]+)\.html$/)[1];pages.add('https://www.dunerealms.com/'+(['index','portal'].includes(name)?'':name+'.html'));}}return[...pages].sort();} +export function recordPageUpdates({root=fileURLToPath(new URL('../',import.meta.url)),paths,newPages=[],version=RELEASE_VERSION}={}){if(!/^\d+(?:\.\d+){3}$/.test(version))throw Error('Invalid release');const repo=path.resolve(root,'..');const publication=path.join(root,'publication-changes.json');if(paths===undefined&&existsSync(publication)){const change=JSON.parse(readFileSync(publication,'utf8'));if(!Array.isArray(change.paths)||!Array.isArray(change.added))throw Error('Invalid publication change record.');paths=change.paths;newPages=pagesForChanges(change.added).filter(href=>!href.startsWith('https://cp.dunerealms.com/'));}if(paths===undefined){let changed='';try{const gitRoot=execFileSync('git',['rev-parse','--show-toplevel'],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();if(path.resolve(gitRoot)===repo)changed=execFileSync('git',['diff','--name-only','HEAD'],{cwd:repo,encoding:'utf8'}).trim();}catch(error){if(error?.status!==128&&error?.status!==129&&error?.code!=='ENOENT')throw error;}paths=changed?changed.split('\n'):[];}const file=path.join(root,'web/menu-new-items.json'),data=JSON.parse(readFileSync(file,'utf8'));const pages=pagesForChanges(paths);if(paths.length||existsSync(publication)){for(const item of data.items)delete item.badge;}for(const href of pages){let entry=data.items.find(x=>x.href===href);if(!entry){entry={href};data.items.push(entry);}entry.updatedIn=version;entry.badge=newPages.includes(href)?'NEW':'UPDATE';}writeFileSync(file,JSON.stringify(data,null,2)+'\n');return pages;} export function menuBadgeScript(){const data=JSON.parse(readFileSync(new URL('../web/menu-new-items.json',import.meta.url),'utf8'));return `\n/* Central automatic release menu badges */\n(()=>{let items=${JSON.stringify(data.items)};function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\\d+(?:\\.\\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?'https://cp.dunerealms.com/#'+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('/menu-new-items.json',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})();\n`;} export function withMenuBadges(s){return s.replace(/\n?\/\* Central automatic release menu badges \*\/[\s\S]*?(?=\n\/\*|$)/,'').replace(/\(\(\)=>\{const items=\[[\s\S]*?new MutationObserver\(mark\)\.observe\(document.body,\{childList:true,subtree:true,characterData:true\}\);\}\)\(\);/,'')+menuBadgeScript();} export function patchMenuBadges(root=fileURLToPath(new URL('../',import.meta.url))){const file=path.join(root,'web/portal-navigation.js');writeFileSync(file,withMenuBadges(readFileSync(file,'utf8')));} diff --git a/website/scripts/publication-changes.mjs b/website/scripts/publication-changes.mjs new file mode 100644 index 00000000..7603da15 --- /dev/null +++ b/website/scripts/publication-changes.mjs @@ -0,0 +1,17 @@ +import {execFileSync} from 'node:child_process'; +import {readFileSync,writeFileSync} from 'node:fs'; +import {fileURLToPath} from 'node:url'; +import path from 'node:path'; +export function publicationChanges(repo,base,head='HEAD'){ + if(!/^[a-f0-9]{40}$/i.test(base)||!(/^[a-f0-9]{40}$/i.test(head)||head==='HEAD'))throw Error('Publication comparison requires exact commit IDs.'); + const raw=execFileSync('git',['diff','--name-status','--no-renames','-z',base,head],{cwd:repo,encoding:'utf8'}).split('\0'); + const paths=[],added=[]; + for(let i=0;i test('V2 workspace tiles use the shared manifest even with the simple Alpha header',()=>{const s=menuBadgeScript();assert(s.includes('#portals .portal[data-id]'));assert(s.includes("'https://cp.dunerealms.com/#'+a.dataset.id"));assert(!s.includes('if(!release)return'));new Function(s);}); test('New publication clears untouched badges and distinguishes a new page from an update',()=>{const repo=mkdtempSync(path.join(tmpdir(),'dune-badge-expiry-'));try{const root=path.join(repo,'website');mkdirSync(path.join(root,'web'),{recursive:true});const file=path.join(root,'web/menu-new-items.json');writeFileSync(file,JSON.stringify({items:[{href:'https://clans.dunerealms.com/',badge:'NEW'},{href:'https://www.dunerealms.com/staff.html',badge:'NEW',introducedIn:'1.0.0.4'}]}));recordPageUpdates({root,version:'1.0.0.4',paths:['website/node/staff-roster.mjs','website/web/rates-and-charges.html'],newPages:['https://www.dunerealms.com/rates-and-charges.html']});const items=JSON.parse(readFileSync(file)).items;assert.equal(items.find(x=>x.href==='https://clans.dunerealms.com/').badge,undefined);assert.equal(items.find(x=>x.href.endsWith('/staff.html')).badge,'UPDATE');assert.equal(items.find(x=>x.href.endsWith('/rates-and-charges.html')).badge,'NEW');}finally{rmSync(repo,{recursive:true,force:true});}}); + +test('Bank changes update the bank workspace badge without marking unrelated workspace tiles',()=>{assert.deepEqual(pagesForChanges(['website/node/postbank-payments.mjs']),['https://cp.dunerealms.com/','https://cp.dunerealms.com/#bank']);assert.deepEqual(pagesForChanges(['website/tests/postbank-payments.test.mjs']),[]);}); diff --git a/website/tests/publication-changes.test.mjs b/website/tests/publication-changes.test.mjs new file mode 100644 index 00000000..193589e2 --- /dev/null +++ b/website/tests/publication-changes.test.mjs @@ -0,0 +1,21 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {execFileSync} from 'node:child_process'; +import {mkdtempSync,writeFileSync,rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import path from 'node:path'; +import {publicationChanges} from '../scripts/publication-changes.mjs'; +test('Publication comparison uses committed changes, including additions and filenames with spaces',()=>{ + const repo=mkdtempSync(path.join(tmpdir(),'dune-push-')); + const git=(...args)=>execFileSync('git',args,{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim(); + try{ + git('init');git('config','user.name','Publication test');git('config','user.email','test@example.invalid'); + writeFileSync(path.join(repo,'existing.txt'),'before');git('add','.');git('commit','-m','base');const base=git('rev-parse','HEAD'); + writeFileSync(path.join(repo,'existing.txt'),'after');writeFileSync(path.join(repo,'new page.html'),'new');git('add','.');git('commit','-m','published');const head=git('rev-parse','HEAD'); + writeFileSync(path.join(repo,'unpublished.txt'),'not published'); + const change=publicationChanges(repo,base,head); + assert.deepEqual(change.paths,['existing.txt','new page.html']);assert.deepEqual(change.added,['new page.html']); + assert.deepEqual(publicationChanges(repo,head,head).paths,[]); + assert.throws(()=>publicationChanges(repo,'HEAD~1'),/exact commit/); + }finally{rmSync(repo,{recursive:true,force:true});} +}); From 85339bc1525eed415f765ca4945cc3ab87a94c24 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:07:58 +0100 Subject: [PATCH 11/16] Preview effective organisation rights and expose scoped staff access provenance --- .../public/cp-v2/citizen-directory.mjs | 14 +++++++- website/docs/great-migration.md | 2 ++ website/node/organisation-effective.mjs | 28 +++++++++++++++ website/node/organisation-management.mjs | 15 ++++++-- website/node/permissions.mjs | 1 + website/tests/organisation-effective.test.mjs | 35 +++++++++++++++++++ 6 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 website/node/organisation-effective.mjs create mode 100644 website/tests/organisation-effective.test.mjs diff --git a/website/control-panel/public/cp-v2/citizen-directory.mjs b/website/control-panel/public/cp-v2/citizen-directory.mjs index 6b4c9be1..d85b08ba 100644 --- a/website/control-panel/public/cp-v2/citizen-directory.mjs +++ b/website/control-panel/public/cp-v2/citizen-directory.mjs @@ -65,11 +65,22 @@ export function mountCitizenDirectory(host){ for(const event of data.events){const row=element('div',undefined,'md-assignment');row.append(element('strong',event.action+' · '+event.scope_key.replaceAll('_',' ')),element('p',event.reason),element('small',(event.actor||'System')+' · '+new Date(Number(event.created_at)).toLocaleString('en-GB')));panel.append(row);} }catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.append(element('p',e.message,'md-note'));} } + async function loadAccessPreview(panel){ + const target=selected.id;panel.append(element('p','Checking the central role mapping…','md-muted')); + try{const data=await request('/api/admin/organisation/effective?userId='+encodeURIComponent(target),controller?.signal); + if(disposed||selected?.id!==target||context!=='staff'||tab!=='permissions'||!panel.isConnected)return; + panel.replaceChildren(element('h3','Effective access preview'),element('p','Preparation only. These mapped permissions have not replaced live access.','md-note')); + for(const source of data.sources){const row=element('details',undefined,'md-assignment');row.append(element('summary',source.scopeKey.replaceAll('_',' ')+' · '+source.role.replaceAll('_',' ')+' · '+source.nodes.length+' permissions'));for(const node of source.nodes)row.append(element('p',node,'md-muted'));panel.append(row);} + panel.append(element('p',data.nodes.length+' unique permissions · '+data.missingPolicies.length+' missing policy mappings · '+data.blocked.length+' unsafe grants blocked.')); + for(const missing of data.missingPolicies)panel.append(element('p','Mapping required: '+missing.scopeKey+' / '+missing.role,'md-note')); + if(!data.sources.length&&!data.missingPolicies.length)panel.append(element('p','No active mapped staff functions. Existing live rights remain unchanged.')); + }catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.replaceChildren(element('p',e.message,'md-note'));} + } function renderAccount(){ view.replaceChildren();heading();const back=button('← '+(context==='staff'?'Staff Directory':'User Directory'),()=>{selected=null;void load();});view.append(back); const hero=element('header',undefined,'md-identity');const avatar=element('img');avatar.alt='';avatar.width=56;avatar.height=56;avatar.src=selected.minecraftUuid?'/api/avatars/minecraft/'+encodeURIComponent(selected.minecraftUuid):'https://www.dunerealms.com/assets/nav-account-v2.webp'; 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 tabs=context==='staff'?[['overview','Overview'],['account','Account'],['assignments','Staff assignments'],['permissions','Access preview'],['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); @@ -77,6 +88,7 @@ export function mountCitizenDirectory(host){ }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'){const panel=assignments();view.append(panel);if(context==='staff')void loadAssignments(panel);} + else if(tab==='permissions'&&context==='staff'){const panel=box('Effective access preview');view.append(panel);void loadAccessPreview(panel);} else if(tab==='honours'){const panel=box('Seals & honours');panel.append(element('p','Existing awards are preserved. The new seal ledger and compact award controls follow in the recognition batch.','md-muted'));panel.append(publicLink.cloneNode(true));view.append(panel);} else{const panel=box('Account activity');view.append(panel);void loadActivity(panel);} } diff --git a/website/docs/great-migration.md b/website/docs/great-migration.md index 42e9581e..aeecd603 100644 --- a/website/docs/great-migration.md +++ b/website/docs/great-migration.md @@ -94,3 +94,5 @@ or four-hour compensation queue. Reuse existing posting/audit infrastructure. Cash conversion is reserved for the future in-game GUI + central API in both directions. No cash web page, redeem code flow or game changes in this batch. + +Effective-access preview: GET /api/admin/organisation/effective?userId=UUID requires web.ranks.manage and computes explicit new-model grants with provenance. Branch Leads inherit their own Officer policy. Missing policies and blocked unsafe grants are reported. Staff Directory has an Access preview tab; User context does not. Payroll requires a pinned Big Four control principal (Dev service exception), never an Executive title alone. No live rank mutation or native projection is activated by this endpoint. diff --git a/website/node/organisation-effective.mjs b/website/node/organisation-effective.mjs new file mode 100644 index 00000000..602da8b5 --- /dev/null +++ b/website/node/organisation-effective.mjs @@ -0,0 +1,28 @@ +import {validStaffRole} from './organisation-model.mjs'; +const nativeEditors=new Set(['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()}){ + const nodes=new Set(),sources=[],missing=[],blocked=[]; + for(const a of assignments){ + if(a.status!=='active'||Number(a.starts_at)>now||a.ends_at!==null&&a.ends_at!==undefined&&Number(a.ends_at)<=now)continue; + if(!validStaffRole(a.scope_type,a.scope_key,a.role_key))continue; + const roles=a.scope_type==='branch'&&a.role_key==='branch_lead'?['officer','branch_lead']:[a.role_key]; + for(const role of roles){ + const p=policies.find(p=>p.scope_type===a.scope_type&&p.scope_key===a.scope_key&&p.role_key===role); + const source={scopeType:a.scope_type,scopeKey:a.scope_key,role,assignmentId:a.id}; + if(!p){missing.push(source);continue;} + let requested;try{requested=JSON.parse(p.permissions_json);}catch{throw Error('Invalid stored organisation policy.');} + if(!Array.isArray(requested)||requested.some(n=>typeof n!=='string'))throw Error('Invalid stored organisation policy.'); + const granted=[]; + for(const n of requested){ + const management=a.scope_type==='organisation'&&['owner_ceo','executive'].includes(role)||a.scope_type==='department'&&role==='department_head'; + const payroll=['web.payroll.manage','cp.payroll.manage'].includes(n); + if(!Object.hasOwn(registry,n)||n.includes('*')||/(^|\.)op($|\.)/.test(n)||nativeEditors.has(n)||officialBank.has(n)&&!management||payroll&&!(['owner','executive','service'].includes(principalKind)&&a.scope_type==='organisation'&&['owner_ceo','executive'].includes(role))){blocked.push({...source,node:n});continue;} + nodes.add(n);granted.push(n); + } + sources.push({...source,version:Number(p.version),nodes:[...new Set(granted)].sort()}); + } + } + return {nodes:[...nodes].sort(),sources,missingPolicies:missing,blocked,enforcement:'preparing',permissionsChanged:false}; +} diff --git a/website/node/organisation-management.mjs b/website/node/organisation-management.mjs index 54198017..b7043e1b 100644 --- a/website/node/organisation-management.mjs +++ b/website/node/organisation-management.mjs @@ -1,3 +1,4 @@ +import {effectiveOrganisationAccess} from './organisation-effective.mjs'; import {randomUUID} from 'node:crypto'; import {identity} from './auth.mjs'; import {can,NODES} from './permissions.mjs'; @@ -24,6 +25,7 @@ export function validatePolicyNodes(nodes,scopeType,role){ const unique=[...new Set(nodes)].sort(); for(const n of unique){ if(!Object.hasOwn(NODES,n)||n.includes('*')||/(^|\.)op($|\.)/.test(n))throw fault('Unregistered or unrestricted permission: '+n,400); + if(['web.payroll.manage','cp.payroll.manage'].includes(n)&&!(scopeType==='organisation'&&['owner_ceo','executive'].includes(role)))throw fault('Payroll management is reserved for the Big Four.',400); if(nativeEditorNodes.has(n))throw fault('Native permission editors remain reserved for the Dev service.',400); if(['web.bank.staff.manage','cp.bank.staff.manage','web.bank.staff.deposit','cp.bank.staff.deposit'].includes(n)&&!((scopeType==='organisation'&&['owner_ceo','executive'].includes(role))||(scopeType==='department'&&role==='department_head')))throw fault('Official banking management is reserved for executives and department heads.',400); } @@ -52,8 +54,8 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c return async request=>{ const actor=await authenticate(request,db);if(!actor)return reply({message:'Sign in first.'},401); const url=new URL(request.url),policy=url.pathname==='/api/admin/organisation/policies'; - if(!['/api/admin/organisation/assignments','/api/admin/organisation/policies','/api/admin/organisation/activity','/api/admin/organisation/authority'].includes(url.pathname))return reply({message:'Not found.'},404); - if(!await authorize(db,actor,policy?'web.ranks.manage':'web.accounts.view'))return reply({message:'Central management permission required.'},403); + if(!['/api/admin/organisation/assignments','/api/admin/organisation/policies','/api/admin/organisation/activity','/api/admin/organisation/authority','/api/admin/organisation/effective'].includes(url.pathname))return reply({message:'Not found.'},404); + 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'}); @@ -63,6 +65,15 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c return reply({scopes:staffScopes(),versions,policies:policies.map(p=>({...p,nodes:JSON.parse(p.permissions_json),permissions_json:undefined})),catalogue:Object.entries(NODES).filter(([n])=>!n.includes('*')).map(([node,label])=>({node,label})),canEdit:globalPrincipal(auth.principal),enforcement:'preparing'}); } const userId=url.searchParams.get('userId');if(!identifier(userId))return reply({message:'Select a registered account.'},400); + if(url.pathname.endsWith('/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 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]); + return effectiveOrganisationAccess({assignments,policies,registry:NODES,principalKind:principal?.principal_kind,now}); + });return reply(result); + } if(url.pathname.endsWith('/activity')){ const context=url.searchParams.get('context')||'users';if(!['users','staff'].includes(context))return reply({message:'Invalid context.'},400); const clause=context==='staff'?"IN ('organisation','department','branch')":"NOT IN ('organisation','department','branch')"; diff --git a/website/node/permissions.mjs b/website/node/permissions.mjs index caf5f70c..4865c4b7 100644 --- a/website/node/permissions.mjs +++ b/website/node/permissions.mjs @@ -1,4 +1,5 @@ export const NODES={ + 'web.payroll.manage':'Manage P&O payroll (Big Four only)', 'web.bank.projects.approve':'Approve Support requests for temporary project bank accounts', 'cp.menu.staffmanual':'Read the staff manual', 'cp.menu.items':'Custom item designer page','cp.items.manage':'Design and publish custom items','dune.items.give':'Issue registered custom items', diff --git a/website/tests/organisation-effective.test.mjs b/website/tests/organisation-effective.test.mjs new file mode 100644 index 00000000..f1a49594 --- /dev/null +++ b/website/tests/organisation-effective.test.mjs @@ -0,0 +1,35 @@ +import {createOrganisationManagement} from '../node/organisation-management.mjs'; +import test from 'node:test';import assert from 'node:assert/strict'; +import {effectiveOrganisationAccess} from '../node/organisation-effective.mjs'; +const registry={'web.posts.view':'read','web.posts.manage':'write','web.bank.staff.manage':'bank','web.payroll.manage':'payroll','web.luckperms.edit':'native'}; +const position=(role,scope='news_media',type='branch')=>({id:role,scope_type:type,scope_key:scope,role_key:role,status:'active',starts_at:10,ends_at:null}); +const policy=(role,nodes,scope='news_media',type='branch')=>({scope_type:type,scope_key:scope,role_key:role,permissions_json:JSON.stringify(nodes),version:2}); +const run=(assignments,policies,principalKind=null)=>effectiveOrganisationAccess({assignments,policies,registry,principalKind,now:100}); +test('Lead inherits only its own branch officer policy; multiple assignments union explicit grants',()=>{ + const result=run([position('branch_lead')],[policy('officer',['web.posts.view']),policy('branch_lead',['web.posts.manage']),policy('officer',['web.bank.staff.manage'],'engineering')]); + assert.deepEqual(result.nodes,['web.posts.manage','web.posts.view']);assert.equal(result.sources.length,2);assert.equal(result.permissionsChanged,false); +}); +test('Expired, revoked, future and invalid assignments cannot contribute',()=>{ + const result=run([{...position('officer'),ends_at:100},{...position('officer'),status:'revoked'},{...position('officer'),starts_at:101},position('officer','invented')],[policy('officer',['web.posts.manage'])]);assert.deepEqual(result.nodes,[]); +}); +test('Stored unsafe nodes are blocked even if an old policy bypassed current validation',()=>{ + const result=run([position('officer')],[policy('officer',['web.posts.view','web.bank.staff.manage','web.payroll.manage','web.luckperms.edit','*'])]);assert.deepEqual(result.nodes,['web.posts.view']);assert.equal(result.blocked.length,4); +}); +test('Department heads have bank management but payroll remains executive-only',()=>{ + const head=run([position('department_head','community_operations','department')],[policy('department_head',['web.bank.staff.manage','web.payroll.manage'],'community_operations','department')]);assert.deepEqual(head.nodes,['web.bank.staff.manage']); + const exec=run([position('executive','dunerealms','organisation')],[policy('executive',['web.bank.staff.manage','web.payroll.manage'],'dunerealms','organisation')],'executive');assert.deepEqual(exec.nodes,['web.bank.staff.manage','web.payroll.manage']); +}); +test('Missing policies are explicit and corrupt stored data fails closed',()=>{ + assert.equal(run([position('officer')],[]).missingPolicies.length,1); + assert.throws(()=>run([position('officer')],[{...policy('officer',[]),permissions_json:'bad'}]),/Invalid stored/); +}); + +test('Executive title alone cannot bypass the pinned Big Four payroll boundary',()=>{const result=run([position('executive','dunerealms','organisation')],[policy('executive',['web.payroll.manage'],'dunerealms','organisation')]);assert.deepEqual(result.nodes,[]);assert.equal(result.blocked.length,1);}); + +test('Effective access endpoint requires policy-view authority and returns a non-mutating target preview',async()=>{ + const actor={id:'11111111-1111-4111-8111-111111111111'},target='22222222-2222-4222-8222-222222222222';const queries=[]; + const tx={first:async(sql,args)=>{queries.push([sql,args]);return sql.includes('site_accounts')?actor:{principal_kind:'executive'};},query:async(sql,args)=>{queries.push([sql,args]);if(sql.startsWith('SELECT id,scope_type'))return [position('officer')];if(sql.includes('org_role_policies'))return [policy('officer',['web.posts.view'])];return [];}}; + const db={transaction:fn=>fn(tx)};const endpoint=new Request('https://cp.dunerealms.com/api/admin/organisation/effective?userId='+target); + const denied=createOrganisationManagement(db,{authenticate:async()=>actor,authorize:async()=>false});assert.equal((await denied(endpoint)).status,403);assert.equal(queries.length,0); + const api=createOrganisationManagement(db,{authenticate:async()=>actor,authorize:async(_db,_user,node)=>node==='web.ranks.manage',clock:()=>100});const response=await api(endpoint);assert.equal(response.status,200);const data=await response.json();assert.deepEqual(data.nodes,['web.posts.view']);assert.equal(data.permissionsChanged,false);assert(queries.every(([sql])=>sql.startsWith('SELECT')));assert(queries.some(([sql,args])=>sql.startsWith('SELECT id,scope_type')&&args[0]===target)); +}); From 35dd7f8dca8793ae5570f871696f85100aca2dac Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:34:45 +0100 Subject: [PATCH 12/16] Map explicit department and branch policies with audited idempotent bootstrap --- website/docs/great-migration.md | 2 + .../node/organisation-default-policies.mjs | 40 +++++++++++++++++++ .../bootstrap-organisation-policies.mjs | 32 +++++++++++++++ .../organisation-default-policies.test.mjs | 20 ++++++++++ .../organisation-policy-bootstrap.test.mjs | 19 +++++++++ 5 files changed, 113 insertions(+) create mode 100644 website/node/organisation-default-policies.mjs create mode 100644 website/scripts/bootstrap-organisation-policies.mjs create mode 100644 website/tests/organisation-default-policies.test.mjs create mode 100644 website/tests/organisation-policy-bootstrap.test.mjs diff --git a/website/docs/great-migration.md b/website/docs/great-migration.md index aeecd603..6d591bed 100644 --- a/website/docs/great-migration.md +++ b/website/docs/great-migration.md @@ -96,3 +96,5 @@ Cash conversion is reserved for the future in-game GUI + central API in both directions. No cash web page, redeem code flow or game changes in this batch. Effective-access preview: GET /api/admin/organisation/effective?userId=UUID requires web.ranks.manage and computes explicit new-model grants with provenance. Branch Leads inherit their own Officer policy. Missing policies and blocked unsafe grants are reported. Staff Directory has an Access preview tab; User context does not. Payroll requires a pinned Big Four control principal (Dev service exception), never an Executive title alone. No live rank mutation or native projection is activated by this endpoint. + +Default policies now enumerate 22 function mappings (nine branches with Officer/Lead, two Department Heads, Owner/Executive). Native permission editors are excluded for humans; official bank management remains departmental/executive, payroll requires pinned control identity. bootstrap-organisation-policies.mjs defaults to a plan; explicit --apply --actor=UUID requires an active control principal, retains existing policies, versions each scope and audits inserts atomically. It stores preparation data only, with no legacy rank replacement, user appointments or native group projection. diff --git a/website/node/organisation-default-policies.mjs b/website/node/organisation-default-policies.mjs new file mode 100644 index 00000000..7e079665 --- /dev/null +++ b/website/node/organisation-default-policies.mjs @@ -0,0 +1,40 @@ +import {NODES} from './permissions.mjs'; +import {ORGANISATION} from './organisation-model.mjs'; +import {validatePolicyNodes} from './organisation-management.mjs'; +const staff=['web.menu.staffmanual','web.mail.internal.view']; +const branchNodes={ + customer_support:['web.menu.tickets','web.tickets.staff','web.accounts.view','dune.tickets.staff','dune.staff.open','dune.staff.history'], + sales_accounts:['web.menu.tickets','web.tickets.staff','web.shop.support','web.accounts.view','web.bank.staff.view'], + content_creative:['web.menu.items','web.items.manage','web.menu.inventory','web.quests.view','web.quests.manage','dune.items.give','dune.quests.view','dune.quests.admin','dune.atelier.view','dune.atelier.redeem'], + news_media:['web.menu.posts','web.posts.view','web.posts.edit'], + trust_safety:['web.menu.bans','web.bans.view','web.bans.manage','web.bans.evidence','web.bans.tickets','web.tickets.appeals','web.menu.forum','web.forum.moderate','web.menu.tickets','web.tickets.staff','dune.staff.open','dune.staff.history','dune.staff.kick','dune.staff.warn','dune.staff.mute','dune.staff.ban.local','dune.ban.local','dune.unban.local','dune.moderation.ban','dune.moderation.unban','duneprotect.inspect','duneprotect.lookup'], + it_operations:['web.menu.servers','web.servers.view','web.servers.logs','web.servers.power','web.servers.console','duneprotect.inspect','duneprotect.lookup','duneprotect.regions'], + engineering:['web.menu.items','web.items.manage','web.menu.servers','web.servers.view','web.servers.logs','web.luckperms.view','web.quests.view'], + people_operations:['web.accounts.view','web.menu.staffmanual','web.menu.tickets','web.tickets.staff'], + legal_compliance:['web.accounts.view','web.menu.tickets','web.tickets.staff','web.tickets.appeals','web.bans.view'] +}; +const leadNodes={ + customer_support:['web.tickets.admin'],sales_accounts:['web.bank.projects.approve'], + content_creative:['duneprotect.worldedit','duneprotect.rollback','duneprotect.restore'], + news_media:['web.posts.publish'],trust_safety:['dune.staff.ban.network','dune.ban.global','dune.unban.global'], + it_operations:['web.git.admin'],engineering:['web.menu.permissions','web.ranks.manage','web.accounts.assign'], + people_operations:['web.accounts.assign','web.accounts.revoke'],legal_compliance:[] +}; +const unique=nodes=>[...new Set(nodes)].sort(); +export function defaultOrganisationPolicies(){ + const result=[]; + for(const department of ORGANISATION){ + const departmentNodes=[...staff,'web.bank.staff.view','web.bank.staff.manage','web.bank.staff.deposit','web.bank.projects.approve']; + for(const branch of department.branches){ + const officer=unique([...staff,...branchNodes[branch.key]]),lead=unique(leadNodes[branch.key]); + result.push({scopeType:'branch',scopeKey:branch.key,role:'officer',nodes:officer},{scopeType:'branch',scopeKey:branch.key,role:'branch_lead',nodes:lead}); + departmentNodes.push(...officer,...lead); + } + 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)); + 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; +} diff --git a/website/scripts/bootstrap-organisation-policies.mjs b/website/scripts/bootstrap-organisation-policies.mjs new file mode 100644 index 00000000..e77cd2de --- /dev/null +++ b/website/scripts/bootstrap-organisation-policies.mjs @@ -0,0 +1,32 @@ +import {randomUUID} from 'node:crypto'; +import {fileURLToPath} from 'node:url'; +import {resolve} from 'node:path'; +import {openDatabase} from '../node/mysql.mjs'; +import {initializeOrganisation} from '../node/organisation-model.mjs'; +import {defaultOrganisationPolicies} from '../node/organisation-default-policies.mjs'; +export async function bootstrapPolicies(db,{actorId,apply=false,clock=Date.now}={}){ + if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(actorId||''))throw Error('An existing control actor UUID is required.'); + const templates=defaultOrganisationPolicies(); + if(!apply)return {applied:false,templates,permissionsChanged:false}; + return db.transaction(async tx=>{ + const actor=await tx.first("SELECT a.id,p.principal_kind FROM site_accounts a JOIN org_control_principals p ON p.user_id=a.id WHERE a.id=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[actorId]); + if(!actor||!['owner','executive','service'].includes(actor.principal_kind))throw Error('Current control principal required.'); + let created=0,retained=0; + for(const p of templates){ + await tx.query('INSERT IGNORE INTO org_scope_versions(scope_type,scope_key,version) VALUES(?,?,1)',[p.scopeType,p.scopeKey]); + await tx.first('SELECT version FROM org_scope_versions WHERE scope_type=? AND scope_key=? FOR UPDATE',[p.scopeType,p.scopeKey]); + const existing=await tx.first('SELECT version FROM org_role_policies WHERE scope_type=? AND scope_key=? AND role_key=? FOR UPDATE',[p.scopeType,p.scopeKey,p.role]); + if(existing){retained++;continue;} + const now=clock(); + await tx.query('INSERT INTO org_role_policies(scope_type,scope_key,role_key,permissions_json,version,updated_by,updated_at) VALUES(?,?,?,?,1,?,?)',[p.scopeType,p.scopeKey,p.role,JSON.stringify(p.nodes),actorId,now]); + await tx.query('UPDATE org_scope_versions SET version=version+1 WHERE scope_type=? AND scope_key=?',[p.scopeType,p.scopeKey]); + await tx.query('INSERT INTO org_assignment_events(id,user_id,actor_id,action,scope_type,scope_key,reason,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[randomUUID(),null,actorId,'policy-baseline',p.scopeType,p.scopeKey,'Owner-approved Great Migration explicit function mapping',JSON.stringify({role:p.role,nodes:p.nodes,permissionsChanged:false}),now]); + created++; + } + return {applied:true,created,retained,permissionsChanged:false,enforcement:'preparing'}; + }); +} +if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){ + const db=await openDatabase(process.env); + try{await initializeOrganisation(db);console.log(JSON.stringify(await bootstrapPolicies(db,{actorId:process.argv.find(a=>a.startsWith('--actor='))?.slice(8),apply:process.argv.includes('--apply')})));}finally{await db.close();} +} diff --git a/website/tests/organisation-default-policies.test.mjs b/website/tests/organisation-default-policies.test.mjs new file mode 100644 index 00000000..2aeb5293 --- /dev/null +++ b/website/tests/organisation-default-policies.test.mjs @@ -0,0 +1,20 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {defaultOrganisationPolicies} from '../node/organisation-default-policies.mjs'; +import {effectiveOrganisationAccess} from '../node/organisation-effective.mjs'; +import {NODES} from '../node/permissions.mjs'; +const policies=defaultOrganisationPolicies(); +test('All nine branches, two departments and executive functions have registered explicit policies',()=>{ + assert.equal(policies.length,22);assert.equal(new Set(policies.map(p=>p.scopeType+':'+p.scopeKey+':'+p.role)).size,22); + for(const p of policies)for(const n of p.nodes){assert(Object.hasOwn(NODES,n));assert(!n.includes('*'));assert(!n.endsWith('.op'));assert.notEqual(n,'web.luckperms.edit');} +}); +test('Bank management belongs to department/executive policies and payroll only to the Big Four policy',()=>{ + for(const p of policies){if(p.scopeType==='branch')assert(!p.nodes.includes('web.bank.staff.manage'));if(p.scopeType!=='organisation')assert(!p.nodes.includes('web.payroll.manage'));} +}); +test('Job-specific rights do not leak between news, support and technical officers',()=>{ + const by=key=>policies.find(p=>p.scopeKey===key&&p.role==='officer').nodes; + assert(by('news_media').includes('web.posts.edit'));assert(!by('news_media').includes('web.posts.publish'));assert(!by('customer_support').includes('dune.staff.ban.network'));assert(!by('sales_accounts').includes('web.servers.console'));assert(by('it_operations').includes('web.servers.console')); +}); +test('Lead policy plus own officer policy yields a complete branch role',()=>{ + const result=effectiveOrganisationAccess({assignments:[{id:'news',scope_type:'branch',scope_key:'news_media',role_key:'branch_lead',status:'active',starts_at:1,ends_at:null}],policies:policies.map(p=>({scope_type:p.scopeType,scope_key:p.scopeKey,role_key:p.role,permissions_json:JSON.stringify(p.nodes),version:1})),registry:NODES,now:2}); + assert(result.nodes.includes('web.posts.edit'));assert(result.nodes.includes('web.posts.publish'));assert(!result.nodes.includes('web.bank.staff.manage'));assert.equal(result.blocked.length,0); +}); diff --git a/website/tests/organisation-policy-bootstrap.test.mjs b/website/tests/organisation-policy-bootstrap.test.mjs new file mode 100644 index 00000000..9580966c --- /dev/null +++ b/website/tests/organisation-policy-bootstrap.test.mjs @@ -0,0 +1,19 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {bootstrapPolicies} from '../scripts/bootstrap-organisation-policies.mjs'; +const actorId='11111111-1111-4111-8111-111111111111'; +function fixture({principal='owner',auditFail=false}={}){ + const policies=new Map(),events=[];const tx={async first(sql,args){if(sql.includes('JOIN org_control_principals'))return principal?{id:actorId,principal_kind:principal}:null;if(sql.includes('FROM org_scope_versions'))return {version:1};if(sql.includes('FROM org_role_policies'))return policies.get(args.join(':'))||null;throw Error(sql);},async query(sql,args){if(sql.startsWith('INSERT INTO org_role_policies'))policies.set(args.slice(0,3).join(':'),{version:1,nodes:args[3]});if(sql.startsWith('INSERT INTO org_assignment_events')){if(auditFail)throw Error('audit failure');events.push(args);}}}; + return {policies,events,db:{async transaction(fn){const before=new Map(policies),count=events.length;try{return await fn(tx);}catch(e){policies.clear();for(const [k,v]of before)policies.set(k,v);events.length=count;throw e;}}}}; +} +test('Policy plan does not mutate a database and requires a valid control actor ID',async()=>{ + const plan=await bootstrapPolicies(null,{actorId});assert.equal(plan.templates.length,22);assert.equal(plan.applied,false);assert.equal(plan.permissionsChanged,false);await assert.rejects(bootstrapPolicies(null,{actorId:'owner'})); +}); +test('Policy baseline is audited and idempotent without overwriting a custom policy',async()=>{ + const f=fixture();f.policies.set('branch:news_media:officer',{version:8,nodes:'custom'}); + const result=await bootstrapPolicies(f.db,{actorId,apply:true});assert.equal(result.created,21);assert.equal(result.retained,1);assert.equal(f.events.length,21);assert.equal(f.policies.get('branch:news_media:officer').nodes,'custom'); + const again=await bootstrapPolicies(f.db,{actorId,apply:true});assert.equal(again.created,0);assert.equal(again.retained,22);assert.equal(f.events.length,21); +}); +test('Missing principal and failed auditing cannot leave partial policy mappings',async()=>{ + const denied=fixture({principal:null});await assert.rejects(bootstrapPolicies(denied.db,{actorId,apply:true}),/principal/);assert.equal(denied.policies.size,0); + const failed=fixture({auditFail:true});await assert.rejects(bootstrapPolicies(failed.db,{actorId,apply:true}),/audit/);assert.equal(failed.policies.size,0); +}); From 5291938c1a9160f7b91373f97820d01356e70b8f Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:43:05 +0100 Subject: [PATCH 13/16] Integrate central function policies into runtime access behind migration switch --- website/docs/great-migration.md | 2 ++ website/node/mysql.mjs | 1 + website/node/organisation-runtime.mjs | 31 ++++++++++++++++ website/node/permissions.mjs | 4 ++- website/node/server.mjs | 3 +- website/tests/organisation-runtime.test.mjs | 40 +++++++++++++++++++++ 6 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 website/node/organisation-runtime.mjs create mode 100644 website/tests/organisation-runtime.test.mjs diff --git a/website/docs/great-migration.md b/website/docs/great-migration.md index 6d591bed..b2bed5ab 100644 --- a/website/docs/great-migration.md +++ b/website/docs/great-migration.md @@ -98,3 +98,5 @@ directions. No cash web page, redeem code flow or game changes in this batch. Effective-access preview: GET /api/admin/organisation/effective?userId=UUID requires web.ranks.manage and computes explicit new-model grants with provenance. Branch Leads inherit their own Officer policy. Missing policies and blocked unsafe grants are reported. Staff Directory has an Access preview tab; User context does not. Payroll requires a pinned Big Four control principal (Dev service exception), never an Executive title alone. No live rank mutation or native projection is activated by this endpoint. Default policies now enumerate 22 function mappings (nine branches with Officer/Lead, two Department Heads, Owner/Executive). Native permission editors are excluded for humans; official bank management remains departmental/executive, payroll requires pinned control identity. bootstrap-organisation-policies.mjs defaults to a plan; explicit --apply --actor=UUID requires an active control principal, retains existing policies, versions each scope and audits inserts atomically. It stores preparation data only, with no legacy rank replacement, user appointments or native group projection. + +Runtime integration: ORGANISATION_ACCESS_ENABLED=true opts the central database adapter into fresh, read-snapshot organisation access. The default remains disabled. Enabled accessFor replaces legacy staff/owner bypass with new explicit policies, preserves ordinary/VIP/Order membership, and keeps only the pinned exempt Dev service on its existing access path. Invalid policy data fails closed, never falls back to old admin grants. This switch must not be enabled before control baseline, assignments, policy coverage and native projections are reconciled. This source batch does not enable it in production. Public session exports the account's own active functions. diff --git a/website/node/mysql.mjs b/website/node/mysql.mjs index 8ac595a8..8e34d197 100644 --- a/website/node/mysql.mjs +++ b/website/node/mysql.mjs @@ -14,6 +14,7 @@ export async function openDatabase(env) { catch(error){c.release();throw error;} } const db={ + organisationAccessEnabled:env.ORGANISATION_ACCESS_ENABLED==='true', async query(sql,values=[]) {const c=await connection();try{return (await c.execute(mysqlSql(sql),values))[0];}finally{c.release();}}, prepare(sql) { let values=[]; diff --git a/website/node/organisation-runtime.mjs b/website/node/organisation-runtime.mjs new file mode 100644 index 00000000..7b8ee1fe --- /dev/null +++ b/website/node/organisation-runtime.mjs @@ -0,0 +1,31 @@ +import {effectiveOrganisationAccess} from './organisation-effective.mjs'; +import {assignmentLabel,validStaffRole} from './organisation-model.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.'); +const nativeEditor=node=>['web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor'].includes(node); +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]; + 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 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})}; + }); + 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.nodes||[]).some(privileged)); + const ranks=[basicRank,...citizenRanks.filter(r=>r.key!==basicRank.key)]; + const nodes=new Set(ranks.flatMap(r=>r.nodes||[]).filter(n=>Object.hasOwn(registry,n)&&!nativeEditor(n)&&!n.includes('*'))); + for(const n of snapshot.access.nodes)nodes.add(n); + for(const n of [...nodes])if(n.startsWith('cp.')&&Object.hasOwn(registry,'web.'+n.slice(3)))nodes.add('web.'+n.slice(3)); + const active=snapshot.assignments.filter(a=>validStaffRole(a.scope_type,a.scope_key,a.role_key)&&a.status==='active'&&Number(a.starts_at)<=now&&(a.ends_at===null||Number(a.ends_at)>now)); + 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}}; +} diff --git a/website/node/permissions.mjs b/website/node/permissions.mjs index 4865c4b7..892f34b5 100644 --- a/website/node/permissions.mjs +++ b/website/node/permissions.mjs @@ -1,3 +1,4 @@ +import {organisationRuntimeAccess} from './organisation-runtime.mjs'; export const NODES={ 'web.payroll.manage':'Manage P&O payroll (Big Four only)', 'web.bank.projects.approve':'Approve Support requests for temporary project bank accounts', @@ -81,6 +82,7 @@ export async function accessFor(db,user){ const requested=[user.role,...(Array.isArray(user.ranks)?user.ranks:[])].filter(r=>typeof r==='string'&&r.length>0); const keys=[...new Set(requested.map(rankKey))]; const ranks=await Promise.all(keys.map(key=>rankFor(db,key))); + if(db.organisationAccessEnabled===true){const central=await organisationRuntimeAccess(db,user,{registry:NODES,basicRank:DEFAULT_RANKS.find(r=>r.key==='user'),legacyRanks:ranks});if(central)return central;} const owner=ranks.some(rank=>isOwnerRank(rank.key)); const granted=ranks.flatMap(rank=>Array.isArray(rank.nodes)?rank.nodes:[]); const normalized=granted.flatMap(node=>node.startsWith('cp.')? [node,'web.'+node.slice(3)]:[node]); @@ -101,7 +103,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.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}; + 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}:{} )}; } 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(); diff --git a/website/node/server.mjs b/website/node/server.mjs index e1219f7f..d1b0946f 100644 --- a/website/node/server.mjs +++ b/website/node/server.mjs @@ -1,3 +1,4 @@ +import {initializeOrganisation} from './organisation-model.mjs'; import {createGitIdentityRoute,initializeGitIdentities,gitProxyIdentity} from './git-identity.mjs'; import {createPublicExchange} from './exchange-public.mjs'; import {publicBanCards,publicAppealCards,publicBanList,publicAccountBans} from './public-bans.mjs'; @@ -78,7 +79,7 @@ export function createApplication(db,settings={}) { }; } export async function start(settings=process.env) { - const db=await openDatabase(settings);await initializeRanks(db);await initializeGitIdentities(db);await initializePublicRoster(db);await initializeCompanyRegistry(db);await initializeShareLedger(db);const handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin; + const db=await openDatabase(settings);if(db.organisationAccessEnabled)await initializeOrganisation(db);await initializeRanks(db);await initializeGitIdentities(db);await initializePublicRoster(db);await initializeCompanyRegistry(db);await initializeShareLedger(db);const handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin; let forgeHeader=settings.FORGEJO_AUTH_HEADER; if(!forgeHeader&&settings.FORGEJO_URL){const config=await readFile(settings.FORGEJO_CONFIG_FILE||'/home/dunerealms/apps/forgejo/custom/conf/app.ini','utf8');forgeHeader=forgejoIdentityHeader(config);} if(settings.FORGEJO_URL&&!/^[A-Za-z0-9-]+$/.test(forgeHeader||''))throw Error('DuneGit proxy identity header is not configured.'); diff --git a/website/tests/organisation-runtime.test.mjs b/website/tests/organisation-runtime.test.mjs new file mode 100644 index 00000000..fc73aa24 --- /dev/null +++ b/website/tests/organisation-runtime.test.mjs @@ -0,0 +1,40 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {organisationRuntimeAccess} from '../node/organisation-runtime.mjs'; +import {accessFor,DEFAULT_RANKS,NODES} from '../node/permissions.mjs'; +const user={id:'11111111-1111-4111-8111-111111111111',role:'owners'}; +const position={id:'job',scope_type:'branch',scope_key:'news_media',role_key:'officer',status:'active',starts_at:1,ends_at:null}; +function database({assignments=[position],principal=null,service=null,nodes=['web.posts.edit']}={}){ + const db={organisationAccessEnabled:true,reads:0, + async readSnapshot(fn){db.reads++;return fn({query:async sql=>{ + if(sql.includes('org_control_principals'))return principal?[{principal_kind:principal}]:[]; + if(sql.includes('site_account_policies'))return service?[service]:[]; + if(sql.includes('org_assignments'))return assignments; + return [{scope_type:'branch',scope_key:'news_media',role_key:'officer',permissions_json:JSON.stringify(nodes),version:1}]; + }});}, + prepare(){return {bind(key){return {first:async()=>{ + const r=DEFAULT_RANKS.find(r=>r.key===key); + return r?{rank_key:r.key,label:r.label,rank_level:r.level,kind:r.kind,permissions_json:JSON.stringify(r.nodes),version:1}:null; + }};}};} + };return db; +} +const resolve=(db,u=user,legacyRanks=[DEFAULT_RANKS.find(r=>r.key==='owners')])=>organisationRuntimeAccess(db,u,{registry:NODES,basicRank:DEFAULT_RANKS[0],legacyRanks,clock:()=>10}); +test('Central activation removes legacy Owner bypass while preserving ordinary citizen access',async()=>{ + const result=await resolve(database());assert(result.nodes.includes('web.posts.edit'));assert(result.nodes.includes('web.bank.personal.view'));assert(!result.nodes.includes('web.bank.staff.manage'));assert(!result.nodes.includes('web.luckperms.edit'));assert.equal(result.rank,'org_officer'); +}); +test('Current legacy mode is unchanged; activated accessFor uses central assignments',async()=>{ + const db=database();db.organisationAccessEnabled=false;assert((await accessFor(db,user)).nodes.includes('web.bank.staff.manage'));assert.equal(db.reads,0); + db.organisationAccessEnabled=true;assert(!(await accessFor(db,user)).nodes.includes('web.bank.staff.manage'));assert.equal(db.reads,1); +}); +test('Revocation takes effect on the next request without cached grants',async()=>{ + const assignments=[{...position}],db=database({assignments});assert((await resolve(db)).nodes.includes('web.posts.edit'));assignments.length=0;const result=await resolve(db);assert(!result.nodes.includes('web.posts.edit'));assert.equal(result.rank,'user');assert.equal(db.reads,2); +}); +test('Earned VIP and Order memberships survive while legacy staff grants disappear',async()=>{ + const ranks=[DEFAULT_RANKS.find(r=>r.key==='vip'),DEFAULT_RANKS.find(r=>r.key==='crysknife'),DEFAULT_RANKS.find(r=>r.key==='staff')];const result=await resolve(database({assignments:[]}),user,ranks);assert(result.ranks.includes('vip'));assert(result.ranks.includes('crysknife'));assert(!result.ranks.includes('staff'));assert(result.nodes.includes('duneess.chat.colors'));assert(!result.nodes.includes('web.tickets.staff')); +}); +test('Only the pinned, exempt Dev identity retains its existing service access',async()=>{ + const db=database({principal:'service',service:{service_uuid:'00000000-0000-4000-8000-00000000de01',game_link_exempt:1}}); + assert.equal(await resolve(db,{...user,id:'f7b88778-f0bc-41cc-9227-d8ef2f52264d'}),null);await assert.rejects(resolve(db),/Invalid service/); +}); +test('A malformed policy denies resolution instead of falling back to old privileged ranks',async()=>{ + const db=database();db.readSnapshot=async fn=>fn({query:async sql=>sql.includes('org_control')?[]:sql.includes('org_assignments')?[position]:[{scope_type:'branch',scope_key:'news_media',role_key:'officer',permissions_json:'corrupt',version:1}]});await assert.rejects(resolve(db),/Invalid stored/); +}); From 04532cb7ecd53a7d4edf686ea18b4cf494180055 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:52:48 +0100 Subject: [PATCH 14/16] Project central game rights and reuse native support department adapters --- website/docs/great-migration.md | 2 ++ website/node/game-permission-sync.mjs | 15 +++++++++++-- website/node/native-agents.mjs | 3 ++- .../node/organisation-default-policies.mjs | 10 ++++----- website/node/organisation-game-projection.mjs | 22 +++++++++++++++++++ .../node/organisation-native-projection.mjs | 7 ++++++ website/node/permissions.mjs | 5 +++++ .../organisation-game-projection.test.mjs | 17 ++++++++++++++ website/tests/organisation-game-sync.test.mjs | 15 +++++++++++++ .../organisation-native-projection.test.mjs | 15 +++++++++++++ 10 files changed, 103 insertions(+), 8 deletions(-) create mode 100644 website/node/organisation-game-projection.mjs create mode 100644 website/node/organisation-native-projection.mjs create mode 100644 website/tests/organisation-game-projection.test.mjs create mode 100644 website/tests/organisation-game-sync.test.mjs create mode 100644 website/tests/organisation-native-projection.test.mjs diff --git a/website/docs/great-migration.md b/website/docs/great-migration.md index b2bed5ab..86dfc5b3 100644 --- a/website/docs/great-migration.md +++ b/website/docs/great-migration.md @@ -100,3 +100,5 @@ Effective-access preview: GET /api/admin/organisation/effective?userId=UUID requ Default policies now enumerate 22 function mappings (nine branches with Officer/Lead, two Department Heads, Owner/Executive). Native permission editors are excluded for humans; official bank management remains departmental/executive, payroll requires pinned control identity. bootstrap-organisation-policies.mjs defaults to a plan; explicit --apply --actor=UUID requires an active control principal, retains existing policies, versions each scope and audits inserts atomically. It stores preparation data only, with no legacy rank replacement, user appointments or native group projection. Runtime integration: ORGANISATION_ACCESS_ENABLED=true opts the central database adapter into fresh, read-snapshot organisation access. The default remains disabled. Enabled accessFor replaces legacy staff/owner bypass with new explicit policies, preserves ordinary/VIP/Order membership, and keeps only the pinned exempt Dev service on its existing access path. Invalid policy data fails closed, never falls back to old admin grants. This switch must not be enabled before control baseline, assignments, policy coverage and native projections are reconciled. This source batch does not enable it in production. Public session exports the account's own active functions. + +Native bridge integration: activated game sync sends stable permission-set groups through the existing revision-confirmed /permissions/teams bridge. Explicit canonical game nodes plus retained citizen gameplay perks are combined; wildcard/OP/LuckPerms editor grants and service identities are excluded. Duplicate verified UUIDs abort the projection. Unactivated game sync stays on its existing path. Native agent sync reuses the installed osTicket adapter and maps ticket department tags; active human payloads omit native administration flags while retaining business department access. Dev service payload is unchanged. No game server or native application code is rewritten or deployed by this source batch. diff --git a/website/node/game-permission-sync.mjs b/website/node/game-permission-sync.mjs index 105ec203..59aef9df 100644 --- a/website/node/game-permission-sync.mjs +++ b/website/node/game-permission-sync.mjs @@ -1,11 +1,22 @@ +import {projectOrganisationGameUsers} from './organisation-game-projection.mjs'; import {randomUUID} from 'node:crypto'; -import {accessFor,rankFor} from './permissions.mjs'; -import {gameNodesForRank} from './game-ranks.mjs'; +import {accessFor,rankFor,NODES} from './permissions.mjs'; +import {gameNodesForRank,GAME_NODE_SET,BANK_MAP} from './game-ranks.mjs'; export async function syncGamePermissions(db,{settings=process.env,fetcher=fetch,access=user=>accessFor(db,user)}={}){ if((settings.SERVER_CONTROL_TOKEN||'').length<64)throw Error('Game permission bridge unavailable'); + if(db.organisationAccessEnabled){ + const {results:accounts}=await db.prepare("SELECT a.id,a.username,a.role,l.minecraft_uuid FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND a.role<>'memorial' AND NOT EXISTS (SELECT 1 FROM site_account_policies p WHERE p.user_id=a.id AND p.game_link_exempt=1) ORDER BY a.id").all(); + const projection=await projectOrganisationGameUsers(accounts,{access,gameNodes:new Set([...GAME_NODE_SET,...Object.keys(NODES).filter(n=>/^(?:dune|duneess|duneprotect|dunelobby)\./.test(n))]),bankMap:BANK_MAP,citizenGameNodes:async keys=>{ + const nodes=[];for(const key of keys.filter(k=>!k.startsWith('org_'))){const rank=await rankFor(db,key);for(const node of(await gameNodesForRank(db,rank)).nodes)nodes.push(node);}return nodes; + }}); + return deliverGamePermissions(projection,{settings,fetcher}); + } const {results:stored}=await db.prepare("SELECT rank_key FROM cp_ranks WHERE kind='access' AND rank_level>0 ORDER BY rank_key").all();const ranks=[]; for(const row of stored){if(!/^[a-z][a-z0-9_]{2,29}$/.test(row.rank_key))throw Error('Rank cannot be projected to game');const rank=await rankFor(db,row.rank_key),game=await gameNodesForRank(db,rank);ranks.push({id:rank.key,permissions:Object.fromEntries(game.nodes.map(n=>[n,true]))});} const {results:accounts}=await db.prepare("SELECT a.id,a.username,a.role,l.minecraft_uuid FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND a.role<>'memorial' ORDER BY a.id").all();const users=[]; for(const user of accounts){if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(user.minecraft_uuid))throw Error('Invalid verified identity');const rights=await access(user);users.push({uuid:user.minecraft_uuid.toLowerCase(),ranks:rights.ranks});} + return deliverGamePermissions({ranks,users},{settings,fetcher}); +} +async function deliverGamePermissions({ranks,users},{settings,fetcher}){ const revision=randomUUID(),r=await fetcher('http://127.0.0.1:15433/permissions/teams',{method:'POST',headers:{Authorization:'Bearer '+settings.SERVER_CONTROL_TOKEN,'Content-Type':'application/json'},body:JSON.stringify({revision,actor:'website-sync',ranks,users}),signal:AbortSignal.timeout(20000)});if(!r.ok)throw Error('Game permission synchronization unavailable');const d=await r.json();if(d.ok!==true||d.revision!==revision)throw Error('Game permission synchronization unconfirmed'); } diff --git a/website/node/native-agents.mjs b/website/node/native-agents.mjs index d337830c..e2dc2b1d 100644 --- a/website/node/native-agents.mjs +++ b/website/node/native-agents.mjs @@ -1,3 +1,4 @@ +import {nativeAgentIdentity} from './organisation-native-projection.mjs'; import {syncGamePermissions} from './game-permission-sync.mjs'; import {spawn} from 'node:child_process'; import {existsSync} from 'node:fs'; @@ -7,7 +8,7 @@ const native='/home/dunerealms/apps/integrations/osticket/sync-agents.php'; export async function syncNativeAgents(db){ if(!existsSync(native))return; const {results}=await db.prepare('SELECT id,username,role FROM site_accounts').all(); - const accounts=[];for(const user of results){const access=await accessFor(db,user);accounts.push({...user,role:access.rank,ranks:access.ranks,permissions:access.nodes});} + const accounts=[];for(const user of results){const access=await accessFor(db,user);accounts.push(nativeAgentIdentity(user,access));} await new Promise((resolve,reject)=>{const child=spawn('/usr/bin/php',[native],{stdio:['pipe','ignore','pipe']});let error='';child.stderr.on('data',chunk=>{error+=chunk.toString().slice(0,1000)});const timer=setTimeout(()=>{child.kill();reject(Error('Native staff sync timed out'));},20000);child.once('error',reject);child.once('exit',code=>{clearTimeout(timer);code===0?resolve():reject(Error('Native staff sync failed'));});child.stdin.on('error',()=>{});child.stdin.end(JSON.stringify(accounts));}); await syncNativeSeals(db); await syncGamePermissions(db); diff --git a/website/node/organisation-default-policies.mjs b/website/node/organisation-default-policies.mjs index 7e079665..fb7ec876 100644 --- a/website/node/organisation-default-policies.mjs +++ b/website/node/organisation-default-policies.mjs @@ -3,15 +3,15 @@ import {ORGANISATION} from './organisation-model.mjs'; import {validatePolicyNodes} from './organisation-management.mjs'; const staff=['web.menu.staffmanual','web.mail.internal.view']; const branchNodes={ - customer_support:['web.menu.tickets','web.tickets.staff','web.accounts.view','dune.tickets.staff','dune.staff.open','dune.staff.history'], - sales_accounts:['web.menu.tickets','web.tickets.staff','web.shop.support','web.accounts.view','web.bank.staff.view'], + customer_support:['web.tickets.support','web.tickets.staff','web.menu.tickets','web.accounts.view','dune.tickets.staff','dune.staff.open','dune.staff.history'], + sales_accounts:['web.tickets.sales','web.tickets.staff','web.menu.tickets','web.shop.support','web.accounts.view','web.bank.staff.view'], content_creative:['web.menu.items','web.items.manage','web.menu.inventory','web.quests.view','web.quests.manage','dune.items.give','dune.quests.view','dune.quests.admin','dune.atelier.view','dune.atelier.redeem'], news_media:['web.menu.posts','web.posts.view','web.posts.edit'], trust_safety:['web.menu.bans','web.bans.view','web.bans.manage','web.bans.evidence','web.bans.tickets','web.tickets.appeals','web.menu.forum','web.forum.moderate','web.menu.tickets','web.tickets.staff','dune.staff.open','dune.staff.history','dune.staff.kick','dune.staff.warn','dune.staff.mute','dune.staff.ban.local','dune.ban.local','dune.unban.local','dune.moderation.ban','dune.moderation.unban','duneprotect.inspect','duneprotect.lookup'], - it_operations:['web.menu.servers','web.servers.view','web.servers.logs','web.servers.power','web.servers.console','duneprotect.inspect','duneprotect.lookup','duneprotect.regions'], - engineering:['web.menu.items','web.items.manage','web.menu.servers','web.servers.view','web.servers.logs','web.luckperms.view','web.quests.view'], + it_operations:['web.tickets.network','web.tickets.staff','web.menu.tickets','web.menu.servers','web.servers.view','web.servers.logs','web.servers.power','web.servers.console','duneprotect.inspect','duneprotect.lookup','duneprotect.regions'], + engineering:['web.tickets.dev','web.tickets.staff','web.menu.tickets','web.menu.items','web.items.manage','web.menu.servers','web.servers.view','web.servers.logs','web.luckperms.view','web.quests.view'], people_operations:['web.accounts.view','web.menu.staffmanual','web.menu.tickets','web.tickets.staff'], - legal_compliance:['web.accounts.view','web.menu.tickets','web.tickets.staff','web.tickets.appeals','web.bans.view'] + legal_compliance:['web.tickets.legal','web.tickets.staff','web.menu.tickets','web.accounts.view','web.tickets.appeals','web.bans.view'] }; const leadNodes={ customer_support:['web.tickets.admin'],sales_accounts:['web.bank.projects.approve'], diff --git a/website/node/organisation-game-projection.mjs b/website/node/organisation-game-projection.mjs new file mode 100644 index 00000000..a0d2e8b8 --- /dev/null +++ b/website/node/organisation-game-projection.mjs @@ -0,0 +1,22 @@ +import {createHash} from 'node:crypto'; +const serviceId='f7b88778-f0bc-41cc-9227-d8ef2f52264d'; +const blocked=node=>node.includes('*')||/(^|\.)op($|\.)/.test(node)||node.startsWith('luckperms.')||node.startsWith('minecraft.command.op'); +export async function projectOrganisationGameUsers(accounts,{access,citizenGameNodes,gameNodes,bankMap}){ + const groups=new Map(),users=[],seen=new Set(); + for(const account of accounts){ + if(account.id===serviceId||account.game_link_exempt)continue; + const uuid=account.minecraft_uuid?.toLowerCase(); + if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(uuid||'')||seen.has(uuid))throw Error('Game projection requires unique verified player identities.'); + seen.add(uuid); + const rights=await access(account); + if(rights.organisation?.mode!=='active')throw Error('Central game projection requires active organisation authority.'); + const nodes=new Set(rights.nodes.filter(n=>gameNodes.has(n)&&!blocked(n))); + for(const n of await citizenGameNodes(rights.ranks))if(gameNodes.has(n)&&!blocked(n)&&!Object.hasOwn(bankMap,n))nodes.add(n); + for(const [game,web]of Object.entries(bankMap))if(rights.nodes.includes(web)&&gameNodes.has(game)&&!blocked(game))nodes.add(game); + const permissions=Object.fromEntries([...nodes].sort().map(n=>[n,true])); + const id='org_'+createHash('sha256').update(JSON.stringify(permissions)).digest('hex').slice(0,20); + if(!groups.has(id))groups.set(id,{id,permissions}); + users.push({uuid,ranks:[id]}); + } + return {ranks:[...groups.values()].sort((a,b)=>a.id.localeCompare(b.id)),users}; +} diff --git a/website/node/organisation-native-projection.mjs b/website/node/organisation-native-projection.mjs new file mode 100644 index 00000000..dce14e96 --- /dev/null +++ b/website/node/organisation-native-projection.mjs @@ -0,0 +1,7 @@ +const localPrivilegeEditors=new Set(['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, + permissions:centralHuman?access.nodes.filter(n=>!localPrivilegeEditors.has(n)):access.nodes, + ...(centralHuman?{organisation:access.organisation,nativePermissionManagement:false}:{} )}; +} diff --git a/website/node/permissions.mjs b/website/node/permissions.mjs index 892f34b5..d99dabba 100644 --- a/website/node/permissions.mjs +++ b/website/node/permissions.mjs @@ -1,5 +1,10 @@ import {organisationRuntimeAccess} from './organisation-runtime.mjs'; export const NODES={ + 'web.tickets.support':'Work Customer Support tickets', + 'web.tickets.sales':'Work Sales and Account Services tickets', + 'web.tickets.network':'Work IT Operations tickets', + 'web.tickets.dev':'Work Engineering tickets', + 'web.tickets.legal':'Work Legal and Compliance tickets', 'web.payroll.manage':'Manage P&O payroll (Big Four only)', 'web.bank.projects.approve':'Approve Support requests for temporary project bank accounts', 'cp.menu.staffmanual':'Read the staff manual', diff --git a/website/tests/organisation-game-projection.test.mjs b/website/tests/organisation-game-projection.test.mjs new file mode 100644 index 00000000..1ee0654a --- /dev/null +++ b/website/tests/organisation-game-projection.test.mjs @@ -0,0 +1,17 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {projectOrganisationGameUsers} from '../node/organisation-game-projection.mjs'; +const account=(id='11111111-1111-4111-8111-111111111111')=>({id,minecraft_uuid:id}); +const rights={organisation:{mode:'active'},ranks:['user','org_officer'],nodes:['dune.staff.warn','web.bank.personal.view','worldedit.*','luckperms.editor','minecraft.command.op']}; +const options={access:async()=>rights,citizenGameNodes:async()=>['duneess.basics','dunebank.staff.manage'],gameNodes:new Set(['dune.staff.warn','duneess.basics','dunebank.use','dunebank.staff.manage','worldedit.*','luckperms.editor','minecraft.command.op']),bankMap:{'dunebank.use':'web.bank.personal.view','dunebank.staff.manage':'web.bank.staff.manage'}}; +test('Game groups contain explicit effective rights, no stale staff labels or privileged citizen banking',async()=>{ + const result=await projectOrganisationGameUsers([account()],options);assert.deepEqual(result.ranks[0].permissions,{'dune.staff.warn':true,'dunebank.use':true,'duneess.basics':true});assert.match(result.ranks[0].id,/^org_[a-f0-9]{20}$/);assert.deepEqual(result.users[0].ranks,[result.ranks[0].id]); +}); +test('Identical effective rights reuse one stable group independent of node order',async()=>{ + const accounts=[account(),account('22222222-2222-4222-8222-222222222222')];const first=await projectOrganisationGameUsers(accounts,options);assert.equal(first.ranks.length,1); + const second=await projectOrganisationGameUsers(accounts,{...options,access:async()=>({...rights,nodes:[...rights.nodes].reverse()})});assert.deepEqual(first,second); +}); +test('Dev service never receives a player group; duplicate player UUIDs and legacy fallback abort',async()=>{ + assert.deepEqual(await projectOrganisationGameUsers([account('f7b88778-f0bc-41cc-9227-d8ef2f52264d')],options),{ranks:[],users:[]}); + await assert.rejects(projectOrganisationGameUsers([account(),account()],options),/unique verified/); + await assert.rejects(projectOrganisationGameUsers([account()],{...options,access:async()=>({...rights,organisation:undefined})}),/active organisation/); +}); diff --git a/website/tests/organisation-game-sync.test.mjs b/website/tests/organisation-game-sync.test.mjs new file mode 100644 index 00000000..27f474e7 --- /dev/null +++ b/website/tests/organisation-game-sync.test.mjs @@ -0,0 +1,15 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {syncGamePermissions} from '../node/game-permission-sync.mjs'; +test('Activated game sync sends central effective groups through the existing revision-confirmed bridge',async()=>{ + const player={id:'11111111-1111-4111-8111-111111111111',role:'owners',username:'test',minecraft_uuid:'22222222-2222-4222-8222-222222222222'}; + const db={organisationAccessEnabled:true,prepare(sql){assert(sql.includes('game_link_exempt'));return {all:async()=>({results:[player]})};}}; + let posted; + await syncGamePermissions(db,{settings:{SERVER_CONTROL_TOKEN:'test'.repeat(16)},access:async()=>({organisation:{mode:'active'},ranks:[],nodes:['dune.staff.warn','web.bank.personal.view']}),fetcher:async(url,options)=>{ + assert.equal(url,'http://127.0.0.1:15433/permissions/teams');posted=JSON.parse(options.body);return Response.json({ok:true,revision:posted.revision}); + }}); + assert.deepEqual(posted.ranks[0].permissions,{'dune.staff.warn':true,'dunebank.use':true});assert(!posted.users[0].ranks.includes('owners'));assert.equal(posted.users[0].uuid,player.minecraft_uuid); +}); +test('A game bridge response with the wrong revision is never treated as successful',async()=>{ + const db={organisationAccessEnabled:true,prepare(){return {all:async()=>({results:[]})};}}; + await assert.rejects(syncGamePermissions(db,{settings:{SERVER_CONTROL_TOKEN:'test'.repeat(16)},fetcher:async()=>Response.json({ok:true,revision:'wrong'})}),/unconfirmed/); +}); diff --git a/website/tests/organisation-native-projection.test.mjs b/website/tests/organisation-native-projection.test.mjs new file mode 100644 index 00000000..3b400346 --- /dev/null +++ b/website/tests/organisation-native-projection.test.mjs @@ -0,0 +1,15 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {nativeAgentIdentity} from '../node/organisation-native-projection.mjs'; +import {defaultOrganisationPolicies} from '../node/organisation-default-policies.mjs'; +const user={id:'account',username:'staff'}; +test('Central staff retains ticket department access but not native user/permission administration',()=>{ + const access={rank:'org_executive',ranks:['user','org_executive'],nodes:['web.tickets.admin','web.tickets.staff','web.tickets.support','web.tickets.sales','web.luckperms.edit'],organisation:{mode:'active',assignments:[]}}; + const result=nativeAgentIdentity(user,access);assert.deepEqual(result.permissions,['web.tickets.staff','web.tickets.support','web.tickets.sales']);assert.equal(result.nativePermissionManagement,false);assert.equal(access.nodes.length,5); +}); +test('Existing legacy access and verified Dev service payload remain unchanged',()=>{ + const access={rank:'network_admin',ranks:['network_admin'],nodes:['web.tickets.admin','web.luckperms.edit']};assert.deepEqual(nativeAgentIdentity(user,access).permissions,access.nodes);assert.equal(nativeAgentIdentity(user,access).nativePermissionManagement,undefined); +}); +test('Native ticket tags are present for existing support, sales, technical and legal adapters',()=>{ + const policies=defaultOrganisationPolicies(),officer=key=>policies.find(p=>p.scopeKey===key&&p.role==='officer').nodes; + for(const [key,node]of [['customer_support','web.tickets.support'],['sales_accounts','web.tickets.sales'],['it_operations','web.tickets.network'],['engineering','web.tickets.dev'],['legal_compliance','web.tickets.legal']])assert(officer(key).includes(node)); +}); From fc9549ee719364579db2fdaa092210bd86c4d01a Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:31:58 +0100 Subject: [PATCH 15/16] Build the new public staff directory and audited Great Migration appointments --- .../public/cp-v2/citizen-directory.mjs | 4 +-- website/control-panel/public/cp-v2/v2.js | 10 +++--- website/docs/great-migration.md | 2 ++ website/node/game-staff-seals.mjs | 2 +- website/node/integration-sso.mjs | 4 ++- website/node/native-seals.mjs | 2 +- website/node/native-sync-outbox.mjs | 7 ++-- website/node/native-sync-schema.mjs | 5 +++ website/node/organisation-appointments.mjs | 22 ++++++++++++ .../node/organisation-default-policies.mjs | 2 +- website/node/organisation-effective.mjs | 2 +- website/node/organisation-management.mjs | 11 +++--- website/node/organisation-model.mjs | 3 +- .../node/organisation-native-projection.mjs | 2 +- website/node/organisation-public-roster.mjs | 32 +++++++++++++++++ website/node/permissions.mjs | 3 +- website/node/public-staff-roster.mjs | 3 +- website/node/server.mjs | 2 ++ .../bootstrap-organisation-appointments.mjs | 36 +++++++++++++++++++ .../tests/organisation-appointments.test.mjs | 12 +++++++ .../tests/organisation-management.test.mjs | 6 ++-- .../tests/organisation-public-roster.test.mjs | 17 +++++++++ website/web/staff-directory.css | 1 + website/web/staff-directory.js | 18 ++++++++++ website/web/staff.html | 2 +- 25 files changed, 181 insertions(+), 29 deletions(-) create mode 100644 website/node/native-sync-schema.mjs create mode 100644 website/node/organisation-appointments.mjs create mode 100644 website/node/organisation-public-roster.mjs create mode 100644 website/scripts/bootstrap-organisation-appointments.mjs create mode 100644 website/tests/organisation-appointments.test.mjs create mode 100644 website/tests/organisation-public-roster.test.mjs create mode 100644 website/web/staff-directory.css create mode 100644 website/web/staff-directory.js diff --git a/website/control-panel/public/cp-v2/citizen-directory.mjs b/website/control-panel/public/cp-v2/citizen-directory.mjs index d85b08ba..574b814e 100644 --- a/website/control-panel/public/cp-v2/citizen-directory.mjs +++ b/website/control-panel/public/cp-v2/citizen-directory.mjs @@ -33,7 +33,7 @@ export function mountCitizenDirectory(host){ try{ const data=await request('/api/admin/organisation/assignments?userId='+encodeURIComponent(target),controller?.signal); if(disposed||selected?.id!==target||context!=='staff'||tab!=='assignments'||!panel.isConnected)return; - assignmentData=data;selected.assignments=data.assignments;panel.replaceChildren(element('h3','Staff assignments'),element('p','Changes are audited in the new register. Live permission activation follows after the mapping is verified.','md-note')); + assignmentData=data;selected.assignments=data.assignments;panel.replaceChildren(element('h3','Staff assignments'),element('p',data.enforcement==='active'?'Function changes update central access and queue native synchronisation.':'Changes are audited in the new register. Live permission activation follows after the mapping is verified.','md-note')); const message=element('p','');message.setAttribute('role','status'); for(const a of data.assignments){ const row=element('div',undefined,'md-assignment');row.append(element('strong',a.roleLabel),element('p',a.scopeLabel),badge(a.source)); @@ -52,7 +52,7 @@ export function mountCitizenDirectory(host){ const save=button('Save assignment',()=>{});save.type='submit'; for(const[label,input]of [['Department or branch',scope],['Role',role],['Reason',reason]]){const wrap=element('label',label,'md-field');wrap.append(input);form.append(wrap);}form.append(save); form.onsubmit=async e=>{e.preventDefault();if(!form.reportValidity())return;const[type,key]=scope.value.split(':');if(!confirm('Record '+role.selectedOptions[0].textContent+' for '+selected.username+'?'))return;save.disabled=true; - try{await send({action:'assign',userId:target,scopeType:type,scopeKey:key,role:role.value,scopeVersion:scopeVersion({scopeType:type,scopeKey:key}),reason:reason.value});await loadAssignments(panel);status.textContent='Assignment recorded; current live permissions remain unchanged.';}catch(error){message.textContent=error.message;save.disabled=false;} + try{const result=await send({action:'assign',userId:target,scopeType:type,scopeKey:key,role:role.value,scopeVersion:scopeVersion({scopeType:type,scopeKey:key}),reason:reason.value});await loadAssignments(panel);status.textContent=result.permissionsChanged?'Function assigned. Central access updated; native synchronisation queued.':'Assignment recorded; current live permissions remain unchanged.';}catch(error){message.textContent=error.message;save.disabled=false;} };panel.append(form); }else panel.append(element('p','You have no assignment-management authority in this register.','md-muted')); panel.append(message); diff --git a/website/control-panel/public/cp-v2/v2.js b/website/control-panel/public/cp-v2/v2.js index d6284a3b..361d7c71 100644 --- a/website/control-panel/public/cp-v2/v2.js +++ b/website/control-panel/public/cp-v2/v2.js @@ -1,4 +1,4 @@ -const menu={"version":2,"mode":"static-design-preview","source":"independent-v2-registry","workspaces":[{"id":"realm","label":"My Realm","icon":"user-round","groups":[{"label":"Identity","items":[{"id":"game","label":"Citizen Passport","viewPermission":"web.cp.v2.game.view","managePermission":"web.cp.v2.game.manage"},{"id":"site-profile","label":"Personal Records","viewPermission":"web.cp.v2.site.profile.view","managePermission":"web.cp.v2.site.profile.manage"},{"id":"security","label":"Account Security","viewPermission":"web.cp.v2.security.view","managePermission":"web.cp.v2.security.manage"},{"id":"discord-link","label":"Discord Link","viewPermission":"web.cp.v2.discord.link.view","managePermission":"web.cp.v2.discord.link.manage"},{"id":"planetary-inventory","label":"My Inventory","viewPermission":"web.cp.v2.planetary.inventory.view","managePermission":"web.cp.v2.planetary.inventory.manage"}]},{"label":"Communications","items":[{"id":"shared-inbox","label":"My Correspondence","viewPermission":"web.cp.v2.shared.inbox.view","managePermission":"web.cp.v2.shared.inbox.manage"},{"id":"tickets","label":"Petition Hall","viewPermission":"web.cp.v2.tickets.view","managePermission":"web.cp.v2.tickets.manage"},{"id":"rewards-codes","label":"Rewards & Seals","viewPermission":"web.cp.v2.rewards.codes.view","managePermission":"web.cp.v2.rewards.codes.manage"}]},{"label":"Adventures","items":[{"id":"quests","label":"Contracts & Quests","viewPermission":"web.cp.v2.quests.view","managePermission":"web.cp.v2.quests.manage"},{"id":"clans","label":"Clans & Alliances","viewPermission":"web.cp.v2.clans.view","managePermission":"web.cp.v2.clans.manage"},{"id":"kits-exchange","label":"Imperial Tailor","viewPermission":"web.cp.v2.kits.exchange.view","managePermission":"web.cp.v2.kits.exchange.manage"},{"id":"crysknife","label":"Order of the Crysknife","viewPermission":"web.cp.v2.crysknife.view","managePermission":"web.cp.v2.crysknife.manage"}]},{"label":"Commerce","items":[{"id":"personal-bank","label":"My Treasury","viewPermission":"web.cp.v2.personal.bank.view","managePermission":"web.cp.v2.personal.bank.manage"},{"id":"transactions","label":"Transaction Ledger","viewPermission":"web.cp.v2.transactions.view","managePermission":"web.cp.v2.transactions.manage"},{"id":"sales-history","label":"Sales History","viewPermission":"web.cp.v2.sales.history.view","managePermission":"web.cp.v2.sales.history.manage"},{"id":"exchange-settings","label":"Exchange Preferences","viewPermission":"web.cp.v2.exchange.settings.view","managePermission":"web.cp.v2.exchange.settings.manage"},{"id":"shop-settings","label":"Merchant Preferences","viewPermission":"web.cp.v2.shop.settings.view","managePermission":"web.cp.v2.shop.settings.manage"}]},{"label":"Companies","items":[{"id":"companies","label":"Companies","viewPermission":"web.cp.v2.companies.view","managePermission":"web.cp.v2.companies.manage"}]}]},{"id":"bureau","label":"Imperial Bureau","icon":"shield","groups":[{"label":"Citizens & Authority","items":[{"id":"user-management","label":"Citizens Registry","viewPermission":"web.cp.v2.user.management.view","managePermission":"web.cp.v2.user.management.manage"},{"id":"permissions","label":"Imperial Permissions","viewPermission":"web.cp.v2.permissions.view","managePermission":"web.cp.v2.permissions.manage"},{"id":"manual-seals","label":"Honours & Seals","viewPermission":"web.cp.v2.manual.seals.view","managePermission":"web.cp.v2.manual.seals.manage"},{"id":"seal-generator","label":"Seal Generator · V2.1","viewPermission":"web.cp.v2.manual.seals.view","managePermission":"web.cp.v2.manual.seals.manage"},{"id":"company-management","label":"Company Directorate","viewPermission":"web.cp.v2.company.management.view","managePermission":"web.cp.v2.company.management.manage"},{"id":"company-management-v2","label":"Corporate Administration","viewPermission":"web.cp.v2.company.management.v2.view","managePermission":"web.cp.v2.company.management.v2.manage"},{"id":"company-audit","label":"Corporate Audit","viewPermission":"web.cp.v2.company.audit.view","managePermission":"web.cp.v2.company.audit.manage"}]},{"label":"Commerce & Kits","items":[{"id":"staff-bank","label":"Imperial Revenue","viewPermission":"web.cp.v2.staff.bank.view","managePermission":"web.cp.v2.staff.bank.manage"},{"id":"server-kits","label":"Kit Directorate","viewPermission":"web.cp.v2.server.kits.view","managePermission":"web.cp.v2.server.kits.manage"},{"id":"kit-publishing","label":"Kit Publications","viewPermission":"web.cp.v2.kit.publishing.view","managePermission":"web.cp.v2.kit.publishing.manage"},{"id":"kit-claims","label":"Claim Registry","viewPermission":"web.cp.v2.kit.claims.view","managePermission":"web.cp.v2.kit.claims.manage"},{"id":"exchange-admin","label":"Exchange Authority","viewPermission":"web.cp.v2.exchange.admin.view","managePermission":"web.cp.v2.exchange.admin.manage"},{"id":"shop-admin","label":"Merchant Directorate","viewPermission":"web.cp.v2.shop.admin.view","managePermission":"web.cp.v2.shop.admin.manage"},{"id":"items","label":"Item Registry","viewPermission":"web.cp.v2.items.view","managePermission":"web.cp.v2.items.manage"}]},{"label":"Community","items":[{"id":"website-posts","label":"Imperial Newsroom","viewPermission":"web.cp.v2.website.posts.view","managePermission":"web.cp.v2.website.posts.manage"},{"id":"staff-tickets","label":"Petition Office","viewPermission":"web.cp.v2.staff.tickets.view","managePermission":"web.cp.v2.staff.tickets.manage"},{"id":"bans","label":"Tribunal","viewPermission":"web.cp.v2.bans.view","managePermission":"web.cp.v2.bans.manage"},{"id":"ban-evidence","label":"Evidence Registry","viewPermission":"web.cp.v2.ban.evidence.view","managePermission":"web.cp.v2.ban.evidence.manage"},{"id":"forum-admin","label":"Forum Wardens","viewPermission":"web.cp.v2.forum.admin.view","managePermission":"web.cp.v2.forum.admin.manage"},{"id":"quests-admin","label":"Campaign Directorate","viewPermission":"web.cp.v2.quests.admin.view","managePermission":"web.cp.v2.quests.admin.manage"},{"id":"community-goals","label":"Community Treasury","viewPermission":"web.cp.v2.community.goals.view","managePermission":"web.cp.v2.community.goals.manage"},{"id":"support-management","label":"Petition Administration","viewPermission":"web.cp.v2.support.management.view","managePermission":"web.cp.v2.support.management.manage"}]},{"label":"Network","items":[{"id":"server-operations","label":"Network Command","viewPermission":"web.cp.v2.server.operations.view","managePermission":"web.cp.v2.server.operations.manage"},{"id":"hosting-control","label":"Hosting Command","viewPermission":"web.cp.v2.hosting.control.view","managePermission":"web.cp.v2.hosting.control.manage"}]},{"label":"Bank Management","items":[{"id":"tax-treasury","label":"Tax Treasury Payments","viewPermission":"web.bank.staff.manage","managePermission":"web.bank.staff.manage"},{"id":"account-authorisations","label":"Account Authorisations","viewPermission":"web.bank.staff.view","managePermission":"web.bank.staff.manage"}]}]},{"id":"forge","label":"DuneForge","icon":"code-2","groups":[{"label":"Dev Control","items":[{"id":"dev-panel","label":"Dev Control","viewPermission":"web.cp.v2.dev.panel.view","managePermission":"web.cp.v2.dev.panel.manage"},{"id":"dev-queue","label":"Dev Listing","viewPermission":"web.cp.v2.dev.queue.view","managePermission":"web.cp.v2.dev.queue.manage"},{"id":"dev-approvals","label":"Dev Approvals","viewPermission":"web.cp.v2.dev.approvals.view","managePermission":"web.cp.v2.dev.approvals.manage"},{"id":"dev-new","label":"Submit Dev Request","viewPermission":"web.cp.v2.dev.new.view","managePermission":"web.cp.v2.dev.new.manage"},{"id":"dev-archive","label":"Dev Archive","viewPermission":"web.cp.v2.dev.archive.view","managePermission":"web.cp.v2.dev.archive.manage"}]},{"label":"Engineering","items":[{"id":"dev-builds","label":"Build & CI Monitor","viewPermission":"web.cp.v2.dev.builds.view","managePermission":"web.cp.v2.dev.builds.manage"},{"id":"dev-releases","label":"Release Ledger","viewPermission":"web.cp.v2.dev.releases.view","managePermission":"web.cp.v2.dev.releases.manage"},{"id":"dev-api","label":"API Reference","viewPermission":"web.cp.v2.dev.api.view","managePermission":"web.cp.v2.dev.api.manage"},{"id":"dev-audit","label":"Change Audit","viewPermission":"web.cp.v2.dev.audit.view","managePermission":"web.cp.v2.dev.audit.manage"}]},{"label":"DuneGit","items":[{"id":"git-workspace","label":"DuneGit Workspace","viewPermission":"web.menu.security","managePermission":"web.git.admin"},{"id":"git-repositories","label":"Repositories","viewPermission":"web.menu.security","managePermission":"web.git.admin"},{"id":"git-administration","label":"Git Administration","viewPermission":"web.git.admin","managePermission":"web.git.admin"}]}]},{"id":"politics","label":"Realm & Politics","icon":"crown","groups":[{"label":"Assembly","items":[{"id":"politics-overview","label":"Overview","viewPermission":"web.menu.game"},{"id":"landsraad","label":"Landsraad Assembly","viewPermission":"web.menu.game"},{"id":"council-motd","label":"Proclamations","viewPermission":"web.menu.game"},{"id":"applications","label":"Election Applications","viewPermission":"web.menu.game"},{"id":"house-elections","label":"House Elections","viewPermission":"web.menu.game"},{"id":"imperial-elections","label":"Emperor Elections","viewPermission":"web.menu.game"},{"id":"electoral-roll","label":"Electoral Roll","viewPermission":"web.menu.game"}]},{"label":"Councils","items":[{"id":"formal-council","label":"Faction Council","viewPermission":"web.menu.game"},{"id":"imperial-command","label":"Imperial Council","viewPermission":"web.menu.game"},{"id":"imperial-water","label":"Water Rights","viewPermission":"web.menu.game"},{"id":"imperial-spice","label":"Spice Rights","viewPermission":"web.menu.game"}]}]},{"id":"post","label":"Imperial Post","icon":"mail","groups":[{"label":"Correspondence","items":[{"id":"mail-inbox","label":"Incoming Dispatches","viewPermission":"web.cp.v2.mail.inbox.view","managePermission":"web.cp.v2.mail.inbox.manage"},{"id":"mail-compose","label":"Compose Dispatch","viewPermission":"web.cp.v2.mail.compose.view","managePermission":"web.cp.v2.mail.compose.manage"},{"id":"mail-sent","label":"Sent Dispatches","viewPermission":"web.cp.v2.mail.sent.view","managePermission":"web.cp.v2.mail.sent.manage"},{"id":"mail-drafts","label":"Draft Dispatches","viewPermission":"web.cp.v2.mail.drafts.view","managePermission":"web.cp.v2.mail.drafts.manage"},{"id":"mail-archive","label":"Imperial Archives","viewPermission":"web.cp.v2.mail.archive.view","managePermission":"web.cp.v2.mail.archive.manage"},{"id":"mail-trash","label":"Discarded Dispatches","viewPermission":"web.cp.v2.mail.trash.view","managePermission":"web.cp.v2.mail.trash.manage"}]},{"label":"Channels","items":[{"id":"shared-inbox","label":"Internal Dispatches","viewPermission":"web.cp.v2.shared.inbox.view","managePermission":"web.cp.v2.shared.inbox.manage"},{"id":"webmail","label":"External Mail","viewPermission":"web.cp.v2.webmail.view","managePermission":"web.cp.v2.webmail.manage"},{"id":"mail-contacts","label":"Address Book","viewPermission":"web.cp.v2.mail.contacts.view","managePermission":"web.cp.v2.mail.contacts.manage"},{"id":"mail-settings","label":"Correspondence Settings","viewPermission":"web.cp.v2.mail.settings.view","managePermission":"web.cp.v2.mail.settings.manage"},{"id":"mail-admin","label":"Postmaster Administration","viewPermission":"web.cp.v2.mail.admin.view","managePermission":"web.cp.v2.mail.admin.manage"}]}]},{"id":"bank","label":"Imperial Postbank","icon":"landmark","groups":[{"label":"Accounts & Payments","items":[{"id":"bank-overview","label":"My Accounts","viewPermission":"web.cp.v2.bank.overview.view","managePermission":"web.cp.v2.bank.overview.manage"},{"id":"personal-bank","label":"My Products","viewPermission":"web.cp.v2.personal.bank.view","managePermission":"web.cp.v2.personal.bank.manage"},{"id":"bank-transfers","label":"Transfers","viewPermission":"web.cp.v2.bank.transfers.view","managePermission":"web.cp.v2.bank.transfers.manage"},{"id":"bank-statements","label":"Transactions","viewPermission":"web.cp.v2.bank.statements.view","managePermission":"web.cp.v2.bank.statements.manage"},{"id":"bank-beneficiaries","label":"Beneficiaries","viewPermission":"web.cp.v2.bank.beneficiaries.view","managePermission":"web.cp.v2.bank.beneficiaries.manage"},{"id":"bank-authorisations","label":"My Authorisations","viewPermission":"web.bank.personal.view"}]},{"label":"Credit","items":[{"id":"loan-centre","label":"Loans & Grants","viewPermission":"web.cp.v2.loan.centre.view","managePermission":"web.cp.v2.loan.centre.manage"},{"id":"bank-loans","label":"My Credit","viewPermission":"web.cp.v2.bank.loans.view","managePermission":"web.cp.v2.bank.loans.manage"},{"id":"loan-administration","label":"Credit Management","viewPermission":"web.cp.v2.loan.administration.view","managePermission":"web.cp.v2.loan.administration.manage"}]},{"label":"Transparency","items":[{"id":"federal-reserve","label":"Federal Reserve Ledger"}]},{"label":"Administration","items":[{"id":"bank-dashboard","label":"Operations Dashboard","viewPermission":"web.cp.v2.bank.dashboard.view","managePermission":"web.cp.v2.bank.dashboard.manage"},{"id":"staff-bank","label":"Treasury Accounts","viewPermission":"web.cp.v2.staff.bank.view","managePermission":"web.cp.v2.staff.bank.manage"},{"id":"company-finance","label":"Business Accounts","viewPermission":"web.cp.v2.company.finance.view","managePermission":"web.cp.v2.company.finance.manage"},{"id":"bank-audit","label":"Audit Log","viewPermission":"web.cp.v2.bank.audit.view","managePermission":"web.cp.v2.bank.audit.manage"}]}]},{"id":"market","label":"CHOAM Exchange","icon":"chart-no-axes-combined","groups":[{"label":"Commodity Exchange","items":[{"id":"commodity-listings","label":"Player Goods"},{"id":"commodity-mine","label":"My Listings"}]},{"label":"Markets","items":[{"id":"stock-overview","label":"Market Overview","viewPermission":"web.cp.v2.stock.overview.view","managePermission":"web.cp.v2.stock.overview.manage"},{"id":"stock-listings","label":"Listed Enterprises","viewPermission":"web.cp.v2.stock.listings.view","managePermission":"web.cp.v2.stock.listings.manage"},{"id":"stock-quotes","label":"Market Prices","viewPermission":"web.cp.v2.stock.quotes.view","managePermission":"web.cp.v2.stock.quotes.manage"},{"id":"stock-portfolio","label":"My Holdings","viewPermission":"web.cp.v2.stock.portfolio.view","managePermission":"web.cp.v2.stock.portfolio.manage"},{"id":"stock-orders","label":"Trading Floor","viewPermission":"web.cp.v2.stock.orders.view","managePermission":"web.cp.v2.stock.orders.manage"},{"id":"stock-trades","label":"Trade Ledger","viewPermission":"web.cp.v2.stock.trades.view","managePermission":"web.cp.v2.stock.trades.manage"},{"id":"stock-watchlist","label":"Watchlist","viewPermission":"web.cp.v2.stock.watchlist.view","managePermission":"web.cp.v2.stock.watchlist.manage"}]},{"label":"Enterprises","items":[{"id":"companies","label":"Companies","viewPermission":"web.cp.v2.companies.view","managePermission":"web.cp.v2.companies.manage"},{"id":"stock-ipo","label":"Listing Applications","viewPermission":"web.cp.v2.stock.ipo.view","managePermission":"web.cp.v2.stock.ipo.manage"},{"id":"stock-dividends","label":"Dividends","viewPermission":"web.cp.v2.stock.dividends.view","managePermission":"web.cp.v2.stock.dividends.manage"}]},{"label":"Oversight","items":[{"id":"stock-admin","label":"Market Authority","viewPermission":"web.cp.v2.stock.admin.view","managePermission":"web.cp.v2.stock.admin.manage"},{"id":"stock-surveillance","label":"Market Surveillance","viewPermission":"web.cp.v2.stock.surveillance.view","managePermission":"web.cp.v2.stock.surveillance.manage"}]}]}]};const art={politics:'seals/office-landsraad.png',realm:'nav-account-v2.webp',bureau:'nav-staff-v2.webp',forge:'nav-manual-v2.webp',post:'nav-support-v2.webp',bank:'imperial-postbank-v2.png',market:'nav-exchange-v2.webp'};const asset=n=>'https://www.dunerealms.com/assets/'+n;const portals=document.querySelector('#portals'),sidebar=document.querySelector('#sidebar'),content=document.querySelector('#content');let current='realm';let disposePage=()=>{};let postMenuTime=0,postMenuRequest=null,renderSequence=0; +const menu={"version":2,"mode":"static-design-preview","source":"independent-v2-registry","workspaces":[{"id":"realm","label":"My Realm","icon":"user-round","groups":[{"label":"Identity","items":[{"id":"game","label":"Citizen Passport","viewPermission":"web.cp.v2.game.view","managePermission":"web.cp.v2.game.manage"},{"id":"site-profile","label":"Personal Records","viewPermission":"web.cp.v2.site.profile.view","managePermission":"web.cp.v2.site.profile.manage"},{"id":"security","label":"Account Security","viewPermission":"web.cp.v2.security.view","managePermission":"web.cp.v2.security.manage"},{"id":"discord-link","label":"Discord Link","viewPermission":"web.cp.v2.discord.link.view","managePermission":"web.cp.v2.discord.link.manage"},{"id":"planetary-inventory","label":"My Inventory","viewPermission":"web.cp.v2.planetary.inventory.view","managePermission":"web.cp.v2.planetary.inventory.manage"}]},{"label":"Communications","items":[{"id":"shared-inbox","label":"My Correspondence","viewPermission":"web.cp.v2.shared.inbox.view","managePermission":"web.cp.v2.shared.inbox.manage"},{"id":"tickets","label":"Petition Hall","viewPermission":"web.cp.v2.tickets.view","managePermission":"web.cp.v2.tickets.manage"},{"id":"rewards-codes","label":"Rewards & Seals","viewPermission":"web.cp.v2.rewards.codes.view","managePermission":"web.cp.v2.rewards.codes.manage"}]},{"label":"Adventures","items":[{"id":"quests","label":"Contracts & Quests","viewPermission":"web.cp.v2.quests.view","managePermission":"web.cp.v2.quests.manage"},{"id":"clans","label":"Clans & Alliances","viewPermission":"web.cp.v2.clans.view","managePermission":"web.cp.v2.clans.manage"},{"id":"kits-exchange","label":"Imperial Tailor","viewPermission":"web.cp.v2.kits.exchange.view","managePermission":"web.cp.v2.kits.exchange.manage"},{"id":"crysknife","label":"Order of the Crysknife","viewPermission":"web.cp.v2.crysknife.view","managePermission":"web.cp.v2.crysknife.manage"}]},{"label":"Commerce","items":[{"id":"personal-bank","label":"My Treasury","viewPermission":"web.cp.v2.personal.bank.view","managePermission":"web.cp.v2.personal.bank.manage"},{"id":"transactions","label":"Transaction Ledger","viewPermission":"web.cp.v2.transactions.view","managePermission":"web.cp.v2.transactions.manage"},{"id":"sales-history","label":"Sales History","viewPermission":"web.cp.v2.sales.history.view","managePermission":"web.cp.v2.sales.history.manage"},{"id":"exchange-settings","label":"Exchange Preferences","viewPermission":"web.cp.v2.exchange.settings.view","managePermission":"web.cp.v2.exchange.settings.manage"},{"id":"shop-settings","label":"Merchant Preferences","viewPermission":"web.cp.v2.shop.settings.view","managePermission":"web.cp.v2.shop.settings.manage"}]},{"label":"Companies","items":[{"id":"companies","label":"Companies","viewPermission":"web.cp.v2.companies.view","managePermission":"web.cp.v2.companies.manage"}]}]},{"id":"bureau","label":"Imperial Bureau","icon":"shield","groups":[{"label":"Accounts & Permissions","items":[{"id":"user-management","label":"User & Staff Directory","viewPermission":"web.cp.v2.user.management.view","managePermission":"web.cp.v2.user.management.manage"},{"id":"permissions","label":"Roles & Permissions","viewPermission":"web.cp.v2.permissions.view","managePermission":"web.cp.v2.permissions.manage"},{"id":"manual-seals","label":"Seals & Honours","viewPermission":"web.cp.v2.manual.seals.view","managePermission":"web.cp.v2.manual.seals.manage"},{"id":"seal-generator","label":"Seal Designer","viewPermission":"web.cp.v2.manual.seals.view","managePermission":"web.cp.v2.manual.seals.manage"},{"id":"company-management","label":"Company Registry","viewPermission":"web.cp.v2.company.management.view","managePermission":"web.cp.v2.company.management.manage"},{"id":"company-management-v2","label":"Company Management","viewPermission":"web.cp.v2.company.management.v2.view","managePermission":"web.cp.v2.company.management.v2.manage"},{"id":"company-audit","label":"Company Audit","viewPermission":"web.cp.v2.company.audit.view","managePermission":"web.cp.v2.company.audit.manage"}]},{"label":"Shops & Items","items":[{"id":"staff-bank","label":"Treasury Accounts","viewPermission":"web.cp.v2.staff.bank.view","managePermission":"web.cp.v2.staff.bank.manage"},{"id":"server-kits","label":"Kit Management","viewPermission":"web.cp.v2.server.kits.view","managePermission":"web.cp.v2.server.kits.manage"},{"id":"kit-publishing","label":"Kit Publishing","viewPermission":"web.cp.v2.kit.publishing.view","managePermission":"web.cp.v2.kit.publishing.manage"},{"id":"kit-claims","label":"Kit Claims","viewPermission":"web.cp.v2.kit.claims.view","managePermission":"web.cp.v2.kit.claims.manage"},{"id":"exchange-admin","label":"Exchange Management","viewPermission":"web.cp.v2.exchange.admin.view","managePermission":"web.cp.v2.exchange.admin.manage"},{"id":"shop-admin","label":"Shop Management","viewPermission":"web.cp.v2.shop.admin.view","managePermission":"web.cp.v2.shop.admin.manage"},{"id":"items","label":"Item Management","viewPermission":"web.cp.v2.items.view","managePermission":"web.cp.v2.items.manage"}]},{"label":"Community Services","items":[{"id":"website-posts","label":"News Management","viewPermission":"web.cp.v2.website.posts.view","managePermission":"web.cp.v2.website.posts.manage"},{"id":"staff-tickets","label":"Support Tickets","viewPermission":"web.cp.v2.staff.tickets.view","managePermission":"web.cp.v2.staff.tickets.manage"},{"id":"bans","label":"Bans & Appeals","viewPermission":"web.cp.v2.bans.view","managePermission":"web.cp.v2.bans.manage"},{"id":"ban-evidence","label":"Ban Evidence","viewPermission":"web.cp.v2.ban.evidence.view","managePermission":"web.cp.v2.ban.evidence.manage"},{"id":"forum-admin","label":"Forum Moderation","viewPermission":"web.cp.v2.forum.admin.view","managePermission":"web.cp.v2.forum.admin.manage"},{"id":"quests-admin","label":"Quest Management","viewPermission":"web.cp.v2.quests.admin.view","managePermission":"web.cp.v2.quests.admin.manage"},{"id":"community-goals","label":"Community Projects","viewPermission":"web.cp.v2.community.goals.view","managePermission":"web.cp.v2.community.goals.manage"},{"id":"support-management","label":"Support Administration","viewPermission":"web.cp.v2.support.management.view","managePermission":"web.cp.v2.support.management.manage"}]},{"label":"Infrastructure","items":[{"id":"server-operations","label":"Server Operations","viewPermission":"web.cp.v2.server.operations.view","managePermission":"web.cp.v2.server.operations.manage"},{"id":"hosting-control","label":"Hosting Management","viewPermission":"web.cp.v2.hosting.control.view","managePermission":"web.cp.v2.hosting.control.manage"}]},{"label":"Bank Management","items":[{"id":"tax-treasury","label":"Tax Treasury Payments","viewPermission":"web.bank.staff.manage","managePermission":"web.bank.staff.manage"},{"id":"account-authorisations","label":"Account Authorisations","viewPermission":"web.bank.staff.view","managePermission":"web.bank.staff.manage"}]}]},{"id":"forge","label":"DuneForge","icon":"code-2","groups":[{"label":"Dev Control","items":[{"id":"dev-panel","label":"Dev Control","viewPermission":"web.cp.v2.dev.panel.view","managePermission":"web.cp.v2.dev.panel.manage"},{"id":"dev-queue","label":"Dev Listing","viewPermission":"web.cp.v2.dev.queue.view","managePermission":"web.cp.v2.dev.queue.manage"},{"id":"dev-approvals","label":"Dev Approvals","viewPermission":"web.cp.v2.dev.approvals.view","managePermission":"web.cp.v2.dev.approvals.manage"},{"id":"dev-new","label":"Submit Dev Request","viewPermission":"web.cp.v2.dev.new.view","managePermission":"web.cp.v2.dev.new.manage"},{"id":"dev-archive","label":"Dev Archive","viewPermission":"web.cp.v2.dev.archive.view","managePermission":"web.cp.v2.dev.archive.manage"}]},{"label":"Engineering","items":[{"id":"dev-builds","label":"Build & CI Monitor","viewPermission":"web.cp.v2.dev.builds.view","managePermission":"web.cp.v2.dev.builds.manage"},{"id":"dev-releases","label":"Release Ledger","viewPermission":"web.cp.v2.dev.releases.view","managePermission":"web.cp.v2.dev.releases.manage"},{"id":"dev-api","label":"API Reference","viewPermission":"web.cp.v2.dev.api.view","managePermission":"web.cp.v2.dev.api.manage"},{"id":"dev-audit","label":"Change Audit","viewPermission":"web.cp.v2.dev.audit.view","managePermission":"web.cp.v2.dev.audit.manage"}]},{"label":"DuneGit","items":[{"id":"git-workspace","label":"DuneGit Workspace","viewPermission":"web.menu.security","managePermission":"web.git.admin"},{"id":"git-repositories","label":"Repositories","viewPermission":"web.menu.security","managePermission":"web.git.admin"},{"id":"git-administration","label":"Git Administration","viewPermission":"web.git.admin","managePermission":"web.git.admin"}]}]},{"id":"politics","label":"Realm & Politics","icon":"crown","groups":[{"label":"Assembly","items":[{"id":"politics-overview","label":"Overview","viewPermission":"web.menu.game"},{"id":"landsraad","label":"Landsraad Assembly","viewPermission":"web.menu.game"},{"id":"council-motd","label":"Proclamations","viewPermission":"web.menu.game"},{"id":"applications","label":"Election Applications","viewPermission":"web.menu.game"},{"id":"house-elections","label":"House Elections","viewPermission":"web.menu.game"},{"id":"imperial-elections","label":"Emperor Elections","viewPermission":"web.menu.game"},{"id":"electoral-roll","label":"Electoral Roll","viewPermission":"web.menu.game"}]},{"label":"Councils","items":[{"id":"formal-council","label":"Faction Council","viewPermission":"web.menu.game"},{"id":"imperial-command","label":"Imperial Council","viewPermission":"web.menu.game"},{"id":"imperial-water","label":"Water Rights","viewPermission":"web.menu.game"},{"id":"imperial-spice","label":"Spice Rights","viewPermission":"web.menu.game"}]}]},{"id":"post","label":"Imperial Post","icon":"mail","groups":[{"label":"Correspondence","items":[{"id":"mail-inbox","label":"Incoming Dispatches","viewPermission":"web.cp.v2.mail.inbox.view","managePermission":"web.cp.v2.mail.inbox.manage"},{"id":"mail-compose","label":"Compose Dispatch","viewPermission":"web.cp.v2.mail.compose.view","managePermission":"web.cp.v2.mail.compose.manage"},{"id":"mail-sent","label":"Sent Dispatches","viewPermission":"web.cp.v2.mail.sent.view","managePermission":"web.cp.v2.mail.sent.manage"},{"id":"mail-drafts","label":"Draft Dispatches","viewPermission":"web.cp.v2.mail.drafts.view","managePermission":"web.cp.v2.mail.drafts.manage"},{"id":"mail-archive","label":"Imperial Archives","viewPermission":"web.cp.v2.mail.archive.view","managePermission":"web.cp.v2.mail.archive.manage"},{"id":"mail-trash","label":"Discarded Dispatches","viewPermission":"web.cp.v2.mail.trash.view","managePermission":"web.cp.v2.mail.trash.manage"}]},{"label":"Channels","items":[{"id":"shared-inbox","label":"Internal Dispatches","viewPermission":"web.cp.v2.shared.inbox.view","managePermission":"web.cp.v2.shared.inbox.manage"},{"id":"webmail","label":"External Mail","viewPermission":"web.cp.v2.webmail.view","managePermission":"web.cp.v2.webmail.manage"},{"id":"mail-contacts","label":"Address Book","viewPermission":"web.cp.v2.mail.contacts.view","managePermission":"web.cp.v2.mail.contacts.manage"},{"id":"mail-settings","label":"Correspondence Settings","viewPermission":"web.cp.v2.mail.settings.view","managePermission":"web.cp.v2.mail.settings.manage"},{"id":"mail-admin","label":"Postmaster Administration","viewPermission":"web.cp.v2.mail.admin.view","managePermission":"web.cp.v2.mail.admin.manage"}]}]},{"id":"bank","label":"Imperial Postbank","icon":"landmark","groups":[{"label":"Accounts & Payments","items":[{"id":"bank-overview","label":"My Accounts","viewPermission":"web.cp.v2.bank.overview.view","managePermission":"web.cp.v2.bank.overview.manage"},{"id":"personal-bank","label":"My Products","viewPermission":"web.cp.v2.personal.bank.view","managePermission":"web.cp.v2.personal.bank.manage"},{"id":"bank-transfers","label":"Transfers","viewPermission":"web.cp.v2.bank.transfers.view","managePermission":"web.cp.v2.bank.transfers.manage"},{"id":"bank-statements","label":"Transactions","viewPermission":"web.cp.v2.bank.statements.view","managePermission":"web.cp.v2.bank.statements.manage"},{"id":"bank-beneficiaries","label":"Beneficiaries","viewPermission":"web.cp.v2.bank.beneficiaries.view","managePermission":"web.cp.v2.bank.beneficiaries.manage"},{"id":"bank-authorisations","label":"My Authorisations","viewPermission":"web.bank.personal.view"}]},{"label":"Credit","items":[{"id":"loan-centre","label":"Loans & Grants","viewPermission":"web.cp.v2.loan.centre.view","managePermission":"web.cp.v2.loan.centre.manage"},{"id":"bank-loans","label":"My Credit","viewPermission":"web.cp.v2.bank.loans.view","managePermission":"web.cp.v2.bank.loans.manage"},{"id":"loan-administration","label":"Credit Management","viewPermission":"web.cp.v2.loan.administration.view","managePermission":"web.cp.v2.loan.administration.manage"}]},{"label":"Transparency","items":[{"id":"federal-reserve","label":"Federal Reserve Ledger"}]},{"label":"Administration","items":[{"id":"bank-dashboard","label":"Operations Dashboard","viewPermission":"web.cp.v2.bank.dashboard.view","managePermission":"web.cp.v2.bank.dashboard.manage"},{"id":"staff-bank","label":"Treasury Accounts","viewPermission":"web.cp.v2.staff.bank.view","managePermission":"web.cp.v2.staff.bank.manage"},{"id":"company-finance","label":"Business Accounts","viewPermission":"web.cp.v2.company.finance.view","managePermission":"web.cp.v2.company.finance.manage"},{"id":"bank-audit","label":"Audit Log","viewPermission":"web.cp.v2.bank.audit.view","managePermission":"web.cp.v2.bank.audit.manage"}]}]},{"id":"market","label":"CHOAM Exchange","icon":"chart-no-axes-combined","groups":[{"label":"Commodity Exchange","items":[{"id":"commodity-listings","label":"Player Goods"},{"id":"commodity-mine","label":"My Listings"}]},{"label":"Markets","items":[{"id":"stock-overview","label":"Market Overview","viewPermission":"web.cp.v2.stock.overview.view","managePermission":"web.cp.v2.stock.overview.manage"},{"id":"stock-listings","label":"Listed Enterprises","viewPermission":"web.cp.v2.stock.listings.view","managePermission":"web.cp.v2.stock.listings.manage"},{"id":"stock-quotes","label":"Market Prices","viewPermission":"web.cp.v2.stock.quotes.view","managePermission":"web.cp.v2.stock.quotes.manage"},{"id":"stock-portfolio","label":"My Holdings","viewPermission":"web.cp.v2.stock.portfolio.view","managePermission":"web.cp.v2.stock.portfolio.manage"},{"id":"stock-orders","label":"Trading Floor","viewPermission":"web.cp.v2.stock.orders.view","managePermission":"web.cp.v2.stock.orders.manage"},{"id":"stock-trades","label":"Trade Ledger","viewPermission":"web.cp.v2.stock.trades.view","managePermission":"web.cp.v2.stock.trades.manage"},{"id":"stock-watchlist","label":"Watchlist","viewPermission":"web.cp.v2.stock.watchlist.view","managePermission":"web.cp.v2.stock.watchlist.manage"}]},{"label":"Enterprises","items":[{"id":"companies","label":"Companies","viewPermission":"web.cp.v2.companies.view","managePermission":"web.cp.v2.companies.manage"},{"id":"stock-ipo","label":"Listing Applications","viewPermission":"web.cp.v2.stock.ipo.view","managePermission":"web.cp.v2.stock.ipo.manage"},{"id":"stock-dividends","label":"Dividends","viewPermission":"web.cp.v2.stock.dividends.view","managePermission":"web.cp.v2.stock.dividends.manage"}]},{"label":"Oversight","items":[{"id":"stock-admin","label":"Market Authority","viewPermission":"web.cp.v2.stock.admin.view","managePermission":"web.cp.v2.stock.admin.manage"},{"id":"stock-surveillance","label":"Market Surveillance","viewPermission":"web.cp.v2.stock.surveillance.view","managePermission":"web.cp.v2.stock.surveillance.manage"}]}]}]};const art={politics:'seals/office-landsraad.png',realm:'nav-account-v2.webp',bureau:'nav-staff-v2.webp',forge:'nav-manual-v2.webp',post:'nav-support-v2.webp',bank:'imperial-postbank-v2.png',market:'nav-exchange-v2.webp'};const asset=n=>'https://www.dunerealms.com/assets/'+n;const portals=document.querySelector('#portals'),sidebar=document.querySelector('#sidebar'),content=document.querySelector('#content');let current='realm';let disposePage=()=>{};let postMenuTime=0,postMenuRequest=null,renderSequence=0; function el(tag,cls,txt){const e=document.createElement(tag);if(cls)e.className=cls;if(txt!==undefined)e.textContent=txt;return e} function image(name){const x=el('img');x.src=asset(name);x.alt='';x.loading='lazy';return x} /* V1 artwork inventory: use existing /assets/ files; avoid generic repeated symbols. @@ -170,7 +170,7 @@ developer:{entity:'Tasks',create:'New work order',description:'Developer queue, }; function pageType(id,label,workspace){const s=(id+' '+label).toLowerCase();if(/kit|claim|tailor|crysknife/.test(s))return 'kits';if(/bank|treasury|loan|credit|solari|transaction|finance|ledger|revenue/.test(s))return 'finance';if(/stock|market|trade|exchange|merchant|shop|sale|listing|dividend|portfolio/.test(s))return 'market';if(/mail|inbox|dispatch|correspondence|message|ticket|support|petition|appeal/.test(s))return 'messaging';if(/server|network|hosting|monitor|operation|world|backup|status|ban/.test(s))return 'operations';if(workspace==='forge'||/developer|build|forge|git|module|api|blueprint|archive/.test(s))return 'developer';if(/identity|profile|security|discord.link|personal.record/.test(s))return 'identity';return 'records'} function legacyRoute(wid,pid){if(wid==='bank'&&pid==='bank-information')return {wid:'bank',pid:'bank-overview'};if(wid==='bank'&&pid==='bank-history')return {wid:'bank',pid:'bank-statements'};if(wid==='realm'&&pid==='personal-bank')return {wid:'bank',pid:'personal-bank'};if(wid==='realm'&&pid==='transactions')return {wid:'bank',pid:'bank-statements'};if(['realm','post'].includes(wid)&&pid==='shared-inbox')return {wid:'post',pid:'mail-inbox'};if(menu.workspaces.some(w=>w.id===wid))return {wid,pid};const aliases={'exchange':['market','commodity-listings'],'rewards-redeem':['realm','rewards-codes','redeem'],'redeem-code':['realm','rewards-codes','redeem'],'discovery-rewards':['realm','rewards-codes','redeem'],'kit-checkout':['realm','kits-exchange','kit-checkout'],'clan-inbox':['post','clan-inbox'],'faction-inbox':['post','faction-inbox'],'imperial-inbox':['post','imperial-inbox'],'staff-inbox':['post','staff-inbox'],'internal-mail':['post','mail-inbox'],'shared-inbox':['post','mail-inbox'],'personal-bank':['bank','personal-bank'],'transactions':['bank','bank-history']};if(aliases[wid]){const [workspace,page,initialTab]=aliases[wid];return {wid:workspace,pid:page,initialTab};}const workspace=menu.workspaces.find(w=>w.groups.some(g=>g.items.some(item=>item.id===wid)));return workspace?{wid:workspace.id,pid:wid}:{wid,pid};} -let cpReady=false; +let cpReady=false,centralOrganisation=false; function go(wid,pid,context={}){if(!cpReady||!menu.workspaces.length)return;const navigation=++renderSequence;const route=legacyRoute(wid,pid);wid=route.wid;pid=route.pid; if(wid==='post'&&!context.mailDirectoryReady&&Date.now()-postMenuTime>30000){disposePage();disposePage=()=>{};current='post';sidebar.replaceChildren(el('p','','Loading your inboxes…'));content.replaceChildren(el('p','cp-v2-news-status','Loading your authorised inboxes…'));document.querySelector('#sidebar-right').replaceChildren();if(!postMenuRequest)postMenuRequest=import('/v2/cp-v2-post-menu.mjs').then(({loadMailboxMenu})=>loadMailboxMenu()).finally(()=>{postMenuRequest=null;});postMenuRequest.then(inboxes=>{if(navigation!==renderSequence)return;const post=menu.workspaces.find(w=>w.id==='post'),channels=post.groups.find(g=>g.label==='Channels')?.items||[];post.groups=[{label:'Inboxes',items:inboxes},{label:'Channels',items:channels.filter(item=>item.id!=='shared-inbox')}];postMenuTime=Date.now();go('post',pid,{...context,mailDirectoryReady:true});}).catch(error=>{if(navigation!==renderSequence)return;const retry=el('button','gold-button','Retry inbox directory');retry.onclick=()=>go('post',pid);content.replaceChildren(el('p','cp-v2-news-status',error.message),retry);});return;} const initialTab=route.initialTab||context.initialTab;const requestedDesignTab=pid; if(['realm','market'].includes(wid)&&['company-directory','company-registration','company-profile','company-members','company-finance','company-permissions','company-applications'].includes(pid))pid='companies';if(wid==='bureau'&&pid==='dev-approvals'){wid='forge';pid='dev-approvals';}disposePage();disposePage=()=>{};if(wid==='bureau'&&pid==='luckperms')pid='permissions';const w=menu.workspaces.find(x=>x.id===wid)||menu.workspaces[0];current=w.id;const items=w.groups.flatMap(g=>g.items);const item=items.find(x=>x.id===pid)||items[0];for(const b of portals.children)b.setAttribute('aria-selected',String(b.dataset.id===w.id));sidebar.replaceChildren();const sidebarRight=document.querySelector('#sidebar-right');sidebarRight.replaceChildren();const banner=el('div','side-hero',w.id==='forge'?'DEV':w.label.toUpperCase());sidebar.append(banner);sidebarRight.append(el('div','side-hero',w.id==='forge'?'DUNEGIT':w.label.toUpperCase()+' · DIRECTORY'));if(w.id==='realm'){const mail=el('button','mail-shortcut','✉ You’ve Got Mail');mail.onclick=()=>go('post','mail-inbox');sidebar.append(mail)} @@ -199,14 +199,14 @@ 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); - const migrationPreview=new URL(location.href).searchParams.get('migration')==='1'; + const migrationPreview=centralOrganisation||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; } -if(w.id==='bureau'&&item.id==='permissions'&&new URL(location.href).searchParams.get('migration')==='1'){const host=el('div','citizen-live-host');overview.append(host);import('/v2/organisation-permissions.mjs').then(({mountOrganisationPermissions})=>{if(host.isConnected)disposePage=mountOrganisationPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent=error.message});history.replaceState(null,'','#bureau/permissions');return;} +if(w.id==='bureau'&&item.id==='permissions'&&(centralOrganisation||new URL(location.href).searchParams.get('migration')==='1')){const host=el('div','citizen-live-host');overview.append(host);import('/v2/organisation-permissions.mjs').then(({mountOrganisationPermissions})=>{if(host.isConnected)disposePage=mountOrganisationPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent=error.message});history.replaceState(null,'','#bureau/permissions');return;} if(w.id==='bureau'&&item.id==='permissions'){const host=el('div','citizen-live-host');overview.append(host);host.append(el('p','alpha-muted','Loading Imperial Permissions…'));import('/v2/imperial-permissions.mjs?v=rankdelete-20261112a').then(({mountImperialPermissions})=>{if(host.isConnected)mountImperialPermissions(host)}).catch(error=>{if(host.isConnected)host.textContent='Imperial Permissions unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} if(w.id==='bureau'&&item.id==='manual-seals'){const host=el('div','citizen-live-host');overview.append(host);host.append(el('p','alpha-muted','Loading Honours & Seals…'));import('/v2/honours-seals.mjs?v=sealupload-20261112a').then(({mountHonoursSeals})=>{if(host.isConnected)mountHonoursSeals(host)}).catch(error=>{if(host.isConnected)host.textContent='Honours & Seals unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} if(w.id==='bureau'&&['company-management','company-management-v2','company-audit','staff-bank','server-kits','kit-publishing','kit-claims','exchange-admin','shop-admin','items','website-posts','staff-tickets','bans','ban-evidence','forum-admin','quests-admin','community-goals','support-management','server-operations','hosting-control','dev-approvals'].includes(item.id)){const host=el('div','citizen-live-host');overview.append(host);import('/v2/cp-v2-bureau-pages.mjs?v=bureau-registers-20261112c').then(({mountBureauPlaceholder})=>{if(host.isConnected)disposePage=mountBureauPlaceholder(host,item.id)}).catch(error=>{if(host.isConnected)host.textContent='Bureau page unavailable: '+error.message});history.replaceState(null,'','#'+w.id+'/'+item.id);return;} @@ -235,7 +235,7 @@ const status=el('div','alpha-readiness');for(const [name,value] of [['UI','READY const note=card('Integration Checklist','nav-manual-v2.webp',true);const checklist=el('ul','alpha-checklist');for(const step of ['Confirm V1 feature parity and page ownership','Map read endpoints and permission checks','Connect staging API with mock-data fallback','Test empty, loading, error and mobile states','Review and approve before enabling writes'])checklist.append(el('li','',step));note.append(checklist);note.append(el('p','hint','Permission nodes: '+item.viewPermission+' · '+item.managePermission)); } history.replaceState(null,'','#'+w.id+'/'+item.id)} -document.querySelector('#mobile-menu').onclick=()=>{const opened=sidebar.classList.toggle('open');document.querySelector('#sidebar-right').classList.toggle('open',sidebar.classList.contains('open'));document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(opened))};sidebar.addEventListener('click',e=>{if(e.target.closest('.navitem')&&matchMedia('(max-width:720px)').matches)(sidebar.classList.remove('open'),document.querySelector('#sidebar-right').classList.remove('open'))});window.addEventListener('hashchange',()=>{const [w,p,accountId]=location.hash.slice(1).split('/');go(w,p,{accountId,listingId:new URL(location.href).searchParams.get('kit-listing')})});Promise.all([import('/v2/cp-v2-auth.mjs'),import('/v2/cp-v2-access.mjs')]).then(([{startCPAuthentication},{accessibleCPMenu}])=>startCPAuthentication(user=>{menu.workspaces=accessibleCPMenu(menu,user).workspaces;cpReady=true;portals.replaceChildren();for(const w of menu.workspaces){const b=el('button','portal');b.dataset.id=w.id;b.append(image(art[w.id]),el('span','',w.label));b.onclick=()=>go(w.id);portals.append(b)}if(!menu.workspaces.length){content.replaceChildren(el('p','cp-v2-news-status','No workspaces are available for this account.'));return;}const [initial,page,accountId]=location.hash.slice(1).split('/');go(initial||'realm',page,{accountId,listingId:new URL(location.href).searchParams.get('kit-listing')});})).catch(error=>{content.textContent='Account access is temporarily unavailable: '+error.message}); +document.querySelector('#mobile-menu').onclick=()=>{const opened=sidebar.classList.toggle('open');document.querySelector('#sidebar-right').classList.toggle('open',sidebar.classList.contains('open'));document.querySelector('#mobile-menu').setAttribute('aria-expanded',String(opened))};sidebar.addEventListener('click',e=>{if(e.target.closest('.navitem')&&matchMedia('(max-width:720px)').matches)(sidebar.classList.remove('open'),document.querySelector('#sidebar-right').classList.remove('open'))});window.addEventListener('hashchange',()=>{const [w,p,accountId]=location.hash.slice(1).split('/');go(w,p,{accountId,listingId:new URL(location.href).searchParams.get('kit-listing')})});Promise.all([import('/v2/cp-v2-auth.mjs'),import('/v2/cp-v2-access.mjs')]).then(([{startCPAuthentication},{accessibleCPMenu}])=>startCPAuthentication(user=>{centralOrganisation=user.managementModel==='organisation-v2';menu.workspaces=accessibleCPMenu(menu,user).workspaces;cpReady=true;portals.replaceChildren();for(const w of menu.workspaces){const b=el('button','portal');b.dataset.id=w.id;b.append(image(art[w.id]),el('span','',w.label));b.onclick=()=>go(w.id);portals.append(b)}if(!menu.workspaces.length){content.replaceChildren(el('p','cp-v2-news-status','No workspaces are available for this account.'));return;}const [initial,page,accountId]=location.hash.slice(1).split('/');go(initial||'realm',page,{accountId,listingId:new URL(location.href).searchParams.get('kit-listing')});})).catch(error=>{content.textContent='Account access is temporarily unavailable: '+error.message}); // Finish the shared page pattern for retained adapters as they mount. const headingObserver=new MutationObserver(()=>{const hero=content.querySelector(':scope > .hero');if(!hero)return;for(const host of content.querySelectorAll('.citizen-live-host')){for(const heading of host.querySelectorAll(':scope > .cp-v2-template-page > .cp-v2-template-heading')){const title=heading.querySelector('h3')?.textContent,copy=heading.querySelector('p')?.textContent,icon=heading.querySelector('img');if(title)hero.querySelector('h1').textContent=title;if(copy)hero.querySelector('p').textContent=copy;if(icon)hero.querySelector('img').src=icon.src;heading.remove();}for(const duplicate of host.closest('article.card')?.querySelectorAll(':scope > h2, :scope > .hint')||[])duplicate.remove();}});headingObserver.observe(content,{childList:true,subtree:true}); diff --git a/website/docs/great-migration.md b/website/docs/great-migration.md index 86dfc5b3..26575298 100644 --- a/website/docs/great-migration.md +++ b/website/docs/great-migration.md @@ -102,3 +102,5 @@ Default policies now enumerate 22 function mappings (nine branches with Officer/ Runtime integration: ORGANISATION_ACCESS_ENABLED=true opts the central database adapter into fresh, read-snapshot organisation access. The default remains disabled. Enabled accessFor replaces legacy staff/owner bypass with new explicit policies, preserves ordinary/VIP/Order membership, and keeps only the pinned exempt Dev service on its existing access path. Invalid policy data fails closed, never falls back to old admin grants. This switch must not be enabled before control baseline, assignments, policy coverage and native projections are reconciled. This source batch does not enable it in production. Public session exports the account's own active functions. Native bridge integration: activated game sync sends stable permission-set groups through the existing revision-confirmed /permissions/teams bridge. Explicit canonical game nodes plus retained citizen gameplay perks are combined; wildcard/OP/LuckPerms editor grants and service identities are excluded. Duplicate verified UUIDs abort the projection. Unactivated game sync stays on its existing path. Native agent sync reuses the installed osTicket adapter and maps ticket department tags; active human payloads omit native administration flags while retaining business department access. Dev service payload is unchanged. No game server or native application code is rewritten or deployed by this source batch. + +Approved appointments and public staff page: the migration plan resolves 14 existing people into 26 current functions, validates the existing Owner identity and rejects service accounts or conflicting leaders. It defaults to dry-run; explicit application is audited and idempotent. The redesigned staff.html uses the public publication allowlist, one biography card per person, an organigram with explicit vacancies and a separate Crysknife Order gallery. Canonical profile links are retained for Bedrock display names. Active function changes now atomically queue the existing native synchronization outbox; the public process starts its retry worker only in active mode. Forum SSO filters native privilege administration for central human identities while retaining the Dev service path. Existing native products are reused. diff --git a/website/node/game-staff-seals.mjs b/website/node/game-staff-seals.mjs index 7851512a..f0e9e6ad 100644 --- a/website/node/game-staff-seals.mjs +++ b/website/node/game-staff-seals.mjs @@ -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))));} diff --git a/website/node/integration-sso.mjs b/website/node/integration-sso.mjs index e79f6ac8..0389f5c7 100644 --- a/website/node/integration-sso.mjs +++ b/website/node/integration-sso.mjs @@ -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}); } }; } diff --git a/website/node/native-seals.mjs b/website/node/native-seals.mjs index 6c310606..acc7b95f 100644 --- a/website/node/native-seals.mjs +++ b/website/node/native-seals.mjs @@ -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'); diff --git a/website/node/native-sync-outbox.mjs b/website/node/native-sync-outbox.mjs index 56626fd2..0a983b7c 100644 --- a/website/node/native-sync-outbox.mjs +++ b/website/node/native-sync-outbox.mjs @@ -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); diff --git a/website/node/native-sync-schema.mjs b/website/node/native-sync-schema.mjs new file mode 100644 index 00000000..f1205a71 --- /dev/null +++ b/website/node/native-sync-schema.mjs @@ -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 +)`; diff --git a/website/node/organisation-appointments.mjs b/website/node/organisation-appointments.mjs new file mode 100644 index 00000000..e18d0954 --- /dev/null +++ b/website/node/organisation-appointments.mjs @@ -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'}; diff --git a/website/node/organisation-default-policies.mjs b/website/node/organisation-default-policies.mjs index fb7ec876..2b0cbb7e 100644 --- a/website/node/organisation-default-policies.mjs +++ b/website/node/organisation-default-policies.mjs @@ -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; diff --git a/website/node/organisation-effective.mjs b/website/node/organisation-effective.mjs index 602da8b5..4781dc7d 100644 --- a/website/node/organisation-effective.mjs +++ b/website/node/organisation-effective.mjs @@ -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()}){ diff --git a/website/node/organisation-management.mjs b/website/node/organisation-management.mjs index b7043e1b..f25119e3 100644 --- a/website/node/organisation-management.mjs +++ b/website/node/organisation-management.mjs @@ -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); diff --git a/website/node/organisation-model.mjs b/website/node/organisation-model.mjs index 5a5a5ada..c42663d2 100644 --- a/website/node/organisation-model.mjs +++ b/website/node/organisation-model.mjs @@ -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. } diff --git a/website/node/organisation-native-projection.mjs b/website/node/organisation-native-projection.mjs index dce14e96..f3daddde 100644 --- a/website/node/organisation-native-projection.mjs +++ b/website/node/organisation-native-projection.mjs @@ -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, diff --git a/website/node/organisation-public-roster.mjs b/website/node/organisation-public-roster.mjs new file mode 100644 index 00000000..1880682b --- /dev/null +++ b/website/node/organisation-public-roster.mjs @@ -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); + }); +} diff --git a/website/node/permissions.mjs b/website/node/permissions.mjs index d99dabba..047a3aa6 100644 --- a/website/node/permissions.mjs +++ b/website/node/permissions.mjs @@ -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(); diff --git a/website/node/public-staff-roster.mjs b/website/node/public-staff-roster.mjs index e0f23b24..f50bba42 100644 --- a/website/node/public-staff-roster.mjs +++ b/website/node/public-staff-roster.mjs @@ -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'}})}} diff --git a/website/node/server.mjs b/website/node/server.mjs index d1b0946f..2c5898ed 100644 --- a/website/node/server.mjs +++ b/website/node/server.mjs @@ -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.'); diff --git a/website/scripts/bootstrap-organisation-appointments.mjs b/website/scripts/bootstrap-organisation-appointments.mjs new file mode 100644 index 00000000..56163317 --- /dev/null +++ b/website/scripts/bootstrap-organisation-appointments.mjs @@ -0,0 +1,36 @@ +import {randomUUID} from 'node:crypto'; +import {fileURLToPath} from 'node:url';import {resolve} from 'node:path'; +import {openDatabase} from '../node/mysql.mjs'; +import {initializeOrganisation,validStaffRole} from '../node/organisation-model.mjs'; +import {MIGRATION_APPOINTMENTS} from '../node/organisation-appointments.mjs'; +const OWNER_ID='f3ffda37-01e4-41ea-b89d-fbeda82e453e'; +export async function bootstrapAppointments(db,{actorId,apply=false,clock=Date.now}={}){ + const names=[...new Set(MIGRATION_APPOINTMENTS.map(p=>p.username))]; + const {results:accounts}=await db.prepare(`SELECT a.id,a.username,p.game_link_exempt FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.username IN (${names.map(()=>'?')}) AND a.password_hash NOT LIKE '!%'`).bind(...names).all(); + if(accounts.length!==names.length||accounts.some(a=>a.game_link_exempt)||accounts.find(a=>a.username==='unimatrix999')?.id!==OWNER_ID)throw Error('Approved migration identities do not match the existing active accounts.'); + const plan=MIGRATION_APPOINTMENTS.map(p=>({...p,userId:accounts.find(a=>a.username===p.username).id})).sort((a,b)=>(a.scopeType+':'+a.scopeKey+':'+a.role+':'+a.userId).localeCompare(b.scopeType+':'+b.scopeKey+':'+b.role+':'+b.userId)); + if(plan.some(p=>!validStaffRole(p.scopeType,p.scopeKey,p.role)))throw Error('Invalid approved migration function.'); + if(!apply)return {applied:false,accounts:accounts.length,assignments:plan,permissionsChanged:false}; + return db.transaction(async tx=>{ + const actor=await tx.first("SELECT p.principal_kind FROM org_control_principals p JOIN site_accounts a ON a.id=p.user_id WHERE a.id=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[actorId]); + if(!actor||!['owner','executive','service'].includes(actor.principal_kind))throw Error('Existing control actor required.'); + let created=0,retained=0; + for(const p of plan){ + await tx.query('INSERT IGNORE INTO org_scope_versions(scope_type,scope_key,version) VALUES(?,?,1)',[p.scopeType,p.scopeKey]); + await tx.first('SELECT version FROM org_scope_versions WHERE scope_type=? AND scope_key=? FOR UPDATE',[p.scopeType,p.scopeKey]); + const identity=await tx.first("SELECT a.id,p.game_link_exempt FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.id=? AND a.username=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[p.userId,p.username]); + if(!identity||identity.game_link_exempt)throw Error('Migration identity changed.'); + const now=clock(),current=await tx.query("SELECT user_id,role_key FROM org_assignments WHERE scope_type=? AND scope_key=? AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?) FOR UPDATE",[p.scopeType,p.scopeKey,now,now]); + if(current.some(a=>a.user_id===p.userId&&a.role_key===p.role)){retained++;continue;} + if(['branch_lead','department_head','owner_ceo'].includes(p.role)&¤t.some(a=>a.role_key===p.role))throw Error('A migration leadership position already has another holder.'); + const id=randomUUID(); + await tx.query('INSERT INTO org_assignments(id,user_id,scope_type,scope_key,role_key,source_kind,source_ref,status,starts_at,created_by,created_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,?,1)',[id,p.userId,p.scopeType,p.scopeKey,p.role,'manual','great-migration-owner-approved','active',now,actorId,now]); + await tx.query('UPDATE org_scope_versions SET version=version+1 WHERE scope_type=? AND scope_key=?',[p.scopeType,p.scopeKey]); + await tx.query('INSERT INTO org_assignment_events(id,user_id,assignment_id,actor_id,action,scope_type,scope_key,reason,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',[randomUUID(),p.userId,id,actorId,'appointment-baseline',p.scopeType,p.scopeKey,'Owner-approved Great Migration appointment',JSON.stringify({...p,permissionsChanged:false}),now]);created++; + } + return {applied:true,created,retained,permissionsChanged:false}; + }); +} +if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){ + const db=await openDatabase(process.env);try{await initializeOrganisation(db);console.log(JSON.stringify(await bootstrapAppointments(db,{actorId:process.argv.find(a=>a.startsWith('--actor='))?.slice(8),apply:process.argv.includes('--apply')})));}finally{await db.close();} +} diff --git a/website/tests/organisation-appointments.test.mjs b/website/tests/organisation-appointments.test.mjs new file mode 100644 index 00000000..f5957b1b --- /dev/null +++ b/website/tests/organisation-appointments.test.mjs @@ -0,0 +1,12 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {bootstrapAppointments} from '../scripts/bootstrap-organisation-appointments.mjs'; +import {MIGRATION_APPOINTMENTS} from '../node/organisation-appointments.mjs'; +const owner='f3ffda37-01e4-41ea-b89d-fbeda82e453e'; +function fixture({conflict=false,auditFail=false}={}){ + const accounts=[...new Set(MIGRATION_APPOINTMENTS.map(p=>p.username))].map((username,i)=>({username,id:username==='unimatrix999'?owner:'id-'+i,game_link_exempt:0}));const assignments=[],events=[]; + const tx={async first(sql,args){if(sql.includes('org_control_principals'))return {principal_kind:'owner'};if(sql.includes('org_scope_versions'))return {version:1};if(sql.includes('site_accounts'))return accounts.find(a=>a.id===args[0]&&a.username===args[1]);throw Error(sql);},async query(sql,args){if(sql.startsWith('SELECT user_id,role_key')){const list=assignments.filter(a=>a.type===args[0]&&a.scope===args[1]);return conflict?[...list,{user_id:'other',role_key:'branch_lead'}]:list;}if(sql.startsWith('INSERT INTO org_assignments'))assignments.push({user_id:args[1],type:args[2],scope:args[3],role_key:args[4]});if(sql.startsWith('INSERT INTO org_assignment_events')){if(auditFail)throw Error('audit failed');events.push(args);}}}; + const db={prepare(){return {bind(){return {all:async()=>({results:accounts})};}};},async transaction(fn){const a=assignments.length,e=events.length;try{return await fn(tx);}catch(error){assignments.length=a;events.length=e;throw error;}}};return {db,accounts,assignments,events}; +} +test('Approved roster resolves 14 existing people and 26 functions without changing access',async()=>{const f=fixture();const plan=await bootstrapAppointments(f.db);assert.equal(plan.accounts,14);assert.equal(plan.assignments.length,26);assert.equal(plan.permissionsChanged,false);assert.equal(f.assignments.length,0);}); +test('Appointments are audited, idempotent and use the existing Owner identity',async()=>{const f=fixture();const result=await bootstrapAppointments(f.db,{actorId:owner,apply:true});assert.equal(result.created,26);assert.equal(f.events.length,26);const again=await bootstrapAppointments(f.db,{actorId:owner,apply:true});assert.equal(again.created,0);assert.equal(again.retained,26);assert.equal(f.events.length,26);}); +test('A conflicting leader, identity mismatch or audit failure prevents a partial migration',async()=>{const f=fixture({conflict:true});await assert.rejects(bootstrapAppointments(f.db,{actorId:owner,apply:true}),/another holder/);assert.equal(f.assignments.length,0);const bad=fixture();bad.accounts[0].id='wrong';await assert.rejects(bootstrapAppointments(bad.db),/identities/);const fail=fixture({auditFail:true});await assert.rejects(bootstrapAppointments(fail.db,{actorId:owner,apply:true}),/audit/);assert.equal(fail.assignments.length,0);}); diff --git a/website/tests/organisation-management.test.mjs b/website/tests/organisation-management.test.mjs index f7b2dbf7..7785c119 100644 --- a/website/tests/organisation-management.test.mjs +++ b/website/tests/organisation-management.test.mjs @@ -22,7 +22,7 @@ test('policy mapping rejects native editors, unregistered permissions and excess assert.deepEqual(validatePolicyNodes(['web.bank.staff.manage'],'department','department_head'),['web.bank.staff.manage']); assert.deepEqual(validatePolicyNodes(['web.posts.view','web.posts.view'],'branch','officer'),['web.posts.view']); }); -function fixture({principal='owner',positions=[],scopeVersion=1,current=[],existing=null,service=false,authenticated=true,allowed=true,auditFail=false,dbError=null}={}){ +function fixture({principal='owner',positions=[],scopeVersion=1,current=[],existing=null,service=false,authenticated=true,allowed=true,auditFail=false,dbError=null,active=false}={}){ const writes=[]; const tx={async first(sql,args){ if(sql.includes('SELECT a.id,p.game_link_exempt'))return {id:target,game_link_exempt:service?1:0}; @@ -38,7 +38,7 @@ function fixture({principal='owner',positions=[],scopeVersion=1,current=[],exist if(auditFail&&sql.includes('INSERT INTO org_assignment_events'))throw Error('audit unavailable'); writes.push({sql,args});return []; }}; - const db={async transaction(fn){if(dbError)throw Object.assign(new Error('Concurrent transaction'),{code:dbError});const start=writes.length;try{return await fn(tx);}catch(e){writes.splice(start);throw e;}},prepare(){return {bind(){return this;},all:async()=>({results:[]})};}}; + const db={organisationAccessEnabled:active,async transaction(fn){if(dbError)throw Object.assign(new Error('Concurrent transaction'),{code:dbError});const start=writes.length;try{return await fn(tx);}catch(e){writes.splice(start);throw e;}},prepare(){return {bind(){return this;},all:async()=>({results:[]})};}}; const api=createOrganisationManagement(db,{authenticate:async()=>authenticated?{id:owner}:null,authorize:async()=>allowed,clock:()=>100});return {api,writes}; } const body=(extra={})=>({action:'assign',userId:target,scopeType:'branch',scopeKey:'news_media',role:'officer',scopeVersion:1,reason:'Approved appointment',...extra}); @@ -84,3 +84,5 @@ test('control bootstrap pins existing identities, is idempotent and rejects conf principals.set(owner,'owner');await assert.rejects(()=>bootstrapControl(db,{apply:true}),/differs/); rows[0].id=target;await assert.rejects(()=>bootstrapControl(db),/identities/); }); + +test('Activated assignment change queues the native sync in the same transaction',async()=>{const f=fixture({active:true});const r=await f.api(request(body()));assert.equal(r.status,200);const data=await r.json();assert.equal(data.permissionsChanged,true);assert.equal(data.enforcement,'active');assert.equal(data.nativeSyncPending,true);assert(f.writes.some(w=>w.sql.startsWith('INSERT INTO native_sync_outbox')));}); diff --git a/website/tests/organisation-public-roster.test.mjs b/website/tests/organisation-public-roster.test.mjs new file mode 100644 index 00000000..77d7d11e --- /dev/null +++ b/website/tests/organisation-public-roster.test.mjs @@ -0,0 +1,17 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {projectPublicOrganisation} from '../node/organisation-public-roster.mjs'; +const row=(username,scope_type,scope_key,role_key,extra={})=>({username,display_name:username,bio:'A public biography',scope_type,scope_key,role_key,...extra}); +test('One public biography card per person retains multiple functions and executive ordering',()=>{ + const data=projectPublicOrganisation([row('mr_blueray','branch','customer_support','branch_lead'),row('mr_blueray','organisation','dunerealms','executive'),row('unimatrix999','organisation','dunerealms','owner_ceo'),row('mr_blueray','branch','customer_support','branch_lead')]); + assert.equal(data.staff.length,2);assert.equal(data.staff[0].username,'unimatrix999');assert.equal(data.staff[1].functions.length,2);assert.equal(data.staff[1].title,'Chief Community Officer');assert.equal(data.organisation[0].branches[0].leads[0].username,'mr_blueray');assert.deepEqual(data.organisation[1].heads,[]); +}); +test('Service and invalid staff scopes never appear; private database fields are not projected',()=>{ + const data=projectPublicOrganisation([row('dev','branch','engineering','officer',{game_link_exempt:1}),row('hidden','branch','invented','officer'),row('staff','branch','news_media','officer',{email:'private@example.invalid',user_id:'private-id'})]); + assert.equal(data.staff.length,1);assert(!JSON.stringify(data).includes('private@example'));assert(!JSON.stringify(data).includes('private-id')); +}); +test('Only verified Bedrock source identity strips the display prefix; canonical profile link is preserved',()=>{ + const verified=row('bedrock_test','branch','news_media','officer',{source_name:'.test',source_uuid:'uuid',minecraft_uuid:'uuid'});assert.equal(projectPublicOrganisation([verified]).staff[0].displayName,'test');assert.equal(projectPublicOrganisation([verified]).staff[0].profile,'/people/bedrock_test');assert.equal(projectPublicOrganisation([{...verified,minecraft_uuid:'other'}]).staff[0].displayName,'bedrock_test'); +}); +test('Order membership is a separate gallery and never implies a staff role',()=>{ + const data=projectPublicOrganisation([],[{username:'honoured',display_name:'Honoured',citation:'For service'},{username:'picard',slug:'picard',citation:'In remembrance'}]);assert.equal(data.staff.length,0);assert.equal(data.order.length,2);assert.equal(data.order[1].profile,'/memorial/picard'); +}); diff --git a/website/web/staff-directory.css b/website/web/staff-directory.css new file mode 100644 index 00000000..c2377ed0 --- /dev/null +++ b/website/web/staff-directory.css @@ -0,0 +1 @@ +*{box-sizing:border-box}body{margin:0;background:#0a2119;color:#e7eadc;font:15px/1.6 Arial,sans-serif}a{color:#ecd597}main.staff-directory{max-width:1420px;margin:44px auto;padding:0 30px}.staff-hero{display:flex;align-items:center;gap:32px;padding:40px;border:1px solid #b59c59;border-radius:20px;background:linear-gradient(115deg,#244736,#102b22)}.staff-hero>img{width:125px;height:125px;object-fit:contain}.staff-eyebrow,.staff-directory small{font-size:10px;letter-spacing:.14em;color:#beaa73}.staff-directory h1{font:48px/1.15 Georgia,serif;color:#efdaa1;margin:8px 0}.staff-directory h2{font:30px Georgia,serif;color:#efdaa1}.staff-directory h3{font:23px Georgia,serif;color:#efdaa1}.staff-directory h4{font-size:15px;color:#efdaa1;margin:0 0 15px}.staff-section{margin:40px 0}.staff-section>p{color:#bacabd;max-width:760px}.staff-executives{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin:25px 0}.staff-executives article{padding:25px;border:1px solid #aa925a;border-radius:12px;background:linear-gradient(145deg,#3b4431,#142c23)}.staff-executives small,.staff-executives a{display:block}.staff-executives a{font-size:21px;font-weight:700;text-decoration:none;margin-top:10px}.staff-departments{display:grid;grid-template-columns:1fr 1fr;gap:25px}.staff-department{border:1px solid #687c57;border-radius:16px;padding:25px;background:#143226}.staff-department>header{display:flex;gap:16px;align-items:center}.staff-department>header img{width:65px;height:65px;object-fit:contain}.staff-holders{display:flex;gap:8px;flex-wrap:wrap;margin:6px 0 15px}.staff-holders a{padding:3px 9px;border:1px solid #5b7153;border-radius:6px;text-decoration:none;font-size:13px;background:#1d3e2e}.staff-vacant{font-size:11px;color:#a8b6a4}.staff-branches{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:20px}.staff-branches article{border:1px solid #405d46;border-radius:10px;padding:16px;background:#0f291f}.staff-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:20px}.staff-person{border:1px solid #607c59;border-radius:14px;padding:24px;background:linear-gradient(145deg,#1b392b,#112b21)}.staff-person header{display:flex;gap:16px;align-items:center}.staff-person header img{border-radius:12px;background:#0a2119;object-fit:cover}.staff-person header a{font:700 22px Georgia,serif;text-decoration:none}.staff-title{color:#d4bd7c;font-size:13px}.staff-bio{color:#c2cfc0;white-space:pre-wrap;font-size:14px}.staff-person ul{list-style:none;margin:20px 0;padding:0}.staff-person li{padding:9px 0;border-top:1px solid #3c5842}.staff-person li strong,.staff-person li span{display:block;font-size:12px}.staff-person li span{color:#a8bcab}.staff-marks{display:flex;gap:12px;flex-wrap:wrap;margin-top:15px}.staff-marks img{height:70px;width:70px;object-fit:contain}.staff-person summary{cursor:pointer;color:#d9c386;font-size:12px}.staff-order{padding:30px;border:1px solid #ae934d;border-radius:18px;background:radial-gradient(at top right,#4a4429,#183127 70%)}.staff-order-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.staff-order-member{padding:22px;border:1px solid #796e46;border-radius:12px}.staff-order-member>img{width:72px;height:72px;object-fit:contain;float:left;margin-right:16px}.staff-order-member a{font:21px Georgia,serif}.staff-order-member p{white-space:pre-wrap;font-size:13px}.staff-contact{display:flex;align-items:center;justify-content:space-between;gap:25px;padding:25px;border:1px solid #607c59;border-radius:14px}.staff-contact a{padding:12px 20px;border:1px solid #ad9554;border-radius:8px;text-decoration:none;white-space:nowrap}.staff-empty{color:#becbbb;padding:18px;border:1px dashed #6b7953;border-radius:10px}#staff-status{font-size:13px;color:#c7d2bf}#organisation-chart{overflow-x:auto}.staff-directory :focus-visible{outline:2px solid #f1d182;outline-offset:4px} diff --git a/website/web/staff-directory.js b/website/web/staff-directory.js new file mode 100644 index 00000000..4f8774db --- /dev/null +++ b/website/web/staff-directory.js @@ -0,0 +1,18 @@ +const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;}; +const files={community_operations:'department-support-150.png',dunerealms_operations:'department-network-staff-150.png',customer_support:'department-support-150.png',sales_accounts:'department-sales-150.png',trust_safety:'department-ban-appeals-150.png',it_operations:'department-network-staff-150.png',engineering:'department-dev-150.png',legal_compliance:'department-legal-v2-150.png'}; +function seal(file,label){const img=el('img');img.src='/assets/seals/'+file;img.alt=label;img.loading='lazy';img.addEventListener('error',()=>{img.hidden=true;},{once:true});return img;} +function profile(p){const a=el('a',p.displayName||p.username);a.href=/^\/(?:people|memorial)\/[a-z0-9_%.-]+$/i.test(p.profile||'')?p.profile:'/people/'+encodeURIComponent(p.username);return a;} +function holders(people,empty='VACANT'){const wrap=el('div',undefined,'staff-holders');if(!people.length)wrap.append(el('span',empty,'staff-vacant'));for(const p of people)wrap.append(profile(p));return wrap;} +function card(p){const c=el('article',undefined,'staff-person'),head=el('header'),avatar=el('img');avatar.src=p.avatar||'https://cp.dunerealms.com/api/avatars/roster/'+encodeURIComponent(p.username);avatar.alt='';avatar.loading='lazy';avatar.width=avatar.height=64;head.append(avatar,profile(p));c.append(head,el('p',p.title||p.rank||'Staff','staff-title'),el('p',p.bio||'No public biography added yet.','staff-bio')); + const list=el('ul');for(const f of p.functions||[]){const li=el('li');li.append(el('strong',f.scopeLabel),el('span',f.roleLabel));list.append(li);}c.append(list); + const marks=el('div',undefined,'staff-marks'),seen=new Set();for(const f of p.functions||[]){const file=files[f.scopeKey];if(file&&!seen.has(file)){marks.append(seal(file,f.scopeLabel+' function seal'));seen.add(file);}} + for(const a of p.seals||[])if(/^[a-z0-9_-]+\.png$/.test(a.file||''))marks.append(seal(a.file,a.label||'Earned honour'));if(marks.childElementCount){const details=el('details');details.append(el('summary','Function seals & earned honours'),marks);c.append(details);}return c;} +function render(data){const chart=document.querySelector('#organisation-chart'),cards=document.querySelector('#staff-members'),order=document.querySelector('#order-members'); + if(data.model!=='organisation-v2'){const people=new Map();for(const g of data.groups||[])for(const p of g.staff||[])people.set(p.username,p);for(const p of people.values())cards.append(card(p));chart.append(el('p','The new organigram will appear when its migration is activated.','staff-empty'));document.querySelector('#staff-status').textContent=people.size+' existing public staff profiles.';return;} + const exec=el('div',undefined,'staff-executives');for(const p of data.executives){const c=el('article');c.append(el('small',p.title),profile(p));exec.append(c);}chart.append(exec); + const deps=el('div',undefined,'staff-departments');for(const d of data.organisation){const section=el('section',undefined,'staff-department'),head=el('header');head.append(seal(files[d.key],d.label),el('h3',d.label));section.append(head,el('small','DEPARTMENT HEAD'),holders(d.heads));const branches=el('div',undefined,'staff-branches');for(const b of d.branches){const c=el('article');c.append(el('h4',b.label),el('small','BRANCH LEAD'),holders(b.leads),el('small','OFFICERS'),holders(b.members,'No published officers'));branches.append(c);}section.append(branches);deps.append(section);}chart.append(deps); + for(const p of data.staff)cards.append(card(p));if(!data.staff.length)cards.append(el('p','No staff profiles are published yet.','staff-empty')); + for(const p of data.order){const c=el('article',undefined,'staff-order-member');c.append(seal('order-crysknife-v1.png','Holy Order of the Crysknife'),profile(p));if(p.citation)c.append(el('p',p.citation));order.append(c);}if(!data.order.length)order.append(el('p','No public Order memberships are listed.','staff-empty')); + document.querySelector('#staff-status').textContent=data.staff.length+' published staff profiles · Functions from the central organisation register.'; +} +try{const r=await fetch('/api/staff/roster',{cache:'no-store',headers:{Accept:'application/json'}});if(!r.ok)throw Error();const data=await r.json();if(data.model!=='organisation-v2'&&!Array.isArray(data.groups))throw Error();render(data);}catch{document.querySelector('#staff-status').textContent='The staff register is temporarily unavailable. Please contact Support for assistance.';} diff --git a/website/web/staff.html b/website/web/staff.html index f7884baf..0107f2d9 100644 --- a/website/web/staff.html +++ b/website/web/staff.html @@ -1 +1 @@ -Staff & Contributors — dunerealms.com

dunerealms.com / THE ROCKHAVEN COUNCIL

Staff & Contributors

The people who support the community, and the development work behind the dunes.

DUNEREALMS STAFF BUREAU

Full Staff Roster

Meet the publicly listed members of our network staff. Appointments are grouped by their primary department and subteam; personal seals and recognitions remain distinct from staff authority.

Loading published staff roster…

FOUR DEPARTMENTS · SEVEN SPECIALIST TEAMS

Departments & Subteams

PRIVATE SUPPORT · STAFF CONTACT

Contact our teams

Choose the appropriate team to open a private support request. Do not post personal information on public profiles.

\ No newline at end of file +Our People | DuneRealmsSkip to staff directory
DuneRealms staff emblem

THE PEOPLE BEHIND THE REALMS

Our people

Clear responsibilities. Connected teams. One community.

LEADERSHIP & RESPONSIBILITY

Our organisation

Explore our leadership, departments and branches. A person may hold several functions; each remains accountable within its own scope.

Loading the public staff register…

MEET THE TEAM

Staff directory

One profile per person, with their current functions and public biography.

SERVICE BEYOND OFFICE

Holy Order of the Crysknife

The Order recognises service to DuneRealms. Membership is distinct from staff authority and may include community members.

THE RIGHT TEAM, IN ONE PLACE

How can we help?

Contact Support for account help, appeals, sales, technical issues or private enquiries.

Open Support Center →
\ No newline at end of file From 37bbfdc88275333fdf658189d432c89a15321a9f Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:47:18 +0100 Subject: [PATCH 16/16] Preserve citizen benefits and derive bank staff eligibility from current functions --- website/node/organisation-runtime.mjs | 6 +++--- website/node/permissions.mjs | 2 +- website/node/postbank-authority.mjs | 4 +++- website/tests/organisation-runtime.test.mjs | 7 +++++++ 4 files changed, 14 insertions(+), 5 deletions(-) diff --git a/website/node/organisation-runtime.mjs b/website/node/organisation-runtime.mjs index 7b8ee1fe..39f85b88 100644 --- a/website/node/organisation-runtime.mjs +++ b/website/node/organisation-runtime.mjs @@ -2,7 +2,7 @@ import {effectiveOrganisationAccess} from './organisation-effective.mjs'; import {assignmentLabel,validStaffRole} from './organisation-model.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.'); +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); const nativeEditor=node=>['web.luckperms.edit','cp.luckperms.edit','luckperms.editor','luckperms.applyedits','luckperms.trusteditor'].includes(node); export async function organisationRuntimeAccess(db,user,{registry,basicRank,legacyRanks,clock=Date.now}={}){ const now=clock(); @@ -18,9 +18,9 @@ export async function organisationRuntimeAccess(db,user,{registry,basicRank,lega return {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.nodes||[]).some(privileged)); + const citizenRanks=legacyRanks.filter(r=>!legacyStaff.has(r.key)&&!r.key.startsWith('web_')&&!r.key.startsWith('game_')); const ranks=[basicRank,...citizenRanks.filter(r=>r.key!==basicRank.key)]; - const nodes=new Set(ranks.flatMap(r=>r.nodes||[]).filter(n=>Object.hasOwn(registry,n)&&!nativeEditor(n)&&!n.includes('*'))); + const nodes=new Set(ranks.flatMap(r=>r.nodes||[]).filter(n=>Object.hasOwn(registry,n)&&!privileged(n)&&!nativeEditor(n)&&!n.includes('*'))); for(const n of snapshot.access.nodes)nodes.add(n); for(const n of [...nodes])if(n.startsWith('cp.')&&Object.hasOwn(registry,'web.'+n.slice(3)))nodes.add('web.'+n.slice(3)); const active=snapshot.assignments.filter(a=>validStaffRole(a.scope_type,a.scope_key,a.role_key)&&a.status==='active'&&Number(a.starts_at)<=now&&(a.ends_at===null||Number(a.ends_at)>now)); diff --git a/website/node/permissions.mjs b/website/node/permissions.mjs index 047a3aa6..7dbc1c94 100644 --- a/website/node/permissions.mjs +++ b/website/node/permissions.mjs @@ -88,7 +88,7 @@ export async function accessFor(db,user){ const requested=[user.role,...(Array.isArray(user.ranks)?user.ranks:[])].filter(r=>typeof r==='string'&&r.length>0); const keys=[...new Set(requested.map(rankKey))]; const ranks=await Promise.all(keys.map(key=>rankFor(db,key))); - if(db.organisationAccessEnabled===true){const central=await organisationRuntimeAccess(db,user,{registry:NODES,basicRank:DEFAULT_RANKS.find(r=>r.key==='user'),legacyRanks:ranks});if(central)return central;} + if(db.organisationAccessEnabled===true){const central=await organisationRuntimeAccess(db,user,{registry:NODES,basicRank:await rankFor(db,'user'),legacyRanks:ranks});if(central)return central;} const owner=ranks.some(rank=>isOwnerRank(rank.key)); const granted=ranks.flatMap(rank=>Array.isArray(rank.nodes)?rank.nodes:[]); const normalized=granted.flatMap(node=>node.startsWith('cp.')? [node,'web.'+node.slice(3)]:[node]); diff --git a/website/node/postbank-authority.mjs b/website/node/postbank-authority.mjs index d5021039..0afac3b6 100644 --- a/website/node/postbank-authority.mjs +++ b/website/node/postbank-authority.mjs @@ -39,7 +39,9 @@ export function createPostbankAuthority(central,{clock=Date.now,rightsFor=access } // Staff eligibility follows current central access roles, not cosmetic honours. const staff=await rows("SELECT a.id,a.username,a.role FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND COALESCE(p.game_link_exempt,0)=0"); - const eligibleStaff=staff.filter(a=>STAFF_ROLES.has(a.role)); + const currentStaff=central.organisationAccessEnabled?await rows("SELECT DISTINCT user_id FROM org_assignments WHERE scope_type IN ('organisation','department','branch') AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?)",[now,now]):null; + const currentStaffIds=currentStaff?new Set(currentStaff.map(a=>a.user_id)):null; + const eligibleStaff=staff.filter(a=>currentStaffIds?currentStaffIds.has(a.id):STAFF_ROLES.has(a.role)); for(const actor of eligibleStaff)add('staff',actor.id,actor.username+' · Staff',[actor.id]); return delegatedAuthority({entities:sources,readAdmin,manageAdmin,rankKeys:rights.ranks||[user.role],eligibleStaff:eligibleStaff.map(a=>({id:a.id,username:a.username})),server:{state:'not_linked',name:'Game server account'}},user,store,now); }; diff --git a/website/tests/organisation-runtime.test.mjs b/website/tests/organisation-runtime.test.mjs index fc73aa24..9cf89151 100644 --- a/website/tests/organisation-runtime.test.mjs +++ b/website/tests/organisation-runtime.test.mjs @@ -38,3 +38,10 @@ test('Only the pinned, exempt Dev identity retains its existing service access', test('A malformed policy denies resolution instead of falling back to old privileged ranks',async()=>{ const db=database();db.readSnapshot=async fn=>fn({query:async sql=>sql.includes('org_control')?[]:sql.includes('org_assignments')?[position]:[{scope_type:'branch',scope_key:'news_media',role_key:'officer',permissions_json:'corrupt',version:1}]});await assert.rejects(resolve(db),/Invalid stored/); }); + +test('Safe persisted citizen features survive while accidental staff grants on User/VIP are removed',async()=>{ + const base={...DEFAULT_RANKS[0],nodes:[...DEFAULT_RANKS[0].nodes,'web.mail.internal.view','web.quests.view','web.bank.staff.manage']}; + const vip={key:'vip',label:'VIP',level:20,kind:'access',nodes:['duneess.chat.colors','web.accounts.assign']}; + const result=await organisationRuntimeAccess(database({assignments:[]}),user,{registry:NODES,basicRank:base,legacyRanks:[vip],clock:()=>10}); + assert(result.nodes.includes('web.mail.internal.view'));assert(result.nodes.includes('web.quests.view'));assert(result.nodes.includes('duneess.chat.colors'));assert(result.ranks.includes('vip'));assert(!result.nodes.includes('web.bank.staff.manage'));assert(!result.nodes.includes('web.accounts.assign')); +});