Merge pull request 'Alpha 1.0.0.7 — The Great Migration' (#301) from dev/MC:dev/alpha-1.0.0.7-the-great-migration into main

This commit is contained in:
Dev 2026-11-15 03:14:32 +01:00
commit 351d6535d3
16 changed files with 236 additions and 35 deletions

View file

@ -1,4 +1,15 @@
.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 nav.md-tabs button[role=tab]{background:#102b22!important;color:#d9c98e!important;border:1px solid #68816b!important;box-shadow:none!important;transform:none!important}
.migration-directory nav.md-tabs button[aria-selected=true]{background:#dec47d!important;color:#14291f!important;border-color:#f8e6af!important;box-shadow:inset 0 -4px #9c7735,0 0 0 2px #d9be6b33!important;font-weight:750!important}
.migration-directory nav.md-tabs button[aria-selected=false]:hover{background:#244c38!important;border-color:#b5a363!important}
.migration-directory .md-rank-table caption{text-align:left;padding:16px;color:#ead399;font-weight:650;background:#1e422f}
.migration-directory .md-rank-table th:not(:first-child),.migration-directory .md-rank-table td{text-align:center;vertical-align:middle}
.migration-directory .md-rank-table tbody th{text-transform:none;letter-spacing:normal;min-width:160px;font-size:13px;background:#1b3b2d}
.migration-directory .md-rank-table tbody th small{font-size:11px;font-weight:400;margin-top:4px}
.migration-directory .md-rank-choice{display:flex;align-items:center;justify-content:center;gap:8px;padding:12px 10px;min-height:40px;border:1px solid #66846b;border-radius:7px;cursor:pointer;color:#e7dfbb;background:#102b22}
.migration-directory .md-rank-choice.selected{border-color:#e8cf87;background:#71603155;box-shadow:inset 0 0 0 1px #d2b86d;color:#ffe9a9}
.migration-directory .md-rank-choice input{accent-color:#dec47d;width:18px;height:18px;padding:0;flex-shrink:0}
.migration-directory .md-rank-choice span{font-size:12px}.migration-directory .md-unavailable{color:#77917d}
.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}

View file

@ -12,10 +12,10 @@ 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()));
const diagnostics=element('details',undefined,'md-diagnostics');diagnostics.append(element('summary','+ Workspace details'),element('p','Central account directory. Function changes are versioned and audited.'),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:[]},assignmentData=null;
let searchTimer;
let searchTimer,assignmentMode='unknown';
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;}
@ -24,7 +24,10 @@ 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','The new assignment register is being prepared. Recorded changes do not replace existing permissions until migration activation.','md-note'));
if(context==='staff'){
panel.append(element('p',assignmentMode==='active'?'Staff assignments control current access. Function changes update central permissions and synchronise connected services.':assignmentMode==='preparing'?'The assignment register is being prepared. Permission activation is pending.':'Current functions are listed above. Open Staff assignments to manage access.','md-note'));
if(tab!=='assignments')panel.append(button('Manage assignments',()=>{tab='assignments';renderAccount();}));
}
return panel;
}
function scopeVersion(a){return Number(assignmentData.versions.find(v=>v.scope_type===a.scopeType&&v.scope_key===a.scopeKey)?.version||1);}
@ -45,14 +48,23 @@ export function mountCitizenDirectory(host){
}
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 form=element('form',undefined,'md-assignment-form');let selection=null;
const roleNames={officer:'Officer',branch_lead:'Branch Lead',department_head:'Department Head',executive:'Executive',owner_ceo:'Owner & CEO'};
const roles=Object.keys(roleNames).filter(r=>data.editable.some(s=>s.role===r));
const unique=[...new Map(data.editable.map(s=>[s.type+':'+s.key,s])).values()];
const wrap=element('div',undefined,'md-table-wrap'),table=element('table',undefined,'md-table md-rank-table'),head=element('thead'),headRow=element('tr'),body=element('tbody');
table.append(element('caption','Choose a department or branch and the function to assign'));headRow.append(element('th','Department / branch'));
for(const r of roles)headRow.append(element('th',roleNames[r]));head.append(headRow);table.append(head);
for(const s of unique){const row=element('tr'),name=element('th',s.label);name.scope='row';name.append(element('small',s.type==='organisation'?'Leadership':s.type==='department'?'Department':'Branch'));row.append(name);
for(const r of roles){const cell=element('td'),option=data.editable.find(a=>a.type===s.type&&a.key===s.key&&a.role===r);
if(option){const label=element('label',undefined,'md-rank-choice'),radio=element('input');radio.type='radio';radio.name='appointment-role';radio.required=true;radio.value=s.type+':'+s.key+':'+r;radio.setAttribute('aria-label',roleNames[r]+' · '+s.label);radio.onchange=()=>{selection=option;for(const item of body.querySelectorAll('label'))item.classList.toggle('selected',item.contains(radio));save.disabled=false;};label.append(radio,element('span',roleNames[r]));cell.append(label);}else{cell.textContent='—';cell.className='md-unavailable';}row.append(cell);
}body.append(row);
}table.append(body);wrap.append(table);form.append(wrap);
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{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;}
const save=button('Save assignment',()=>{});save.type='submit';save.disabled=true;
const reasonField=element('label','Reason','md-field');reasonField.append(reason);form.append(reasonField,save);
form.onsubmit=async e=>{e.preventDefault();if(!selection||!form.reportValidity())return;const {type,key,role}=selection;if(!confirm('Assign '+roleNames[role]+' in '+selection.label+' to '+selected.username+'?'))return;save.disabled=true;
try{const result=await send({action:'assign',userId:target,scopeType:type,scopeKey:key,role,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);
@ -69,19 +81,19 @@ export function mountCitizenDirectory(host){
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'));
panel.replaceChildren(element('h3','Effective function permissions'),element('p',data.enforcement==='active'?'These function permissions are active. Ordinary citizen and membership benefits are added separately.':'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.'));
if(!data.sources.length&&!data.missingPolicies.length)panel.append(element('p','No active mapped staff functions.'));
}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 hero=element('header',undefined,'md-identity');const avatar=element('img');avatar.alt='';avatar.width=56;avatar.height=56;avatar.src=selected.minecraftUuid?'/api/avatars/face/'+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'],['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);
const nav=element('nav',undefined,'md-tabs');nav.setAttribute('role','tablist');nav.setAttribute('aria-label','Manage '+(context==='staff'?'staff':'user'));for(const[key,label]of tabs){const b=button(label,()=>{tab=key;renderAccount();});b.setAttribute('role','tab');b.setAttribute('aria-selected',String(tab===key));if(tab===key)b.setAttribute('aria-current','page');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);}
@ -94,7 +106,7 @@ export function mountCitizenDirectory(host){
}
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);
view.replaceChildren();heading();const nav=element('nav',undefined,'md-tabs');nav.setAttribute('role','tablist');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('role','tab');b.setAttribute('aria-selected',String(context===key));if(context===key)b.setAttribute('aria-current','page');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();}));
@ -105,7 +117,7 @@ export function mountCitizenDirectory(host){
}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);}
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(context==='staff'?'Manage staff →':'Manage user →',()=>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'));
@ -117,7 +129,7 @@ export function mountCitizenDirectory(host){
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;}}}
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;assignmentMode=data.assignmentMode;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;assignmentMode=data.assignmentMode;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();};
}

View file

@ -10,7 +10,7 @@ export function mountOrganisationPermissions(host){
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'));
content.replaceChildren();content.append(el('p',data.enforcement==='active'?'Active permission policies: saved changes update central access and synchronise connected services. All changes are versioned and audited.':'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;
@ -22,8 +22,8 @@ export function mountOrganisationPermissions(host){
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;}
form.onsubmit=async e=>{e.preventDefault();if(busy||!data.canEdit||!form.reportValidity()||!confirm(data.enforcement==='active'?'Save this policy and update current access?':'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=data.enforcement==='active'?'Policy saved and audited. Central access updated; native synchronisation queued.':'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);

View file

@ -10,8 +10,25 @@ export async function avatarForAccount(db,userId){
const fallback='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" shape-rendering="crispEdges"><path fill="#976e50" d="M0 0h8v8H0z"/><path fill="#493225" d="M0 0h8v3H0zM0 3h1v2H0zM7 3h1v2H7z"/><path fill="#bc916a" d="M1 3h6v3H1z"/><path fill="#eee8d8" d="M1 4h2v1H1zM5 4h2v1H5z"/><path fill="#5c77b7" d="M2 4h1v1H2zM5 4h1v1H5z"/><path fill="#79513c" d="M3 5h2v1H3zM2 7h4v1H2z"/><path fill="#432c25" d="M2 6h1v1H2zM5 6h1v1H5zM3 7h2v1H3z"/></svg>';
const fallbackSkin=fallback.replace('viewBox="0 0 8 8"','width="64" height="64" viewBox="0 0 64 64"').replace('shape-rendering="crispEdges">','shape-rendering="crispEdges"><g transform="translate(8 8)">').replace('</svg>','</g></svg>');
const fallbackResponse=skin=>new Response(skin?fallbackSkin:fallback,{headers:{'Content-Type':'image/svg+xml','Cache-Control':'public,max-age=300','X-Content-Type-Options':'nosniff'}});
function faceResponse(skin){
if(!skin)return fallbackResponse(false);
const png=Buffer.from(skin.bytes).toString('base64'),height=skin.height===32?32:64;
const svg=`<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 8 8" style="image-rendering:pixelated"><defs><image id="skin" width="64" height="${height}" href="data:image/png;base64,${png}"/></defs><use href="#skin" x="-8" y="-8"/><use href="#skin" x="-40" y="-8"/></svg>`;
return new Response(svg,{headers:{'Content-Type':'image/svg+xml','Cache-Control':'public,max-age=300','X-Content-Type-Options':'nosniff'}});
}
export function createAvatars(db,settings,{fetcher=fetch,resolver=fetcher===fetch?minecraftSkins:createSkinResolver({fetcher})}={}){const handle=async request=>{
const path=new URL(request.url).pathname;if(request.method!=='GET')return new Response('Method not allowed',{status:405});
const face=path.match(/^\/api\/avatars\/face\/(?:(member|roster)\/([a-z0-9_]{3,32})|([0-9a-f-]{36}))$/i);
if(face){
let linked=face[3];
if(face[1]){
const account=await db.prepare("SELECT a.id,l.minecraft_uuid FROM site_accounts a LEFT JOIN site_game_links l ON l.user_id=a.id WHERE a.username=? AND a.password_hash NOT LIKE '!%'").bind(face[2]).first();
if(!account)return new Response('Not found',{status:404});
if(face[1]==='member'){const avatar=await avatarForAccount(db,account.id);if(avatar.mode==='image')return handle(new Request(new URL(avatar.url,request.url)));}
linked=account.minecraft_uuid;
}
return faceResponse(uuid.test(linked||'')?await resolver.resolve(linked):null);
}
const member=path.match(/^\/api\/avatars\/member\/([a-z0-9_]{3,32})$/);
if(member){
const account=await db.prepare("SELECT id FROM site_accounts WHERE username=? AND password_hash NOT LIKE '!%'").bind(member[1]).first();if(!account)return new Response('Not found',{status:404});

View file

@ -52,8 +52,9 @@ export function createCitizenDirectory(db,{authenticate=identity,authorize=can,c
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 assignmentMode=db.organisationAccessEnabled?'active':'preparing';
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});
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,permissionsChanged:false});
const match=url.pathname.match(/^\/api\/admin\/citizens\/([0-9a-f-]{36})$/i);
if(match){
// Staff managers may open a human candidate before their first appointment.
@ -68,11 +69,11 @@ export function createCitizenDirectory(db,{authenticate=identity,authorize=can,c
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});
return reply({account,context:filter.context,assignmentMode,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'});
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});
};
}

View file

@ -240,6 +240,96 @@
"label": "All WorldGuard tools",
"source": "Approved plugin wildcard: network administrator only",
"highRisk": true
},
{
"node": "dune.items.give",
"label": "Issue registered custom items",
"source": "DuneRealms central registered permission catalogue",
"highRisk": true
},
{
"node": "dune.staff.ban.local",
"label": "Ban from one server",
"source": "DuneRealms central registered permission catalogue",
"highRisk": true
},
{
"node": "dune.staff.ban.network",
"label": "Ban from the network",
"source": "DuneRealms central registered permission catalogue",
"highRisk": true
},
{
"node": "dune.staff.history",
"label": "View punishment history",
"source": "DuneRealms central registered permission catalogue",
"highRisk": true
},
{
"node": "dune.staff.kick",
"label": "Kick players",
"source": "DuneRealms central registered permission catalogue",
"highRisk": true
},
{
"node": "dune.staff.mute",
"label": "Mute players",
"source": "DuneRealms central registered permission catalogue",
"highRisk": true
},
{
"node": "dune.staff.open",
"label": "Open staff GUI",
"source": "DuneRealms central registered permission catalogue",
"highRisk": true
},
{
"node": "dune.staff.warn",
"label": "Warn players",
"source": "DuneRealms central registered permission catalogue",
"highRisk": true
},
{
"node": "duneess.exchange",
"label": "Exchange shop",
"source": "DuneRealms central registered permission catalogue",
"highRisk": false
},
{
"node": "duneess.shops.use",
"label": "Use NPC shops",
"source": "DuneRealms central registered permission catalogue",
"highRisk": false
},
{
"node": "duneess.tokens.buy",
"label": "Buy guild tokens",
"source": "DuneRealms central registered permission catalogue",
"highRisk": false
},
{
"node": "duneess.travel",
"label": "Guild travel",
"source": "DuneRealms central registered permission catalogue",
"highRisk": false
},
{
"node": "dunelobby.admin",
"label": "Lobby administration",
"source": "DuneRealms central registered permission catalogue",
"highRisk": true
},
{
"node": "dunelobby.build",
"label": "Build in protected lobby",
"source": "DuneRealms central registered permission catalogue",
"highRisk": true
},
{
"node": "dunelobby.visit",
"label": "Visit lobby",
"source": "DuneRealms central registered permission catalogue",
"highRisk": false
}
],
"networkAdministratorRoles": [

View file

@ -9,6 +9,7 @@ import{publicProfileFor}from'./profile.mjs';
import{badgesFor,BADGES,communityBadgeVisible}from'./community-badges.mjs';
import {activeSealEntitlements} from './seal-entitlement-store.mjs';
import {isShowcaseSeal} from './seal-entitlements.mjs';
import {EXECUTIVE_TITLES} from './organisation-appointments.mjs';
import{staffSealFor,departmentsFor}from'./native-seals.mjs';
import{staffClosureStats,statsForAccount,departmentAwardEarned}from'./staff-closure-stats.mjs';
const origin='https://www.dunerealms.com',base=origin+'/assets/seals/';
@ -36,7 +37,7 @@ export async function memberProfileData(db,target,settings={}){
const showcase=target.username.toLowerCase()==='dunerealms';
// Showcase never impersonates other people's personalized seals or the Crysknife Order.
const showcaseSealAllowed=(key,asset)=>!(/^(owner-|personal-staff-|network-staff-mr_|main-network-admin-|corestaff-)/i.test(key)||/crysknife/i.test(key+' '+(asset?.label||'')+' '+(asset?.footer150||'')));
const ranks=[];for(const key of access.ranks){const r=await rankFor(db,key);if(!ranks.some(x=>x.label===r.label))ranks.push({key:r.key,label:r.label});}
const ranks=[];for(const key of access.ranks){const functionRole=key.startsWith('org_')?access.organisation?.assignments.find(a=>'org_'+a.role===key):null;const r=functionRole?{key,label:functionRole.scopeType==='organisation'?(EXECUTIVE_TITLES[target.username]||functionRole.roleLabel):functionRole.roleLabel}:await rankFor(db,key);if(!ranks.some(x=>x.label===r.label))ranks.push({key:r.key,label:r.label});}
const medals=[];const add=(key,label,url,group)=>{if(!medals.some(m=>m.key===key)&&typeof url==='string'&&/^https:\/\/(www|support|forums)\.dunerealms\.com\/assets\/seals\/[a-zA-Z0-9_./-]+\.png$/.test(url))medals.push({key,label,url:url.replace(/^https:\/\/(support|forums)\.dunerealms\.com\//,'https://www.dunerealms.com/'),group});};
const personal=showcase?Object.values(manifest).find(a=>a.label?.toLowerCase()===target.username.toLowerCase()&&a.role==='OWNER')?.footer150||null:staffSealFor({...target,ranks:access.ranks},manifest);const namedPersonal=personal&&!personal.includes('/rank-network-staff-');if(personal)add('personal-role',namedPersonal?target.username+' · Personal seal':access.label,personal.startsWith('/')?(personal.includes('main-network')?'https://support.dunerealms.com':'https://www.dunerealms.com')+personal:personal,'Staff');
for(const key of departmentsFor(access.nodes,access.ranks,target.username)){
@ -64,7 +65,7 @@ export async function memberProfileData(db,target,settings={}){
const office=await optional(()=>db.prepare('SELECT roles_json,expires_at FROM drforum_dune_political_roles WHERE website_id=?').bind(target.id).first(),null);
if(office&&Number(office.expires_at)>Date.now()/1000){const known={emperor:'Emperor',house_leader:'Faction leader',specerhuis:'Specerhuis',welvaart:'House of Water',guild_staff:'Vaerkring',landsraad:'Landsraad'};for(const key of JSON.parse(office.roles_json||'[]'))if(known[key])add('office-'+key,known[key],'https://forums.dunerealms.com/assets/seals/office-'+key+'.png','Political offices');}
const clan=await optional(()=>db.prepare('SELECT c.name,c.tag,c.description,m.clan_role,m.joined_at,(SELECT COUNT(*) FROM site_clan_members n WHERE n.clan_id=c.id) AS member_count FROM site_clan_members m JOIN site_clans c ON c.id=m.clan_id WHERE m.user_id=? AND c.active=1').bind(target.id).first(),undefined);
return{showcase,personalSeal:namedPersonal?medals.find(m=>m.key==='personal-role'):null,username:target.username,displayName:target.display_name,joinedAt:Number(target.created_at),avatar:'https://cp.dunerealms.com/api/avatars/member/'+encodeURIComponent(target.username),avatarMode:publicProfile.avatar.mode,bio:publicProfile.bio,publicInfo:publicProfile.publicInfo,socials:publicProfile.socials,ranks,medals,forum:await publicForumFor(db,target.id),support:{status:staff?(stats?'available':'unavailable'):'not-staff',closed:stats?.totalClosed??null,departments:stats?.departments||{}},quests:{status:'placeholder',completed:null,active:null},clan:clan===undefined?{status:'unavailable'}:clan?{status:'member',name:clan.name,tag:clan.tag,description:clan.description,role:clan.clan_role,joinedAt:Number(clan.joined_at),members:Math.max(0,Number(clan.member_count))}:{status:'none'}};
return{showcase,personalSeal:namedPersonal?medals.find(m=>m.key==='personal-role'):null,username:target.username,displayName:target.display_name,joinedAt:Number(target.created_at),functions:access.organisation?.assignments||[],avatar:'https://cp.dunerealms.com/api/avatars/face/member/'+encodeURIComponent(target.username),avatarMode:'image',bio:publicProfile.bio,publicInfo:publicProfile.publicInfo,socials:publicProfile.socials,ranks,medals,forum:await publicForumFor(db,target.id),support:{status:staff?(stats?'available':'unavailable'):'not-staff',closed:stats?.totalClosed??null,departments:stats?.departments||{}},quests:{status:'placeholder',completed:null,active:null},clan:clan===undefined?{status:'unavailable'}:clan?{status:'member',name:clan.name,tag:clan.tag,description:clan.description,role:clan.clan_role,joinedAt:Number(clan.joined_at),members:Math.max(0,Number(clan.member_count))}:{status:'none'}};
}
export function createMemberProfiles(db,settings={}){return async request=>{
const from=request.headers.get('origin');if(from&&from!==origin)return json({message:'Origin rejected.'},403);

View file

@ -72,7 +72,7 @@ export function createOrganisationManagement(db,{origin='https://cp.dunerealms.c
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);
});return reply({...result,enforcement:db.organisationAccessEnabled?'active':'preparing'});
}
if(url.pathname.endsWith('/activity')){
const context=url.searchParams.get('context')||'users';if(!['users','staff'].includes(context))return reply({message:'Invalid context.'},400);

View file

@ -9,7 +9,7 @@ export function projectPublicOrganisation(rows,orderRows=[]){
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);
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/face/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});

View file

@ -1 +1 @@
*{box-sizing:border-box}body{margin:0;background:#0c1312;color:#f0e8d6;font:16px system-ui,sans-serif;background-image:radial-gradient(circle at 50% 0%,#27372e,#0c1312 65%)}a{color:#e2c485}.top{padding:18px max(22px,calc((100vw - 1060px)/2));display:flex;justify-content:space-between;gap:20px;border-bottom:1px solid #6e6448;background:#101b19}.top a{font-weight:800;text-decoration:none;letter-spacing:.15em}.top span,.eyebrow{font-size:11px;letter-spacing:.19em;color:#c5ae79}main{max-width:1060px;margin:36px auto;padding:0 18px}.passport,.panel{background:#172320e8;border:1px solid #635b43;border-radius:15px;padding:28px;margin-bottom:20px;box-shadow:0 14px 30px #0004}.passport{border-top:4px solid #b99c5e}.identity{display:flex;align-items:center;gap:24px;margin:22px 0}#avatar{width:110px;height:110px;border-radius:12px;border:2px solid #b99c5e;object-fit:cover}h1{font-size:clamp(28px,5vw,45px);margin:0}h2{font-size:20px;color:#e3cb96;margin:0 0 18px}#handle,.muted,#status{color:#b4beb6}.metadata{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}.metadata>div{border-top:1px solid #536057;padding-top:13px}.metadata small{display:block;color:#9aa69f;margin-bottom:7px}.metadata strong{overflow-wrap:anywhere}.chips{display:flex;flex-wrap:wrap;gap:10px}.chip{border:1px solid #827354;background:#24322c;border-radius:24px;padding:9px 14px}.seals{display:grid;grid-template-columns:repeat(auto-fill,minmax(145px,1fr));gap:16px}.seal{text-align:center;background:#1c2b26;border:1px solid #4f5a4a;border-radius:12px;padding:14px}.seal img{max-width:120px;width:100%;height:120px;object-fit:contain}.seal figcaption{font-size:13px;margin-top:10px}.seal small{color:#b8a675}footer{text-align:center;color:#81938a;padding:25px}@media(max-width:620px){.top{flex-direction:column}.metadata{grid-template-columns:1fr}.identity{align-items:flex-start}#avatar{width:75px;height:75px}.passport,.panel{padding:18px}}
*{box-sizing:border-box}body{margin:0;background:#0b221b;color:#eee6ce;font:15px/1.7 system-ui,sans-serif}a{color:#e4ca83}.citizen-profile{max-width:1240px;margin:36px auto 60px;padding:0 28px}.citizen-profile [hidden]{display:none!important}.profile-breadcrumb{margin-bottom:22px;font-size:13px;color:#b8c5b7}.profile-breadcrumb a{text-decoration:none}.profile-hero,.profile-panel{border:1px solid #7f8c61;border-radius:16px;padding:30px;margin-bottom:24px;background:linear-gradient(135deg,#1d4031,#102c23);box-shadow:0 8px 25px #0002}.profile-hero{border-top:3px solid #d2b76b;background:linear-gradient(105deg,#173e2bf2,#102e28e8),url('/assets/sietch.webp') center/cover}.citizen-profile .eyebrow{font-size:10px;font-weight:700;letter-spacing:.16em;color:#c4ad6d;margin:0 0 12px}.identity{display:flex;align-items:center;gap:26px;margin:22px 0}.identity>div{min-width:0}#avatar{width:112px;height:112px;flex-shrink:0;border-radius:13px;border:2px solid #c6ab64;object-fit:cover;image-rendering:pixelated;background:#0a241b}.citizen-profile h1,.citizen-profile h2,.citizen-profile h3{font-family:Georgia,serif;color:#efdcab;line-height:1.25;overflow-wrap:anywhere}.citizen-profile h1{font-size:38px;margin:0 0 6px}.citizen-profile h2{font-size:25px;margin:0 0 18px}.citizen-profile h3{font-size:18px}.citizen-profile p{margin-top:0}.muted,#handle,#status{color:#b9ccbd}#handle{margin-bottom:6px}.metadata{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:24px;margin-top:26px}.metadata>div{border-top:1px solid #8d9a6b55;padding-top:16px}.metadata small{display:block;color:#b5c6b5;font-size:12px;margin-bottom:5px}.metadata strong{overflow-wrap:anywhere}.chips{display:flex;gap:10px;flex-wrap:wrap}.chip{display:inline-block;border:1px solid #a89058;border-radius:20px;padding:5px 13px;background:#9b87481c;font-size:12px;text-decoration:none}.chip[data-staff=true]{border-color:#90b2bb;color:#b8d8e3;background:#456d7b30}.profile-columns{display:grid;grid-template-columns:minmax(0,1.1fr) minmax(0,1fr);gap:24px}.profile-prose{white-space:pre-line;overflow-wrap:anywhere;color:#d4dfce}.profile-functions{display:grid;gap:12px;margin-bottom:20px}.profile-function{padding:13px 16px;border:1px solid #71856677;border-left:3px solid #d1b66c;border-radius:8px;background:#0b281d}.profile-function strong{display:block;color:#e4cb8e}.profile-function span,.profile-function small{display:block;color:#b8cdbb;font-size:12px}.profile-award-groups{display:grid;gap:28px;margin-top:26px}.profile-awards{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:18px}.profile-seal{margin:0!important;min-width:0;padding:22px 16px;border:1px solid #7f8b645c;border-radius:12px;background:linear-gradient(145deg,#274936,#102d24);text-align:center;display:flex;flex-direction:column;align-items:center;gap:14px}.profile-seal img{width:128px;height:128px;max-width:100%;object-fit:contain;filter:drop-shadow(0 4px 7px #0005)}.profile-seal figcaption{font-size:13px;color:#e8d6a5;overflow-wrap:anywhere;line-height:1.5;width:100%}.profile-seal small{font-size:11px;color:#b4bd9f}.personal-seal-panel,.profile-order{display:flex;align-items:center;justify-content:space-between;gap:30px}.personal-seal-panel .profile-seal{min-width:210px}.profile-order{justify-content:flex-start;border-color:#c7a955;background:linear-gradient(115deg,#5d502936,#173b2c)}.profile-order>img{object-fit:contain;flex-shrink:0}.profile-community{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:18px}.profile-community>article{padding:20px;border:1px solid #6e886777;border-radius:10px;background:#0c281e}.profile-community strong{display:block;color:#e8d6a5;font-size:21px}.profile-community small{color:#b7cbb8}.profile-community a{font-size:12px}.citizen-profile a:focus-visible{outline:2px solid #e8cb7c;outline-offset:4px}

View file

@ -1 +1,10 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#131a18"><title>DuneRealms | Citizen Passport</title><link rel="stylesheet" href="/passport.css"></head><body><header class="top"><a href="/">DUNEREALMS</a><span>CITIZEN PASSPORT · IMPERIAL REGISTRY</span></header><main><section class="passport" aria-labelledby="passport-title"><div class="eyebrow">OFFICIAL NETWORK IDENTITY</div><div class="identity"><img id="avatar" alt="Member avatar" hidden><div><h1 id="passport-title">Loading passport…</h1><p id="handle"></p><p id="status" role="status">Retrieving public member record.</p></div></div><div class="metadata"><div><small>Member since</small><strong id="joined">—</strong></div><div><small>Faction / Clan</small><strong id="clan">—</strong></div><div><small>Forum</small><strong id="forum">—</strong></div></div></section><section class="panel"><h2>Official ranks</h2><div id="ranks" class="chips">Not available</div></section><section class="panel"><h2>Department &amp; service</h2><div id="department" class="chips">Not available</div><p id="tickets" class="muted"></p></section><section class="panel"><h2>Seals &amp; earned awards</h2><div id="seals" class="seals">Not available</div></section><section class="panel"><h2>Citizen record</h2><p id="bio" class="muted">No public biography.</p><div id="socials" class="chips"></div></section><footer>Public profile data only · DuneRealms Imperial Registry</footer></main><script type="module" src="/passport.js"></script></body></html>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#102b22"><title>Citizen Profile | DuneRealms</title><link rel="stylesheet" href="/passport.css"><link rel="stylesheet" href="/portal-navigation.css"><script src="/portal-navigation.js" defer></script><script type="module" src="/passport.js"></script></head>
<body><!--SHARED_HEADER--><main class="citizen-profile" id="profile-content">
<nav class="profile-breadcrumb" aria-label="Profile navigation"><a href="/staff.html">Our people</a><span> / Citizen profile</span></nav>
<section class="profile-hero" aria-labelledby="passport-title"><p class="eyebrow">DUNEREALMS · CITIZEN REGISTER</p><div class="identity"><img id="avatar" alt="Member portrait" width="112" height="112" hidden><div><h1 id="passport-title">Citizen profile</h1><p id="handle"></p><p id="status" role="status">Loading the member record…</p></div></div><div id="ranks" class="chips"></div><div class="metadata"><div><small>Member since</small><strong id="joined">—</strong></div><div><small>Clan</small><strong id="clan">—</strong></div><div><small>Community forum</small><strong id="forum">—</strong></div></div></section>
<div class="profile-columns"><section class="profile-panel"><p class="eyebrow">THE PERSON BEHIND THE NAME</p><h2>About</h2><p id="bio" class="profile-prose">No public biography added yet.</p><p id="public-info" class="profile-prose" hidden></p><div id="socials" class="chips"></div></section><section class="profile-panel"><p class="eyebrow">CURRENT RESPONSIBILITIES</p><h2>Functions &amp; service</h2><div id="department" class="profile-functions"></div><p id="tickets" class="muted"></p></section></div>
<section id="personal-seal-panel" class="profile-panel personal-seal-panel" hidden><div><p class="eyebrow">PERSONAL RECOGNITION</p><h2>Personal seal</h2><p>Issued in this member’s name.</p></div><div id="personal-seal"></div></section>
<section id="order-panel" class="profile-panel profile-order" hidden><img src="/assets/seals/order-crysknife-v1.png" alt="Holy Order of the Crysknife" width="120" height="120"><div><p class="eyebrow">SERVICE BEYOND OFFICE</p><h2>Holy Order of the Crysknife</h2><p>Order membership recognises service to DuneRealms and is separate from staff authority.</p></div></section>
<section class="profile-panel"><p class="eyebrow">SERVICE &amp; RECOGNITION</p><h2>Seals &amp; earned awards</h2><p class="muted">Current function seals and recorded community achievements.</p><div id="seals" class="profile-award-groups"></div></section>
<section class="profile-panel"><p class="eyebrow">AROUND THE REALMS</p><h2>Community activity</h2><div id="community" class="profile-community"></div></section>
</main><footer><a href="/">DuneRealms</a><nav><a href="https://support.dunerealms.com/">Support</a><a href="/rates-and-charges.html">Rates &amp; Charges</a></nav></footer></body></html>

View file

@ -1 +1,28 @@
const $=id=>document.getElementById(id);const username=decodeURIComponent(location.pathname.split('/').filter(Boolean)[1]||'');const api='https://cp.dunerealms.com/api/people/';const text=(id,value)=>{$(id).textContent=value??'—'};const chip=value=>{const el=document.createElement('span');el.className='chip';el.textContent=value;return el};function render(profile){text('passport-title',profile.displayName||profile.username);text('handle','@'+profile.username);text('status','Verified public network record');text('joined',profile.joinedAt?new Date(profile.joinedAt).toLocaleDateString():null);text('clan',profile.clan?.status==='member'?profile.clan.name:'Not listed');text('forum',profile.forum?.status==='linked'?profile.forum.username:'Not linked');if(profile.avatar&&new URL(profile.avatar).hostname==='cp.dunerealms.com'){$('avatar').src=profile.avatar;$('avatar').hidden=false}for(const rank of profile.ranks||[])$('ranks').append(chip(rank.label));if(profile.ranks?.length)$('ranks').firstChild?.nodeType===3&&$('ranks').replaceChildren(...[...$('ranks').children]);const departments=(profile.medals||[]).filter(x=>x.group==='Departments');if(departments.length){$('department').replaceChildren(...departments.map(x=>chip(x.label)))}if(profile.support?.status==='available')text('tickets',`${profile.support.closed??0} verified tickets closed`);const medals=(profile.medals||[]).filter(x=>x.url&&/^https:\/\/(www|support|forums)\.dunerealms\.com\/assets\/seals\/[a-zA-Z0-9_./-]+\.png$/.test(x.url));if(medals.length){$('seals').replaceChildren(...medals.map(m=>{const figure=document.createElement('figure');figure.className='seal';const img=document.createElement('img');img.src=m.url;img.alt=m.label;img.loading='lazy';const cap=document.createElement('figcaption');cap.textContent=m.label;const group=document.createElement('small');group.textContent=m.group||'Seal';figure.append(img,cap,group);return figure}))}if(profile.bio)text('bio',profile.bio);for(const [label,url] of Object.entries(profile.socials||{})){if(typeof url!=='string'||!/^https:\/\//.test(url))continue;const link=document.createElement('a');link.className='chip';link.textContent=label;link.href=url;link.rel='noopener noreferrer';link.target='_blank';$('socials').append(link)}}async function load(){if(!/^[a-z0-9_]{3,32}$/.test(username)){text('status','Invalid passport name');return}text('handle','@'+username);try{const res=await fetch(api+encodeURIComponent(username),{credentials:'include',headers:{Accept:'application/json'}});if(res.status===401){text('status','Sign in to DuneRealms to view this passport.');const a=document.createElement('a');a.href='https://cp.dunerealms.com/?return_to='+encodeURIComponent('/people/'+username);a.textContent='Sign in';$('status').append(' ',a);return}if(!res.ok){text('status',res.status===404?'Passport not found':'Passport temporarily unavailable');return}const data=await res.json();render(data.profile)}catch{text('status','Unable to load passport. Please try again later.')}}load();
const $=id=>document.getElementById(id),el=(tag,value,cls)=>{const n=document.createElement(tag);if(value!=null)n.textContent=value;if(cls)n.className=cls;return n;};
const text=(id,value)=>{$(id).textContent=value??'—';},username=decodeURIComponent(location.pathname.split('/').filter(Boolean)[1]||'');
function sealCard(m){const card=el('figure',null,'profile-seal'),image=el('img');image.src=m.url;image.alt=m.label;image.loading='lazy';image.width=image.height=128;card.append(image,el('figcaption',m.label),el('small',m.group||'Recognition'));return card;}
function render(p){
document.title=(p.displayName||p.username)+' | DuneRealms';text('passport-title',p.displayName||p.username);text('handle','@'+p.username);text('status','DuneRealms community member');text('joined',p.joinedAt?new Date(p.joinedAt).toLocaleDateString('en-GB'):null);text('clan',p.clan?.status==='member'?p.clan.name:'No clan listed');text('forum',p.forum?.status==='linked'?p.forum.username:'Not linked');
if(typeof p.avatar==='string'&&/^https:\/\/cp\.dunerealms\.com\/api\/avatars\//.test(p.avatar)){$('avatar').src=p.avatar;$('avatar').hidden=false;}
for(const rank of p.ranks||[]){if(rank.label==='Unknown rank')continue;const chip=el('span',rank.label,'chip');chip.dataset.staff=String(rank.key.startsWith('org_'));$('ranks').append(chip);}
const functions=p.functions||[];
for(const f of functions){const card=el('article',null,'profile-function');card.append(el('strong',f.roleLabel),el('span',f.scopeLabel));$('department').append(card);}
if(!functions.length)$('department').append(el('p','No staff functions listed.','muted'));
if(p.support?.status==='available')text('tickets',(p.support.closed??0)+' verified support tickets closed');
if(p.bio)text('bio',p.bio);if(p.publicInfo){text('public-info',p.publicInfo);$('public-info').hidden=false;}
for(const [label,value]of Object.entries(p.socials||{})){try{const u=new URL(value);if(u.protocol!=='https:'||u.username||u.password)continue;const a=el('a',label,'chip');a.href=u.href;a.rel='noopener noreferrer';a.target='_blank';$('socials').append(a);}catch{}}
const medals=(p.medals||[]).filter(m=>typeof m.url==='string'&&/^https:\/\/(www|support|forums)\.dunerealms\.com\/assets\/seals\/[a-zA-Z0-9_./-]+\.png$/.test(m.url));
const personal=medals.find(m=>m.key==='personal-role');if(personal){$('personal-seal-panel').hidden=false;$('personal-seal').append(sealCard(personal));}
if((p.ranks||[]).some(r=>r.key==='crysknife'))$('order-panel').hidden=false;
const groups=new Map();for(const m of medals){if(['personal-role','rank-crysknife'].includes(m.key))continue;const group=m.group||'Recognition';if(!groups.has(group))groups.set(group,[]);groups.get(group).push(m);}
for(const [name,items]of groups){const section=el('section'),cards=el('div',null,'profile-awards');section.append(el('h3',name));for(const m of items)cards.append(sealCard(m));section.append(cards);$('seals').append(section);}
if(!groups.size)$('seals').append(el('p','No additional seals or awards recorded.','muted'));
const community=(heading,value,note,link)=>{const c=el('article');c.append(el('h3',heading),el('strong',value),el('small',note));if(link){const a=el('a','Open →');a.href=link;c.append(el('br'),a);}$('community').append(c);};
if(p.forum?.status==='linked')community('Forum contributions',String(p.forum.posts||0)+' posts',String(p.forum.threads||0)+' threads · '+String(p.forum.reputation||0)+' reputation',p.forum.url);
else community('Forum','Not linked','No linked forum record is available.');
if(p.clan?.status==='member')community('Clan',p.clan.name,(p.clan.role||'Member')+' · '+String(p.clan.members||0)+' members','https://clans.dunerealms.com/');
else community('Clan','No membership listed','Clan membership is maintained by the clan system.');
community('Adventures',p.quests?.completed==null?'No verified totals':String(p.quests.completed)+' completed',p.quests?.completed==null?'Quest statistics are not connected yet.':'Verified quest progress');
}
async function load(){if(!/^[a-z0-9_]{3,32}$/.test(username)){text('status','Invalid profile name');return;}text('handle','@'+username);try{const response=await fetch('https://cp.dunerealms.com/api/people/'+encodeURIComponent(username),{credentials:'include',cache:'no-store'});if(response.status===401){text('status','Sign in to view this member’s profile.');const a=el('a','Sign in');a.href='https://cp.dunerealms.com/?return_to='+encodeURIComponent('/people/'+username);$('status').append(' ',a);return;}if(!response.ok){text('status',response.status===404?'Profile not found':'Profile temporarily unavailable');return;}render((await response.json()).profile);}catch{text('status','Unable to load the profile. Please try again.');}}
void load();

View file

@ -1,4 +1,5 @@
import {startNativeSyncRetryWorker} from './native-sync-outbox.mjs';
import {SHARED_HEADER} from '../scripts/portal-navigation.mjs';
import {initializeOrganisation} from './organisation-model.mjs';
import {createGitIdentityRoute,initializeGitIdentities,gitProxyIdentity} from './git-identity.mjs';
import {createPublicExchange} from './exchange-public.mjs';
@ -44,7 +45,8 @@ export function createApplication(db,settings={}) {
if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});
const asset=url.pathname.startsWith('/people/')?'passport.html':url.pathname.slice(1);
const type=asset.endsWith('.html')?'text/html':asset.endsWith('.css')?'text/css':'text/javascript';
return new Response(request.method==='HEAD'?null:await readFile(new URL(asset,root)),{headers:{...security,'Content-Type':type+'; charset=utf-8','Cache-Control':'no-store'}});
const content=request.method==='HEAD'?null:await readFile(new URL(asset,root));
return new Response(asset==='passport.html'&&content?content.toString().replace('<!--SHARED_HEADER-->',SHARED_HEADER):content,{headers:{...security,'Content-Type':type+'; charset=utf-8','Cache-Control':'no-store'}});
}
if(url.pathname.startsWith('/api/community/'))return rewards(request);
if(url.pathname==='/api/game-link'||url.pathname.startsWith('/api/game-link/'))return gameLink(request);

View file

@ -0,0 +1,24 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {createAvatars} from '../node/avatar.mjs';
const uuid='49d2fe76-7977-4d49-bd39-e48fc8c648b8';
const request=path=>new Request('https://cp.dunerealms.com/api/avatars/'+path);
function fixture({skin={bytes:Buffer.from('trusted-resolver-png'),height:64},uploaded=false,linked=uuid,exists=true}={}){
const db={prepare(sql){return{bind(){return this;},async first(){if(sql.includes('SELECT avatar_key'))return uploaded?{avatar_key:uuid}:null;if(sql.includes('SELECT avatar_mime'))return null;return exists?{id:uuid,minecraft_uuid:linked}:null;}};}};
return createAvatars(db,{}, {resolver:{resolve:async value=>value===uuid?skin:null}});
}
test('face rendering crops the front face and hat without changing the raw skin API',async()=>{
const api=fixture(),face=await api(request('face/'+uuid));assert.equal(face.status,200);assert.equal(face.headers.get('Content-Type'),'image/svg+xml');const svg=await face.text();
assert.match(svg,/viewBox="0 0 8 8"/);assert.match(svg,/x="-8" y="-8"/);assert.match(svg,/x="-40" y="-8"/);assert.match(svg,/data:image\/png;base64,/);
const raw=await api(request('minecraft/'+uuid));assert.equal(raw.headers.get('Content-Type'),'image/png');assert.equal(await raw.text(),'trusted-resolver-png');
});
test('Java, Bedrock and legacy skins use the same resolver and correct texture height',async()=>{
for(const prefix of ['face/','face/roster/member','face/member/member']){
const path=prefix==='face/'?prefix+uuid:prefix;
const svg=await (await fixture({skin:{bytes:Buffer.from('legacy'),height:32}})(request(path))).text();assert.match(svg,/height="32"/);
}
});
test('missing skins and unlinked accounts have a face fallback, unknown accounts remain 404',async()=>{
for(const opts of [{skin:null},{linked:null}]){const r=await fixture(opts)(request('face/roster/member'));assert.equal(r.status,200);assert.match(await r.text(),/viewBox="0 0 8 8"/);}
assert.equal((await fixture({exists:false})(request('face/roster/member'))).status,404);
assert.equal((await fixture()(request('face/not-a-valid-uuid'))).status,404);
});

View file

@ -6,9 +6,9 @@ import {ORGANISATION,initializeOrganisation} from '../node/organisation-model.mj
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}={}){
function fixture({rows=[row],grants=[assignment('clan','clan-example','member'),assignment('branch','trust_safety','officer')],authenticated=true,allowed=true,active=false}={}){
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(){
const db={organisationAccessEnabled:active,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};
@ -16,6 +16,13 @@ function fixture({rows=[row],grants=[assignment('clan','clan-example','member'),
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 reports actual activation in list, account and catalogue responses',async()=>{
for(const active of [false,true])for(const suffix of ['?context=staff','/'+id+'?context=staff','/catalogue?context=staff']){
const data=await (await fixture({active}).api(req(suffix))).json();
assert.equal(data.assignmentMode,active?'active':'preparing');
}
});
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);}
});

View file

@ -3,7 +3,7 @@ const files={community_operations:'department-support-150.png',dunerealms_operat
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'));
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/face/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;}