From 323c4d67f9a92e3dd7b5c2d83dfe923d5477d47c Mon Sep 17 00:00:00 2001 From: unimatrix Date: Tue, 17 Nov 2026 19:58:41 +0000 Subject: [PATCH 1/2] feat(realm): reuse shared MOTD settings for Company and Politics --- .../public/cp-v2/cp-v2-organisation-shell.css | 2 + .../public/cp-v2/cp-v2-organisation-shell.mjs | 6 ++- .../public/organisation-dashboard.mjs | 12 ++--- .../public/organisation-editor.mjs | 15 ++++++ website/control-panel/server.mjs | 8 +-- website/node/news.mjs | 7 ++- website/node/organisation-settings-route.mjs | 51 +++++++++++++++++++ website/scripts/news-announcements.json | 8 +++ website/tests/news-announcement-seed.test.mjs | 7 +++ .../organisation-settings-route.test.mjs | 24 +++++++++ 10 files changed, 127 insertions(+), 13 deletions(-) create mode 100644 website/control-panel/public/organisation-editor.mjs create mode 100644 website/node/organisation-settings-route.mjs create mode 100644 website/scripts/news-announcements.json create mode 100644 website/tests/news-announcement-seed.test.mjs create mode 100644 website/tests/organisation-settings-route.test.mjs diff --git a/website/control-panel/public/cp-v2/cp-v2-organisation-shell.css b/website/control-panel/public/cp-v2/cp-v2-organisation-shell.css index 55503a4f..a06f9075 100644 --- a/website/control-panel/public/cp-v2/cp-v2-organisation-shell.css +++ b/website/control-panel/public/cp-v2/cp-v2-organisation-shell.css @@ -2,3 +2,5 @@ .organisation-portals{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;padding:18px 28px;background:#0c261f;border-bottom:1px solid #aa8e4f}.organisation-portal{display:grid;justify-items:center;align-content:center;gap:10px;padding:20px 12px;min-height:130px;box-sizing:border-box;border:3px double #bfa15c;border-radius:10px;background:linear-gradient(135deg,#284349,#102d28);color:#edd18b;text-decoration:none;font:700 21px Georgia,serif;box-shadow:inset 0 0 0 3px #10231e,0 5px 18px #0003}.organisation-portal:nth-child(2){background:linear-gradient(135deg,#3e402c,#142e25)}.organisation-portal:nth-child(4){background:linear-gradient(135deg,#393044,#15342a)}.organisation-portal img{width:78px;height:78px;object-fit:contain}.organisation-portal:hover,.organisation-portal[aria-current]{border-color:#ffe3a2;background-color:#315648}.organisation-portal:focus-visible{outline:3px solid #ffe3a2;outline-offset:3px}@media(max-width:720px){.organisation-portals{grid-template-columns:repeat(2,minmax(0,1fr));padding:16px;gap:12px}.organisation-portal{font-size:17px;min-height:118px}.organisation-portal img{width:60px;height:60px}} .company-cp-shell #portals,.politics-cp-shell #portals{display:block}.organisation-switcher label{min-width:0}.organisation-switcher select{min-width:0;width:min(440px,100%)} + +.organisation-settings-form{display:grid;gap:16px;margin-top:20px}.organisation-settings-form label{display:grid;gap:8px}.organisation-settings-form input,.organisation-settings-form textarea{box-sizing:border-box;max-width:100%;width:100%;padding:12px;border:1px solid #7d8b60;border-radius:8px;background:#102b25;color:#eadfbf;font:inherit}.organisation-settings-form textarea{min-height:150px;resize:vertical}.organisation-settings-form button{justify-self:start;padding:12px 20px;border:1px solid #bda05c;border-radius:8px;background:#203f39;color:#f1d99a;cursor:pointer}.organisation-settings-form button:disabled{opacity:.5} diff --git a/website/control-panel/public/cp-v2/cp-v2-organisation-shell.mjs b/website/control-panel/public/cp-v2/cp-v2-organisation-shell.mjs index 8d3f5558..d78c745e 100644 --- a/website/control-panel/public/cp-v2/cp-v2-organisation-shell.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-organisation-shell.mjs @@ -1,3 +1,4 @@ +import {mountOrganisationEditor} from '../organisation-editor.mjs'; import {mountOrganisationRegister} from '../organisation-register.mjs'; import {ORGANISATION_MENU_GROUPS as groups,organisationPage} from './cp-v2-organisation-navigation.mjs'; import {startCPAuthentication} from './cp-v2-auth.mjs'; @@ -28,12 +29,13 @@ export function startOrganisationCP(kind){ const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host clan-center');card.append(host);cards.append(card);content.replaceChildren(hero,cards); if(page==='directory'){dispose=mountOrganisationRegister(host,kind);return;} if(!record){pending(host,'Your '+noun.toLowerCase()+' workspace',company?'No company is registered to you as founder or CEO.':'Political office membership could not be verified.');return;} + const loadSettings=async()=>{const r=await fetch('/api/organisations/'+kind+'/'+encodeURIComponent(record.id)+'/settings',{credentials:'same-origin',cache:'no-store'});const data=await r.json();if(!r.ok)throw Error(data.message||'Settings unavailable.');return data;}; const navigate={onMembers:()=>go('people'),onRequests:()=>go('applications')}; if(page==='overview'&&(!company&&!route()&&location.hash&& !location.hash.startsWith('#household/'))){const old=location.hash.slice(1).split('/').at(-1);if(old&&!['politics-overview','dashboard'].includes(old)){dispose=mountPoliticsPage(host,old);return;}} if(page==='overview'){ - host.append(createOrganisationDashboard({kind,organisation:{...record,tag:record.tag||record.slug||'REGISTERED',emblem:record.emblem||assets+fallback,homeworldName:record.homeworldName||(company?'Company register':'Political office'),titles:{officeholder:'Office deed holder'}},members:record.members||[],role:record.role==='Founder'||record.role==='CEO'?'owner':record.role,memberSummary:company?'Verified leadership · the full company roster will be connected here.':undefined,activityStatus:'unavailable',links:{claims:'#'+prefix+'/claims'},...navigate})); + host.append(createOrganisationDashboard({kind,organisation:{...record,tag:record.tag||record.slug||'REGISTERED',emblem:record.emblem||assets+fallback,homeworldName:record.homeworldName||(company?'Company register':'Political office'),titles:{officeholder:'Office deed holder'}},members:record.members||[],role:record.role==='Founder'||record.role==='CEO'?'owner':record.role,memberSummary:company?'Verified leadership · the full company roster will be connected here.':undefined,loadMotd:record.role==='visitor'?undefined:async()=>(await loadSettings()).motd,activityStatus:'unavailable',links:{claims:'#'+prefix+'/claims'},...navigate})); }else if(page==='settings'){ - const sections=[['Identity & homeworld','Registered organisation identity.',record.name],['Message of the day','Organisation messages will use the shared service.',null],['Ownership deed & dynasty',company?'Company clan charter · COM keys.':'Protected political clan charter · political-clan keys. Political decision keys are separate.',record.membership?'Active office deed · ends '+new Date(record.membership.expiresAt).toLocaleString('en-GB'):'No new charter entitlement is inferred.'],['Claim charter & capacity','The shared claim model will be connected to this organisation.',null],['Relations & subhouses','The shared parent-deed mechanism will manage subordinate organisations.',null]].map(([title,description,text])=>({title,description,content:text?el('p',text):null,pending:!text}));host.append(createOrganisationSettings(sections));const note=el('p',company?'COM clan keys belong to company charters.':'Political-clan keys belong to protected organisation deeds; POL decision keys remain separate.');host.append(note); + const sections=[['Identity & homeworld','Registered organisation identity.',record.name],['Message of the day','Organisation messages will use the shared service.',null],['Ownership deed & dynasty',company?'Company clan charter · COM keys.':'Protected political clan charter · political-clan keys. Political decision keys are separate.',record.membership?'Active office deed · ends '+new Date(record.membership.expiresAt).toLocaleString('en-GB'):'No new charter entitlement is inferred.'],['Claim charter & capacity','The shared claim model will be connected to this organisation.',null],['Relations & subhouses','The shared parent-deed mechanism will manage subordinate organisations.',null]].map(([title,description,text])=>({title,description,content:text?el('p',text):null,pending:!text}));host.append(createOrganisationSettings(sections));dispose=mountOrganisationEditor(host,{kind,id:record.id,onSaved:data=>Object.assign(record,{name:data.name,description:data.description,motd:data.motd})});const note=el('p',company?'COM clan keys belong to company charters.':'Political-clan keys belong to protected organisation deeds; POL decision keys remain separate.');host.append(note); Promise.resolve().then(async()=>{const r=await fetch('/api/organisation-keys',{credentials:'same-origin',cache:'no-store'});if(!r.ok)throw Error();const data=await r.json();if(turn!==generation||stopped)return;const rows=(data.keys||[]).filter(k=>company?k.type==='company':k.type==='politics-clan');const box=el('section',undefined,'organisation-settings-card');box.append(el('h3',noun+' clan keys'));for(const key of rows){box.append(el('p',key.status+(key.code?' · '+key.code:'')));}if(!rows.length)box.append(el('p','No organisation-clan keys are present in your private register.'));host.append(box);}).catch(()=>{if(turn===generation)note.append(el('span',' The private key register is unavailable.'));}); }else if(page==='claims'){dispose=mountClaims(host,{kind:company?'company':'protected',name:record.name});} else if(page==='boards'){if(company)dispose=mountNativeService(host,'company-boards',{singleHeading:true,organisationId:record.id});else dispose=mountNativeService(host,'election-boards',{singleHeading:true});} diff --git a/website/control-panel/public/organisation-dashboard.mjs b/website/control-panel/public/organisation-dashboard.mjs index 00dd2eed..a81f109a 100644 --- a/website/control-panel/public/organisation-dashboard.mjs +++ b/website/control-panel/public/organisation-dashboard.mjs @@ -5,21 +5,21 @@ import {createActivityFeed} from './organisation-activity.mjs'; // Shared presentation only. Callers supply verified records and existing navigation. const el=(tag,text,cls)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;if(cls)node.className=cls;return node;}; const assets='https://www.dunerealms.com/assets/'; -export function createOrganisationDashboard({kind='clan',organisation,members=[],role,canReview=false,requests=[],onMembers,onRequests,loadMailbox,loadTreasury,loadClaims,activity=[],activityStatus,links={},memberSummary}={}){ +export function createOrganisationDashboard({kind='clan',organisation,members=[],role,canReview=false,requests=[],onMembers,onRequests,loadMailbox,loadTreasury,loadClaims,loadMotd,activity=[],activityStatus,links={},memberSummary}={}){ if(!document.querySelector('link[data-organisation-dashboard]')){const css=el('link');css.rel='stylesheet';css.href=new URL('./organisation-dashboard.css',import.meta.url).href;css.dataset.organisationDashboard='';document.head.append(css);} const company=kind==='company',noun=kind==='politics'?'Office':company?'Company':'Clan',root=el('div',undefined,'organisation-dashboard'); const backgrounds={'Members':'guild.webp','Applications':'political-small-council-v1.png','News & activity':'political-imperial-chamber-v1.png','Events':'clan-atelier-v1.webp','Treasury':'postbank-transfer-hall-v1.png','Land & claims':'guild.webp','Mailbox':'imperial-post-office-v1.png','Needs attention':'political-small-council-v1.png','Subhouses & subsidiaries':'clan-atelier-v1.webp'}; function card(title,art,{pending=false}={}){const box=el('article',undefined,'organisation-dashboard-card'),header=el('header'),image=el('img');image.src=assets+art;image.alt='';image.width=image.height=48;box.dataset.dashboardCard=title.toLowerCase().replaceAll(/[^a-z]+/g,'-');box.style.setProperty('--dashboard-art','url("'+assets+(backgrounds[title]||'political-imperial-chamber-v1.png')+'")');header.append(image,el('h3',title));if(pending)header.append(el('span','Coming soon','organisation-dashboard-status'));box.append(header);root.append(box);return box;} function action(box,label,handler){const button=el('button',label);button.type='button';button.onclick=handler;box.append(button);} - const welcome=card('Welcome to '+organisation.name,company?'clans/vaerkring-v1.png':'nav-clan-v2.webp');welcome.classList.add('organisation-dashboard-welcome');const emblem=welcome.querySelector('header img');if(organisation.emblem)emblem.src=organisation.emblem;welcome.append(el('small','YOUR '+noun.toUpperCase()+' · YOUR PEOPLE · YOUR NEXT CHAPTER'));const welcomeBoxes=el('div',undefined,'organisation-welcome-boxes');for(const [title,message] of [[noun+' description',organisation.description||'No introduction has been published yet.'],['Message of the day',organisation.motd||(role?'No message of the day has been published.':'The message of the day is visible to members.')]]){const box=el('section',undefined,'organisation-welcome-subbox');box.append(el('h4',title),el('p',message));welcomeBoxes.append(box);}welcome.append(welcomeBoxes,el('p','['+organisation.tag+'] · '+(organisation.homeworldName||'Homeworld not selected')+' · '+(organisation.titles?.[role]||{owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'}[role]||'Visitor'))); + const welcome=card('Welcome to '+organisation.name,company?'clans/vaerkring-v1.png':'nav-clan-v2.webp');welcome.classList.add('organisation-dashboard-welcome');const emblem=welcome.querySelector('header img');if(organisation.emblem)emblem.src=organisation.emblem;welcome.append(el('small','YOUR '+noun.toUpperCase()+' · YOUR PEOPLE · YOUR NEXT CHAPTER'));const welcomeBoxes=el('div',undefined,'organisation-welcome-boxes');for(const [title,message] of [[noun+' description',organisation.description||'No introduction has been published yet.'],['Message of the day',organisation.motd||(role?'No message of the day has been published.':'The message of the day is visible to members.')]]){const box=el('section',undefined,'organisation-welcome-subbox');const text=el('p',title==='Message of the day'&&loadMotd?'Loading your message…':message);box.append(el('h4',title),text);if(title==='Message of the day'&&loadMotd)Promise.resolve().then(loadMotd).then(value=>{if(root.isConnected)text.textContent=value||'No message of the day has been published.';}).catch(()=>{if(root.isConnected)text.textContent='The message of the day could not be loaded.';});welcomeBoxes.append(box);}welcome.append(welcomeBoxes,el('p','['+organisation.tag+'] · '+(organisation.homeworldName||'Homeworld not selected')+' · '+(organisation.titles?.[role]||{owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'}[role]||'Visitor'))); const people=card('Members','nav-account-v2.webp'),faces=el('div',undefined,'organisation-dashboard-members');people.append(el('p',memberSummary||members.length+' '+(members.length===1?'member':'members')+' in the register')); for(const member of members.slice(0,8)){const link=el('a',undefined,'organisation-dashboard-member'),image=el('img'),copy=el('span');image.src='https://cp.dunerealms.com/api/avatars/face/roster/'+encodeURIComponent(member.username);image.alt='';image.width=image.height=44;image.loading='lazy';copy.append(el('strong',member.username),el('small',organisation.titles?.[member.clan_role||member.role]||({owner:noun+' owner',heir:'Heir',officer:'Officer',member:'Member'})[member.clan_role||member.role]||'Member'));link.href='https://www.dunerealms.com/people/'+encodeURIComponent(member.username);link.target='_top';link.append(image,copy);faces.append(link);}people.append(faces);if(onMembers)action(people,'View all members →',onMembers); const applications=card('Applications','nav-support-v2.webp');applications.append(el('p',canReview?(requests.length?requests.length+' '+(requests.length===1?'application awaits':'applications await')+' review.':'No applications are waiting for review.'):'Applications are reviewed by the owner and authorised officers.')); if(canReview){for(const request of requests.slice(0,3))applications.append(el('p',request.username,'organisation-dashboard-request'));if(onRequests)action(applications,'Review applications →',onRequests);} - const news=card('News & activity','nav-manual-v2.webp');news.append(createActivityFeed(activity,{emptyMessage:activityStatus==='restricted'?'Activity is visible to organisation members.':activityStatus==='unavailable'?'Activity could not be loaded.':'No clan activity has been recorded yet.'})); - for(const [title,art,message] of [['Events','nav-manual-full-v2.webp','Upcoming activities, dates and participation will appear here.'],['Treasury','imperial-postbank-v2.png','Available funds and the account reference will appear here once the authorised bank summary is connected.'],['Land & claims','clans/house-veyr-v1.png','Claims share one total chunk budget. Capacity upgrades will be performed ingame by right-clicking the Home Block.']]){const box=card(title,art,{pending:title==='Events'||title==='Land & claims'&&!loadClaims});box.append(el('p',message),el('small','Not connected yet · no records are shown.'));if(title==='Land & claims'){box.querySelectorAll('p,small').forEach(n=>n.remove());const note=el('p',loadClaims?'Checking your claim registry…':'Claims are not connected for this organisation yet.'),info=el('dl');box.append(note,info);if(loadClaims)Promise.resolve().then(loadClaims).then(view=>{if(!root.isConnected)return;if(view.state!=='connected')throw Error('unavailable');note.textContent='Your registered land and claim allowance.';for(const [label,value]of [['Estate rank',claimDisplayName(view.tier)],['Claimed chunks',view.usedChunks+' / '+view.capacity],['Available chunks',view.availableChunks],['Monthly upkeep',view.monthlyUpkeep]])info.append(el('dt',label),el('dd',String(value)));}).catch(()=>{if(root.isConnected)note.textContent='Claim records could not be loaded. Open Claims to refresh.';});const link=el('a','Open land & claims →');link.href=links.claims||(company?'https://corp.dunerealms.com/#company/claims':'https://clans.dunerealms.com/#clan/clan-claims');link.target='_top';box.append(link);}if(title==='Treasury'){const table=el('table');for(const [label,value] of [['Available funds','Not connected'],['Account','Authorised view required']]){const row=el('tr');row.append(el('th',label),el('td',value));table.append(row);}box.append(table);if(loadTreasury){box.querySelectorAll('p,small').forEach(n=>n.remove());table.replaceChildren();const note=el('p','Checking authorised clan funds…');box.append(note);Promise.resolve().then(loadTreasury).then(entity=>{if(!root.isConnected)return;note.textContent=entity.state==='not_activated'?'Clan banking has not been activated.':'Current accounts · Imperial Postbank';table.replaceChildren();for(const account of entity.accounts){const row=el('tr'),link=el('a',account.number);link.href='https://cp.dunerealms.com/#bank/bank-statements/'+encodeURIComponent(account.id);link.target='_top';const cell=el('td');cell.append(link);row.append(cell,el('td',account.available+' DM available'));table.append(row);}if(!entity.accounts.length&&entity.state!=='not_activated')note.textContent='No active current accounts are visible with your bank permissions.';}).catch(()=>{if(root.isConnected){table.replaceChildren();note.textContent='Clan funds could not be confirmed. Open Imperial Postbank to check your access.';}});}else{table.replaceChildren();box.querySelector('p').textContent='Clan funds are available only with authorised banking access.';}const bank=el('a','Open Imperial Postbank →');bank.href='https://cp.dunerealms.com/#bank/bank-overview';bank.target='_top';box.append(bank);}} + const news=card('News & activity','nav-manual-v2.webp');news.append(createActivityFeed(activity,{emptyMessage:activityStatus==='restricted'?'Activity is visible to organisation members.':activityStatus==='unavailable'?'Activity could not be loaded.':'No '+noun.toLowerCase()+' activity has been recorded yet.'})); + for(const [title,art,message] of [['Events','nav-manual-full-v2.webp','Upcoming activities, dates and participation will appear here.'],['Treasury','imperial-postbank-v2.png','Available funds and the account reference will appear here once the authorised bank summary is connected.'],['Land & claims','clans/house-veyr-v1.png','Claims share one total chunk budget. Capacity upgrades will be performed ingame by right-clicking the Home Block.']]){const box=card(title,art,{pending:title==='Events'||title==='Land & claims'&&!loadClaims});box.append(el('p',message),el('small','Not connected yet · no records are shown.'));if(title==='Land & claims'){box.querySelectorAll('p,small').forEach(n=>n.remove());const note=el('p',loadClaims?'Checking your claim registry…':'Claims are not connected for this organisation yet.'),info=el('dl');box.append(note,info);if(loadClaims)Promise.resolve().then(loadClaims).then(view=>{if(!root.isConnected)return;if(view.state!=='connected')throw Error('unavailable');note.textContent='Your registered land and claim allowance.';for(const [label,value]of [['Estate rank',claimDisplayName(view.tier)],['Claimed chunks',view.usedChunks+' / '+view.capacity],['Available chunks',view.availableChunks],['Monthly upkeep',view.monthlyUpkeep]])info.append(el('dt',label),el('dd',String(value)));}).catch(()=>{if(root.isConnected)note.textContent='Claim records could not be loaded. Open Claims to refresh.';});const link=el('a','Open land & claims →');link.href=links.claims||(company?'https://corp.dunerealms.com/#company/claims':'https://clans.dunerealms.com/#clan/clan-claims');link.target='_top';box.append(link);}if(title==='Treasury'){const table=el('table');for(const [label,value] of [['Available funds','Not connected'],['Account','Authorised view required']]){const row=el('tr');row.append(el('th',label),el('td',value));table.append(row);}box.append(table);if(loadTreasury){box.querySelectorAll('p,small').forEach(n=>n.remove());table.replaceChildren();const note=el('p','Checking authorised '+noun.toLowerCase()+' funds…');box.append(note);Promise.resolve().then(loadTreasury).then(entity=>{if(!root.isConnected)return;note.textContent=entity.state==='not_activated'?noun+' banking has not been activated.':'Current accounts · Imperial Postbank';table.replaceChildren();for(const account of entity.accounts){const row=el('tr'),link=el('a',account.number);link.href='https://cp.dunerealms.com/#bank/bank-statements/'+encodeURIComponent(account.id);link.target='_top';const cell=el('td');cell.append(link);row.append(cell,el('td',account.available+' DM available'));table.append(row);}if(!entity.accounts.length&&entity.state!=='not_activated')note.textContent='No active current accounts are visible with your bank permissions.';}).catch(()=>{if(root.isConnected){table.replaceChildren();note.textContent=noun+' funds could not be confirmed. Open Imperial Postbank to check your access.';}});}else{table.replaceChildren();box.querySelector('p').textContent=noun+' funds are available only with authorised banking access.';}const bank=el('a','Open Imperial Postbank →');bank.href='https://cp.dunerealms.com/#bank/bank-overview';bank.target='_top';box.append(bank);}} const children=card('Subhouses & subsidiaries','clans/vaerkring-v1.png',{pending:true});children.append(el('p','Subordinate organisations will appear here. Claim rights and management pass to the mother organisation; upkeep and upgrade costs remain with the original organisation.'));const relations=el('table'),head=el('thead'),heading=el('tr');for(const label of ['Organisation','Type','Relationship']){const cell=el('th',label);cell.scope='col';heading.append(cell);}head.append(heading);const body=el('tbody'),row=el('tr'),empty=el('td','Hierarchy records are not connected yet.');empty.colSpan=3;row.append(empty);body.append(row);relations.append(head,body);children.append(relations); - const mail=card('Mailbox','imperial-post-office-v1.png'),mailStatus=el('p',loadMailbox?'Checking unread clan mail…':'Clan mail is available to the owner and authorised officers.');mailStatus.setAttribute('role','status');mail.append(mailStatus);if(loadMailbox){const link=el('a','Open clan mailbox →');link.href=links.mail||'https://clans.dunerealms.com/#clan/clan-mail';link.target='_top';mail.append(link);Promise.resolve().then(loadMailbox).then(count=>{if(root.isConnected)mailStatus.textContent=Number.isSafeInteger(count)&&count>=0?'You have '+count+' unread '+(count===1?'message.':'messages.'):'Unread count is unavailable.';}).catch(()=>{if(root.isConnected)mailStatus.textContent='Mail service unavailable. Open the mailbox to retry.';});} - const attention=card('Needs attention','nav-support-v2.webp');attention.append(el('p',canReview&&requests.length?requests.length+' pending '+(requests.length===1?'application needs':'applications need')+' your attention.':'No additional dashboard alerts are connected yet.'));if(canReview&&requests.length&&onRequests)action(attention,'Open pending applications →',onRequests);const groups=[['overview','Overview',['welcome','land-claims','needs-attention']],['people','People',['members','applications']],['household','Household',['treasury','mailbox','subhouses-subsidiaries']],['activity','Activity',['news-activity','events']]].map(([id,title,names])=>{const content=el('div',undefined,'organisation-dashboard');for(const node of [...root.children])if(names.includes(node.dataset.dashboardCard)||id==='overview'&&node.classList.contains('organisation-dashboard-welcome'))content.append(node);return{id,title,content};});root.classList.remove('organisation-dashboard');root.replaceChildren(organisationTabs(groups,{label:noun+' dashboard sections'}));return root; + const mail=card('Mailbox','imperial-post-office-v1.png'),mailStatus=el('p',loadMailbox?'Checking unread '+noun.toLowerCase()+' mail…':noun+' mail is available to authorised managers.');mailStatus.setAttribute('role','status');mail.append(mailStatus);if(loadMailbox){const link=el('a','Open '+noun.toLowerCase()+' mailbox →');link.href=links.mail||'https://clans.dunerealms.com/#clan/clan-mail';link.target='_top';mail.append(link);Promise.resolve().then(loadMailbox).then(count=>{if(root.isConnected)mailStatus.textContent=Number.isSafeInteger(count)&&count>=0?'You have '+count+' unread '+(count===1?'message.':'messages.'):'Unread count is unavailable.';}).catch(()=>{if(root.isConnected)mailStatus.textContent='Mail service unavailable. Open the mailbox to retry.';});} + const attention=card('Needs attention','nav-support-v2.webp');attention.append(el('p',canReview&&requests.length?requests.length+' pending '+(requests.length===1?'application needs':'applications need')+' your attention.':'No additional dashboard alerts are connected yet.'));if(canReview&&requests.length&&onRequests)action(attention,'Open pending applications →',onRequests);const groups=[['overview','Overview',['welcome','land-claims','needs-attention']],['people','People',['members','applications']],['household',company?'Company':kind==='politics'?'Office':'Household',['treasury','mailbox','subhouses-subsidiaries']],['activity','Activity',['news-activity','events']]].map(([id,title,names])=>{const content=el('div',undefined,'organisation-dashboard');for(const node of [...root.children])if(names.includes(node.dataset.dashboardCard)||id==='overview'&&node.classList.contains('organisation-dashboard-welcome'))content.append(node);return{id,title,content};});root.classList.remove('organisation-dashboard');root.replaceChildren(organisationTabs(groups,{label:noun+' dashboard sections'}));return root; } diff --git a/website/control-panel/public/organisation-editor.mjs b/website/control-panel/public/organisation-editor.mjs new file mode 100644 index 00000000..a7b3f276 --- /dev/null +++ b/website/control-panel/public/organisation-editor.mjs @@ -0,0 +1,15 @@ +// Settings forms for both organisation adapters; dashboards remain display-only. +export function mountOrganisationEditor(host,{kind,id,onSaved=()=>{}}){ + const controller=new AbortController(),url='/api/organisations/'+kind+'/'+encodeURIComponent(id)+'/settings';let active=true; + const card=title=>[...host.querySelectorAll('.organisation-settings-card')].find(n=>n.querySelector('h3')?.textContent===title); + const request=async input=>{const response=await fetch(url,{method:input?'POST':'GET',credentials:'same-origin',cache:'no-store',headers:input?{'Content-Type':'application/json'}:undefined,body:input?JSON.stringify(input):undefined,signal:controller.signal});const data=await response.json();if(!response.ok)throw Error(data.message||'Settings unavailable.');return data;}; + const field=(label,value,multiline=false)=>{const node=document.createElement('label'),input=document.createElement(multiline?'textarea':'input');node.textContent=label;input.value=value||'';input.maxLength=multiline?1000:120;node.append(input);return{node,input};}; + request().then(data=>{if(!active)return; + function form(title,action,fields,revision){const box=card(title);if(!box)return;box.querySelector('.organisation-settings-status')?.remove();const form=document.createElement('form');form.className='organisation-settings-form';const status=document.createElement('p');status.setAttribute('role','status');const save=document.createElement('button');save.type='submit';save.textContent=action==='motd'?'Save message':'Save details';form.append(...fields.map(f=>f.node),save,status);let version=revision; + form.onsubmit=async e=>{e.preventDefault();save.disabled=true;status.textContent='Saving…';try{const input={action,revision:version};for(const f of fields)input[f.key]=f.input.value;const updated=await request(input);if(!active)return;version=action==='motd'?updated.motdRevision:updated.identityRevision;onSaved(updated);status.textContent='Saved.';}catch(error){if(active)status.textContent=error.message;}finally{if(active)save.disabled=false;}};box.append(form); + } + if(data.canEditIdentity){const name=field('Company name',data.name),description=field('Company description',data.description,true);name.key='name';description.key='description';form('Identity & homeworld','identity',[name,description],data.identityRevision);} + const message=field('Message for your members · up to 1,000 characters',data.motd,true);message.key='message';form('Message of the day','motd',[message],data.motdRevision); + }).catch(error=>{if(!active)return;const box=card('Message of the day');if(box){box.querySelector('.organisation-settings-status')?.remove();const note=document.createElement('p');note.textContent=error.message;box.append(note);}}); + return()=>{active=false;controller.abort();}; +} diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 8d9e5e10..1965362f 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,4 @@ +import {createOrganisationSettingsRoute} from '../node/organisation-settings-route.mjs'; import {createPublicOrganisations} from '../node/public-organisations.mjs'; import {companyCPReferenceDocument} from './company-cp-reference.mjs'; import {politicsCPReferenceDocument} from './politics-cp-reference.mjs'; @@ -130,7 +131,7 @@ export function createPanel(db,settings={},dependencies={}){ const internalMail=createInternalMail(db,{origin,settings,...dependencies.internalMail}); const terms=createFirstLoginTerms(db,origin); const auth=createAuth(db,origin,{...settings,trackFirstLogin:true,onAccountReady:async user=>{if(dependencies.organisationKeys)await ensureOriginalKeys(dependencies.organisationKeys,user.id);}}),links=createGameLink(db,settings,origin),rewards=createCommunityRewards(db,settings,origin); - const clanDeeds=createClanDeedRoute(db,{origin}),publicClans=createPublicClans(db),publicOrganisations=createPublicOrganisations(db); + const clanDeeds=createClanDeedRoute(db,{origin}),publicClans=createPublicClans(db),publicOrganisations=createPublicOrganisations(db),organisationSettings=createOrganisationSettingsRoute(db,{origin}); const characterChoice=createCharacterChoice(db,{origin}),clanKeyReceipts=createClanKeyReceipts(db,{keys:dependencies.organisationKeys,origin}); const claimProducts=dependencies.bankDatabase?new PostbankClaimProducts(db,dependencies.bankDatabase,createPostbankAuthority(db,{bank:dependencies.bankDatabase}),{readCharter:id=>readClanCharter(db,id)}):null; const claimUpgrades=createClaimUpgrades(db,claimProducts,settings); @@ -200,7 +201,8 @@ export function createPanel(db,settings={},dependencies={}){ if(path==='/api/organisation-keys')return clanKeyReceipts(request); if(path.startsWith('/api/clan-deeds/'))return clanDeeds(request); if(/^\/api\/public\/(companies|political-houses)(?:\/|$)/.test(path))return publicOrganisations(request); - if(path.startsWith('/api/public/clans/'))return publicClans(request); + if(path.startsWith('/api/organisations/'))return organisationSettings(request); + if(path.startsWith('/api/public/clans/'))return publicClans(request); if(path==='/api/politics/charters')return imperialCharters(request); if(path==='/api/politics/proclamations')return proclamations(request); if(path==='/api/politics/electoral-roll')return electoralRoll(request); @@ -325,7 +327,7 @@ export function createPanel(db,settings={},dependencies={}){ return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); } const file=path==='/'?'index.html':path==='/servers'?'servers.html':path.slice(1); - if(!['organisation-register.mjs','user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-directory-view.mjs','clan-profile-panels.mjs','clan-titles.mjs','dynastic-address.mjs','organisation-palette.mjs','organisation-palette-model.mjs','organisation-palette.css','clan-dynasty.mjs','clan-dynasty.css','clan-deed-settings.mjs','dune-date.mjs','organisation-settings.mjs','organisation-settings.css','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); + if(!['organisation-editor.mjs','organisation-register.mjs','user-service.html','user-service-entry.mjs','user-service.css','kit-receipt-status.mjs','clan-center.html','clan-center-entry.mjs','clan-center.css','bank-transfer-view.mjs','bank-dashboard.mjs','mail-service-ui.mjs','mail-workspace.css','hosting-control.mjs','internal-mail.mjs','internal-mail.css','election-voting-view.mjs','imperial-charters-view.mjs','proclamations-view.mjs','electoral-roll-view.mjs','election-applications-view.mjs','election-rules.mjs','political-catalog.mjs','menu-ribbons.mjs','council-preview.mjs','politics.mjs','crysknife.mjs','x-news-draft.mjs','terms.html','admin-registration.mjs','mail-signature.mjs','webmail.mjs','git-control.mjs','git-control.css','site-profile.mjs','site-profile.css','servers.html','servers.js','servers.css','pages.mjs','user-page-hero.mjs','commerce-settings.mjs','shop-management.mjs','center-portals.mjs','panel-layout.mjs','embed-size.mjs','dev-request-access.mjs','center-portals.css','overview.mjs','overview.css','page-groups.mjs','ban-register.mjs','moderation-form-response.mjs','ban-record-cards.css','ban-evidence.mjs','ban-evidence.css','ranks.mjs','ranks.css','staff-manual.mjs','luckperms.mjs','community-admin.mjs','native-community.mjs','exchange.mjs','exchange.css','clans.mjs','clan-shop.mjs','house-tailor.mjs','banking.mjs','banking.css','game-ranks.mjs','upgrade-shop.mjs','kit-generator.mjs','kit-design-model.mjs','kit-equipment-editor.mjs','kit-texture-preview.mjs','kit-generator.css','kit-market.mjs','kit-market.css','kit-cart.mjs','imperial-atelier.mjs','quests.mjs','quests.css','clans.css','clan-request-gate.mjs','clan-directory-model.mjs','clan-directory-view.mjs','clan-profile-panels.mjs','clan-titles.mjs','dynastic-address.mjs','organisation-palette.mjs','organisation-palette-model.mjs','organisation-palette.css','clan-dynasty.mjs','clan-dynasty.css','clan-deed-settings.mjs','dune-date.mjs','organisation-settings.mjs','organisation-settings.css','organisation-dashboard.mjs','organisation-dashboard.css','organisation-activity.mjs','clan-dashboard-data.mjs','quest-rewards.mjs','quest-rewards.css','inventory/inventory-view.mjs','inventory/inventory-mount.mjs','inventory/inventory.css'].includes(file))return new Response('Not found',{status:404}); return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/'+file,import.meta.url)),{headers:{'Content-Type':types[file.slice(file.lastIndexOf('.'))],'Cache-Control':'no-store'}}); }; } diff --git a/website/node/news.mjs b/website/node/news.mjs index 448273d2..8828fce2 100644 --- a/website/node/news.mjs +++ b/website/node/news.mjs @@ -9,11 +9,14 @@ export async function initializeNews(db){ for(const [key,label] of Object.entries(NEWS_CATEGORIES))await db.prepare('INSERT INTO website_post_categories(category_key,label,artwork) VALUES(?,?,?) ON CONFLICT(category_key) DO UPDATE SET label=excluded.label').bind(key,label,'assets/news-'+(key==='unis_blog'?'news':key)+'.png').run(); // Only published release records become posts. Pending work never becomes a release announcement. let releases=[];try{const file=JSON.parse(await readFile(new URL('../scripts/changelog.json',import.meta.url),'utf8'));releases=Array.isArray(file)?file:file.releases||[];}catch{} + // Requested official news is distinct from the development patchnote bundles. + let announcements=[];try{announcements=JSON.parse(await readFile(new URL('../scripts/news-announcements.json',import.meta.url),'utf8'));}catch{} + if(Array.isArray(announcements))for(const item of announcements)if(/^[a-z0-9-]{1,80}$/.test(item.id||'')&&typeof item.title==='string'&&typeof item.body==='string')releases.push({sourceKey:'announcement:'+item.id,category:'news',publishedAt:item.publishedAt,title:item.title,synopsis:item.body}); for(const release of releases){ - const key='release:'+String(release.version).slice(0,100),existing=await db.prepare('SELECT id FROM website_posts WHERE source_key=?').bind(key).first();if(existing)continue; + const key=release.sourceKey||'release:'+String(release.version).slice(0,100),existing=await db.prepare('SELECT id FROM website_posts WHERE source_key=?').bind(key).first();if(existing)continue; const date=Date.parse(release.publishedAt||release.date);if(!Number.isFinite(date)||date>Date.now())continue; const body=[release.synopsis,...(release.tasks||[]).flatMap(t=>[t.title,...(t.changes||[]).map(x=>'• '+x)])].filter(Boolean).join('\n\n').slice(0,12000); - await db.prepare('INSERT INTO website_posts(id,source_key,category,title,body,status,author_id,created_at,updated_at,published_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,1) ON CONFLICT(source_key) DO UPDATE SET source_key=excluded.source_key').bind(randomUUID(),key,'changelogs',String(release.title||release.version).slice(0,120),body,'published',OFFICIAL_ACCOUNT.id,date,date,date).run(); + await db.prepare('INSERT INTO website_posts(id,source_key,category,title,body,status,author_id,created_at,updated_at,published_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,1) ON CONFLICT(source_key) DO UPDATE SET source_key=excluded.source_key').bind(randomUUID(),key,release.category||'changelogs',String(release.title||release.version).slice(0,120),body,'published',OFFICIAL_ACCOUNT.id,date,date,date).run(); } } export async function forumLinks(db,posts){try{if(!posts.length)return posts;const{results}=await db.prepare('SELECT post_id,thread_id FROM forum_news_delivery WHERE post_id IN ('+posts.map(()=>'?').join(',')+") AND thread_id>0 AND state='sent'").bind(...posts.map(p=>p.id)).all();const links=new Map(results.filter(r=>Number.isSafeInteger(Number(r.thread_id))&&Number(r.thread_id)>0).map(r=>[r.post_id,'https://forums.dunerealms.com/showthread.php?tid='+Number(r.thread_id)]));return posts.map(p=>({...p,forum_url:links.get(p.id)||null}));}catch{return posts.map(p=>({...p,forum_url:null}));}} diff --git a/website/node/organisation-settings-route.mjs b/website/node/organisation-settings-route.mjs new file mode 100644 index 00000000..3aeb52a9 --- /dev/null +++ b/website/node/organisation-settings-route.mjs @@ -0,0 +1,51 @@ +import {randomUUID} from 'node:crypto'; +import {identity} from './auth.mjs'; +import {accessFor} from './permissions.mjs'; +import {PUBLIC_OFFICES} from './public-government.mjs'; +import {validateMotd} from './organisation-motd.mjs'; +const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i; +const failure=(message,status)=>Object.assign(Error(message),{status}); +export function createOrganisationSettingsRoute(db,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=u=>accessFor(db,u),clock=Date.now}={}){return async request=>{ + const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}),url=new URL(request.url),match=/^\/api\/organisations\/(company|politics)\/([a-z0-9_-]{1,36})\/settings$/i.exec(url.pathname); + if(!match||url.search)return reply({message:'Settings not found.'},404); + if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405); + const user=await authenticate(request);if(!user)return reply({message:'Sign in to manage organisation settings.'},401); + if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403); + const [,kind,id]=match;if(kind==='company'&&!uuid.test(id)||kind==='politics'&&!PUBLIC_OFFICES.some(o=>o.key===id))return reply({message:'Organisation not found.'},404); + if(request.method==='POST'&&request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); + try{ + let input;if(request.method==='POST'){const text=await request.text();if(text.length>6000)throw failure('Settings request too large.',413);try{input=JSON.parse(text);}catch{throw failure('Invalid settings.',400);}if(!input||!['motd','identity'].includes(input.action)||!Number.isSafeInteger(input.revision)||input.revision<0)throw failure('Refresh and review the current settings.',400);} + return await db.transaction(async tx=>{ + const fresh=await authenticate(request);if(fresh?.id!==user.id)throw failure('Your session changed.',403); + let organisation; + if(kind==='company'){ + organisation=await tx.first("SELECT id,name,description,updated_at,founded_by,ceo_account_id FROM corrino_companies WHERE id=? AND status IN ('active','pending') FOR UPDATE",[id]); + if(!organisation||![organisation.founded_by,organisation.ceo_account_id].includes(user.id))throw failure('Company management authority required.',403); + }else{ + const office=PUBLIC_OFFICES.find(o=>o.key===id),kinds=office.kind==='bene'?['bene','house']:office.kind==='guild'?['guild','court']:[office.kind],now=clock(); + const terms=await tx.query("SELECT user_id,kind FROM political_office_terms WHERE faction=? AND office=? AND outcome='winner' AND starts_at<=? AND expires_at>? FOR UPDATE",[office.faction,office.office,now,now]); + const valid=terms.filter(t=>kinds.includes(t.kind));if(valid.length!==1||valid[0].user_id!==user.id)throw failure('A current unambiguous office deed is required.',403); + organisation={name:office.scope,description:office.description,updated_at:0}; + } + const message=await tx.first('SELECT message,updated_at FROM organisation_motd WHERE organisation_kind=? AND organisation_id=? FOR UPDATE',[kind,id]); + if(input){ + if(input.action==='identity'){ + if(kind!=='company')throw failure('Protected office identity follows the office register.',403); + const name=typeof input.name==='string'?input.name.trim():'',description=typeof input.description==='string'?input.description.trim():''; + if(!name||name.length>120||description.length>1000||/[\x00-\x1f\x7f]/.test(name)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(description))throw failure('Enter a name up to 120 characters and description up to 1,000.',400); + if(input.revision!==Number(organisation.updated_at))throw failure('The identity changed. Refresh before saving.',409); + const now=Math.max(clock(),Number(organisation.updated_at)+1);await tx.query('UPDATE corrino_companies SET name=?,description=?,updated_at=? WHERE id=?',[name,description,now,id]);organisation={...organisation,name,description,updated_at:now}; + }else{ + if(input.revision!==Number(message?.updated_at||0))throw failure('The message changed. Refresh before saving.',409); + let text;try{text=validateMotd(input.message);}catch(e){throw failure(e.message,400);} + const now=Math.max(clock(),Number(message?.updated_at||0)+1); + await tx.query('INSERT INTO organisation_motd(organisation_kind,organisation_id,message,updated_by,updated_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE message=VALUES(message),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)',[kind,id,text,user.id,now]); + await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),user.id,'organisation-motd',JSON.stringify({kind,id}),now]); + return reply({name:organisation.name,description:organisation.description,identityRevision:Number(organisation.updated_at),motd:text,motdRevision:now,canEditIdentity:kind==='company'}); + } + } + if(input)await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),user.id,'organisation-identity',JSON.stringify({kind,id}),clock()]); + return reply({name:organisation.name,description:organisation.description,identityRevision:Number(organisation.updated_at),motd:message?.message||'',motdRevision:Number(message?.updated_at||0),canEditIdentity:kind==='company'}); + }); + }catch(error){return reply({message:error.status?error.message:'Organisation settings are temporarily unavailable.'},error.status||503);} +};} diff --git a/website/scripts/news-announcements.json b/website/scripts/news-announcements.json new file mode 100644 index 00000000..e3c5f152 --- /dev/null +++ b/website/scripts/news-announcements.json @@ -0,0 +1,8 @@ +[ + { + "id": "realm-nexus-1011", + "publishedAt": "2026-11-17T19:00:00Z", + "title": "Alpha 1.0.1.1 · Realm Nexus & J.A.R.V.I.S.", + "body": "One connected foundation for clans, companies and political Houses. This website update brings shared workspaces, public registers and charter keys together while keeping each organisation’s identity and authority separate.\n\nClans, Companies & Politics\n\nSwitch between the three themed workspaces through Realm Nexus. Company and political House registers open their public profiles directly.\n\nCompany leaders and current officeholders can publish a separate message of the day through Settings. Dashboards remain for reading.\n\nJ.A.R.V.I.S. foundation\n\nOrganisation charter keys now distinguish their purpose and edition. Clan recruitment capacity follows the deed: Basic 5, Keyed 25 and Royal 50 members.\n\nLoan applications use J.A.R.V.I.S. dossiers while Imperial Postbank retains its existing approval and payment rules.\n\nRecruitment publishing, applications through Starport and promotions remain the next integration step; their previews do not submit listings." + } +] diff --git a/website/tests/news-announcement-seed.test.mjs b/website/tests/news-announcement-seed.test.mjs new file mode 100644 index 00000000..4dc514cd --- /dev/null +++ b/website/tests/news-announcement-seed.test.mjs @@ -0,0 +1,7 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {LocalD1} from './d1-adapter.mjs';import {initializeNews} from '../node/news.mjs'; +test('requested official announcement is public news, idempotent and separate from patchnote releases',async()=>{ + const db=new LocalD1('CREATE TABLE website_post_categories(category_key TEXT PRIMARY KEY,label TEXT,artwork TEXT);CREATE TABLE website_posts(id TEXT PRIMARY KEY,source_key TEXT UNIQUE,category TEXT,title TEXT,body TEXT,status TEXT,author_id TEXT,created_at INT,updated_at INT,published_at INT,version INT);'),actual=Date.now;Date.now=()=>Date.parse('2026-11-18T00:00:00Z'); + try{await initializeNews(db);const count=db.sqlite.prepare('SELECT COUNT(*) n FROM website_posts').get().n;await initializeNews(db);assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM website_posts').get().n,count);const row=db.sqlite.prepare("SELECT * FROM website_posts WHERE source_key='announcement:realm-nexus-1011'").get();assert.equal(row.category,'news');assert.equal(row.status,'published');assert.match(row.body,/remain the next integration step/);assert.equal(db.sqlite.prepare("SELECT COUNT(*) n FROM website_posts WHERE source_key='release:1.0.1.1'").get().n,0); + }finally{Date.now=actual;db.close();} +}); diff --git a/website/tests/organisation-settings-route.test.mjs b/website/tests/organisation-settings-route.test.mjs new file mode 100644 index 00000000..b339e7bf --- /dev/null +++ b/website/tests/organisation-settings-route.test.mjs @@ -0,0 +1,24 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {BankFixture} from './postbank-fixture.mjs'; +import {createOrganisationSettingsRoute} from '../node/organisation-settings-route.mjs'; +const id='11111111-1111-4111-8111-111111111111',origin='https://cp.dunerealms.com'; +function setup(){const db=new BankFixture();db.sqlite.exec(`CREATE TABLE corrino_companies(id TEXT,name TEXT,description TEXT,updated_at INT,founded_by TEXT,ceo_account_id TEXT,status TEXT);CREATE TABLE political_office_terms(user_id TEXT,kind TEXT,faction TEXT,office TEXT,outcome TEXT,starts_at INT,expires_at INT);CREATE TABLE organisation_motd(organisation_kind TEXT,organisation_id TEXT,message TEXT,updated_by TEXT,updated_at INT,PRIMARY KEY(organisation_kind,organisation_id));CREATE TABLE account_audit(id TEXT,actor_id TEXT,action TEXT,details TEXT,created_at INT);INSERT INTO corrino_companies VALUES('${id}','Enterprise','Description',1,'owner','ceo','active');INSERT INTO political_office_terms VALUES('officeholder','house','atreides','house_leader','winner',10,100);`);let actor='owner',now=50; + const api=createOrganisationSettingsRoute(db,{authenticate:async()=>actor?{id:actor}:null,access:async()=>({nodes:['web.menu.game']}),clock:()=>now}); + const call=(kind='company',body,headers={})=>api(new Request(origin+'/api/organisations/'+kind+'/'+(kind==='company'?id:'atreides')+'/settings',body?{method:'POST',headers:{origin,'Content-Type':'application/json',...headers},body:JSON.stringify(body)}:{}));return {db,call,setActor:v=>actor=v,setTime:v=>now=v};} +test('Company identity and MOTD reuse organisation storage with independent revision checks and audit',async()=>{const f=setup();try{ + let response=await f.call();assert.equal(response.status,200);let data=await response.json();assert.equal(data.identityRevision,1);assert.equal(data.motdRevision,0); + response=await f.call('company',{action:'identity',revision:1,name:'New Enterprise',description:'New introduction'});assert.equal(response.status,200);assert.equal((await response.json()).name,'New Enterprise'); + assert.equal((await f.call('company',{action:'identity',revision:1,name:'Stale',description:''})).status,409); + response=await f.call('company',{action:'motd',revision:0,message:'Welcome aboard'});assert.equal(response.status,200);data=await response.json();assert.equal(data.motd,'Welcome aboard');assert.equal((await f.call('company',{action:'motd',revision:0,message:'Lost update'})).status,409); + f.setActor('ceo');assert.equal((await f.call()).status,200);f.setActor('stranger');assert.equal((await f.call()).status,403);assert.equal(f.db.sqlite.prepare('SELECT COUNT(*) n FROM account_audit').get().n,2); + }finally{f.db.close();}}); +test('protected political settings grant only the current sole officeholder, never identity edits',async()=>{const f=setup();try{ + assert.equal((await f.call('politics')).status,403);f.setActor('officeholder');assert.equal((await f.call('politics')).status,200); + assert.equal((await f.call('politics',{action:'identity',revision:0,name:'Impersonated institution'})).status,403); + assert.equal((await f.call('politics',{action:'motd',revision:0,message:'Office welcome'})).status,200); + f.db.sqlite.exec("INSERT INTO political_office_terms VALUES('other','house','atreides','house_leader','winner',20,100)");assert.equal((await f.call('politics')).status,403);f.db.sqlite.exec("DELETE FROM political_office_terms WHERE user_id='other'");f.setTime(100);assert.equal((await f.call('politics')).status,403); + }finally{f.db.close();}}); +test('settings reject forged origin, anonymous access and oversized or invalid messages',async()=>{const f=setup();try{ + assert.equal((await f.call('company',{action:'motd',revision:0,message:'Forgery'},{origin:'https://other.example'})).status,403); + assert.equal((await f.call('company',{action:'motd',revision:0,message:'x'.repeat(1001)})).status,400);assert.equal((await f.call('company',{action:'motd',revision:0,message:'x\u0000'})).status,400);f.setActor(null);assert.equal((await f.call()).status,401); + }finally{f.db.close();}}); From c0c2e8b35ec7ddcc705e23ad4eec3b88acad06ba Mon Sep 17 00:00:00 2001 From: unimatrix Date: Tue, 17 Nov 2026 20:01:24 +0000 Subject: [PATCH 2/2] fix(realm): revalidate settings sessions before acquiring a transaction connection --- website/node/organisation-settings-route.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/website/node/organisation-settings-route.mjs b/website/node/organisation-settings-route.mjs index 3aeb52a9..9922ba05 100644 --- a/website/node/organisation-settings-route.mjs +++ b/website/node/organisation-settings-route.mjs @@ -15,8 +15,9 @@ export function createOrganisationSettingsRoute(db,{origin='https://cp.dunerealm if(request.method==='POST'&&request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); try{ let input;if(request.method==='POST'){const text=await request.text();if(text.length>6000)throw failure('Settings request too large.',413);try{input=JSON.parse(text);}catch{throw failure('Invalid settings.',400);}if(!input||!['motd','identity'].includes(input.action)||!Number.isSafeInteger(input.revision)||input.revision<0)throw failure('Refresh and review the current settings.',400);} + // Revalidate before acquiring a transaction connection; authentication uses the same pool. + const fresh=await authenticate(request);if(fresh?.id!==user.id||!(await access(fresh)).nodes.includes('web.menu.game'))throw failure('Your session changed.',403); return await db.transaction(async tx=>{ - const fresh=await authenticate(request);if(fresh?.id!==user.id)throw failure('Your session changed.',403); let organisation; if(kind==='company'){ organisation=await tx.first("SELECT id,name,description,updated_at,founded_by,ceo_account_id FROM corrino_companies WHERE id=? AND status IN ('active','pending') FOR UPDATE",[id]);