Merge pull request 'System Boards: private clan/company forums and CP embeds' (#351) from release/system-boards-20261116 into main

This commit is contained in:
unimatrix 2026-11-16 18:21:32 +00:00
commit 39bb548648
26 changed files with 530 additions and 14 deletions

View file

@ -0,0 +1,54 @@
# System Boards
Implementation batch: central access projection, native provisioning, scoped child forum management and shared CP embeds. Written and checked; not live yet.
## Agreed structure
System Boards is one bottom-of-index category, collapsed by default. Clan
Boards, Company Boards and Election Board live beneath it. Clan and company
CPs embed their own organisation board. The menu structure is shared.
Use MyBB's native forum permissions, moderator records and inheritance.
Membership is authoritative in the central organisation records, never in
browser parameters. Revoke stale managed forum groups before content is
served, retaining unrelated political and staff groups. Existing staff retain
global moderation. The Big 4.1 retain inspection rights; inspection itself
does not grant moderation. Clan owners moderate only their own subtree and
can create unlimited nested forums/categories there. No global ACP access.
`website/node/system-board-access.mjs` is the shared server-side projection.
Clan owners must have both current ownership and the owner membership role.
Company access reuses the current founder/CEO registry; scoped management
belongs to the current CEO. Additional company-member roles must use the
actual membership service when it is implemented, rather than fabricated
memberships. Every identity refresh must reload the projection, so leaving,
removal and changes of ownership invalidate old grants.
Public feeds, search, attachments, direct links and main-index counts must
respect private forum permissions. The existing website's public forum-feed
adapter also needs explicit exclusion of private System Boards descendants.
Election topics are discussions of already confirmed candidatures. MyBB does
not create candidatures, cast votes or decide election results. Publish topics
idempotently by application ID; never expose private application records.
## Publication order
1. CI must pass for the exact commit. Keep PR #337 open.
2. Stage the matching native PHP helpers and run lint plus test-system-board-policy.php. No native helper is installed in production yet.
3. Run website/ops/system-board-snapshot.mjs with the existing application environment; pipe its organisation snapshot to provision-system-boards.php as the native application owner. No credentials or private account records are emitted.
4. Run test-system-board-native.php against actual MyBB. It checks guest/nonmember denial, every organisation pair and existing staff using native permission merging, without modifying users.
5. Activate the matching central release with SYSTEM_BOARDS_ENABLED=1, install the helpers and reviewed plugin hook together. Preserve newer unrelated plugin changes; apply the small hook diff rather than overwriting an unverified live plugin.
6. Forum frame-ancestors must include every ancestor: CP, clans, corp and the politics shell (currently www). The present policy lacks clans/corp and needs a scoped update before nested embeds will work.
7. Publish the matching Clan/Company outer shells, then verify real membership revocation, post/reply forms, attachments, search, subtree creation and mobile layout before calling this live.
## Remaining work
- Execute publication and authenticated live verification.
- Add idempotent confirmed-candidature topic publication and lifecycle synchronization. Election Board navigation is provided; automatic candidature topics are not implemented. Applications and ballots remain authoritative in the existing election service.
Ordinary SSH as unimatrix works; sudo -n currently requires interactive authentication. Native publication therefore needs restored privileged access or the server administrator. Uploading approved sources into /tmp is not publication.
## Deleted organisations
On clan deletion, current central membership grants disappear. Preserve forum history and let native MyBB autoprune handle eventual post cleanup. No custom clan/forum deletion or cleanup worker is required (user decision, 16 November 2026).

View file

@ -1,4 +1,4 @@
export const COMPANY_MENU=Object.freeze([ export const COMPANY_MENU=Object.freeze([
['overview','Company Dashboard'],['people','People & Roles'],['treasury','Treasury'],['commerce','Commerce & Contracts'],['claims','Claims'],['acquisitions','Sale & Acquisitions'],['subsidiaries','Subsidiaries'],['projects','Projects & Quests'],['settings','Company Settings'] ['overview','Company Dashboard'],['boards','Company Boards'],['people','People & Roles'],['treasury','Treasury'],['commerce','Commerce & Contracts'],['claims','Claims'],['acquisitions','Sale & Acquisitions'],['subsidiaries','Subsidiaries'],['projects','Projects & Quests'],['settings','Company Settings']
]); ]);
export function companyPage(hash=''){const parts=hash.replace(/^#/,'').split('/');const page=parts.at(-1);return COMPANY_MENU.some(([id])=>id===page)?page:'overview';} export function companyPage(hash=''){const parts=hash.replace(/^#/,'').split('/');const page=parts.at(-1);return COMPANY_MENU.some(([id])=>id===page)?page:'overview';}

View file

@ -1,6 +1,7 @@
import {startCPAuthentication} from './cp-v2-auth.mjs'; import {startCPAuthentication} from './cp-v2-auth.mjs';
import {element as el} from './cp-v2-page-template.mjs'; import {element as el} from './cp-v2-page-template.mjs';
import {COMPANY_MENU,companyPage} from './cp-v2-company-navigation.mjs'; import {COMPANY_MENU,companyPage} from './cp-v2-company-navigation.mjs';
import {mountNativeService} from './cp-v2-native-services.mjs';
import {mountClaims} from './cp-v2-claims.mjs'; import {mountClaims} from './cp-v2-claims.mjs';
import {watchMenuHighlights} from './cp-v2-menu-highlights.mjs'; import {watchMenuHighlights} from './cp-v2-menu-highlights.mjs';
const outer='https://corp.dunerealms.com',assets='https://www.dunerealms.com/assets/',content=document.querySelector('#content'),left=document.querySelector('#sidebar'),right=document.querySelector('#sidebar-right'),portals=document.querySelector('#portals'); const outer='https://corp.dunerealms.com',assets='https://www.dunerealms.com/assets/',content=document.querySelector('#content'),left=document.querySelector('#sidebar'),right=document.querySelector('#sidebar-right'),portals=document.querySelector('#portals');
@ -21,6 +22,7 @@ function render(){
const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host');card.append(host);cards.append(card);content.replaceChildren(hero,cards); const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host');card.append(host);cards.append(card);content.replaceChildren(hero,cards);
if(!company){host.append(el('h2','Your enterprise starts here'),el('p','No company is currently registered with you as founder or CEO. Your companies will appear here when the registry grants you access.'));} if(!company){host.append(el('h2','Your enterprise starts here'),el('p','No company is currently registered with you as founder or CEO. Your companies will appear here when the registry grants you access.'));}
else if(page==='claims')dispose=mountClaims(host,{kind:'company',name:company.name}); else if(page==='claims')dispose=mountClaims(host,{kind:'company',name:company.name});
else if(page==='boards'){dispose=mountNativeService(host,'company-boards',{singleHeading:true,organisationId:company.id});}
else if(page==='overview'){ else if(page==='overview'){
const banner=el('section',undefined,'company-charter');banner.append(el('small','REGISTERED ENTERPRISE'),el('h2',company.name),el('p',company.description||'The company charter has no description yet.'));host.append(banner); const banner=el('section',undefined,'company-charter');banner.append(el('small','REGISTERED ENTERPRISE'),el('h2',company.name),el('p',company.description||'The company charter has no description yet.'));host.append(banner);
const grid=el('div',undefined,'company-facts');for(const [key,value]of [['Registry',company.slug],['Standing',company.status],['Founder',company.founder_name||'Not listed'],['CEO',company.ceo_name||'Not appointed']]){const tile=el('article');tile.append(el('small',key),el('strong',value));grid.append(tile);}host.append(grid); const grid=el('div',undefined,'company-facts');for(const [key,value]of [['Registry',company.slug],['Standing',company.status],['Founder',company.founder_name||'Not listed'],['CEO',company.ceo_name||'Not appointed']]){const tile=el('article');tile.append(el('small',key),el('strong',value));grid.append(tile);}host.append(grid);

View file

@ -1,6 +1,9 @@
import {canSubmitDevRequest} from '../dev-request-access.mjs'; import {canSubmitDevRequest} from '../dev-request-access.mjs';
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs'; import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
export const NATIVE_SERVICES=Object.freeze({ export const NATIVE_SERVICES=Object.freeze({
'clan-boards':{title:'Clan Boards',label:'Clan discussion board',description:'Private discussions for your clan. Existing forum moderation and membership rules apply.',permissions:['web.menu.game'],url:'https://forums.dunerealms.com/system-board.php?kind=clan&dune_embed=1',bootstrapUrl:'https://forums.dunerealms.com/dune-sso.php'},
'company-boards':{title:'Company Boards',label:'Company discussion board',description:'Private discussions for your company. Existing forum moderation and membership rules apply.',permissions:[],url:'https://forums.dunerealms.com/system-board.php?kind=company&dune_embed=1',bootstrapUrl:'https://forums.dunerealms.com/dune-sso.php'},
'election-boards':{title:'Election Board',label:'Election discussions',description:'Discuss confirmed candidatures. Applications and votes remain in the election service.',permissions:['web.menu.game'],url:'https://forums.dunerealms.com/system-board.php?kind=elections&dune_embed=1',bootstrapUrl:'https://forums.dunerealms.com/dune-sso.php'},
'politics':{title:'Realm & Politics',label:'Political chamber',description:'Existing election, candidature, proclamation and council services.',permissions:['web.menu.game'],url:'https://cp.dunerealms.com/user-service.html?service=politics#landsraad',selfResize:true}, 'politics':{title:'Realm & Politics',label:'Political chamber',description:'Existing election, candidature, proclamation and council services.',permissions:['web.menu.game'],url:'https://cp.dunerealms.com/user-service.html?service=politics#landsraad',selfResize:true},
'exchange-listings':{title:'Commodity Exchange',label:'Live player listings',description:'Existing player goods and asking prices in Dunemarks. Purchases and delivery remain in game.',permissions:[],url:'https://cp.dunerealms.com/user-service.html?service=exchange#exchange',selfResize:true}, 'exchange-listings':{title:'Commodity Exchange',label:'Live player listings',description:'Existing player goods and asking prices in Dunemarks. Purchases and delivery remain in game.',permissions:[],url:'https://cp.dunerealms.com/user-service.html?service=exchange#exchange',selfResize:true},
'post-mail':{title:'Imperial Post',label:'Your correspondence',description:'Your existing internal mailbox, folders, compose and attachments.',permissions:[],url:'https://cp.dunerealms.com/user-service.html?service=inbox#shared-inbox',selfResize:true}, 'post-mail':{title:'Imperial Post',label:'Your correspondence',description:'Your existing internal mailbox, folders, compose and attachments.',permissions:[],url:'https://cp.dunerealms.com/user-service.html?service=inbox#shared-inbox',selfResize:true},
@ -26,15 +29,15 @@ export const NATIVE_SERVICES=Object.freeze({
'forum-admin':{title:'Forum Wardens',label:'Forum moderation',description:'The existing community boards and moderation tools, retaining their native permissions.',permissions:['web.menu.forum','web.forum.moderate'],url:'https://forums.dunerealms.com/dune-sso.php'} 'forum-admin':{title:'Forum Wardens',label:'Forum moderation',description:'The existing community boards and moderation tools, retaining their native permissions.',permissions:['web.menu.forum','web.forum.moderate'],url:'https://forums.dunerealms.com/dune-sso.php'}
}); });
export function nativeServiceAccess(user,spec){return !!user&&(!spec.dev||canSubmitDevRequest(user))&&(spec.permissions||[]).every(node=>user?.permissions?.includes(node))&&(!spec.permissionsAny?.length||spec.permissionsAny.some(node=>user?.permissions?.includes(node)));} export function nativeServiceAccess(user,spec){return !!user&&(!spec.dev||canSubmitDevRequest(user))&&(spec.permissions||[]).every(node=>user?.permissions?.includes(node))&&(!spec.permissionsAny?.length||spec.permissionsAny.some(node=>user?.permissions?.includes(node)));}
export function nativeServiceURL(id,{initialTab,listingId,folder,composeMessage,wireTransfer}={}){const spec=NATIVE_SERVICES[id];if(!spec)throw Error('Unknown native service.');const url=new URL(spec.url);if(id==='clans'&&['overview','roster','requests','settings','directory'].includes(initialTab)){url.searchParams.set('view',initialTab);if(initialTab!=='directory')url.searchParams.set('own','1');}if(id==='clan-operations'&&['clan-shops','clan-kits','clan-bank','clan-quests-clan'].includes(initialTab))url.hash=initialTab;if(id==='kits-exchange'){const listing=typeof listingId==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(listingId);if(listing){url.searchParams.set('kit-listing',listingId);url.hash='kit-checkout';}else if(initialTab==='kit-checkout')url.hash='kit-checkout';}if(id==='politics'&&['landsraad','council-motd','house-elections','imperial-elections','applications','electoral-roll','formal-council','imperial-command','imperial-water','imperial-spice'].includes(initialTab))url.hash=initialTab;if(id==='exchange-listings'&&initialTab==='mine')url.searchParams.set('view','mine');if(id==='personal-bank'&&wireTransfer===true)url.searchParams.set('wire','1');if(id==='post-mail'){url.searchParams.set('mailboxes','sidebar');if(['INBOX','Sent','Drafts','Trash','Archive'].includes(folder))url.searchParams.set('folder',folder);if(composeMessage===true)url.searchParams.set('compose','1');}if(['shared-inbox','post-mail'].includes(id)&&['shared-inbox','clan-inbox','faction-inbox','imperial-inbox','staff-inbox'].includes(initialTab))url.hash=initialTab;return url.href;} export function nativeServiceURL(id,{initialTab,listingId,folder,composeMessage,wireTransfer,organisationId}={}){const spec=NATIVE_SERVICES[id];if(!spec)throw Error('Unknown native service.');const url=new URL(spec.url);if(id==='company-boards'){if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(organisationId||''))throw Error('Choose a valid company.');url.searchParams.set('organisation',organisationId);}if(id==='clans'&&['overview','roster','requests','settings','directory'].includes(initialTab)){url.searchParams.set('view',initialTab);if(initialTab!=='directory')url.searchParams.set('own','1');}if(id==='clan-operations'&&['clan-shops','clan-kits','clan-bank','clan-quests-clan'].includes(initialTab))url.hash=initialTab;if(id==='kits-exchange'){const listing=typeof listingId==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(listingId);if(listing){url.searchParams.set('kit-listing',listingId);url.hash='kit-checkout';}else if(initialTab==='kit-checkout')url.hash='kit-checkout';}if(id==='politics'&&['landsraad','council-motd','house-elections','imperial-elections','applications','electoral-roll','formal-council','imperial-command','imperial-water','imperial-spice'].includes(initialTab))url.hash=initialTab;if(id==='exchange-listings'&&initialTab==='mine')url.searchParams.set('view','mine');if(id==='personal-bank'&&wireTransfer===true)url.searchParams.set('wire','1');if(id==='post-mail'){url.searchParams.set('mailboxes','sidebar');if(['INBOX','Sent','Drafts','Trash','Archive'].includes(folder))url.searchParams.set('folder',folder);if(composeMessage===true)url.searchParams.set('compose','1');}if(['shared-inbox','post-mail'].includes(id)&&['shared-inbox','clan-inbox','faction-inbox','imperial-inbox','staff-inbox'].includes(initialTab))url.hash=initialTab;return url.href;}
export function nativeFrameHeight(event,frame,origin){if(event.source!==frame.contentWindow||event.origin!==origin||!['dune-embed-size','dune-shop-size'].includes(event.data?.type))return null;const height=event.data.height;return Number.isFinite(height)&&height>=100&&height<=200000?Math.max(360,Math.ceil(height)):null;} export function nativeFrameHeight(event,frame,origin){if(event.source!==frame.contentWindow||event.origin!==origin||!['dune-embed-size','dune-shop-size'].includes(event.data?.type))return null;const height=event.data.height;return Number.isFinite(height)&&height>=100&&height<=200000?Math.max(360,Math.ceil(height)):null;}
export function mountNativeService(host,id,{fetcher=fetch,singleHeading=false,initialTab,listingId,folder,composeMessage,title,wireTransfer}={}){ export function mountNativeService(host,id,{fetcher=fetch,singleHeading=false,initialTab,listingId,folder,composeMessage,title,wireTransfer,organisationId}={}){
const base=NATIVE_SERVICES[id];if(!base)throw Error('Unknown native service.');const spec={...base,url:nativeServiceURL(id,{initialTab,listingId,folder,composeMessage,wireTransfer}),...(typeof title==='string'?{title}:{} )}; const base=NATIVE_SERVICES[id];if(!base)throw Error('Unknown native service.');const spec={...base,url:nativeServiceURL(id,{initialTab,listingId,folder,composeMessage,wireTransfer,organisationId}),...(typeof title==='string'?{title}:{} )};
let active=true,controller=null,frame=null,hasSize=false,ownObserver=null; let active=true,controller=null,frame=null,hasSize=false,ownObserver=null;
const status=el('p','Checking your workspace access…','cp-v2-news-status');status.setAttribute('role','status'); const status=el('p','Checking your workspace access…','cp-v2-news-status');status.setAttribute('role','status');
const workspace=el('section',undefined,'cp-v2-native-workspace'),tools=el('details',undefined,'pb-workspace-details'),retry=el('button','Reload workspace');retry.type='button';tools.append(el('summary','+ Workspace details'),el('p','Native workspace connection tools'),retry);workspace.append(status); const workspace=el('section',undefined,'cp-v2-native-workspace'),tools=el('details',undefined,'pb-workspace-details'),retry=el('button','Reload workspace');retry.type='button';tools.append(el('summary','+ Workspace details'),el('p','Native workspace connection tools'),retry);workspace.append(status);
const container=el('div',undefined,'cp-v2-native-frame');workspace.append(container,tools); const container=el('div',undefined,'cp-v2-native-frame');workspace.append(container,tools);
const {root}=createCPV2Page({shellHost:singleHeading?host:null,title:spec.title,description:spec.description,artwork:id==='forum-admin'?'nav-boards-v2.webp':'nav-support-v2.webp',tabs:[{id:'native-workspace',label:spec.label,content:workspace}]});host.replaceChildren(root); const {root}=createCPV2Page({shellHost:singleHeading?host:null,title:spec.title,description:spec.description,artwork:(id==='forum-admin'||id.endsWith('-boards'))?'nav-boards-v2.webp':'nav-support-v2.webp',tabs:[{id:'native-workspace',label:spec.label,content:workspace}]});host.replaceChildren(root);
// A single embedded workspace needs no repeated tab; navigation belongs to the CP shell. // A single embedded workspace needs no repeated tab; navigation belongs to the CP shell.
{ {
root.querySelector('.cp-v2-template-tabs')?.remove(); root.querySelector('.cp-v2-template-tabs')?.remove();

View file

@ -5,7 +5,7 @@ import {element as el} from './cp-v2-page-template.mjs';
import {mountNativeService} from './cp-v2-native-services.mjs'; import {mountNativeService} from './cp-v2-native-services.mjs';
import {mountUserPage} from './cp-v2-user-pages.mjs'; import {mountUserPage} from './cp-v2-user-pages.mjs';
export function mountPlayWorkspace(host,workspace,id,options={}){ export function mountPlayWorkspace(host,workspace,id,options={}){
if(workspace==='clan'){if(id==='clan-patronage')return mountPatronage(host);if(id==='clan-claims')return mountClaims(host,{kind:'clan'});if(id==='clan-subhouses'){const panel=el('section',undefined,'claims-workspace');panel.append(el('h2','Subhouses'),el('p','Clan allegiance, independence and rebellion are coming soon. Subhouses retain their identity, land and local access; political powers and final authority belong to the ruling clan.'),el('strong','Coming soon'));for(const title of ['Buy Independence','Rebel']){const button=el('button',title);button.type='button';button.disabled=true;panel.append(button);}host.replaceChildren(panel);return()=>panel.remove();}if(id==='clan-bank')return mountClanBank(host,options); if(workspace==='clan'){if(id==='clan-boards')return mountNativeService(host,'clan-boards',{...options,singleHeading:true});if(id==='clan-patronage')return mountPatronage(host);if(id==='clan-claims')return mountClaims(host,{kind:'clan'});if(id==='clan-subhouses'){const panel=el('section',undefined,'claims-workspace');panel.append(el('h2','Subhouses'),el('p','Clan allegiance, independence and rebellion are coming soon. Subhouses retain their identity, land and local access; political powers and final authority belong to the ruling clan.'),el('strong','Coming soon'));for(const title of ['Buy Independence','Rebel']){const button=el('button',title);button.type='button';button.disabled=true;panel.append(button);}host.replaceChildren(panel);return()=>panel.remove();}if(id==='clan-bank')return mountClanBank(host,options);
const registry={'clan-overview':'overview','clan-roster':'roster','clan-requests':'requests','clan-settings':'settings','clan-directory':'directory'}; const registry={'clan-overview':'overview','clan-roster':'roster','clan-requests':'requests','clan-settings':'settings','clan-directory':'directory'};
if(registry[id])return mountNativeService(host,'clans',{...options,singleHeading:true,initialTab:registry[id]}); if(registry[id])return mountNativeService(host,'clans',{...options,singleHeading:true,initialTab:registry[id]});
if(id==='clan-mail')return mountNativeService(host,'shared-inbox',{...options,singleHeading:true,initialTab:'clan-inbox'}); if(id==='clan-mail')return mountNativeService(host,'shared-inbox',{...options,singleHeading:true,initialTab:'clan-inbox'});

View file

@ -1,7 +1,7 @@
import {POLICY_OFFICES} from './cp-v2-policy-catalogue.mjs'; import {POLICY_OFFICES} from './cp-v2-policy-catalogue.mjs';
import {ELECTIONS} from '../political-catalog.mjs'; import {ELECTIONS} from '../political-catalog.mjs';
export const POLITICAL_TABS=Object.freeze([ export const POLITICAL_TABS=Object.freeze([
{id:'elections',label:'Elections',pages:[['house-elections','Faction Elections'],['imperial-elections','Emperor Elections'],...ELECTIONS.filter(e=>e.kind!=='house'&&e.kind!=='imperial').map(e=>['election-'+e.id,e.label]),['applications','My applications'],['electoral-roll','Electoral Roll']]}, {id:'elections',label:'Elections',pages:[['house-elections','Faction Elections'],['imperial-elections','Emperor Elections'],...ELECTIONS.filter(e=>e.kind!=='house'&&e.kind!=='imperial').map(e=>['election-'+e.id,e.label]),['applications','My applications'],['election-boards','Election Board'],['electoral-roll','Electoral Roll']]},
{id:'directory',label:'Voting Directory',pages:[['all-applications','All applications'],...ELECTIONS.map(e=>['candidates-'+e.id,e.label])]}, {id:'directory',label:'Voting Directory',pages:[['all-applications','All applications'],...ELECTIONS.map(e=>['candidates-'+e.id,e.label])]},
{id:'offices',label:'Offices',pages:[['office-register','Government & Offices'],['imperial-senate','Imperial Senate'],['small-council','Small Council'],['politics-overview','Your Political Record'],['landsraad','Landsraad Assembly'],['formal-council','Faction Council'],['imperial-command','Imperial Council']]}, {id:'offices',label:'Offices',pages:[['office-register','Government & Offices'],['imperial-senate','Imperial Senate'],['small-council','Small Council'],['politics-overview','Your Political Record'],['landsraad','Landsraad Assembly'],['formal-council','Faction Council'],['imperial-command','Imperial Council']]},
{id:'decisions',label:'Decisions & Schemes',pages:POLICY_OFFICES.map(o=>['decisions-'+o.id,o.label])}, {id:'decisions',label:'Decisions & Schemes',pages:POLICY_OFFICES.map(o=>['decisions-'+o.id,o.label])},

View file

@ -1,3 +1,4 @@
import {mountNativeService} from './cp-v2-native-services.mjs';
import {mountPolicyDecisions} from './cp-v2-politics-decisions.mjs'; import {mountPolicyDecisions} from './cp-v2-politics-decisions.mjs';
import {watchMenuHighlights} from './cp-v2-menu-highlights.mjs'; import {watchMenuHighlights} from './cp-v2-menu-highlights.mjs';
import {startCPAuthentication} from './cp-v2-auth.mjs'; import {startCPAuthentication} from './cp-v2-auth.mjs';
@ -31,7 +32,7 @@ function show(){
menu(sidebarRight,'Tools',POLITICAL_TABS.find(t=>t.id==='tools').pages); menu(sidebarRight,'Tools',POLITICAL_TABS.find(t=>t.id==='tools').pages);
const hero=el('header',undefined,'hero'),seal=el('img'),heading=el('div');seal.src=outer+'/assets/seals/office-landsraad.png';seal.alt='';heading.append(el('h1',page[1]),el('p',tab.id==='decisions'?'Decisions and schemes of this office · Economic, Political and Communal.':tab.id==='directory'?'Meet the candidates, explore their campaigns and cast your eligible votes.':tab.id==='elections'?'Candidatures, verified eligibility and the existing ballots.':tab.id==='offices'?'The offices, councils and elected representatives of the realms.':'Proclamations and the existing government instruments.'));hero.append(seal,heading); const hero=el('header',undefined,'hero'),seal=el('img'),heading=el('div');seal.src=outer+'/assets/seals/office-landsraad.png';seal.alt='';heading.append(el('h1',page[1]),el('p',tab.id==='decisions'?'Decisions and schemes of this office · Economic, Political and Communal.':tab.id==='directory'?'Meet the candidates, explore their campaigns and cast your eligible votes.':tab.id==='elections'?'Candidatures, verified eligibility and the existing ballots.':tab.id==='offices'?'The offices, councils and elected representatives of the realms.':'Proclamations and the existing government instruments.'));hero.append(seal,heading);
const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host');card.append(host);cards.append(card);content.replaceChildren(hero,cards); const cards=el('div',undefined,'cards'),card=el('article',undefined,'card full citizen-page-full'),host=el('div',undefined,'citizen-live-host');card.append(host);cards.append(card);content.replaceChildren(hero,cards);
dispose=route.tab==='decisions'?mountPolicyDecisions(host,page[0].slice('decisions-'.length)):['office-register','imperial-senate','small-council'].includes(page[0])?mountOfficeRegister(host,page[0]):mountPoliticsPage(host,page[0]); dispose=page[0]==='election-boards'?mountNativeService(host,'election-boards',{singleHeading:true}):route.tab==='decisions'?mountPolicyDecisions(host,page[0].slice('decisions-'.length)):['office-register','imperial-senate','small-council'].includes(page[0])?mountOfficeRegister(host,page[0]):mountPoliticsPage(host,page[0]);
history.replaceState(null,'','#'+key);if(parent!==window)parent.postMessage({type:'dune-politics-route',tab:route.tab,page:route.page},outer); history.replaceState(null,'','#'+key);if(parent!==window)parent.postMessage({type:'dune-politics-route',tab:route.tab,page:route.page},outer);
sidebar.classList.remove('open');sidebarRight.classList.remove('open');document.querySelector('#mobile-menu').setAttribute('aria-expanded','false');schedule(); sidebar.classList.remove('open');sidebarRight.classList.remove('open');document.querySelector('#mobile-menu').setAttribute('aria-expanded','false');schedule();
} }

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,25 @@
# Approved House sash artwork
The four individual merchandise images were redesigned with the built-in image
editor. Existing catalogue names and heraldic shield symbols are preserved.
| Shop house | Dune reference | Side bands | Central band | Asset |
| --- | --- | --- | --- | --- |
| Aerdrecht | Atreides | Royal blue | Warm ivory/silver | sash-aerdrecht-v1.png |
| Oordwijk | Ordos | Emerald green | Champagne | sash-oordwijk-v1.png |
| Harkveen | Harkonnen | Deep crimson red | Dark steel grey | sash-harkveen-v1.png |
| Korenholt | Corrino | Imperial purple | Antique gold | sash-korenholt-v1.png |
Shared editing prompt: Change the cloth palette to the side/central colours
above, with no black central stripe. Preserve the full isolated vertical sash,
silver rope edging, silver tie and fringe, gold embroidery, original heraldic
shield and exact house lettering. Preserve DUNEREALMS, UNIMATRIX999 and
PRINCEPS TER ELECTUS. Refine realistic embroidered satin with crisp lettering.
Keep the entire sash in frame on a genuinely transparent background, with no
scenery, extra objects or UI. All four use the same catalogue presentation.
Publication: artwork commit 77644d70 passed Web CI run 340 before the four
native shop assets were replaced. HTTP 200, PNG content types and all four
SHA-256 digests were verified against local artwork. Shop data, checkout,
prices and eligibility were unchanged. The collection overview illustration
is a separate legacy asset and is not regenerated by this batch.

View file

@ -2,6 +2,12 @@
if (!defined('IN_MYBB')) die('Direct access denied'); if (!defined('IN_MYBB')) die('Direct access denied');
require_once MYBB_ROOT.'forum-access.php'; require_once MYBB_ROOT.'forum-access.php';
require_once MYBB_ROOT.'central-account-controls.php'; require_once MYBB_ROOT.'central-account-controls.php';
if(is_file(MYBB_ROOT.'system-board-membership.php')){
require_once MYBB_ROOT.'system-board-membership.php';
require_once MYBB_ROOT.'system-board-policy.php';
require_once MYBB_ROOT.'system-board-embed.php';
$plugins->add_hook('pre_output_page','dune_system_board_embed',20);
}
$plugins->add_hook('global_intermediate','dune_central_account_permissions'); $plugins->add_hook('global_intermediate','dune_central_account_permissions');
$plugins->add_hook('usercp_menu','dune_central_account_menu',1); $plugins->add_hook('usercp_menu','dune_central_account_menu',1);
if(is_file(MYBB_ROOT.'forum-awards.php')){require_once MYBB_ROOT.'forum-awards.php';$plugins->add_hook('postbit','dune_forum_post_awards');$plugins->add_hook('postbit_prev','dune_forum_post_awards');$plugins->add_hook('postbit_announcement','dune_forum_post_awards');$plugins->add_hook('member_profile_end','dune_forum_profile_awards');} if(is_file(MYBB_ROOT.'forum-awards.php')){require_once MYBB_ROOT.'forum-awards.php';$plugins->add_hook('postbit','dune_forum_post_awards');$plugins->add_hook('postbit_prev','dune_forum_post_awards');$plugins->add_hook('postbit_announcement','dune_forum_post_awards');$plugins->add_hook('member_profile_end','dune_forum_profile_awards');}
@ -40,6 +46,10 @@ function dune_accounts_guard(){
$identity=dune_bridge('identity',['sessionRef'=>$_SESSION['dune_session_ref']??'']); $identity=dune_bridge('identity',['sessionRef'=>$_SESSION['dune_session_ref']??'']);
$mapping=$db->fetch_array($db->simple_select('dune_accounts','website_id','uid='.(int)$mybb->user['uid'])); $mapping=$db->fetch_array($db->simple_select('dune_accounts','website_id','uid='.(int)$mybb->user['uid']));
if (!$identity || !$mapping || $mapping['website_id']!==$identity['id']) {my_unsetcookie('mybbuser');header('Location: /dune-sso.php');exit;} if (!$identity || !$mapping || $mapping['website_id']!==$identity['id']) {my_unsetcookie('mybbuser');header('Location: /dune-sso.php');exit;}
if(function_exists('dune_apply_system_board_membership')){
try{dune_apply_system_board_membership($identity);}
catch(Throwable $error){http_response_code(503);exit('Organisation forum access is temporarily unavailable.');}
}
$GLOBALS['dune_central_account_user']=dune_central_account_identity($identity); $GLOBALS['dune_central_account_user']=dune_central_account_identity($identity);
$target=dune_central_account_target($identity,$_SERVER['SCRIPT_NAME']??'',(string)$mybb->get_input('action')); $target=dune_central_account_target($identity,$_SERVER['SCRIPT_NAME']??'',(string)$mybb->get_input('action'));
if($target){header('Location: '.$target,true,303);exit;} if($target){header('Location: '.$target,true,303);exit;}

View file

@ -0,0 +1,106 @@
<?php
// Install from a CI-approved release. CLI input is an explicit organisation
// snapshot from the central service, never a browser's claimed membership.
if (PHP_SAPI !== 'cli') { http_response_code(404); exit; }
$input = json_decode(stream_get_contents(STDIN), true, 512, JSON_THROW_ON_ERROR);
if (!is_array($input) || !isset($input['organisations']) || !is_array($input['organisations'])) throw new RuntimeException('Organisation snapshot required');
foreach ($input['organisations'] as $org) {
if (!in_array($org['kind'] ?? '', ['clan','company'], true) || !preg_match('/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i', $org['id'] ?? '') || !is_string($org['name'] ?? null) || trim($org['name']) === '' || strlen($org['name']) > 120) throw new RuntimeException('Invalid organisation');
}
define('IN_MYBB', 1);
define('MYBB_ROOT', '/home/dunerealms/apps/integrations/mybb/');
require MYBB_ROOT.'inc/init.php';
require __DIR__.'/system-board-policy.php';
$lock = $db->fetch_array($db->write_query("SELECT GET_LOCK('dune_system_boards_provision',10) acquired"));
if ((int)($lock['acquired'] ?? 0) !== 1) throw new RuntimeException('System Boards publication is busy');
try {
$db->write_query('CREATE TABLE IF NOT EXISTS '.TABLE_PREFIX.'dune_system_boards (kind VARCHAR(12) NOT NULL, organisation_id VARCHAR(36) NOT NULL, fid INT NOT NULL, member_gid INT NOT NULL DEFAULT 0, leader_gid INT NOT NULL DEFAULT 0, PRIMARY KEY(kind,organisation_id), UNIQUE KEY forum_id(fid)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
$db->write_query('START TRANSACTION');
$groups = []; $query = $db->simple_select('usergroups');
while ($row = $db->fetch_array($query)) $groups[(int)$row['gid']] = $row;
if (!isset($groups[2])) throw new RuntimeException('Registered group unavailable');
$template = $db->fetch_array($db->simple_select('forums', '*', "type='f'", ['limit'=>1]));
if (!$template) throw new RuntimeException('Native forum template unavailable');
$permissionColumns = ['canview','canviewthreads','canonlyviewownthreads','candlattachments','canpostthreads','canpostreplys','canonlyreplyownthreads','canpostattachments','canratethreads','caneditposts','candeleteposts','candeletethreads','caneditattachments','canviewdeletionnotice','modposts','modthreads','mod_edit_posts','modattachments','canpostpolls','canvotepolls','cansearch'];
function board_row($kind, $id) {
global $db;
return $db->fetch_array($db->simple_select('dune_system_boards', '*', "kind='".$db->escape_string($kind)."' AND organisation_id='".$db->escape_string($id)."'"));
}
function make_board($kind, $id, $name, $parent, $type = 'c') {
global $db, $template;
if ($existing = board_row($kind, $id)) return $existing;
$row = $template; unset($row['fid']);
foreach (['threads','posts','lastpost','lastposteruid','unapprovedthreads','unapprovedposts','deletedthreads','deletedposts'] as $key) if (array_key_exists($key, $row)) $row[$key] = 0;
foreach (['lastposter','lastpostsubject','linkto','password','rules','rulestitle'] as $key) if (array_key_exists($key, $row)) $row[$key] = '';
$row = array_merge($row, ['name'=>htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), 'description'=>'', 'type'=>$type, 'pid'=>$parent, 'parentlist'=>'', 'disporder'=>1000, 'active'=>0, 'open'=>1, 'allowhtml'=>0, 'allowmycode'=>1, 'allowsmilies'=>1, 'allowimgcode'=>1, 'showinjump'=>1]);
foreach ($row as $key=>$value) if (is_string($value)) $row[$key]=$db->escape_string($value);
$fid = (int)$db->insert_query('forums', $row);
$parentRow = $parent ? $db->fetch_array($db->simple_select('forums','parentlist','fid='.$parent)) : null;
$parentlist = ($parentRow ? $parentRow['parentlist'].',' : '').$fid;
$db->update_query('forums', ['parentlist'=>$db->escape_string($parentlist)], 'fid='.$fid);
$db->insert_query('dune_system_boards', ['kind'=>$db->escape_string($kind), 'organisation_id'=>$db->escape_string($id), 'fid'=>$fid]);
return board_row($kind, $id);
}
$root = make_board('system','root','System Boards',0);
$clans = make_board('system','clans','Clan Boards',(int)$root['fid']);
$companies = make_board('system','companies','Company Boards',(int)$root['fid']);
make_board('system','elections','Election Board',(int)$root['fid'],'f');
foreach ($input['organisations'] as $org) {
$board = make_board($org['kind'], $org['id'], $org['name'], (int)($org['kind']==='clan' ? $clans['fid'] : $companies['fid']), 'f');
foreach (['member_gid','leader_gid'] as $field) {
if ((int)$board[$field] > 0) continue;
$group = $groups[2]; unset($group['gid']);
$group['title'] = 'System Board '.substr(hash('sha256', $org['kind'].':'.$org['id']),0,12).' '.$field;
$group['cancp'] = 0; $group['issupermod'] = 0; $group['canmodcp'] = $field==='leader_gid' ? 1 : 0;
foreach ($group as $key=>$value) if (is_string($value)) $group[$key]=$db->escape_string($value);
$gid = (int)$db->insert_query('usergroups', $group);
$board[$field] = $gid; $groups[$gid] = $group;
$db->update_query('dune_system_boards', [$field=>$gid], 'fid='.(int)$board['fid']);
}
// Every known group gets an explicit policy: additional political
// groups cannot accidentally make an unrelated organisation visible.
foreach ($groups as $gid=>$group) {
$member = in_array($gid, [(int)$board['member_gid'],(int)$board['leader_gid'],3,4,6], true);
$permissions = dune_board_private_permissions($permissionColumns, $member);
save_board_permissions((int)$board['fid'], (int)$gid, $permissions);
}
$moderator = ['fid'=>(int)$board['fid'], 'id'=>(int)$board['leader_gid'], 'isgroup'=>1,
'caneditposts'=>1,'cansoftdeleteposts'=>1,'canrestoreposts'=>1,'cansoftdeletethreads'=>1,'canrestorethreads'=>1,
'canopenclosethreads'=>1,'canstickunstickthreads'=>1,'canapproveunapprovethreads'=>1,'canapproveunapproveposts'=>1,
'canapproveunapproveattachs'=>1,'canmanagethreads'=>1,'canmanagepolls'=>1,'canpostclosedthreads'=>1,'canmanagereportedposts'=>1,'canviewmodlog'=>1];
$db->delete_query('moderators', 'fid='.(int)$board['fid'].' AND id='.(int)$board['leader_gid'].' AND isgroup=1');
$db->insert_query('moderators', $moderator);
// Existing native Moderators retain moderation on every new board;
// Super Moderators and Administrators already have native global power.
$moderator['id']=6;
$db->delete_query('moderators', 'fid='.(int)$board['fid'].' AND id=6 AND isgroup=1');
$db->insert_query('moderators', $moderator);
}
// Refresh earlier boards too, since later provisioning adds managed groups.
// These groups must also be denied access to every other private board.
$query = $db->simple_select('dune_system_boards', '*', "kind IN ('clan','company')");
while ($board = $db->fetch_array($query)) foreach ($groups as $gid=>$group) {
$member = in_array($gid, [(int)$board['member_gid'],(int)$board['leader_gid'],3,4,6], true);
save_board_permissions((int)$board['fid'], (int)$gid, dune_board_private_permissions($permissionColumns, $member));
}
// No guest feed may publish System Boards topics.
save_board_permissions((int)$root['fid'], 1, dune_board_private_permissions($permissionColumns, false));
$query = $db->simple_select('dune_system_boards', 'fid');
while ($row = $db->fetch_array($query)) $db->update_query('forums', ['active'=>1], 'fid='.(int)$row['fid']);
$db->write_query('COMMIT');
foreach (['usergroups','forums','forumpermissions','moderators'] as $key) { $method='update_'.$key; $cache->$method(); }
echo json_encode(['status'=>'provisioned', 'organisations'=>count($input['organisations']), 'rootForum'=>(int)$root['fid']], JSON_THROW_ON_ERROR)."\n";
} catch (Throwable $error) {
$db->write_query('ROLLBACK');
throw $error;
} finally {
$db->write_query("SELECT RELEASE_LOCK('dune_system_boards_provision')");
}
function save_board_permissions(int $fid, int $gid, array $permissions): void {
global $db;
$where = 'fid='.$fid.' AND gid='.$gid;
$existing = $db->fetch_array($db->simple_select('forumpermissions', 'pid', $where));
if ($existing) $db->update_query('forumpermissions', $permissions, $where);
else $db->insert_query('forumpermissions', array_merge($permissions, ['fid'=>$fid,'gid'=>$gid]));
}

View file

@ -0,0 +1,25 @@
<?php
function dune_system_board_embed(&$page): void {
global $db;
if (basename($_SERVER['SCRIPT_NAME'] ?? '')==='index.php' && $db->table_exists('dune_system_boards')) {
$root=$db->fetch_array($db->simple_select('dune_system_boards','fid',"kind='system' AND organisation_id='root'"));
$fid=(int)($root['fid'] ?? 0);
if ($fid>0) $page=str_replace('</body>','<script>(()=>{const key="system-boards-expanded",body=document.getElementById("cat_'.$fid.'_e"),button=document.getElementById("cat_'.$fid.'_img");if(!body||!button)return;try{if(localStorage.getItem(key)!=="1"){body.style.display="none";button.src=button.src.replace("collapse.png","collapse_collapsed.png");button.alt="+";}button.addEventListener("click",()=>setTimeout(()=>localStorage.setItem(key,body.style.display==="none"?"0":"1"),0));}catch{}})();</script></body>',$page);
}
if (($_GET['dune_embed'] ?? '') !== '1') return;
$fid=(int)($_GET['fid'] ?? 0); $identity=$GLOBALS['dune_system_board_identity'] ?? [];
$boards=dune_system_board_registry(); $parents=[];
$query=$db->simple_select('forums','fid,pid'); while($row=$db->fetch_array($query))$parents[(int)$row['fid']]=(int)$row['pid'];
foreach($identity['systemBoards']['organisations'] ?? [] as $grant){
$board=$boards[($grant['kind'] ?? '').':'.($grant['id'] ?? '')] ?? null;
if(!$board||($grant['manage'] ?? false)!==true||!dune_board_descendant($fid,(int)$board['fid'],$parents))continue;
$href='/system-board-manage.php?kind='.rawurlencode($grant['kind']).'&amp;organisation='.rawurlencode($grant['id']).'&amp;dune_embed=1';
$page=preg_replace('/(<body\b[^>]*>)/i','$1<div class="system-board-tools"><a href="'.$href.'">Manage board · Add forum or category</a></div>',$page,1);
}
$style = '<style>html,body{min-height:0!important;height:auto!important}#header,#footer,.navigation,.breadcrumb,.dune-shared-header,.dune-shared-footer{display:none!important}#container,#content{width:auto!important;max-width:none!important;margin:0!important;padding:14px!important}.system-board-tools{margin:12px 0}</style>';
$script = <<<'JS'
<script>(()=>{const parents=new Set(['https://cp.dunerealms.com','https://clans.dunerealms.com','https://corp.dunerealms.com','https://pol.dunerealms.com']);const send=()=>{const height=Math.ceil(Math.max(document.body.scrollHeight,document.body.getBoundingClientRect().height))+16;if(parent!==window&&height>=100&&height<=200000)for(const origin of parents)parent.postMessage({type:'dune-embed-size',height},origin);};for(const a of document.querySelectorAll('a[href]')){try{const u=new URL(a.href);if(u.origin===location.origin&&!u.pathname.startsWith('/admin/')&&!u.pathname.endsWith('dune-sso.php')){u.searchParams.set('dune_embed','1');a.href=u.href;}}catch{}}for(const f of document.forms){const input=document.createElement('input');input.type='hidden';input.name='dune_embed';input.value='1';f.append(input);try{const u=new URL(f.action);if(u.origin===location.origin){u.searchParams.set('dune_embed','1');f.action=u.href;}}catch{}}window.addEventListener('message',e=>{if(e.source===parent&&parents.has(e.origin)&&e.data?.type==='dune-embed-measure')send();});new ResizeObserver(send).observe(document.body);send();})();</script>
JS;
$page = str_replace('</head>', $style.'</head>', $page);
$page = str_replace('</body>', $script.'</body>', $page);
}

View file

@ -0,0 +1,46 @@
<?php
define('IN_MYBB', 1);
require __DIR__.'/global.php';
require_once __DIR__.'/system-board-membership.php';
require_once '/home/dunerealms/apps/integrations/bridge.php';
header('Cache-Control: private, no-store');
$identity = dune_bridge('identity', ['sessionRef'=>$_SESSION['dune_session_ref'] ?? '']);
if (!$identity || empty($mybb->user['uid'])) { http_response_code(403); exit('Sign in to manage your board.'); }
try { dune_apply_system_board_membership($identity); }
catch (Throwable $error) { http_response_code(503); exit('Board management is temporarily unavailable.'); }
$kind = $mybb->get_input('kind'); $id = $mybb->get_input('organisation');
$grant = null;
foreach ($identity['systemBoards']['organisations'] as $item) if ($item['kind']===$kind && $item['id']===$id && ($item['manage'] ?? false)===true) $grant=$item;
if (!$grant) { http_response_code(404); exit('Board management is not available to your account.'); }
$boards=dune_system_board_registry(); $board=$boards[$kind.':'.$id] ?? null;
if (!$board) { http_response_code(503); exit('This board has not been published yet.'); }
$root=(int)$board['fid']; $parents=[]; $forums=[];
$query=$db->simple_select('forums','*');
while ($row=$db->fetch_array($query)) { $parents[(int)$row['fid']]=(int)$row['pid']; $forums[(int)$row['fid']]=$row; }
$error='';
if ($mybb->request_method==='post') {
verify_post_check($mybb->get_input('my_post_key'));
$parent=$mybb->get_input('parent', MyBB::INPUT_INT); $name=trim($mybb->get_input('name')); $type=$mybb->get_input('forum_type');
if (!dune_board_descendant($parent,$root,$parents) || !isset($forums[$parent]) || empty($forums[$parent]['active'])) $error='Choose a parent inside your own board.';
elseif ($name==='' || mb_strlen($name)>70 || !in_array($type,['c','f'],true)) $error='Choose a name of up to 70 characters and a valid type.';
else {
$row=$forums[$parent]; unset($row['fid']);
foreach (['threads','posts','lastpost','lastposteruid','unapprovedthreads','unapprovedposts','deletedthreads','deletedposts'] as $key) if (array_key_exists($key,$row)) $row[$key]=0;
foreach (['lastposter','lastpostsubject','linkto','password','rules','rulestitle'] as $key) if (array_key_exists($key,$row)) $row[$key]='';
$row=array_merge($row,['name'=>htmlspecialchars($name,ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'),'description'=>'','pid'=>$parent,'type'=>$type,'parentlist'=>'','disporder'=>1000,'active'=>0,'open'=>1,'allowhtml'=>0]);
foreach ($row as $key=>$value) if (is_string($value)) $row[$key]=$db->escape_string($value);
$fid=(int)$db->insert_query('forums',$row);
$db->update_query('forums',['parentlist'=>$db->escape_string($forums[$parent]['parentlist'].','.$fid),'active'=>1],'fid='.$fid);
// No explicit child grants: MyBB inherits the protected ancestor's
// permissions and local moderators. There is no organisation quota.
$cache->update_forums(); $cache->update_forumpermissions();
log_moderator_action(['fid'=>$fid], 'Created organisation child board');
header('Location: /forumdisplay.php?fid='.$fid.'&dune_embed=1',true,303); exit;
}
}
$h=fn($value)=>htmlspecialchars((string)$value,ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8');
echo '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Manage your board</title><link rel="stylesheet" href="/dune-theme.css"></head><body><main style="max-width:760px;margin:24px auto;padding:24px"><h1>Manage your board</h1><p>Create a forum or category inside your organisation. Membership and moderation are inherited.</p>';
if ($error) echo '<p role="alert">'.$h($error).'</p>';
echo '<form method="post"><input type="hidden" name="my_post_key" value="'.$h($mybb->post_code).'"><input type="hidden" name="kind" value="'.$h($kind).'"><input type="hidden" name="organisation" value="'.$h($id).'"><label>Parent <select name="parent">';
foreach ($forums as $fid=>$forum) if (!empty($forum['active']) && dune_board_descendant($fid,$root,$parents)) echo '<option value="'.$fid.'">'.$h($forum['name']).'</option>';
echo '</select></label><p><label>Name <input name="name" maxlength="70" required></label></p><p><label>Type <select name="forum_type"><option value="f">Discussion forum</option><option value="c">Category</option></select></label></p><button type="submit">Create board</button></form><p><a href="/forumdisplay.php?fid='.$root.'&dune_embed=1">Back to board</a></p></main></body></html>';

View file

@ -0,0 +1,44 @@
<?php
if (!defined('IN_MYBB')) die('Direct access denied');
require_once __DIR__.'/system-board-policy.php';
function dune_system_board_registry(): array {
global $db;
if (!$db->table_exists('dune_system_boards')) throw new RuntimeException('System Boards are not provisioned');
$query = $db->simple_select('dune_system_boards', '*', "kind IN ('clan','company')");
$rows = [];
while ($row = $db->fetch_array($query)) $rows[$row['kind'].':'.$row['organisation_id']] = $row;
return $rows;
}
function dune_apply_system_board_membership(array $identity): void {
global $mybb, $db;
if (empty($mybb->user['uid'])) return;
$boards = dune_system_board_registry();
$gids = array_values(array_unique(array_filter(array_merge([(int)$mybb->user['usergroup']], array_map('intval', explode(',', (string)($mybb->user['additionalgroups'] ?? '')))), fn($gid) => $gid > 0)));
if ($boards) {
$fids = array_map(fn($board) => (int)$board['fid'], array_values($boards));
$checks = $db->simple_select('forumpermissions', 'fid,COUNT(DISTINCT gid) AS policy_count', 'fid IN ('.implode(',', $fids).') AND gid IN ('.implode(',', $gids).')', ['group_by'=>'fid']);
$covered = [];
while ($row = $db->fetch_array($checks)) if ((int)$row['policy_count'] === count($gids)) $covered[(int)$row['fid']] = true;
foreach ($fids as $fid) if (empty($covered[$fid])) throw new RuntimeException('Forum group policies require refresh');
}
$projection = $identity['systemBoards'] ?? null;
if (!is_array($projection)) throw new RuntimeException('Forum membership projection unavailable');
$GLOBALS['dune_system_board_identity'] = $identity;
$managed = [];
foreach ($boards as $board) { $managed[] = (int)$board['member_gid']; $managed[] = (int)$board['leader_gid']; }
$allowed = dune_board_managed_groups($projection, $boards);
$groups = dune_board_additional_groups((string)($mybb->user['additionalgroups'] ?? ''), $managed, $allowed);
$old = array_filter(array_map('intval', explode(',', (string)($mybb->user['additionalgroups'] ?? ''))));
sort($old, SORT_NUMERIC);
if (implode(',', $old) === $groups) return;
$db->update_query('users', ['additionalgroups'=>$groups], 'uid='.(int)$mybb->user['uid']);
// MyBB has already resolved this request's usergroup. Discard it and start
// a fresh GET before permission caches, posting or attachment handlers run.
$path = $_SERVER['REQUEST_URI'] ?? '/';
if (!str_starts_with($path, '/') || str_starts_with($path, '//') || preg_match('/[\r\n]/', $path)) $path = '/';
header('Cache-Control: private, no-store');
header('Location: '.$path, true, 303);
exit;
}

View file

@ -0,0 +1,53 @@
<?php
// Pure policy: no database writes and no browser-supplied identity.
function dune_board_managed_groups(array $projection, array $boards): array {
if (($projection['version'] ?? null) !== 1) throw new RuntimeException('Forum membership projection unavailable');
$allowed = [];
foreach ($projection['organisations'] ?? [] as $grant) {
if (!in_array($grant['kind'] ?? '', ['clan', 'company'], true) || empty($grant['id'])) continue;
$key = $grant['kind'].':'.$grant['id'];
if (!isset($boards[$key])) continue;
$board = $boards[$key];
if (($grant['read'] ?? false) !== true || ($grant['post'] ?? false) !== true) continue;
$allowed[] = (int)$board['member_gid'];
if (($grant['manage'] ?? false) === true) $allowed[] = (int)$board['leader_gid'];
}
if (($projection['inspectAll'] ?? false) === true || ($projection['moderateAll'] ?? false) === true) {
foreach ($boards as $board) $allowed[] = (int)$board['member_gid'];
}
$allowed = array_values(array_unique(array_filter($allowed, fn($id) => $id > 0)));
sort($allowed, SORT_NUMERIC);
return $allowed;
}
function dune_board_additional_groups(string $current, array $managed, array $allowed): string {
// Remove only groups owned by this integration. Political, staff and all
// other unrelated additional groups remain untouched.
$old = array_filter(array_map('intval', explode(',', $current)), fn($id) => $id > 0);
$groups = array_values(array_unique(array_merge(array_diff($old, $managed), $allowed)));
sort($groups, SORT_NUMERIC);
return implode(',', $groups);
}
function dune_board_private_permissions(array $columns, bool $member): array {
$allowed = ['canview', 'canviewthreads', 'candlattachments', 'canpostthreads', 'canpostreplys',
'canpostattachments', 'caneditposts', 'caneditattachments', 'canpostpolls', 'canvotepolls', 'cansearch'];
$result = [];
foreach ($columns as $column) {
if (in_array($column, ['pid', 'fid', 'gid'], true)) continue;
$result[$column] = $member && in_array($column, $allowed, true) ? 1 : 0;
}
return $result;
}
function dune_board_descendant(int $target, int $root, array $parents): bool {
if ($root < 1 || $target < 1) return false;
$seen = [];
while ($target > 0) {
if ($target === $root) return true;
if (isset($seen[$target]) || !array_key_exists($target, $parents)) return false;
$seen[$target] = true;
$target = (int)$parents[$target];
}
return false;
}

View file

@ -0,0 +1,23 @@
<?php
define('IN_MYBB', 1);
require __DIR__.'/global.php';
require_once __DIR__.'/system-board-membership.php';
require_once '/home/dunerealms/apps/integrations/bridge.php';
header('Cache-Control: private, no-store');
$identity = dune_bridge('identity', ['sessionRef'=>$_SESSION['dune_session_ref'] ?? '']);
if (!$identity || empty($mybb->user['uid'])) { header('Location: /dune-sso.php', true, 303); exit; }
try { dune_apply_system_board_membership($identity); }
catch (Throwable $error) { http_response_code(503); exit('Organisation boards are temporarily unavailable.'); }
$kind = $_GET['kind'] ?? 'clan'; $id = $_GET['organisation'] ?? '';
if (!is_string($kind) || !is_string($id) || !in_array($kind, ['clan','company','elections'], true)) { http_response_code(400); exit('Choose a valid board.'); }
$projection = $identity['systemBoards'];
if ($kind === 'elections') {
$board = $db->fetch_array($db->simple_select('dune_system_boards', '*', "kind='system' AND organisation_id='elections'"));
} else {
$grant = null;
foreach ($projection['organisations'] as $item) if ($item['kind'] === $kind && ($id === '' || $item['id'] === $id)) { $grant = $item; break; }
if (!$grant || ($grant['read'] ?? false) !== true) { http_response_code(404); exit('This board is not available to your account.'); }
$boards = dune_system_board_registry(); $board = $boards[$kind.':'.$grant['id']] ?? null;
}
if (!$board) { http_response_code(503); exit('This board has not been published yet.'); }
header('Location: /forumdisplay.php?fid='.(int)$board['fid'].'&dune_embed=1', true, 303);

View file

@ -0,0 +1,30 @@
<?php
// Read-only checks against actual MyBB inheritance after provisioning.
if (PHP_SAPI !== 'cli') exit(1);
$_SERVER['SCRIPT_NAME']='/dune-sso.php'; $_SERVER['REQUEST_METHOD']='GET';
$_SERVER['REMOTE_ADDR']='127.0.0.1'; $_SERVER['HTTP_HOST']='forums.dunerealms.com';
define('IN_MYBB',1); chdir('/home/dunerealms/apps/integrations/mybb');
ob_start(); require 'global.php'; ob_end_clean();
require_once __DIR__.'/system-board-membership.php';
$boards=dune_system_board_registry(); $count=0;
if (!$boards) throw new RuntimeException('No organisation boards were provisioned');
foreach ($boards as $key=>$board) {
$fid=(int)$board['fid'];
foreach (['1','2'] as $groups) {
$permission=forum_permissions($fid,0,$groups);
if (!empty($permission['canview']) || !empty($permission['cansearch']) || !empty($permission['candlattachments'])) throw new RuntimeException('Nonmember access: '.$key);
$count++;
}
foreach ($boards as $otherKey=>$other) foreach (['member_gid','leader_gid'] as $field) {
$permission=forum_permissions($fid,0,'2,'.(int)$other[$field]);
$expected=$key===$otherKey;
if (!empty($permission['canview'])!==$expected || !empty($permission['canpostthreads'])!==$expected || !empty($permission['candlattachments'])!==$expected) throw new RuntimeException('Organisation boundary failed: '.$key.' / '.$otherKey);
$count++;
}
foreach (['3','4','6'] as $groups) {
$permission=forum_permissions($fid,0,$groups);
if (empty($permission['canview'])) throw new RuntimeException('Existing staff lost access: '.$key);
$count++;
}
}
echo json_encode(['status'=>'passed','checks'=>$count,'organisations'=>count($boards),'writes'=>0],JSON_THROW_ON_ERROR)."\n";

View file

@ -0,0 +1,24 @@
<?php
require __DIR__.'/system-board-policy.php';
function check($condition, $message) { if (!$condition) throw new RuntimeException($message); }
$boards = [
'clan:ours' => ['member_gid'=>20, 'leader_gid'=>21],
'clan:other' => ['member_gid'=>22, 'leader_gid'=>23],
'company:ours' => ['member_gid'=>24, 'leader_gid'=>25]
];
$member = ['version'=>1, 'organisations'=>[['kind'=>'clan', 'id'=>'ours', 'read'=>true, 'post'=>true, 'manage'=>false]]];
check(dune_board_managed_groups($member, $boards) === [20], 'Member gained unrelated or leader groups');
$leader = $member; $leader['organisations'][0]['manage'] = true;
check(dune_board_managed_groups($leader, $boards) === [20,21], 'Owner did not receive local group');
$inspect = ['version'=>1, 'organisations'=>[], 'inspectAll'=>true];
check(dune_board_managed_groups($inspect, $boards) === [20,22,24], 'Inspection granted management');
check(dune_board_additional_groups('8,20,21,6', [20,21,22,23,24,25], []) === '6,8', 'Revocation removed political/staff groups or kept stale memberships');
check(dune_board_additional_groups('8,20,21', [20,21,22,23,24,25], [22]) === '8,22', 'Membership replacement failed');
check(dune_board_private_permissions(['pid','fid','gid','canview','cansearch','canpostthreads','candeleteposts'], false) === ['canview'=>0,'cansearch'=>0,'canpostthreads'=>0,'candeleteposts'=>0], 'Private permissions were not denied');
check(dune_board_private_permissions(['canview','cansearch','candeleteposts'], true) === ['canview'=>1,'cansearch'=>1,'candeleteposts'=>0], 'Membership granted deletion');
check(dune_board_descendant(12, 10, [12=>11,11=>10,10=>0]), 'Own descendant rejected');
check(!dune_board_descendant(12, 20, [12=>11,11=>10,10=>0]), 'Other subtree permitted');
check(!dune_board_descendant(12, 20, [12=>11,11=>12]), 'Cycle permitted');
try { dune_board_managed_groups([], $boards); throw new RuntimeException('Missing projection was accepted'); }
catch (RuntimeException $e) { check($e->getMessage() === 'Forum membership projection unavailable', 'Wrong failure'); }
echo "System board policy: 11 checks passed\n";

View file

@ -6,6 +6,8 @@ import {badgesFor} from './community-badges.mjs';
import {randomBytes,createHash,timingSafeEqual} from 'node:crypto'; import {randomBytes,createHash,timingSafeEqual} from 'node:crypto';
import {identity,sessionToken} from './auth.mjs'; import {identity,sessionToken} from './auth.mjs';
import {accessFor} from './permissions.mjs'; import {accessFor} from './permissions.mjs';
import {loadSystemBoardAccess} from './system-board-access.mjs';
import {canInspectAllBankAccounts} from './postbank-recipient-policy.mjs';
const hash=s=>createHash('sha256').update(s).digest('hex'); const hash=s=>createHash('sha256').update(s).digest('hex');
const json=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'no-store'}}); const json=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'no-store'}});
export function createIntegrationSSO(db,settings={}){ export function createIntegrationSSO(db,settings={}){
@ -46,7 +48,8 @@ export function createIntegrationSSO(db,settings={}){
const age=await db.prepare('SELECT age_band FROM site_age_declarations WHERE user_id=?').bind(user.id).first(); const age=await db.prepare('SELECT age_band FROM site_age_declarations WHERE user_id=?').bind(user.id).first();
const policy=await db.prepare('SELECT service_uuid,game_link_exempt FROM site_account_policies WHERE user_id=?').bind(user.id).first(); const policy=await db.prepare('SELECT service_uuid,game_link_exempt FROM site_account_policies WHERE user_id=?').bind(user.id).first();
const native=nativeAgentIdentity(user,access); const native=nativeAgentIdentity(user,access);
return json({...await shopAccountProfile(db,user.id,client),id:user.id,username:user.username,displayName:user.display_name,publicProfile:await publicProfileFor(db,user.id,settings.CP_ORIGIN||'https://cp.dunerealms.com'),role:access.rank,ranks:access.ranks,rankLabel:access.label,rankLevel:access.level,communityBadges:(await badgesFor(db,user.id)).filter(k=>communityBadgeVisible(k,access.ranks)),linked:!!link?.minecraft_uuid,gameLinkExempt:!!policy?.service_uuid&&Number(policy.game_link_exempt)===1,forumAllowed:age?.age_band!=='under15',permissions:native.permissions,...(native.nativePermissionManagement===false?{nativePermissionManagement:false}:{}),sessionRef}); const systemBoards=settings.SYSTEM_BOARDS_ENABLED==='1'?await loadSystemBoardAccess(db,user,{inspectAll:await canInspectAllBankAccounts(db,user),moderateAll:native.permissions.includes('web.forum.moderate')||native.permissions.includes('web.forum.admin')}):null;
return json({...await shopAccountProfile(db,user.id,client),id:user.id,username:user.username,displayName:user.display_name,publicProfile:await publicProfileFor(db,user.id,settings.CP_ORIGIN||'https://cp.dunerealms.com'),role:access.rank,ranks:access.ranks,rankLabel:access.label,rankLevel:access.level,communityBadges:(await badgesFor(db,user.id)).filter(k=>communityBadgeVisible(k,access.ranks)),linked:!!link?.minecraft_uuid,gameLinkExempt:!!policy?.service_uuid&&Number(policy.game_link_exempt)===1,forumAllowed:age?.age_band!=='under15',permissions:native.permissions,...(native.nativePermissionManagement===false?{nativePermissionManagement:false}:{}),...(systemBoards?{systemBoards}:{}),sessionRef});
} }
}; };
} }

View file

@ -0,0 +1,26 @@
// Native forum projections are derived from current organisation records on
// every sign-in/identity refresh. Never accept memberships from browser input.
export function projectSystemBoardAccess({clans=[],companies=[],userId,inspectAll=false,moderateAll=false}={}){
const grants=new Map();
if(typeof userId!=='string'||!userId)return {version:1,inspectAll:false,moderateAll:false,organisations:[]};
for(const clan of clans){
if(Number(clan.active)!==1||clan.user_id!==userId||!['owner','officer','member'].includes(clan.clan_role))continue;
grants.set('clan:'+clan.id,{kind:'clan',id:clan.id,read:true,post:true,manage:clan.owner_id===userId&&clan.clan_role==='owner'});
}
for(const company of companies){
if(company.status!=='active'||company.founded_by!==userId&&company.ceo_account_id!==userId)continue;
// Founder access follows the existing Company CP. Current management,
// including scoped moderation, belongs to the appointed CEO.
grants.set('company:'+company.id,{kind:'company',id:company.id,read:true,post:true,manage:company.ceo_account_id===userId});
}
return {version:1,inspectAll:inspectAll===true,moderateAll:moderateAll===true,organisations:[...grants.values()].sort((a,b)=>(a.kind+':'+a.id).localeCompare(b.kind+':'+b.id))};
}
export async function loadSystemBoardAccess(db,user,{inspectAll=false,moderateAll=false}={}){
if(!user?.id)return projectSystemBoardAccess();
const [{results:clans=[]},{results:companies=[]}]=await Promise.all([
db.prepare('SELECT c.id,c.active,c.owner_id,m.user_id,m.clan_role FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id WHERE m.user_id=? AND c.active=1').bind(user.id).all(),
db.prepare('SELECT id,status,founded_by,ceo_account_id FROM corrino_companies WHERE founded_by=? OR ceo_account_id=?').bind(user.id,user.id).all()
]);
return projectSystemBoardAccess({clans,companies,userId:user.id,inspectAll,moderateAll});
}

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