Publish Federal Reserve currency collection and editorial menu controls

This commit is contained in:
unimatrixgit 2026-11-15 16:47:21 +01:00
commit db61e7ad6c
4 changed files with 432 additions and 200 deletions

View file

@ -0,0 +1,40 @@
import {randomUUID} from 'node:crypto';
import {identity} from './auth.mjs';
import {can} from './permissions.mjs';
import {MAIN_MENU} from '../scripts/main-menu.mjs';
const KEY='main_menu_badges';
export const DEFAULT_BADGES=Object.freeze({'Roster':'NEW','Exchange':'UPDATE','Politics':'NEW','Clans':'NEW','CP':'UPDATE'});
const json=(data,status=200,publicRead=false)=>Response.json(data,{status,headers:{'Cache-Control':'no-store',...(publicRead?{'Access-Control-Allow-Origin':'*'}:{})}});
export function validateMenuBadges(items){
if(!Array.isArray(items)||items.length!==MAIN_MENU.length)throw Error('Choose one badge for every menu item.');
const values=new Map();
for(const item of items){if(!item||!MAIN_MENU.some(([,href])=>href===item.href)||!['','NEW','UPDATE'].includes(item.badge)||values.has(item.href))throw Error('Invalid menu badge.');values.set(item.href,item.badge);}
return MAIN_MENU.map(([label,href])=>({label,href,badge:values.get(href)}));
}
export async function readMenuBadges(db){
let row;try{row=await db.prepare('SELECT setting_value,updated_at FROM website_settings WHERE setting_key=?').bind(KEY).first();}catch{}
const defaults=MAIN_MENU.map(([label,href])=>({label,href,badge:DEFAULT_BADGES[label]||''}));
if(!row)return {items:defaults,revision:0};
try{return {items:validateMenuBadges(JSON.parse(row.setting_value)),revision:Number(row.updated_at)};}catch{return {items:defaults,revision:Number(row.updated_at)||0};}
}
export function createMenuBadges(db,settings={},dependencies={}){
const authenticate=dependencies.authenticate||((request)=>identity(request,db)),allowed=dependencies.allowed||((user)=>can(db,user,'web.posts.publish'));
return async request=>{
const url=new URL(request.url),publicRead=url.pathname==='/api/menu-badges';
if(publicRead)return request.method==='GET'?json(await readMenuBadges(db),200,true):json({message:'Method not allowed'},405);
if(!['GET','PUT'].includes(request.method))return json({message:'Method not allowed'},405);
const user=await authenticate(request);if(!user)return json({message:'Sign in first.'},401);
if(!await allowed(user))return json({message:'Website publication permission required.'},403);
if(request.method==='GET')return json(await readMenuBadges(db));
if(request.headers.get('origin')!==new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin)return json({message:'Origin rejected'},403);
if(!request.headers.get('content-type')?.startsWith('application/json'))return json({message:'JSON required'},415);
const raw=await request.text();if(raw.length>8192)return json({message:'Request too large'},413);
let body,items;try{body=JSON.parse(raw);items=validateMenuBadges(body.items);}catch{return json({message:'Invalid menu badge choices.'},400);}
const previous=await readMenuBadges(db);if(body.revision!==previous.revision)return json({message:'Badges changed elsewhere. Reload before saving.'},409);
const now=Math.max(Date.now(),previous.revision+1),value=JSON.stringify(items);
let change;try{change=previous.revision?await db.prepare('UPDATE website_settings SET setting_value=?,updated_at=? WHERE setting_key=? AND updated_at=?').bind(value,now,KEY,previous.revision).run():await db.prepare('INSERT INTO website_settings(setting_key,setting_value,updated_at) VALUES(?,?,?)').bind(KEY,value,now).run();}catch(error){if(error.code==='ER_DUP_ENTRY'||String(error.message).includes('UNIQUE'))return json({message:'Badges changed elsewhere. Reload before saving.'},409);throw error;}
if(!change.meta.changes)return json({message:'Badges changed elsewhere. Reload before saving.'},409);
await db.prepare('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)').bind(randomUUID(),user.id,'menu-badges-update',JSON.stringify({before:previous.items,after:items}),now).run();
return json({items,revision:now,message:'Menu badges published.'});
};
}

View file

@ -80,7 +80,7 @@ export async function rankFor(db,key){
return DEFAULT_RANKS.find(r=>r.key===rankKey(key))||{key:rankKey(key),label:'Unknown rank',level:0,kind:'access',nodes:[]};
}
// These aliases are administrative *roles*, not user names. No account receives access by name alone.
export const OWNER_RANKS=new Set(['owners','official_account','web_net_admin','web_net_owner','web_network','network_admin']);
export const OWNER_RANKS=new Set(['org_owner_ceo','owners','official_account','web_net_admin','web_net_owner','web_network','network_admin']);
export const isOwnerRank=rank=>OWNER_RANKS.has(typeof rank==='string'?rank:rank?.key);
export const rankKey=role=>role==='player'?'user':role;
export async function accessFor(db,user){

View file

@ -23,6 +23,8 @@ import {createCommunityRewards} from './community-rewards.mjs';
import {initializeCompanyRegistry,listPublicCompanies} from './company-registry.mjs';
import {initializeShareLedger} from './share-ledger.mjs';
import {createPublicNews} from './news.mjs';
import {createMenuBadges} from './menu-badges.mjs';
import {createSearchVisibility} from './search-visibility.mjs';
const root=new URL('./public/',import.meta.url);
const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin','Content-Security-Policy':"default-src 'self'; frame-src https://cp.dunerealms.com; img-src 'self' https://www.dunerealms.com https://cp.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com data:; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self' https://cp.dunerealms.com; base-uri 'self'; object-src 'none'; frame-ancestors 'self'"};
export function createApplication(db,settings={}) {
@ -36,8 +38,14 @@ export function createApplication(db,settings={}) {
const gameLink=createGameLink(db,settings,origin);
const rewards=createCommunityRewards(db,settings,origin);
const publicNews=createPublicNews(db);const publicExchange=createPublicExchange(db,settings);
const searchVisibility=createSearchVisibility(db);const menuBadges=createMenuBadges(db,settings);
return async function handle(request) {
const url=new URL(request.url);
if(url.pathname==='/api/menu-badges')return menuBadges(request);
// Discord publishes canonical /news/:slug-:id links. Route these before
// static assets so published articles cannot fall through to a Worker 404.
const articleResponse=await searchVisibility.route(request);
if(articleResponse)return articleResponse;
if(url.pathname.startsWith('/git/sso/')||url.pathname==='/api/git/me')return gitIdentity(request);
if(url.pathname==='/api/exchange/listings')return publicExchange(request);
// Website articles use the editorial register, before the legacy Discord feed.

View file

@ -14,6 +14,6 @@ export function createWorldStatus(settings,fetcher=fetch){
}
return async()=>{
if(!cached||Date.now()>=expires){inflight||=(async()=>{try{cached=await check();expires=Date.now()+15000;}finally{inflight=null;}})();await inflight;}
return Response.json(cached,{headers:{'Cache-Control':'no-store'}});
return Response.json(cached,{headers:{'Cache-Control':'no-store','Access-Control-Allow-Origin':'*'}});
};
}