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

This commit is contained in:
Dev 2026-11-15 05:11:56 +01:00
commit 34b84f2d09
22 changed files with 345 additions and 90 deletions

View file

@ -17,3 +17,4 @@
.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}}
.md-seal-gallery{display:grid;grid-template-columns:repeat(auto-fill,minmax(145px,1fr));gap:14px;margin:18px 0}.md-seal-gallery figure,.md-seal-choice{margin:0;padding:16px;border:1px solid #607653;border-radius:10px;background:#102b21;text-align:center;overflow-wrap:anywhere}.md-seal-gallery img{display:block;width:96px;height:96px;object-fit:contain;margin:0 auto 10px}.md-seal-gallery figcaption,.md-seal-choice span{display:block;color:#e5cf92;font-size:13px}.md-seal-gallery small{display:block;color:#a7bca7;font-size:11px}.md-seal-choice{cursor:pointer}.md-seal-choice:has(input:checked){border-color:#efcd79;box-shadow:0 0 0 1px #efcd79}.md-seal-choice input{accent-color:#ddbe70}

View file

@ -22,8 +22,9 @@ export function mountCitizenDirectory(host){
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(context==='users')for(const membership of selected.memberships||[]){const row=element('div',undefined,'md-assignment');row.append(element('strong',membership.label),element('p',membership.kind),badge(membership.source));panel.append(row);}
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'));
else if(context==='staff'||!selected.memberships?.length)panel.append(element('p',context==='staff'?'No new-model staff assignments have been activated for this account.':'No additional memberships or offices are recorded.','md-muted'));
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();}));
@ -88,6 +89,34 @@ export function mountCitizenDirectory(host){
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'));}
}
async function loadRecognition(panel){
const target=selected.id,name=selected.username;panel.append(element('p','Loading recognition…'));
try{const [data,publicData]=await Promise.all([request('/api/seals/manual?userId='+encodeURIComponent(target),controller?.signal),request('/api/people/'+encodeURIComponent(name),controller?.signal)]);if(disposed||selected?.id!==target||tab!=='honours'||!panel.isConnected)return;
panel.replaceChildren(element('h3','Seals & honours'));const gallery=element('div',undefined,'md-seal-gallery');
for(const medal of publicData.profile?.medals||[]){if(!/^https:\/\/(www|support|forums)\.dunerealms\.com\/assets\/seals\/[a-zA-Z0-9_./-]+\.png$/.test(medal.url))continue;const card=element('figure'),image=element('img');image.src=medal.url;image.alt=medal.label;image.loading='lazy';card.append(image,element('figcaption',medal.label),element('small',medal.group));gallery.append(card);}panel.append(gallery);
if(!data.canManage){panel.append(element('p','Function and automatic seals follow their source. Manual recognition requires assignment authority and cannot be self-awarded.','md-note'));return;}
const form=element('form',undefined,'md-assignment-form'),table=element('div',undefined,'md-seal-gallery'),reason=element('textarea'),message=element('p');let chosen=null;
for(const seal of data.catalogue){const field=element('label',undefined,'md-seal-choice'),radio=element('input'),image=element('img');radio.type='radio';radio.name='recognition-seal';radio.required=true;radio.onchange=()=>{chosen=seal.key;};image.src='https://www.dunerealms.com/assets/seals/'+seal.file;image.alt='';image.loading='lazy';field.append(radio,image,element('span',seal.label));table.append(field);}
reason.required=true;reason.minLength=3;reason.maxLength=500;reason.placeholder='Reason for recognition';reason.setAttribute('aria-label','Reason for recognition');const save=button('Grant recognition',()=>{});save.type='submit';form.append(element('h4','Grant recognition'),table,reason,save,message);panel.append(form);
const update=async body=>{const response=await fetch('/api/seals/manual',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}),result=await response.json();if(!response.ok)throw Error(result.message);await loadRecognition(panel);status.textContent='Recognition change saved and audited.';};
form.onsubmit=async event=>{event.preventDefault();if(!chosen||!form.reportValidity())return;if(!confirm('Grant '+chosen+' to '+name+'?'))return;save.disabled=true;try{await update({action:'grant',targetId:target,seal:chosen,reason:reason.value});}catch(e){message.textContent=e.message;save.disabled=false;}};
for(const entitlement of data.entitlements.filter(a=>a.source==='staff'&&data.catalogue.some(s=>s.key===a.key))){const row=element('div',undefined,'md-detail');row.append(element('span',entitlement.key+' · '+date(entitlement.grantedAt)),button('Revoke manual award',async()=>{const reason=prompt('Reason for revoking '+entitlement.key+' (3–500 characters):');if(reason===null||reason.trim().length<3)return;try{await update({action:'revoke',targetId:target,seal:entitlement.key,entitlementId:entitlement.id,reason});}catch(e){message.textContent=e.message;}}));panel.append(row);}
}catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.replaceChildren(element('p',e.message));}
}
async function loadLifeStatus(panel){
const target=selected.id;
try{const data=await request('/api/admin/life-status?userId='+encodeURIComponent(target),controller?.signal);if(disposed||selected?.id!==target||tab!=='account'||!panel.isConnected)return;if(!data.canEdit){panel.remove();return;}
panel.replaceChildren(element('h3','Community remembrance'),detail('Deceased marker',data.status==='deceased'?'Recorded':'Not recorded'));
panel.append(element('p','Only the Big Four can record this status. It creates a community memorial and profile link. Account access, linked identity and bank records remain unchanged.','md-note'));
if(data.memorial){const link=element('a','Open existing memorial →');link.href='https://www.dunerealms.com'+data.memorial;link.target='_blank';link.rel='noopener';panel.append(link);}
const form=element('form',undefined,'md-assignment-form'),reason=element('textarea'),confirmation=element('input'),message=element('p');let choice=null;
for(const [value,label]of [['deceased','Record as deceased'],['living','Remove deceased marker']]){const field=element('label',label,'md-field'),radio=element('input');radio.type='radio';radio.name='life-status';radio.value=value;radio.required=true;radio.onchange=()=>{choice=value;};field.prepend(radio);form.append(field);}
reason.required=true;reason.minLength=3;reason.maxLength=500;reason.placeholder='Reason and verified source';reason.setAttribute('aria-label','Reason for remembrance status');confirmation.required=true;confirmation.autocomplete='off';confirmation.placeholder='Type '+selected.username+' to confirm';confirmation.setAttribute('aria-label','Confirm exact username');const save=button('Save remembrance status',()=>{});save.type='submit';form.append(reason,confirmation,save,message);panel.append(form);
form.onsubmit=async event=>{event.preventDefault();if(!choice||!form.reportValidity())return;if(confirmation.value!==selected.username){message.textContent='Type the exact username.';return;}save.disabled=true;
try{const r=await fetch('/api/admin/life-status',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({userId:target,status:choice,version:data.version,confirm:confirmation.value,reason:reason.value})}),result=await r.json();if(!r.ok)throw Error(result.message);await loadLifeStatus(panel);status.textContent=result.changed?'Remembrance status saved and audited.':'Status was already recorded.';}catch(e){message.textContent=e.message;save.disabled=false;}
};
}catch(e){if(e.name!=='AbortError'&&panel.isConnected)panel.replaceChildren(element('p',e.message));}
}
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/face/'+encodeURIComponent(selected.minecraftUuid):'https://www.dunerealms.com/assets/nav-account-v2.webp';
@ -98,10 +127,10 @@ export function mountCitizenDirectory(host){
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);
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);const remembrance=box('Community remembrance');view.append(remembrance);void loadLifeStatus(remembrance);
}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 if(tab==='honours'){const panel=box('Seals & honours');view.append(panel);void loadRecognition(panel);}
else{const panel=box('Account activity');view.append(panel);void loadActivity(panel);}
}
function renderList(data){

View file

@ -69,6 +69,7 @@ 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 {createLifeStatus,initializeLifeStatus} from '../node/life-status.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';
@ -108,7 +109,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 citizenDirectory=createCitizenDirectory(db);const lifeStatus=createLifeStatus(db,{origin});
const organisationManagement=createOrganisationManagement(db,{origin});
const luckperms=createLuckPerms(db,settings,dependencies.luckperms);
const servers=createServerControl(db,settings,dependencies.serverControl);
@ -160,6 +161,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/life-status')return lifeStatus(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);
@ -270,7 +272,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 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';
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 initializeLifeStatus(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"};

View file

@ -72,6 +72,28 @@ alter native application core files. Run native seal/profile reconciliation
after deployment. The native avatar allowlist now accepts the central face
endpoint while retaining its fixed origin and UUID-only path restriction.
## Recognition and remembrance
The directory recognition tab shows current seals and earned awards, with
manual grant/revoke controls backed by the existing entitlement ledger. Automatic
and purchased recognition stays managed at its source; self-awards are blocked.
Native signatures read active entitlements and manual changes queue the existing
synchronisation flow. Support cards use the new branch artwork.
The Account tab exposes remembrance status only to pinned Big Four principals
(and the exempt Dev operator), including the verified owner alias. Changing it
requires an exact username confirmation, reason and current version. Status,
memorial creation and audit commit together. A repeated notification creates no
duplicate page. Corrections hide the page while retaining history. This metadata
does not change login access, linked identity, ranks or bank records. Existing
community tribute content is preserved; no real-life death status is inferred.
Citizen details read earned tiers, house/office/path/Order ranks and current clan
membership from the existing registers. They do not expose staff functions in the
User view or copy membership authority into the staff register. Legacy User/VIP
permission lists cannot retain staff powers through cp.* aliases, native forum
administration, job ticket nodes, item issuance or lobby administration.
## Batch 2: audited assignment editor and policy preparation
Staff assignments can be recorded and revoked within the manager's scope. One

View file

@ -42,11 +42,23 @@ function dune_signature_extra_roles($id){
try{$q=dune_signature_db()->prepare('SELECT seal_key FROM dune_signature_role_seals WHERE website_id=?');$q->execute([$id]);$badges=[];$known=['rank-game-mod'=>['rank-game-mod-150.png','Ingame Moderator'],'rank-game-admin'=>['rank-game-admin-150.png','Ingame Administrator'],'rank-dev'=>['rank-dev-150.png','Development'],'rank-streamer'=>['rank-streamer-150.png','Streamer · News Team'],'rank-crysknife'=>['order-crysknife-v1.png','Holy Order of The Crysknife']];foreach(dune_recognition_catalog()['roles']as$a)$known[$a['key']]=[$a['file'],$a['label']];foreach($q->fetchAll(PDO::FETCH_COLUMN)as$key)if(isset($known[$key])&&is_file(__DIR__.'/osticket/assets/seals/'.$known[$key][0]))$badges[]=['https://support.dunerealms.com/assets/seals/'.$known[$key][0],$known[$key][1]];return $badges;}catch(Throwable$e){return [];}
}
function dune_signature_entitled_badges($id){
try{
$known=dune_signature_recognition_keys($id);$manifest=json_decode(file_get_contents(__DIR__.'/seal-manifest.json'),true,512,JSON_THROW_ON_ERROR);
$q=dune_signature_db()->prepare('SELECT DISTINCT seal_key FROM seal_entitlements WHERE account_id=? AND revoked_at IS NULL');$q->execute([$id]);$badges=[];
foreach($q->fetchAll(PDO::FETCH_COLUMN)as$key){
if(in_array($key,$known,true)||preg_match('/^(personal-|owner-|corestaff-|scope-|function-)|crysknife|crissknife/i',$key))continue;
$asset=$manifest[$key]??null;$path=$asset['footer150']??(in_array($key,['alpha-tester','beta-tester','launch-contributor','dedicated-tester','season-tavren-ii','builder-award','dunegit-owner'],true)?'/assets/seals/'.$key.'-150.png':null);
if(($asset['category']??'')==='Personal'||!is_string($path)||!preg_match('~^/assets/seals/[a-z0-9_-]+\.png$~',$path))continue;
$badges[]=['https://www.dunerealms.com'.$path,$asset['label']??ucwords(str_replace('-',' ',$key))];
}return$badges;
}catch(Throwable$e){return[];}
}
function dune_signature_offices($id){
try{$q=dune_signature_db()->prepare('SELECT roles_json,expires_at FROM drforum_dune_political_roles WHERE website_id=?');$q->execute([$id]);$row=$q->fetch(PDO::FETCH_ASSOC);if(!$row||(int)$row['expires_at']<=time())return[];$labels=['emperor'=>'Emperor','house_leader'=>'Faction leader','specerhuis'=>'Specerhuis','welvaart'=>'House of Water','guild_staff'=>'Vaerkring','landsraad'=>'Landsraad'];$out=[];foreach(json_decode($row['roles_json'],true)?:[]as$key)if(isset($labels[$key]))$out[]=['https://forums.dunerealms.com/assets/seals/office-'.$key.'.png',$labels[$key]];return$out;}catch(Throwable$e){return[];}
}
function dune_render_managed_signature($id,$context='forum'){
$a=dune_signature_account($id);if(!$a)return '';$p=dune_signature_preferences($id);[$personal,$teams]=dune_signature_staff_badges($a);$roles=dune_signature_extra_roles($id);$recognition=[];$offices=$context==='forum'?dune_signature_offices($id):[];
$a=dune_signature_account($id);if(!$a)return '';$p=dune_signature_preferences($id);[$personal,$teams]=dune_signature_staff_badges($a);$roles=dune_signature_extra_roles($id);$recognition=dune_signature_entitled_badges($id);$offices=$context==='forum'?dune_signature_offices($id):[];
if(str_contains($a['personal_path']??'','/rank-')){$roles=array_merge($personal,$roles);$personal=[];}
$labels=array_merge(['alpha-tester'=>'Alpha Tester','beta-tester'=>'Beta Tester','launch-contributor'=>'Launch Contributor','dedicated-tester'=>'Dedicated Tester','season-tavren-ii'=>'Season · Tavren II Aedrecht','dunegit-owner'=>'DuneGit Repository Owner'],dune_recognition_labels());
foreach(dune_signature_recognition_keys($id)as$key)if(is_file(__DIR__.'/osticket/assets/seals/'.$key.'.png'))$recognition[]=['https://support.dunerealms.com/assets/seals/'.$key.'.png',$labels[$key]];
@ -61,7 +73,7 @@ function dune_render_managed_signature($id,$context='forum'){
function dune_signature_bbcode($id){
$a=dune_signature_account($id);if(!$a)return'';$p=dune_signature_preferences($id);[$personal,$teams]=dune_signature_staff_badges($a);
$bb=str_replace(['[',']'],['&#91;','&#93;'],$p['closing'])."\n\n[b]".str_replace(['[',']'],['&#91;','&#93;'],$a['username'])."[/b]\n\n";
foreach([['Personal seals',$personal],['Functions & service',$teams]]as[$label,$badges])if($badges){$bb.='[b]'.$label."[/b]\n";foreach($badges as[$url,$caption])$bb.='[img=48x48]'.$url.'[/img] ';$bb.="\n\n";}
foreach([['Personal seals',$personal],['Functions & service',$teams],['Recognition',dune_signature_entitled_badges($id)]]as[$label,$badges])if($badges){$bb.='[b]'.$label."[/b]\n";foreach($badges as[$url,$caption])$bb.='[img=48x48]'.$url.'[/img] ';$bb.="\n\n";}
foreach(dune_signature_recognition_keys($id)as$key)if(is_file(__DIR__.'/osticket/assets/seals/'.$key.'.png'))$bb.='[img=48x48]https://support.dunerealms.com/assets/seals/'.$key.'.png[/img] ';
if($p['banner_url']!=='')$bb.="\n\n[img]".$p['banner_url'].'[/img]';return trim($bb);
}

View file

@ -0,0 +1,41 @@
<?php
// Public catalogue only: no private ticket information is rendered here.
$publicTopics = Topic::getPublicHelpTopics();
$topicUrl = static function ($name) use ($publicTopics) {
// osTicket prefixes child topics with their public parent path.
$matches=[];
foreach ($publicTopics as $id => $label) if ($label === $name || str_ends_with($label, ' / '.$name)) $matches[]=(int)$id;
return count($matches)===1 ? '/open.php?topicId='.$matches[0] : null;
};
$cards = [
['Build with us','BUILDER APPLICATION','Help shape our cities, sietches, interiors and starports. Tell us your style, rough availability and share examples of your own builds. Staff review every application privately.','Builder Application','Apply to build','seals/scope-content_creative-v1-300.png'],
['Parental requests','FOR PARENTS & GUARDIANS','Request parental consent or ask about a child’s account. The Legal team reviews requests manually; this form does not automatically grant consent or change an account.','Parental consent request [Preview]','Open parental request','seals/scope-legal_compliance-v1-150.png'],
['GDPR data removal','PRIVACY & ACCOUNT DATA','Ask the Legal team to review deletion of your account data. Identify the relevant account and explain your request. Ownership and scope are verified before any action. Do not upload passwords or identity documents.','GDPR data removal request','Request data removal','seals/scope-legal_compliance-v1-150.png'],
['General support','ACCOUNT, WEBSITE & GAME HELP','Tell Support what went wrong, where it happened, when it happened and what you tried. Include the error message or a relevant screenshot without passwords or unrelated personal information.','General support','Get support','nav-support-full-v2.webp'],
['Sales enquiries','ORDERS & SHOP QUESTIONS','Ask Sales about an order, a shop item or a purchase issue. Include the order reference if available. Never send passwords, payment card details or account credentials.','Customer sales enquiries','Contact Sales','seals/scope-sales_accounts-v1-150.png'],
['Forum support','HELP WITH THE BOARDS','Ask for help using the community boards or explain a forum account problem. Include the relevant page and error message without private messages or unrelated personal information.','Forum support','Get forum support','seals/scope-trust_safety-v1-150.png'],
['Report a problem','TECHNICAL ISSUES','Describe the issue, the page or world affected, when it happened and the steps needed to reproduce it. Attach only relevant screenshots or logs without credentials.','Report a Problem','Report a problem','seals/scope-it_operations-v1-150.png'],
['Access issues','GET HELP SIGNING IN','Explain which DuneRealms service you cannot access and the error you see. Staff will verify account ownership before changing access. Do not share passwords or verification codes.','Access Issue','Get access help','nav-account-full-v2.webp'],
['Appeal a ban','REQUEST A MODERATION REVIEW','Use the ban ID to open a private appeal linked to the original ban. Explain the situation and attach relevant evidence. A pending appeal does not itself remove a ban.','Ban appeal','Open ban appeal','seals/scope-trust_safety-v1-150.png'],
['Become an Alpha tester','HELP SHAPE THE REALMS','Java or Bedrock, new or experienced: tell us what you would like to test. Applications are reviewed privately by Support.','Alpha Tester Signup','Sign up for Alpha testing','news-community.webp'],
];
$esc = static fn($v) => htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
?>
<link rel="stylesheet" href="/dune-support-home.css?v=328-1">
<div id="dune-support-home" class="dune-support-home">
<div class="dune-support-options" aria-label="Support request types">
<?php foreach ($cards as [$title,$label,$description,$topic,$button,$art]):
$url = $topicUrl($topic); if (!$url) continue;
if ($topic === 'Ban appeal') $url = '/appeal.php';
if ($topic === 'Alpha Tester Signup') $url = '/alpha-signup.php';
if ($topic === 'Builder Application') $url = '/builder-signup.php'; ?>
<section class="dune-support-card">
<img src="https://www.dunerealms.com/assets/<?=$esc($art)?>" alt="" width="180" height="120" loading="lazy">
<div><p class="eyebrow"><?=$esc($label)?></p><h2><?=$esc($title)?></h2><p><?=$esc($description)?></p><a class="button" href="<?=$esc($url)?>"><?=$esc($button)?></a>
<?php if ($topic === 'Parental consent request [Preview]' && ($removal=$topicUrl('Parental data removal [Preview]'))): ?><a class="dune-secondary-request" href="<?=$esc($removal)?>">Child’s account data removal →</a><?php endif; ?>
</div>
</section>
<?php endforeach; ?>
</div>
<p class="dune-support-track"><a href="/view.php">Check an existing ticket →</a> · Requests are private to the requester and authorised staff. Submitting a request does not automatically change an account.</p>
</div>

View file

@ -1,6 +1,7 @@
import {identity} from './auth.mjs';
import {can} from './permissions.mjs';
import {ORGANISATION,ASSIGNMENT_ROLES,STAFF_SCOPE_TYPES,assignmentLabel} from './organisation-model.mjs';
import {citizenMemberships} from './citizen-memberships.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'];
@ -64,6 +65,7 @@ export function createCitizenDirectory(db,{authenticate=identity,authorize=can,c
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)};
if(filter.context==='users')account.memberships=await citizenMemberships(db,row.id);
// 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();

View file

@ -0,0 +1,13 @@
import {accessFor,rankFor} from './permissions.mjs';
const tiers=new Set(['user','vip','patron_caravan','patron_guild','patron_grand','council_member','memorial']);
export function citizenRankVisible(rank){return ['house','office','path','order'].includes(rank.kind)||tiers.has(rank.key);}
// Read the existing owners of memberships; never create a second authority ledger.
export async function citizenMemberships(db,id){
const target=await db.prepare('SELECT id,username,role FROM site_accounts WHERE id=?').bind(id).first();
if(!target)return [];
const access=await accessFor(db,target),items=[];
for(const key of access.ranks){if(key.startsWith('org_'))continue;const rank=await rankFor(db,key);if(citizenRankVisible(rank))items.push({key:'rank:'+key,label:rank.label,kind:rank.kind==='access'?'Account tier':rank.kind,source:'Central membership register'});}
const {results}=await db.prepare('SELECT c.id,c.name,c.tag,m.clan_role FROM site_clan_members m JOIN site_clans c ON c.id=m.clan_id WHERE m.user_id=? AND c.active=1').bind(id).all();
for(const c of results)items.push({key:'clan:'+c.id,label:c.name+(c.tag?' ['+c.tag+']':''),kind:{leader:'Clan Leader',officer:'Clan Officer',member:'Clan Member'}[c.clan_role]||'Clan Member',source:'Clan Center'});
return items;
}

View file

@ -0,0 +1,56 @@
import {randomUUID} from 'node:crypto';
import {identity} from './auth.mjs';
import {can} from './permissions.mjs';
import {organisationSubject,OFFICIAL_ACCOUNT} from './official-account.mjs';
export async function initializeLifeStatus(db){await db.prepare(`CREATE TABLE IF NOT EXISTS site_life_status (
user_id CHAR(36) PRIMARY KEY, status VARCHAR(16) NOT NULL, version INTEGER NOT NULL,
updated_by CHAR(36) NOT NULL, updated_at BIGINT NOT NULL,
FOREIGN KEY(user_id) REFERENCES site_accounts(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`).run();}
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'no-store'}});
const fail=(message,status=409)=>Object.assign(Error(message),{status});
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
async function authority(tx,id){
const actor=await tx.first("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%' FOR SHARE",[id]);
if(!actor)return false;
const subject=await organisationSubject(tx,id,{lock:true});
const principal=await tx.first('SELECT principal_kind FROM org_control_principals WHERE user_id=? FOR SHARE',[subject.userId]);
return ['owner','executive','service'].includes(principal?.principal_kind);
}
export function createLifeStatus(db,{origin,authenticate=identity,authorize=can,clock=Date.now}={}){return async request=>{
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);
if(request.method==='GET'){
const id=url.searchParams.get('userId');if(!uuid(id))return reply({message:'Select a citizen.'},400);
return db.transaction(async tx=>{
if(!await authority(tx,actor.id))return reply({canEdit:false});
const row=await tx.first('SELECT status,version FROM site_life_status WHERE user_id=?',[id]);
const memorial=await tx.first('SELECT slug FROM site_memorials WHERE user_id=?',[id]);
return reply({canEdit:true,status:row?.status||'not_recorded',version:Number(row?.version||0),memorial:memorial?'/memorial/'+memorial.slug:null});
});
}
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);
let body;try{body=await request.json();}catch{return reply({message:'Invalid JSON.'},400);}
if(!body||!uuid(body.userId)||!['deceased','living'].includes(body.status)||!Number.isSafeInteger(body.version)||body.version<0||typeof body.confirm!=='string'||typeof body.reason!=='string'||body.reason.trim().length<3||body.reason.length>500)return reply({message:'Status, confirmation, version and reason required.'},400);
try{return await db.transaction(async tx=>{
if(!await authority(tx,actor.id))throw fail('Only the Big Four may change this field.',403);
const target=await tx.first("SELECT a.id,a.username,a.display_name,p.game_link_exempt FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.id=? FOR UPDATE",[body.userId]);
if(!target)throw fail('Account not found.',404);
if(target.id===OFFICIAL_ACCOUNT.id||target.game_link_exempt)throw fail('This field is only for human community members.',403);
if(body.confirm!==target.username)throw fail('Type the exact username to confirm.',400);
const before=await tx.first('SELECT status,version FROM site_life_status WHERE user_id=? FOR UPDATE',[target.id]);
if(before?.status===body.status)return reply({ok:true,changed:false});
if(Number(before?.version||0)!==body.version)throw fail('The record changed. Refresh before saving.');
let memorial=await tx.first('SELECT slug FROM site_memorials WHERE user_id=?',[target.id]);
if(body.status==='deceased'&&!memorial){
const slug=target.username.toLowerCase().replaceAll('_','-')+'-'+target.id.slice(0,8);
await tx.query('INSERT INTO site_memorials(slug,user_id,title,summary) VALUES(?,?,?,?)',[slug,target.id,target.display_name+' — Community Memorial','A community remembrance maintained by DuneRealms. Share a respectful memory or message below.']);
memorial={slug};
}
await tx.query('INSERT INTO site_life_status(user_id,status,version,updated_by,updated_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE status=VALUES(status),version=VALUES(version),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)',[target.id,body.status,Number(before?.version||0)+1,actor.id,clock()]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'citizen-life-status',JSON.stringify({targetId:target.id,before:before?.status||null,status:body.status,reason:body.reason.trim(),memorial:memorial?.slug||null}),clock()]);
return reply({ok:true,changed:true,memorial:body.status==='deceased'&&memorial?'/memorial/'+memorial.slug:null});
});}catch(e){if(e.status)return reply({message:e.message},e.status);throw e;}
};}

View file

@ -1,12 +1,27 @@
import {identity} from './auth.mjs';
import {manageManualSeal} from './manual-seal-admin.mjs';
export function createManualSealRoute(db,origin,{authenticate=identity,manage=manageManualSeal}={}){return async request=>{
import {accessFor} from './permissions.mjs';
import {MANUAL_SEALS} from './seal-entitlements.mjs';
import {activeSealEntitlements} from './seal-entitlement-store.mjs';
import {AWARD_LABELS} from './recognition.mjs';
import {nativeSyncChange} from './native-sync-outbox.mjs';
export function createManualSealRoute(db,origin,{authenticate=identity,manage=manageManualSeal,readAccess=accessFor,queue=()=>nativeSyncChange(db).run()}={}){return async request=>{
const actor=await authenticate(request,db);
if(!actor)return Response.json({message:'Sign in first.'},{status:401});
if(request.method==='GET'){
const rights=await readAccess(db,actor);
if(!rights.nodes.includes('web.accounts.view'))return Response.json({message:'Account directory permission required.'},{status:403});
const id=new URL(request.url).searchParams.get('userId');if(!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id||''))return Response.json({message:'Select a citizen.'},{status:400});
const labels={'alpha-tester':'Alpha Tester','beta-tester':'Beta Tester','launch-contributor':'Launch Contributor','dedicated-tester':'Dedicated Tester','season-tavren-ii':'Season Tavren II','dunegit-owner':'DuneGit Owner',...AWARD_LABELS};
const entitlements=(await activeSealEntitlements(db,id)).map(({id,key,source,grantedAt})=>({id,key,source,grantedAt}));
return Response.json({catalogue:[...MANUAL_SEALS].map(key=>({key,label:labels[key]||key,file:key+'-150.png'})),entitlements,canManage:actor.id!==id&&rights.nodes.includes('web.accounts.assign')},{headers:{'Cache-Control':'no-store'}});
}
if(request.method!=='POST')return Response.json({message:'Method not allowed.'},{status:405});
if(request.headers.get('origin')!==origin)return Response.json({message:'Origin rejected.'},{status:403});
let body;try{body=await request.json();}catch{return Response.json({message:'Invalid JSON.'},{status:400});}
if(!body||typeof body!=='object'||Array.isArray(body)||!['grant','revoke'].includes(body.action)||typeof body.targetId!=='string'||typeof body.seal!=='string'||typeof body.reason!=='string'||body.reason.trim().length<3||body.reason.length>500)return Response.json({message:'Action, recipient, seal and reason required.'},{status:400});
const result=await manage(db,actor,body);
// Retrying an already saved grant also retries its derived native signature refresh.
if(result.ok)await queue();
return Response.json(result,{status:result.ok?200:result.status||400,headers:{'Cache-Control':'no-store'}});
};}

View file

@ -68,14 +68,15 @@ export async function memberProfileData(db,target,settings={}){
for(const seal of politicalSeals(access.ranks))add(seal.key,seal.label,base+seal.file,seal.group);
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 memorial=await optional(()=>db.prepare("SELECT m.slug FROM site_memorials m LEFT JOIN site_life_status l ON l.user_id=m.user_id WHERE m.user_id=? AND (l.status IS NULL OR l.status='deceased')").bind(target.id).first(),null);
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),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'}};
return{showcase,memorial:memorial?'/memorial/'+memorial.slug:null,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);
if(request.method==='OPTIONS')return new Response(null,{status:204,headers:json({}).headers});if(request.method!=='GET')return json({message:'Read-only profile.'},405);
const actor=await identity(request,db);if(!actor)return json({message:'Sign in with your DuneRealms account to view this profile.'},401);
const match=new URL(request.url).pathname.match(/^\/api\/people\/([a-z0-9_]{3,32})$/);if(!match)return json({message:'Profile not found.'},404);
const target=await db.prepare("SELECT id,username,display_name,role,created_at FROM site_accounts WHERE username=? AND password_hash NOT LIKE '!%' AND role<>'memorial'").bind(match[1]).first();if(!target)return json({message:'Profile not found.'},404);
const target=await db.prepare("SELECT id,username,display_name,role,created_at FROM site_accounts WHERE username=? AND (password_hash NOT LIKE '!%' OR password_hash='!memorial')").bind(match[1]).first();if(!target)return json({message:'Profile not found.'},404);
return json({profile:await memberProfileData(db,target,settings)});
};}

View file

@ -1,73 +1,74 @@
import {randomUUID,createHash} from 'node:crypto';
import {readFile} from 'node:fs/promises';
import {identity} from './auth.mjs';
import {accessFor} from './permissions.mjs';
import {honoursFor,honourMarkup,HONOUR_CSS} from './honours.mjs';
import {SHARED_HEAD,SHARED_HEADER} from '../scripts/portal-navigation.mjs';
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const json=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store'}});
export function condolenceText(value){return typeof value==='string'&&Array.from(value.trim()).length>=3&&Array.from(value).length<=2000&&!/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value);}
export async function memorialRoleStatements(db,target,keys){
if(!keys.includes('memorial'))return [];
if(await db.prepare('SELECT slug FROM site_memorials WHERE user_id=?').bind(target.id).first())return [];
const account=await db.prepare('SELECT username,display_name FROM site_accounts WHERE id=?').bind(target.id).first();
const slug=account.username.toLowerCase().replaceAll('_','-');
return [db.prepare('INSERT INTO site_memorials(slug,user_id,title,summary) VALUES(?,?,?,?) ON CONFLICT(slug) DO UPDATE SET user_id=excluded.user_id').bind(slug,target.id,account.display_name+' — Community Memorial','A community remembrance maintained by DuneRealms. Share a respectful memory or message below.')];
}
export async function memorialPortalBlock(db){
const {results}=await db.prepare("SELECT m.slug,m.title,m.summary,a.display_name FROM site_memorials m JOIN site_accounts a ON a.id=m.user_id WHERE a.role='memorial' OR EXISTS(SELECT 1 FROM cp_account_ranks r WHERE r.user_id=a.id AND r.rank_key='memorial') ORDER BY m.title,m.slug").all();
if(!results.length)return '';
return '<section class="portal-memorials" aria-labelledby="portal-memorials-title"><header><p class="memorial-kicker">THE IMPERIAL BOOK OF REMEMBRANCE</p><h2 id="portal-memorials-title">Community memorials</h2><p>Remembered by our community. These are tribute pages, never personal or official accounts.</p></header><div class="portal-memorial-grid">'+results.map(m=>'<article><img src="/assets/seals/order-crysknife-v1.png" alt="DuneRealms remembrance seal" width="96" height="96"><h3>'+esc(m.display_name.replace(/\s*[—-]\s*Memorial$/i,''))+'</h3><p>Community memorial · account locked</p><a href="/memorial/'+encodeURIComponent(m.slug)+'">Visit memorial &amp; condolences →</a></article>').join('')+'</div></section>';
}
export function createMemorials(db,settings={}){return async request=>{
const url=new URL(request.url),path=url.pathname,origin=new URL(settings.PUBLIC_ORIGIN||'https://www.dunerealms.com').origin;
if(path==='/memorial.css')return new Response(HONOUR_CSS+await readFile(new URL('./public/memorial.css',import.meta.url),'utf8'),{headers:{'Content-Type':'text/css; charset=utf-8'}});
if(path==='/memorial.js')return new Response(await readFile(new URL('./public/memorial.js',import.meta.url),'utf8'),{headers:{'Content-Type':'text/javascript; charset=utf-8'}});
const api=path.match(/^\/api\/memorials\/([a-z0-9-]{3,64})(?:\/(decision|session))?$/);
if(api){
const memorial=await db.prepare('SELECT slug FROM site_memorials WHERE slug=?').bind(api[1]).first();if(!memorial)return json({message:'Memorial not found.'},404);
const actor=await identity(request,db);if(!actor)return json({message:'Sign in to participate.'},401);
const rights=await accessFor(db,actor),moderator=rights.nodes.includes('web.posts.publish');
if(api[2]==='session')return request.method==='GET'?json({authenticated:true,username:actor.username,canModerate:moderator}):json({message:'Method rejected.'},405);
if(request.method==='GET'&&!api[2]){
if(!moderator)return json({message:'Moderation permission required.'},403);
const {results}=await db.prepare("SELECT c.id,c.body,c.version,a.username FROM site_condolences c JOIN site_accounts a ON a.id=c.user_id WHERE c.memorial_slug=? AND c.status='pending' ORDER BY c.created_at LIMIT 50").bind(api[1]).all();return json({pending:results});
}
if(request.method!=='POST'||request.headers.get('origin')!==origin)return json({message:'Origin or method rejected.'},403);
let body;try{body=await request.json();}catch{return json({message:'Invalid request.'},400);}
if(!body||typeof body!=='object'||Array.isArray(body))return json({message:'Invalid request.'},400);
if(api[2]){
if(!moderator)return json({message:'Moderation permission required.'},403);
if(typeof body.id!=='string'||!/^[a-f0-9-]{36}$/i.test(body.id)||!['approved','denied'].includes(body.status)||!Number.isSafeInteger(body.version))return json({message:'Invalid decision.'},400);
const result=await db.batch([db.prepare("UPDATE site_condolences SET status=?,reviewed_by=?,reviewed_at=?,version=version+1 WHERE id=? AND memorial_slug=? AND status='pending' AND version=?").bind(body.status,actor.id,Date.now(),body.id,api[1],body.version),db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),actor.id,'condolence-review',body.id+' '+body.status,Date.now())]);
return result[0].meta.changes?json({ok:true}):json({message:'This message has already been reviewed.'},409);
}
if(!condolenceText(body.message)||body.website||Object.keys(body).some(k=>!['message','website'].includes(k)))return json({message:'Use a respectful message of 3–2,000 characters.'},400);
const recent=await db.prepare('SELECT COUNT(*) AS n FROM site_condolences WHERE user_id=? AND created_at>?').bind(actor.id,Date.now()-86400000).first();if(Number(recent?.n)>=3)return json({message:'Please wait before posting another tribute.'},429);
const text=body.message.replaceAll('\r\n','\n').trim(),hash=createHash('sha256').update(text).digest('hex');
try{await db.prepare("INSERT INTO site_condolences(id,memorial_slug,user_id,body,body_hash,status,created_at,version) VALUES(?,?,?,?,?,'pending',?,1)").bind(randomUUID(),api[1],actor.id,text,hash,Date.now()).run();}catch(e){if(e.code==='ER_DUP_ENTRY'||String(e.message).includes('UNIQUE'))return json({message:'This tribute has already been submitted.'},409);throw e;}
return json({ok:true,message:'Thank you. Your condolence will appear after review.'},201);
}
if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});
const match=path.match(/^\/(memorial|people)\/([a-z0-9_-]{3,64})$/);if(!match)return new Response('Not found',{status:404});
let account,memorial=null;
if(match[1]==='memorial') {memorial=await db.prepare('SELECT * FROM site_memorials WHERE slug=?').bind(match[2]).first();if(memorial)account=await db.prepare('SELECT id,username,display_name,role FROM site_accounts WHERE id=?').bind(memorial.user_id).first();}
else {
account=await db.prepare("SELECT id,username,display_name,role FROM site_accounts WHERE username=? AND (password_hash NOT LIKE '!%' OR password_hash='!memorial')").bind(match[2]).first();
if(account){const tribute=await db.prepare('SELECT slug FROM site_memorials WHERE user_id=?').bind(account.id).first();if(tribute)return Response.redirect(origin+'/memorial/'+encodeURIComponent(tribute.slug),302);}
}
if(!account)return new Response('Profile not found',{status:404});
if(memorial&&account.role!=='memorial'&&!(await accessFor(db,account)).ranks.includes('memorial'))return new Response('Memorial not found',{status:404});
const honours=account.username.toLowerCase()==='dunerealms'?[]:await honoursFor(db,account);let content='';
if(memorial){
const page=Number(url.searchParams.get('page')||1);if(!Number.isSafeInteger(page)||page<1||page>10000)return json({message:'Invalid page.'},400);
const count=await db.prepare("SELECT COUNT(*) AS n FROM site_condolences WHERE memorial_slug=? AND status='approved'").bind(memorial.slug).first();
const {results}=await db.prepare("SELECT c.body,c.created_at,a.display_name,a.password_hash FROM site_condolences c JOIN site_accounts a ON a.id=c.user_id WHERE c.memorial_slug=? AND c.status='approved' ORDER BY c.created_at DESC,c.id DESC LIMIT 20 OFFSET ?").bind(memorial.slug,(page-1)*20).all();
const pages=Math.max(1,Math.ceil(Number(count?.n)/20));
content='<section class="memorial-box"><h2>Leave a condolence</h2><p>Sign in with your community account to post. Messages are reviewed before appearing. Please do not include private contact details.</p><form id="condolence-form" data-slug="'+esc(memorial.slug)+'"><label>Your message<textarea name="message" rows="6" minlength="3" maxlength="2000" required></textarea></label><input name="website" tabindex="-1" autocomplete="off" class="memorial-trap" aria-hidden="true"><button type="submit">Submit condolence</button><a id="memorial-signin" href="https://cp.dunerealms.com/memorial-login?slug='+encodeURIComponent(memorial.slug)+'">Sign in</a><p id="condolence-status" role="status"></p></form></section><section class="memorial-box"><h2>Community condolences</h2>'+(!results.length?'<p>No condolences have been published yet.</p>':results.map(r=>'<article class="condolence"><strong>'+esc(r.password_hash.startsWith('!')?'Former community member':r.display_name)+'</strong><p>'+esc(r.body)+'</p></article>').join(''))+'<nav class="memorial-pagination" aria-label="Condolence pages">'+(page>1?'<a href="?page='+(page-1)+'">Previous</a>':'')+'<span>Page '+page+' of '+pages+'</span>'+(page<pages?'<a href="?page='+(page+1)+'">Next</a>':'')+'</nav></section><section class="memorial-box" id="condolence-moderation" hidden><h2>Pending condolences</h2><div id="condolence-queue"></div></section>';
}
if(!memorial)content='<section class="member-profile-content" id="member-profile" data-username="'+esc(account.username)+'"><div class="memorial-box member-profile-access"><h2>Community profile</h2><p id="member-profile-status" role="status">Checking your DuneRealms session…</p><a id="member-profile-signin" href="https://cp.dunerealms.com/profile-login?username='+encodeURIComponent(account.username)+'">Sign in to view profile</a></div><div id="member-profile-boxes" class="member-profile-grid" hidden></div></section>';
const title=memorial?.title||account.display_name||account.username;
const html='<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>'+esc(title)+' | DuneRealms</title>'+SHARED_HEAD+'<link rel="stylesheet" href="/memorial.css?v=people-awards-v3"></head><body>'+SHARED_HEADER+'<main class="memorial-main '+(!memorial?'people-main':'')+'"><header class="memorial-box memorial-hero"><p class="memorial-kicker">'+(memorial?'IN MEMORY · COMMUNITY MEMORIAL':'THE IMPERIAL REGISTER · COMMUNITY PROFILE')+'</p><h1>'+esc(title)+'</h1><p>'+esc(memorial?.summary||'DuneRealms community member')+'</p>'+(memorial?'<aside class="memorial-disclaimer"><strong>Community memorial — not the person’s personal or official account.</strong><br>Independently maintained by DuneRealms. Not affiliated with the person’s family, representatives or estate. This account cannot sign in or act as this person.</aside>':'')+'</header>'+honourMarkup(honours)+content+'</main><script src="/memorial.js?v=people-awards-v3" defer></script></body></html>';
return new Response(request.method==='HEAD'?null:html,{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}});
};}
import {randomUUID,createHash} from 'node:crypto';
import {readFile} from 'node:fs/promises';
import {identity} from './auth.mjs';
import {accessFor} from './permissions.mjs';
import {honoursFor,honourMarkup,HONOUR_CSS} from './honours.mjs';
import {SHARED_HEAD,SHARED_HEADER} from '../scripts/portal-navigation.mjs';
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const json=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store'}});
export function condolenceText(value){return typeof value==='string'&&Array.from(value.trim()).length>=3&&Array.from(value).length<=2000&&!/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value);}
export async function memorialRoleStatements(db,target,keys){
if(!keys.includes('memorial'))return [];
if(await db.prepare('SELECT slug FROM site_memorials WHERE user_id=?').bind(target.id).first())return [];
const account=await db.prepare('SELECT username,display_name FROM site_accounts WHERE id=?').bind(target.id).first();
const slug=account.username.toLowerCase().replaceAll('_','-');
return [db.prepare('INSERT INTO site_memorials(slug,user_id,title,summary) VALUES(?,?,?,?) ON CONFLICT(slug) DO UPDATE SET user_id=excluded.user_id').bind(slug,target.id,account.display_name+' — Community Memorial','A community remembrance maintained by DuneRealms. Share a respectful memory or message below.')];
}
export async function memorialPortalBlock(db){
const {results}=await db.prepare("SELECT m.slug,m.title,m.summary,a.display_name FROM site_memorials m JOIN site_accounts a ON a.id=m.user_id LEFT JOIN site_life_status l ON l.user_id=a.id WHERE (l.status='deceased' OR l.status IS NULL AND (a.role='memorial' OR EXISTS(SELECT 1 FROM cp_account_ranks r WHERE r.user_id=a.id AND r.rank_key='memorial'))) ORDER BY m.title,m.slug").all();
if(!results.length)return '';
return '<section class="portal-memorials" aria-labelledby="portal-memorials-title"><header><p class="memorial-kicker">THE IMPERIAL BOOK OF REMEMBRANCE</p><h2 id="portal-memorials-title">Community memorials</h2><p>Remembered by our community. Community remembrance and tribute pages.</p></header><div class="portal-memorial-grid">'+results.map(m=>'<article><img src="/assets/seals/order-crysknife-v1.png" alt="DuneRealms remembrance seal" width="96" height="96"><h3>'+esc(m.display_name.replace(/\s*[—-]\s*Memorial$/i,''))+'</h3><p>Community remembrance</p><a href="/memorial/'+encodeURIComponent(m.slug)+'">Visit memorial &amp; condolences →</a></article>').join('')+'</div></section>';
}
export function createMemorials(db,settings={}){return async request=>{
const url=new URL(request.url),path=url.pathname,origin=new URL(settings.PUBLIC_ORIGIN||'https://www.dunerealms.com').origin;
if(path==='/memorial.css')return new Response(HONOUR_CSS+await readFile(new URL('./public/memorial.css',import.meta.url),'utf8'),{headers:{'Content-Type':'text/css; charset=utf-8'}});
if(path==='/memorial.js')return new Response(await readFile(new URL('./public/memorial.js',import.meta.url),'utf8'),{headers:{'Content-Type':'text/javascript; charset=utf-8'}});
const api=path.match(/^\/api\/memorials\/([a-z0-9-]{3,64})(?:\/(decision|session))?$/);
if(api){
const memorial=await db.prepare("SELECT m.slug FROM site_memorials m LEFT JOIN site_life_status l ON l.user_id=m.user_id WHERE m.slug=? AND (l.status IS NULL OR l.status='deceased')").bind(api[1]).first();if(!memorial)return json({message:'Memorial not found.'},404);
const actor=await identity(request,db);if(!actor)return json({message:'Sign in to participate.'},401);
const rights=await accessFor(db,actor),moderator=rights.nodes.includes('web.posts.publish');
if(api[2]==='session')return request.method==='GET'?json({authenticated:true,username:actor.username,canModerate:moderator}):json({message:'Method rejected.'},405);
if(request.method==='GET'&&!api[2]){
if(!moderator)return json({message:'Moderation permission required.'},403);
const {results}=await db.prepare("SELECT c.id,c.body,c.version,a.username FROM site_condolences c JOIN site_accounts a ON a.id=c.user_id WHERE c.memorial_slug=? AND c.status='pending' ORDER BY c.created_at LIMIT 50").bind(api[1]).all();return json({pending:results});
}
if(request.method!=='POST'||request.headers.get('origin')!==origin)return json({message:'Origin or method rejected.'},403);
let body;try{body=await request.json();}catch{return json({message:'Invalid request.'},400);}
if(!body||typeof body!=='object'||Array.isArray(body))return json({message:'Invalid request.'},400);
if(api[2]){
if(!moderator)return json({message:'Moderation permission required.'},403);
if(typeof body.id!=='string'||!/^[a-f0-9-]{36}$/i.test(body.id)||!['approved','denied'].includes(body.status)||!Number.isSafeInteger(body.version))return json({message:'Invalid decision.'},400);
const result=await db.batch([db.prepare("UPDATE site_condolences SET status=?,reviewed_by=?,reviewed_at=?,version=version+1 WHERE id=? AND memorial_slug=? AND status='pending' AND version=?").bind(body.status,actor.id,Date.now(),body.id,api[1],body.version),db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),actor.id,'condolence-review',body.id+' '+body.status,Date.now())]);
return result[0].meta.changes?json({ok:true}):json({message:'This message has already been reviewed.'},409);
}
if(!condolenceText(body.message)||body.website||Object.keys(body).some(k=>!['message','website'].includes(k)))return json({message:'Use a respectful message of 3–2,000 characters.'},400);
const recent=await db.prepare('SELECT COUNT(*) AS n FROM site_condolences WHERE user_id=? AND created_at>?').bind(actor.id,Date.now()-86400000).first();if(Number(recent?.n)>=3)return json({message:'Please wait before posting another tribute.'},429);
const text=body.message.replaceAll('\r\n','\n').trim(),hash=createHash('sha256').update(text).digest('hex');
try{await db.prepare("INSERT INTO site_condolences(id,memorial_slug,user_id,body,body_hash,status,created_at,version) VALUES(?,?,?,?,?,'pending',?,1)").bind(randomUUID(),api[1],actor.id,text,hash,Date.now()).run();}catch(e){if(e.code==='ER_DUP_ENTRY'||String(e.message).includes('UNIQUE'))return json({message:'This tribute has already been submitted.'},409);throw e;}
return json({ok:true,message:'Thank you. Your condolence will appear after review.'},201);
}
if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});
const match=path.match(/^\/(memorial|people)\/([a-z0-9_-]{3,64})$/);if(!match)return new Response('Not found',{status:404});
let account,memorial=null;
if(match[1]==='memorial') {memorial=await db.prepare('SELECT * FROM site_memorials WHERE slug=?').bind(match[2]).first();if(memorial)account=await db.prepare('SELECT id,username,display_name,role FROM site_accounts WHERE id=?').bind(memorial.user_id).first();}
else {
account=await db.prepare("SELECT id,username,display_name,role FROM site_accounts WHERE username=? AND (password_hash NOT LIKE '!%' OR password_hash='!memorial')").bind(match[2]).first();
if(account){const tribute=await db.prepare('SELECT slug FROM site_memorials WHERE user_id=?').bind(account.id).first();if(tribute)return Response.redirect(origin+'/memorial/'+encodeURIComponent(tribute.slug),302);}
}
if(!account)return new Response('Profile not found',{status:404});
const life=await db.prepare('SELECT status FROM site_life_status WHERE user_id=?').bind(account.id).first();
if(memorial&&(life?.status==='living'||life?.status!=='deceased'&&account.role!=='memorial'&&!(await accessFor(db,account)).ranks.includes('memorial')))return new Response('Memorial not found',{status:404});
const honours=account.username.toLowerCase()==='dunerealms'?[]:await honoursFor(db,account);let content='';
if(memorial){
const page=Number(url.searchParams.get('page')||1);if(!Number.isSafeInteger(page)||page<1||page>10000)return json({message:'Invalid page.'},400);
const count=await db.prepare("SELECT COUNT(*) AS n FROM site_condolences WHERE memorial_slug=? AND status='approved'").bind(memorial.slug).first();
const {results}=await db.prepare("SELECT c.body,c.created_at,a.display_name,a.password_hash FROM site_condolences c JOIN site_accounts a ON a.id=c.user_id WHERE c.memorial_slug=? AND c.status='approved' ORDER BY c.created_at DESC,c.id DESC LIMIT 20 OFFSET ?").bind(memorial.slug,(page-1)*20).all();
const pages=Math.max(1,Math.ceil(Number(count?.n)/20));
content='<section class="memorial-box"><h2>Leave a condolence</h2><p>Sign in with your community account to post. Messages are reviewed before appearing. Please do not include private contact details.</p><form id="condolence-form" data-slug="'+esc(memorial.slug)+'"><label>Your message<textarea name="message" rows="6" minlength="3" maxlength="2000" required></textarea></label><input name="website" tabindex="-1" autocomplete="off" class="memorial-trap" aria-hidden="true"><button type="submit">Submit condolence</button><a id="memorial-signin" href="https://cp.dunerealms.com/memorial-login?slug='+encodeURIComponent(memorial.slug)+'">Sign in</a><p id="condolence-status" role="status"></p></form></section><section class="memorial-box"><h2>Community condolences</h2>'+(!results.length?'<p>No condolences have been published yet.</p>':results.map(r=>'<article class="condolence"><strong>'+esc(r.password_hash.startsWith('!')?'Former community member':r.display_name)+'</strong><p>'+esc(r.body)+'</p></article>').join(''))+'<nav class="memorial-pagination" aria-label="Condolence pages">'+(page>1?'<a href="?page='+(page-1)+'">Previous</a>':'')+'<span>Page '+page+' of '+pages+'</span>'+(page<pages?'<a href="?page='+(page+1)+'">Next</a>':'')+'</nav></section><section class="memorial-box" id="condolence-moderation" hidden><h2>Pending condolences</h2><div id="condolence-queue"></div></section>';
}
if(!memorial)content='<section class="member-profile-content" id="member-profile" data-username="'+esc(account.username)+'"><div class="memorial-box member-profile-access"><h2>Community profile</h2><p id="member-profile-status" role="status">Checking your DuneRealms session…</p><a id="member-profile-signin" href="https://cp.dunerealms.com/profile-login?username='+encodeURIComponent(account.username)+'">Sign in to view profile</a></div><div id="member-profile-boxes" class="member-profile-grid" hidden></div></section>';
const title=memorial?.title||account.display_name||account.username;
const html='<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>'+esc(title)+' | DuneRealms</title>'+SHARED_HEAD+'<link rel="stylesheet" href="/memorial.css?v=people-awards-v3"></head><body>'+SHARED_HEADER+'<main class="memorial-main '+(!memorial?'people-main':'')+'"><header class="memorial-box memorial-hero"><p class="memorial-kicker">'+(memorial?'IN MEMORY · COMMUNITY MEMORIAL':'THE IMPERIAL REGISTER · COMMUNITY PROFILE')+'</p><h1>'+esc(title)+'</h1><p>'+esc(memorial?.summary||'DuneRealms community member')+'</p>'+(memorial?'<aside class="memorial-disclaimer"><strong>Community memorial — maintained by the community.</strong><br>Independently maintained by DuneRealms. Not affiliated with the person’s family, representatives or estate. This tribute is separate from account access and permissions.</aside>':'')+'</header>'+honourMarkup(honours)+content+'</main><script src="/memorial.js?v=people-awards-v3" defer></script></body></html>';
return new Response(request.method==='HEAD'?null:html,{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'}});
};}

View file

@ -3,7 +3,14 @@ import {assignmentLabel,validStaffRole} from './organisation-model.mjs';
import {organisationSubject} from './official-account.mjs';
const SERVICE_ID='f7b88778-f0bc-41cc-9227-d8ef2f52264d';
const legacyStaff=new Set(['owners','owner','corestaff','staff','network_admin','web_net_admin','web_net_owner','web_network','official_account','admin','administrator','moderator','guardian','streamer','twitch','yt']);
const privileged=node=>/^web\.(accounts\.|ranks\.|servers\.|luckperms\.|tickets\.(staff|admin|appeals)|bank\.staff\.|payroll\.|posts\.(edit|publish)|items\.manage|bans\.|forum\.moderate|git\.admin)/.test(node)||/^cp\.(accounts\.|ranks\.|servers\.|luckperms\.|bank\.staff\.|items\.manage)/.test(node)||/^dune\.(admin|staff\.|moderation\.|ban\.|unban\.)/.test(node)||node.startsWith('duneprotect.')||/^(?:web|cp)\.menu\.(?:administration|staffmanual|permissions|servers|luckperms|bans|forum|items|posts)$/.test(node)||/^web\.(?:shop\.support|bank\.projects\.approve|mail\.staff\.)/.test(node);
const privileged=value=>{
const node=value.startsWith('cp.')?'web.'+value.slice(3):value;
return /^web\.(accounts\.|ranks\.|servers\.|luckperms\.|tickets\.|bank\.staff\.|payroll\.|posts\.(edit|publish)|items\.manage|bans\.|forum\.(moderate|admin)|git\.admin|community\.manage|quests\.manage)/.test(node)
||/^dune\.(admin|staff\.|moderation\.|ban\.|unban\.|items\.give|tickets\.staff)/.test(node)
||node.startsWith('duneprotect.')||/^dunelobby\.(admin|build)$/.test(node)
||/^web\.menu\.(?:administration|staffmanual|permissions|servers|luckperms|bans|forum|items|posts|tickets)$/.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();

View file

@ -0,0 +1 @@
*{box-sizing:border-box}body{margin:0;background:#0b211a;color:#e8e7d7;font:16px/1.65 Arial,sans-serif}a{color:#e4c983}.memorial-main{max-width:1100px;margin:48px auto;padding:0 24px}.memorial-box{padding:32px;margin:24px 0;border:1px solid #6b7952;border-radius:16px;background:linear-gradient(135deg,#1c3a2c,#10271f)}.memorial-hero{border-color:#b39a54;padding:48px;background:linear-gradient(120deg,#294235,#10271f)}.memorial-kicker{color:#c6ac6c;font-size:11px;letter-spacing:.18em}.memorial-main h1{font:44px/1.2 Georgia,serif;color:#efdba3;margin:18px 0}.memorial-main h2{font:27px Georgia,serif;color:#e5cc8c}.memorial-disclaimer{padding:18px;border-left:3px solid #ad9254;background:#0c211a80;font-size:13px;color:#bbcabb}.memorial-main label{display:block}.memorial-main textarea{display:block;width:100%;padding:15px;border:1px solid #77815b;border-radius:8px;background:#0c251b;color:#edf0e5;font:inherit;margin:12px 0}.memorial-main button,.memorial-pagination a,#memorial-signin{display:inline-block;padding:10px 18px;border:1px solid #b39a54;border-radius:7px;background:#203b2c;color:#efdaa0;cursor:pointer;font:inherit;text-decoration:none;margin-right:14px}.memorial-main button:disabled{opacity:.6;cursor:wait}.memorial-trap{position:absolute;left:-10000px}.condolence{padding:22px 0;border-top:1px solid #456048}.condolence p{white-space:pre-wrap;overflow-wrap:anywhere}.memorial-pagination{display:flex;gap:18px;align-items:center;flex-wrap:wrap}.memorial-main :focus-visible{outline:2px solid #edcd7d;outline-offset:4px}@media(max-width:600px){.memorial-main{margin:24px auto;padding:0 16px}.memorial-box,.memorial-hero{padding:24px}.memorial-main h1{font-size:32px}}

View file

@ -0,0 +1,7 @@
const form=document.getElementById('condolence-form'),status=document.getElementById('condolence-status');
const api=path=>'https://cp.dunerealms.com/api/memorials/'+encodeURIComponent(form.dataset.slug)+path;
async function request(path,body){const r=await fetch(api(path),{credentials:'include',cache:'no-store',...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});const data=await r.json();if(!r.ok)throw Error(data.message||'Request failed.');return data;}
if(form){
form.onsubmit=async event=>{event.preventDefault();if(!form.reportValidity())return;const submit=form.querySelector('button');submit.disabled=true;status.textContent='Submitting…';try{const data=await request('',{message:form.elements.message.value,website:form.elements.website.value});status.textContent=data.message;form.reset();}catch(e){status.textContent=e.message;}finally{submit.disabled=false;}};
request('/session').then(async session=>{document.getElementById('memorial-signin').hidden=true;if(!session.canModerate)return;const panel=document.getElementById('condolence-moderation'),queue=document.getElementById('condolence-queue');panel.hidden=false;const data=await request('');for(const item of data.pending){const card=document.createElement('article'),text=document.createElement('p');card.className='condolence';text.textContent=item.username+': '+item.body;card.append(text);for(const [label,value]of [['Publish','approved'],['Decline','denied']]){const button=document.createElement('button');button.type='button';button.textContent=label;button.onclick=async()=>{button.disabled=true;try{await request('/decision',{id:item.id,status:value,version:item.version});card.remove();}catch(e){status.textContent=e.message;button.disabled=false;}};card.append(button);}queue.append(card);}}).catch(()=>{});
}

View file

@ -17,6 +17,7 @@ function render(p){
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'));
if(/^\/memorial\/[a-z0-9-]+$/.test(p.memorial||'')){const a=el('a','Visit community memorial →','chip');a.href=p.memorial;$('socials').append(a);text('status','Community remembrance profile');}
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.');

View file

@ -1,4 +1,6 @@
import {startNativeSyncRetryWorker} from './native-sync-outbox.mjs';
import {createMemorials} from './memorials.mjs';
import {initializeLifeStatus} from './life-status.mjs';
import {SHARED_HEADER} from '../scripts/portal-navigation.mjs';
import {initializeOrganisation} from './organisation-model.mjs';
import {createGitIdentityRoute,initializeGitIdentities,gitProxyIdentity} from './git-identity.mjs';
@ -27,7 +29,7 @@ export function createApplication(db,settings={}) {
const auth=createAuth(db,origin);
const gitIdentity=createGitIdentityRoute(db,settings,origin);
const worldStatus=createWorldStatus(settings);
const publicRoster=createPublicStaffRoster(db);
const publicRoster=createPublicStaffRoster(db);const memorials=createMemorials(db,settings);
const contact=createContact(settings);
const gameLink=createGameLink(db,settings,origin);
const rewards=createCommunityRewards(db,settings,origin);
@ -40,6 +42,7 @@ export function createApplication(db,settings={}) {
if(url.pathname==='/api/news'||url.pathname.startsWith('/api/news/')||url.pathname==='/api/home/forum')return publicNews(request);
const publicModeration={'/api/public/bans':()=>publicBanCards(db),'/api/public/appeals':()=>publicAppealCards(db,request),'/api/public/ban-list':()=>publicBanList(db,request),'/api/public/account-bans':()=>publicAccountBans(db)};
if(Object.hasOwn(publicModeration,url.pathname))return request.method==='GET'?publicModeration[url.pathname]():new Response('Method not allowed',{status:405});
if(url.pathname.startsWith('/memorial/')||['/memorial.css','/memorial.js'].includes(url.pathname))return memorials(request);
// Rebuilt Citizen Passport pages; never fall through to missing Worker routes.
if(/^\/people\/[a-z0-9_]{3,32}\/?$/.test(url.pathname)||['/passport.css','/passport.js'].includes(url.pathname)){
if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});
@ -82,7 +85,7 @@ export function createApplication(db,settings={}) {
};
}
export async function start(settings=process.env) {
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;
const db=await openDatabase(settings);if(db.organisationAccessEnabled)await initializeOrganisation(db);await initializeRanks(db);await initializeGitIdentities(db);await initializePublicRoster(db);await initializeLifeStatus(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.');

View file

@ -7,7 +7,7 @@ import sys
root = Path(__file__).resolve().parents[1]
target = Path('/home/dunerealms/apps/integrations')
names = ('sync-public-profile.php', 'sync-staff-seals.php', 'managed-signatures.php')
names = ('sync-public-profile.php', 'sync-staff-seals.php', 'managed-signatures.php', 'osticket/dune-support-home.php')
for name in names:
subprocess.run(['php', '-l', str(root / 'integrations' / name)], check=True)
catalogue = json.loads((root / 'artwork/seals/great-migration/catalogue.json').read_text())
@ -21,7 +21,7 @@ for key, metadata in catalogue.items():
raise ValueError(f'Missing PNG: {name}')
entries[key][field] = '/assets/seals/' + name
if '--apply' not in sys.argv:
print(f'Plan: {len(entries)} seals, three custom adapters; no changes applied')
print(f'Plan: {len(entries)} seals, four custom adapters; no changes applied')
sys.exit(0)
def atomic(path, content):
temporary = path.with_name(path.name + '.migration-new')

View file

@ -0,0 +1,7 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {citizenRankVisible} from '../node/citizen-memberships.mjs';
test('Citizen views retain earned tiers, houses, paths and Order membership while excluding staff titles',()=>{
for(const key of ['user','vip','patron_caravan','patron_guild','patron_grand','council_member'])assert(citizenRankVisible({key,kind:'access'}));
for(const kind of ['house','office','path','order'])assert(citizenRankVisible({key:'source-role',kind}));
for(const key of ['org_owner_ceo','org_officer','staff','corestaff','web_dev','game_admin'])assert(!citizenRankVisible({key,kind:'access'}));
});

View file

@ -0,0 +1,27 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {createLifeStatus} from '../node/life-status.mjs';
const actor='11111111-1111-4111-8111-111111111111',target='22222222-2222-4222-8222-222222222222',origin='https://cp.dunerealms.com';
function fixture(kind='owner'){
let state={life:null,memorial:null,audits:[],identity:{id:target,username:'citizen',display_name:'Citizen'}};let auditFails=false;
const db={transaction:async work=>{const draft=structuredClone(state);const tx={
first:async sql=>sql.includes('org_control_principals')?{principal_kind:kind}:sql.includes('SELECT id FROM site_accounts')?{id:actor}:sql.includes('SELECT a.id')?draft.identity:sql.includes('site_life_status')?draft.life:sql.includes('site_memorials')?draft.memorial:null,
query:async(sql,args)=>{if(sql.startsWith('INSERT INTO site_memorials'))draft.memorial={slug:args[0]};else if(sql.startsWith('INSERT INTO site_life_status'))draft.life={status:args[1],version:args[2]};else if(sql.startsWith('INSERT INTO account_audit')){if(auditFails)throw Error('Audit unavailable');draft.audits.push(args);}}
};const result=await work(tx);state=draft;return result;}};
const handle=createLifeStatus(db,{origin,authenticate:async()=>({id:actor}),authorize:async()=>true});
const send=(body,from=origin)=>handle(new Request(origin+'/api/admin/life-status',{method:'POST',headers:{origin:from,'Content-Type':'application/json'},body:JSON.stringify({userId:target,status:'deceased',confirm:'citizen',reason:'Verified community notification',version:0,...body})}));
return{send,get:()=>handle(new Request(origin+'/api/admin/life-status?userId='+target)),state:()=>state,failAudit:()=>{auditFails=true;}};
}
test('Only pinned control principals may record death; branch authority and cross-origin requests cannot',async()=>{
const f=fixture('branch_lead');assert.equal((await f.send({})).status,403);assert.equal((await f.get()).status,200);assert.deepEqual(await(await f.get()).json(),{canEdit:false});assert.equal(f.state().life,null);
assert.equal((await fixture().send({},'https://evil.invalid')).status,403);
});
test('Explicit confirmation creates one memorial and audited marker; retry cannot create another page',async()=>{
const f=fixture();assert.equal((await f.send({confirm:'someone_else'})).status,400);
const response=await f.send({});assert.equal(response.status,200);assert((await response.json()).memorial.startsWith('/memorial/citizen-'));
const first=structuredClone(f.state());assert.equal(first.audits.length,1);assert.equal((await f.send({})).status,200);assert.deepEqual(f.state(),first);
const correction=await f.send({status:'living',version:1});assert.equal(correction.status,200);assert.equal(f.state().life.status,'living');assert.deepEqual(f.state().memorial,first.memorial);
});
test('Stale conflicting changes and audit failure cannot leave a partial status or memorial',async()=>{
const f=fixture();await f.send({});assert.equal((await f.send({status:'living',version:0})).status,409);assert.equal(f.state().life.status,'deceased');
const broken=fixture();broken.failAudit();await assert.rejects(broken.send({}),/Audit unavailable/);assert.equal(broken.state().life,null);assert.equal(broken.state().memorial,null);
});

Some files were not shown because too many files have changed in this diff Show more