Merge pull request 'Extend the existing newsroom with safe shared article formatting' (#444) from feature/dev-ticket-batch-20261121 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 2m29s

This commit is contained in:
unimatrix 2026-11-20 23:42:12 +00:00
commit 6c8a57496b
17 changed files with 194 additions and 31 deletions

View file

@ -0,0 +1,29 @@
# Existing newsroom formatting — ticket 407
The existing Imperial Newsroom keeps its register, optimistic article versions,
draft storage, authorship, publication permissions and delivery outboxes. Its
editor adds bold, italic, code, heading, bullet and numbered-list controls, plus
labelled HTTPS links and asset images with required alt text. Saving a draft does
not publish it. The existing publication confirmation remains required.
`website/web/news-format.mjs` is the shared bounded grammar. Node article pages,
browser article pages and editorial preview use the same HTML renderer. HTML is
escaped, links require HTTPS without embedded credentials, and image sources are
restricted to PNG/WebP/JPEG files beneath the public DuneRealms assets path. The
save API validates content independently of the browser. Existing plain articles
and approved local MP4 embeds remain supported.
The same grammar produces plain Discord summaries and escaped native MyBB
formatting. Forum payload version 3 includes the server-generated `body_bbcode`
inside the existing immutable delivery revision; browser article inputs cannot
supply it. The native CLI helper retains version-2 handling for old workers and
all existing source-marker, locking, author, first-post and revision protections.
Install the reviewed `integrations/mybb/forum-news.php` at the existing native
`/home/dunerealms/apps/integrations/forum-news.php` before restarting news delivery.
This does not introduce a second publisher or outbox.
No live test article or public notification is required to validate the parser.
Focused fixtures cover draft/publication rights, hostile content, equivalent
HTML/BBCode/plain output and unchanged once-only delivery behavior. The other
keygen audit work in ticket 407 remains separate; editor publication alone is
not sufficient to close that complete ticket.

View file

@ -1,4 +1,5 @@
import {retiredTicketResponse} from '../node/retired-tickets.mjs';
import {validateNewsContent} from '../node/news-format.mjs';
import {randomUUID} from 'node:crypto';
import {identity} from '../node/auth.mjs';
import {can} from '../node/permissions.mjs';
@ -48,6 +49,7 @@ export function createCommunityAdmin(db,settings,{pool}={}){return async request
if(path!=='/api/cp/posts/save'||request.method!=='POST')return json({message:'Not found'},404);
let body;try{body=await request.json();}catch{return json({message:'Invalid request'},400);}
if(typeof body.title!=='string'||body.title.trim().length<5||body.title.length>120||typeof body.body!=='string'||body.body.trim().length<10||body.body.length>12000||!['draft','published','archived'].includes(body.status))return json({message:'Enter a title of 5–120 characters and a post of 10–12000 characters.'},400);
try{body.body=validateNewsContent(body.body);}catch(error){return json({message:error.message},400);}
const category=await db.prepare('SELECT category_key FROM website_post_categories WHERE category_key=?').bind(body.category||'').first();if(!category)return json({message:'Choose a news category.'},400);
const previous=body.id?await db.prepare('SELECT id,status,published_at,version FROM website_posts WHERE id=?').bind(body.id).first():null;
if(body.id&&(!previous||previous.status==='deleted'))return json({message:'Post not found'},404);

View file

@ -1,4 +1,5 @@
import {createCPV2Page,element as el} from './cp-v2-page-template.mjs';
import {renderNewsBody,validateNewsContent,newsLink,newsImage} from '../news-format.mjs';
const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
const states=['draft','published','archived'];
export function newsroomRights(user){const p=new Set(user?.permissions||[]);return {view:p.has('web.menu.posts')&&p.has('web.posts.view'),edit:p.has('web.menu.posts')&&p.has('web.posts.edit'),publish:p.has('web.posts.publish')};}
@ -14,12 +15,11 @@ export function newsPayload(input,previous,categories,rights){
if(title.length<5||title.length>120||body.length<10||body.length>12000||!states.includes(status)||!categories.some(c=>c.category_key===category))throw Error('Choose a category, a title of 5–120 characters and content of 10–12,000 characters.');
if((status!=='draft'||previous&&previous.status!=='draft')&&!rights.publish)throw Error('Publishing permission is required to change published or archived posts.');
if(previous&&(!uuid.test(previous.id||'')||!Number.isSafeInteger(Number(previous.version))))throw Error('Refresh the article before saving.');
return {title,body,category,status,...(previous?{id:previous.id,version:Number(previous.version)}:{})};
return {title,body:validateNewsContent(body),category,status,...(previous?{id:previous.id,version:Number(previous.version)}:{})};
}
const time=value=>{const d=new Date(Number(value));return value&&Number.isFinite(d.getTime())?d.toLocaleString('en-GB'):'Not recorded';};
function articlePreview(host,title,body){
host.replaceChildren(el('h3',title||'Untitled article'));let list=null;
for(const line of body.split(/\r?\n/)){const text=line.trim();if(!text){list=null;continue;}if(/^#{1,3}\s/.test(text)){host.append(el('h4',text.replace(/^#{1,3}\s+/,'')));list=null;}else if(/^[-•]\s/.test(text)){if(!list){list=el('ul');host.append(list);}list.append(el('li',text.replace(/^[-•]\s+/,'')));}else{list=null;host.append(el('p',text));}}
const content=el('div',undefined,'article-body');content.innerHTML=renderNewsBody(body);for(const style of content.querySelectorAll('link'))style.remove();host.replaceChildren(el('h3',title||'Untitled article'),content);
}
export function mountNewsroom(host,{fetcher=fetch}={}){
let active=true,posts=[],categories=[],rights={view:false,edit:false,publish:false},current=null,busy=false,uncertain=false,readGeneration=0,readController=null,registerPage=1,archivePage=1;
@ -36,7 +36,11 @@ export function mountNewsroom(host,{fetcher=fetch}={}){
const title=field('Article title','title');title.required=true;title.minLength=5;title.maxLength=120;
const category=field('News category','category','select');category.required=true;
const body=field('Article content','body','textarea');body.required=true;body.minLength=10;body.maxLength=12000;body.rows=14;body.placeholder='Write paragraphs, # headings and - list items.';
form.append(el('p','Formatting: separate paragraphs with a blank line. Use # for headings and - for list items.','cp-v2-news-help'));
const formatting=el('div',undefined,'cp-v2-company-actions');formatting.setAttribute('role','group');formatting.setAttribute('aria-label','Article formatting');
function insert(before,after='',fallback='text',lines=false,literal=false){let start=body.selectionStart,end=body.selectionEnd;if(lines){start=body.value.lastIndexOf('\n',start-1)+1;const next=body.value.indexOf('\n',end);end=next<0?body.value.length:next;}const selected=body.value.slice(start,end)||fallback;const value=literal?before:lines?selected.split('\n').map((line,i)=>(before==='1. '?String(i+1)+'. ':before)+line).join('\n'):before+selected+after;if(body.value.length-(end-start)+value.length>12000){mark('Article content cannot exceed 12,000 characters.');return;}body.setRangeText(value,start,end,'select');body.focus();previewNow();}
for(const [label,before,after,fallback,lines]of [['Bold','**','**','bold text'],['Italic','*','*','italic text'],['Code','`','`','code'],['Heading','# ','','Heading',true],['Bullet list','- ','','List item',true],['Numbered list','1. ','','List item',true]]){const button=el('button',label);button.type='button';button.onclick=()=>insert(before,after,fallback,lines);formatting.append(button);}body.parentElement.before(formatting);
const media=el('details');media.append(el('summary','Insert a link or image'));const mediaLabel=el('label','Link label / image alt text'),mediaText=el('input'),addressLabel=el('label','HTTPS address'),address=el('input');mediaText.maxLength=200;address.type='url';address.placeholder='https://www.dunerealms.com/assets/…';mediaLabel.append(mediaText);addressLabel.append(address);media.append(mediaLabel,addressLabel);
for(const [label,image]of [['Insert link',false],['Insert image',true]]){const button=el('button',label);button.type='button';button.onclick=()=>{const text=mediaText.value.trim(),url=(image?newsImage:newsLink)(address.value.trim());if(!text||/[\[\]\r\n]/.test(text)||!url){mark(image?'Choose a DuneRealms asset image and describe it with alt text.':'Enter a label and a valid HTTPS address.');return;}insert((image?'\n\n!':'')+'['+text+']('+url+')'+(image?'\n\n':''),'','',false,true);};media.append(button);}form.append(media,el('p','Use the controls or Markdown. Images must come from DuneRealms assets and include alt text. Save as Draft to keep your article without publishing.','cp-v2-news-help'));
const state=field('Publication status','status','select');for(const value of states){const option=el('option',value[0].toUpperCase()+value.slice(1));option.value=value;state.append(option);}
const consent=el('input');consent.type='checkbox';const consentLabel=el('label',' I confirm the selected publication or archive action.');consentLabel.className='cp-v2-news-confirm';consentLabel.prepend(consent);form.append(consentLabel);
const save=el('button','Save article');save.type='submit';const clear=el('button','New draft');clear.type='button';const actions=el('div',undefined,'cp-v2-company-actions');actions.append(save,clear);form.append(actions);

View file

@ -278,3 +278,5 @@
/* Navigation is in the side menus; remove the duplicated portal row on every CP. */
#portals[hidden]{display:none!important}.cp-workspace-switch{display:grid;gap:8px;padding:12px;color:#ead49a}.cp-workspace-switch select{width:100%;min-width:0;padding:10px;border:1px solid #b29a5e;border-radius:8px;background:#102820;color:#f0dfb4;font:inherit}
.cp-v2-news-form .article-picture{margin:18px 0}.cp-v2-news-form .article-picture img,.cp-v2-news-form video{display:block;max-width:100%;height:auto;border-radius:10px}.cp-v2-news-form .article-seal img{width:150px}.cp-v2-news-form figcaption{color:#c7cbae;font-size:.9rem}.cp-v2-news-form details>label{display:grid;gap:8px;margin:12px 0}

View file

@ -0,0 +1,2 @@
// Node-side imports of the editor use the same authored browser formatter.
export * from '../../web/news-format.mjs';

View file

@ -267,6 +267,7 @@ export function createPanel(db,settings={},dependencies={}){
const market=(settings.EXCHANGE_READ_TOKEN||'').length>=32?createMarketBridge({pool,readToken:settings.EXCHANGE_READ_TOKEN}):null;
return async request=>{const retiredTickets=retiredTicketResponse(request);if(retiredTickets)return retiredTickets;
const path=new URL(request.url).pathname;
if(path==='/news-format.mjs'&&['GET','HEAD'].includes(request.method))return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/news-format.mjs',import.meta.url)),{headers:{'Content-Type':'text/javascript; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}});
if(path==='/api/dmpaint'||path==='/dmpaint'||path.startsWith('/dmpaint/'))return dmpaint(request);
if(path==='/api/public/government')return publicGovernment(request);
if(['/api/menu-badges','/api/staff/menu-badges'].includes(path))return menuBadges(request);

View file

@ -0,0 +1,72 @@
<?php
// Private CLI adapter: native forum validation and exact source ownership remain authoritative.
if(PHP_SAPI!=='cli')exit(1);
$input=json_decode(stream_get_contents(STDIN),true);
if(!is_array($input)||!preg_match('/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i',$input['id']??''))exit(2);
$status=$input['status']??'published';$modern=isset($input['revision']);
if(!in_array($status,['published','archived'],true)||($modern&&!preg_match('/^[0-9a-f]{64}$/',$input['revision'])))exit(2);
if($status==='published'&&(!is_numeric($input['published_at']??null)||(int)$input['published_at']>(int)(microtime(true)*1000)||!is_string($input['title']??null)||!is_string($input['body']??null)))exit(2);
$_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();
$fid=14;$uid=2;$author=get_user($uid);if(strtolower($author['username']??'')!=='dunerealms')exit(3);$mybb->user=$author;$permissions=forum_permissions($fid,$uid);if(empty($permissions['canpostthreads'])||empty($permissions['canview']))exit(3);
$current=$fid;$seen=[];while($current){if(isset($seen[$current]))exit(3);$seen[$current]=true;$forum=get_forum($current);$guest=forum_permissions($current,0,1);if(empty($forum['active'])||!empty($forum['password'])||empty($guest['canview'])||empty($guest['canviewthreads'])||!empty($guest['canonlyviewownthreads']))exit(3);$current=(int)$forum['pid'];}
$id=$db->escape_string($input['id']);$lock='dune-news-'.$id;$locked=$db->fetch_field($db->query("SELECT GET_LOCK('{$lock}',5) AS acquired"),'acquired');if(!$locked)exit(4);
try{
$db->write_query('CREATE TABLE IF NOT EXISTS '.TABLE_PREFIX.'dune_news_delivery(post_id CHAR(36) PRIMARY KEY,state VARCHAR(16) NOT NULL,tid INT NOT NULL DEFAULT 0,pid INT NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
$db->write_query('CREATE TABLE IF NOT EXISTS '.TABLE_PREFIX.'dune_news_revision(post_id CHAR(36) PRIMARY KEY,revision VARCHAR(64) NOT NULL,state VARCHAR(16) NOT NULL,updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
$mapping=$db->fetch_array($db->simple_select('dune_news_delivery','*',"post_id='{$id}'"));
$marker='DuneRealms source: '.$input['id'];
if(!$mapping||!in_array($mapping['state'],['sent','archived'],true)){
// Reconcile a timeout/crash by immutable marker; never blindly create twice.
$query=$db->query('SELECT t.tid,p.pid FROM '.TABLE_PREFIX.'threads t JOIN '.TABLE_PREFIX.'posts p ON p.pid=t.firstpost WHERE t.fid=14 AND t.uid=2 AND p.message LIKE \'%'.$db->escape_string($marker).'%\' LIMIT 2');$matches=[];while($row=$db->fetch_array($query))$matches[]=$row;
if(count($matches)===1){$mapping=['post_id'=>$input['id'],'state'=>'sent','tid'=>(int)$matches[0]['tid'],'pid'=>(int)$matches[0]['pid']];$db->replace_query('dune_news_delivery',$mapping,'post_id');}
elseif($mapping||count($matches)>1)throw new Exception('Interrupted native creation requires review');
}
$thread=null;$first=null;
if($mapping){
$thread=get_thread((int)$mapping['tid']);$first=get_post((int)$mapping['pid']);
if(!$thread||!$first||(int)$thread['fid']!==14||(int)$thread['visible']!==1||(int)$thread['uid']!==2||(int)$thread['firstpost']!==(int)$first['pid']||(int)$first['uid']!==2||(int)$first['tid']!==(int)$thread['tid']||(int)$first['visible']!==1||strpos($first['message'],$marker)===false)throw new Exception('Managed topic ownership or visibility changed');
}
if($status==='archived'&&!$mapping)throw new Exception('Withdrawal cannot create a new topic');
$revision=$modern?$input['revision']:hash('sha256',json_encode($input));
$saved=$db->fetch_array($db->simple_select('dune_news_revision','*',"post_id='{$id}'"));
$state=$status==='published'?'sent':'archived';
$reply=function($tid)use($state,$revision,$modern){$out=['state'=>$state,'thread_id'=>(int)$tid];if($modern)$out['revision']=$revision;echo json_encode($out);};
if($saved&&!$mapping)throw new Exception('Revision mapping requires reconciliation');
if($saved&&$saved['revision']===$revision&&$saved['state']===$state){$reply($mapping['tid']);exit;}
$safe=fn($s)=>str_replace(['[',']'],['&#91;','&#93;'],(string)$s);$url='https://www.dunerealms.com/news-archive.html?post='.$input['id'];
$formatBody=function($body)use($safe,$input){
if(($input['format_version']??0)===3){if(!is_string($input['body_bbcode']??null)||strlen($input['body_bbcode'])>96000)throw new Exception('Invalid formatted article');return $input['body_bbcode'];}
$out=[];$list=false;foreach(preg_split('/\r\n|\r|\n/',$body)as$line){
if(preg_match('/^#{1,3}\s+(.+)$/u',trim($line),$heading)){if($list){$out[]='[/list]';$list=false;}$out[]='[b]'.$safe($heading[1]).'[/b]';}
elseif(preg_match('/^[-*]\s+(.+)$/u',trim($line),$bullet)){if(!$list){$out[]='[list]';$list=true;}$out[]='[*]'.$safe($bullet[1]);}
else{if($list){$out[]='[/list]';$list=false;}$out[]=$safe($line);}
}if($list)$out[]='[/list]';return implode("\n",$out);
};
if($status==='published'){
$labels=['world'=>'World','news'=>'NEWS','maintenance'=>'Maintenance','changelogs'=>'Changelogs','events'=>'Events','community'=>'Community','unis_blog'=>"Uni’s Blog"];$label=$labels[$input['category']??'news']??'NEWS';$prefix=$db->fetch_array($db->simple_select('threadprefixes','pid',"prefix='".$db->escape_string($label)."' AND forums='14'"));
if(!$prefix){$prefix=['pid'=>$db->insert_query('threadprefixes',['prefix'=>$label,'displaystyle'=>'<span class="dune-news-tag">'.htmlspecialchars_uni($label).'</span>','forums'=>'14','groups'=>'-1'])];$cache->update_threadprefixes();}
// MyBB's native validator limits subjects to85 characters; website titles allow120.
$subject=my_substr($input['title'],0,85);$prefix_id=(int)$prefix['pid'];
$message='[b]'.$safe($label).'[/b]'."\n".'Written by '.$safe($input['author_name']??'DuneRealms')."\n".'Originally published '.gmdate('j F Y, H:i',(int)($input['published_at']/1000))." UTC\n\n".$formatBody($input['body'])."\n\n[url=".$url."]Read the original article[/url]\n\n[size=x-small]".$marker.'[/size]';
if(my_strlen($input['title'])>85)$message='[b]'.$safe($input['title'])."[/b]\n\n".$message;
}else{
$subject=my_substr('[Archived] '.preg_replace('/^\[Archived\] /','',$thread['subject']),0,85);$prefix_id=(int)$thread['prefix'];
$message="[b]Archived announcement[/b]\n\nThis article has been withdrawn from the DuneRealms website. Earlier replies are retained for context.\n\n[size=x-small]".$marker.'[/size]';
}
require_once MYBB_ROOT.'inc/datahandlers/post.php';
if($mapping){
if(empty($permissions['caneditposts'])&&!is_moderator($fid,'caneditposts',$uid))throw new Exception('Native edit permission denied');
$earliest=$db->fetch_array($db->simple_select('posts','pid',"tid='".(int)$thread['tid']."'",['order_by'=>'dateline,pid','limit'=>1]));if((int)($earliest['pid']??0)!==(int)$first['pid'])throw new Exception('Native first post requires review');
if($first['subject']!==$subject||$first['message']!==$message||(int)$thread['prefix']!==$prefix_id){
$handler=new PostDataHandler('update');$handler->set_data(['pid'=>(int)$first['pid'],'tid'=>(int)$thread['tid'],'fid'=>$fid,'uid'=>$uid,'edit_uid'=>$uid,'subject'=>$subject,'prefix'=>$prefix_id,'message'=>$message,'editreason'=>$status==='published'?'Synchronized website article revision':'Website article withdrawn; replies retained','options'=>['signature'=>0,'disablesmilies'=>1]]);
if(!$handler->validate_post())throw new Exception('Native edit validation failed');$handler->update_post();
$check=$db->fetch_array($db->simple_select('posts','message,subject,visible',"pid='".(int)$first['pid']."'"));$checkThread=$db->fetch_array($db->simple_select('threads','subject,prefix',"tid='".(int)$thread['tid']."'"));if(!$check||!$checkThread||$check['message']!==$message||$check['subject']!==$subject||(int)$check['visible']!==1||$checkThread['subject']!==$subject||(int)$checkThread['prefix']!==$prefix_id)throw new Exception('Native edit requires review');
}
$tid=(int)$thread['tid'];$pid=(int)$first['pid'];
}else{
$handler=new PostDataHandler('insert');$handler->action='thread';$handler->set_data(['fid'=>$fid,'uid'=>$uid,'username'=>$author['username'],'subject'=>$subject,'prefix'=>$prefix_id,'message'=>$message,'dateline'=>(int)($input['published_at']/1000),'ipaddress'=>'127.0.0.1','savedraft'=>0,'options'=>['signature'=>0,'disablesmilies'=>1,'subscriptionmethod'=>0]]);
if(!$handler->validate_thread())throw new Exception('Native post validation failed');$db->insert_query('dune_news_delivery',['post_id'=>$input['id'],'state'=>'creating','tid'=>0,'pid'=>0]);$result=$handler->insert_thread();$tid=(int)($result['tid']??0);$pid=(int)($result['pid']??0);$thread=get_thread($tid);if(!$tid||!$pid||!$thread||(int)$thread['visible']!==1)throw new Exception('Native topic visibility requires review');
}
$db->update_query('dune_news_delivery',['state'=>$state,'tid'=>$tid,'pid'=>$pid],"post_id='{$id}'");
$db->replace_query('dune_news_revision',['post_id'=>$input['id'],'revision'=>$revision,'state'=>$state,'updated_at'=>(int)(microtime(true)*1000)],'post_id');$reply($tid);
}catch(Throwable $e){fwrite(STDERR,'Forum news delivery requires review'.PHP_EOL);exit(5);}finally{$db->query("SELECT RELEASE_LOCK('{$lock}')");}

View file

@ -1,3 +1,4 @@
import {newsPlainText} from './news-format.mjs';
import {readFile} from 'node:fs/promises';
import {GAZETTE_NAME} from './jarvis-gazette.mjs';
import {randomUUID} from 'node:crypto';
@ -6,7 +7,7 @@ const ORIGIN='https://www.dunerealms.com';
const categories=new Set(['world','news','maintenance','changelogs','events','community','unis_blog']);
export function newsWebhookPayload(post,{test=false}={}){
const category=categories.has(post.category)?post.category:'news';
const summary=String(post.body||'').replace(/<[^>]*>/g,'').replace(/\[([^\]]+)\]\(https?:[^)]+\)/g,'$1').replace(/[#*_`]/g,'').replace(/\s+/g,' ').trim().slice(0,500);
const summary=newsPlainText(post.body||'').slice(0,500);
return {username:GAZETTE_NAME,avatar_url:'https://cdn.discordapp.com/avatars/1567239700610285618/dc3ff7eb9f86481f52b4293affa3bbfd.png',allowed_mentions:{parse:[]},embeds:[{title:(test?'[TEST] ':'')+'['+({news:'NEWS',world:'World',maintenance:'Maintenance',changelogs:'Changelogs',events:'Events',community:'Community',unis_blog:'Uni’s Blog'}[post.category]||'NEWS')+'] '+String(post.title).slice(0,220),description:summary,url:ORIGIN+newsPath(post),color:0xc6a551,image:{url:ORIGIN+'/assets/news-'+(category==='unis_blog'?'news':category)+'.webp'},footer:{text:test?'Integration test — not a new published article':'Written by '+(post.author_name||'DuneRealms')+' • '+GAZETTE_NAME},timestamp:new Date(Number(post.published_at)).toISOString()}]};
}
export function validateNewsWebhook(config,{channelId='1567237542040834250'}={}){

View file

@ -1,3 +1,4 @@
import {newsBBCode} from './news-format.mjs';
import {execFile} from 'node:child_process';
import {GAZETTE_NAME} from './jarvis-gazette.mjs';
import {existsSync} from 'node:fs';
@ -10,7 +11,7 @@ const nativeSend=post=>new Promise((resolve,reject)=>{const child=execFile('/usr
export function forumNewsRevision(row,time){
// Withdrawal payloads deliberately contain no current draft/private/future content.
const post=row.status==='published'&&row.published_at!=null&&Number.isFinite(Number(row.published_at))&&Number(row.published_at)<=time
?{id:row.id,status:'published',title:row.title,body:row.body,category:row.category,published_at:Number(row.published_at),author_name:row.author_name||'DuneRealms',publisher:GAZETTE_NAME,format_version:2}
?{id:row.id,status:'published',title:row.title,body:row.body,category:row.category,published_at:Number(row.published_at),author_name:row.author_name||'DuneRealms',publisher:GAZETTE_NAME,format_version:3,body_bbcode:newsBBCode(row.body)}
:{id:row.id,status:'archived'};
return {...post,revision:createHash('sha256').update(JSON.stringify(post)).digest('hex')};
}

View file

@ -1,8 +1 @@
const esc=v=>String(v).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function inline(text){let result='',from=0;for(const m of text.matchAll(/\[([^\]\n]{1,200})\]\((https:\/\/[^\s)]+)\)/g)){result+=esc(text.slice(from,m.index));let url;try{url=new URL(m[2]);}catch{}result+=url?.protocol==='https:'?'<a class="dispatch-read-more" href="'+esc(url.href)+'" rel="noopener noreferrer">'+esc(m[1])+'</a>':esc(m[0]);from=m.index+m[0].length;}return result+esc(text.slice(from));}
export function renderNewsBody(value){let html='',paragraph=[],list=false;const flush=()=>{if(paragraph.length){html+='<p>'+inline(paragraph.join(' '))+'</p>';paragraph=[];}if(list){html+='</ul>';list=false;}};for(const raw of String(value).replace(/\r/g,'').split('\n')){const line=raw.trim();if(!line){flush();continue;}
const picture=line.match(/^!\[([^\]\n]{1,200})\]\((https:\/\/www\.dunerealms\.com\/assets\/(?:seals\/)?[a-z0-9-]+\.(?:png|webp|jpg))\)$/i);
if(picture){flush();const seal=picture[2].includes('/seals/');html+='<link rel="stylesheet" href="/news-images.css?v=20261108"><figure class="article-picture'+(seal?' article-seal':'')+'"><img loading="lazy" src="'+esc(picture[2])+'" alt="'+esc(picture[1])+'"><figcaption>'+esc(picture[1])+'</figcaption></figure>';continue;}
const video=line.match(/^\[([^\]\n]{1,200})\]\((https:\/\/www\.dunerealms\.com\/assets\/video\/[a-z0-9-]+\.mp4)\)$/i);
if(video){flush();html+='<link rel="stylesheet" href="/news-video.css?v=20261107"><figure class="article-video"><video controls autoplay muted loop playsinline preload="metadata" aria-label="'+esc(video[1])+'" poster="'+esc(video[2].replace(/\.mp4$/i,'-poster.png'))+'"><source src="'+esc(video[2])+'" type="video/mp4">Your browser does not support embedded video.</video><figcaption>Enable sound in the player for the original epic soundtrack.</figcaption></figure>';continue;}
const heading=line.match(/^#{1,3}\s+(.+)$/),bullet=line.match(/^[-*]\s+(.+)$/);if(heading){flush();html+='<h3>'+inline(heading[1])+'</h3>';}else if(bullet){if(paragraph.length)flush();if(!list){html+='<ul>';list=true;}html+='<li>'+inline(bullet[1])+'</li>';}else{if(list)flush();paragraph.push(line);}}flush();return html;}
export {renderNewsBody,validateNewsContent,newsBBCode,newsPlainText} from '../web/news-format.mjs';

View file

@ -47,7 +47,7 @@ export function createRebellionQuests(central,keys,{clock=Date.now,authorizeProd
const season=await readActiveXPSeason(polProgressionStore(central),clock());
const fields={clanId:input.clanId,officeKey:input.officeKey,expectedTermId:input.expectedTermId,expectedHomeBlockId:input.expectedHomeBlockId},scope=season.season_id+':REBELLION_'+input.requestId;
const grant=await keys.issue({accountId:actor.id,keyType:'quest',scopeId:scope,authorize:async(tx,{keyId})=>{
const prior=await tx.first('SELECT account_id,fields_json FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[input.requestId,DECLARE]);if(prior){if(prior.account_id!==actor.id||prior.fields_json!==JSON.stringify(fields))reject('Rebellion reference conflict.');return;}
const prior=await tx.first('SELECT i.account_id,i.fields_json,k.scope_id FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.request_id=? AND i.action_id=?',[input.requestId,DECLARE]);if(prior){if(prior.scope_id!==scope||prior.account_id!==actor.id||prior.fields_json!==JSON.stringify(fields))reject('Rebellion reference conflict.');return;}
const declaration={...await target(tx,actor,input.clanId,input.officeKey),seasonId:season.season_id,declaredAt:clock()};if(declaration.sourceTermId!==input.expectedTermId||declaration.homeBlockId!==input.expectedHomeBlockId)reject('The incumbent or Home Block changed. Review the current decision.');
const active=await tx.first("SELECT i.key_id FROM jarvis_generated_instructions i JOIN organisation_keys k ON k.id=i.key_id WHERE i.action_id=? AND i.account_id=? AND i.state='issued' AND k.revoked_at IS NULL AND i.fields_json=?",[DECLARE,actor.id,JSON.stringify(fields)]);if(active)reject('This clan already has an open rebellion quest for that office.');
await insert(tx,{keyId,requestId:input.requestId,accountId:actor.id,action:DECLARE,fields,manifest:{declaration},state:'issued'});

View file

@ -69,7 +69,7 @@ export function createApplication(db,settings={}) {
if(url.pathname.startsWith('/api/company-emblems/'))return createCompanyEmblems(db)(request);
if(/^\/api\/public\/(companies|political-houses)(?:\/|$)/.test(url.pathname))return publicOrganisations(request);
if(url.pathname.startsWith('/api/public/clans/'))return publicClans(request);
if(/^\/(?:clans\/[a-z0-9]{2,6}|(?:companies|political-houses)(?:\/[a-z0-9_-]{1,64})?)\/?$/i.test(url.pathname)||['/organisation-network.mjs','/organisation-public.js','/clans.css','/clan-directory-view.mjs','/clan-public.css','/clan-public.js','/clan-dynasty.js','/dynastic-address.mjs','/clan-dynasty.css','/dune-date.js','/dune-date.mjs'].includes(url.pathname)){
if(/^\/(?:clans\/[a-z0-9]{2,6}|(?:companies|political-houses)(?:\/[a-z0-9_-]{1,64})?)\/?$/i.test(url.pathname)||['/news-format.mjs','/organisation-network.mjs','/organisation-public.js','/clans.css','/clan-directory-view.mjs','/clan-public.css','/clan-public.js','/clan-dynasty.js','/dynastic-address.mjs','/clan-dynasty.css','/dune-date.js','/dune-date.mjs'].includes(url.pathname)){
if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});
const asset=/^\/(clans|companies|political-houses)(?:\/|$)/.test(url.pathname)?'clan.html':url.pathname.slice(1),shared={'organisation-network.mjs':'organisation-network.mjs','clans.css':'clans.css','clan-directory-view.mjs':'clan-directory-view.mjs','dune-date.mjs':'dune-date.mjs','dynastic-address.mjs':'dynastic-address.mjs','clan-dynasty.js':'clan-dynasty.mjs','clan-dynasty.css':'clan-dynasty.css','dune-date.js':'dune-date.mjs'};
const content=request.method==='HEAD'?null:await readFile(shared[asset]?new URL('../control-panel/public/'+shared[asset],import.meta.url):new URL(asset,root));

View file

@ -40,7 +40,7 @@ for(const [source,target] of [['cp-v2/cp-v2-exchange-design.mjs','codex-exchange
writeFileSync(path.join(web,target),content);
}
writeFileSync(path.join(web,'rates-and-charges.html'),bankRatesPage());
let assetCount=0;let assetWriter=null,shardSize=0;const shardNames=[];let shardTemporary;function openShard(){shardTemporary=path.join(dist,'server','.assets-build-'+process.pid);assetWriter=openSync(shardTemporary,'w');writeSync(assetWriter,'export default {');shardSize=0;}function closeShard(){writeSync(assetWriter,'};\n');closeSync(assetWriter);const hash=createHash('sha256').update(readFileSync(shardTemporary)).digest('hex'),name='assets-'+hash+'.mjs',target=path.join(dist,'server',name);if(existsSync(target))unlinkSync(shardTemporary);else renameSync(shardTemporary,target);shardNames.push(name);}function writeAsset(entry){if(shardSize>32*1024*1024){closeShard();openShard();}writeSync(assetWriter,entry);shardSize+=Buffer.byteLength(entry);}const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.mp4':'video/mp4','.pdf':'application/pdf','.zip':'application/zip','.svg':'image/svg+xml'};
let assetCount=0;let assetWriter=null,shardSize=0;const shardNames=[];let shardTemporary;function openShard(){shardTemporary=path.join(dist,'server','.assets-build-'+process.pid);assetWriter=openSync(shardTemporary,'w');writeSync(assetWriter,'export default {');shardSize=0;}function closeShard(){writeSync(assetWriter,'};\n');closeSync(assetWriter);const hash=createHash('sha256').update(readFileSync(shardTemporary)).digest('hex'),name='assets-'+hash+'.mjs',target=path.join(dist,'server',name);if(existsSync(target))unlinkSync(shardTemporary);else renameSync(shardTemporary,target);shardNames.push(name);}function writeAsset(entry){if(shardSize>32*1024*1024){closeShard();openShard();}writeSync(assetWriter,entry);shardSize+=Buffer.byteLength(entry);}const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.mp4':'video/mp4','.pdf':'application/pdf','.zip':'application/zip','.svg':'image/svg+xml'};
function collect(directory){for(const entry of readdirSync(directory).sort()){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const relative=path.relative(web,p).split(path.sep).join('/');if(/^assets\/seals\/[^/]+-provenance\.txt$/.test(relative)||/^assets\/organisation-deed(?:s)?-[a-z0-9-]+\.png$/.test(relative))continue;const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);const bytes=readFileSync(p);const payload=relative.endsWith('.html')?Buffer.from(preparePublicHtml(bytes.toString('utf8'))):relative==='portal-navigation.js'?Buffer.from(withRealmSwitch(withCanonicalMenu(withMenuBadges(bytes.toString('utf8'))))):relative==='portal-navigation.css'?Buffer.concat([bytes,Buffer.from(HOUSE_STYLE_CSS+REALM_SWITCH_CSS)]):bytes;writeAsset(JSON.stringify('/'+relative)+':['+JSON.stringify(type)+','+JSON.stringify(payload.toString('base64'))+'],');assetCount++}}}
mkdirSync(path.join(dist,'server'),{recursive:true});mkdirSync(path.join(dist,'.openai'),{recursive:true});const workerTemporary=path.join(dist,'server/index.js.build-'+process.pid);process.once('exit',()=>{if(existsSync(workerTemporary))try{unlinkSync(workerTemporary);}catch{}});openShard();collect(web);const buildCommit=process.env.GITHUB_SHA;if(buildCommit&&/^[0-9a-f]{40}$/.test(buildCommit)){writeAsset(JSON.stringify('/ci-build.json')+':'+JSON.stringify(['application/json; charset=utf-8',Buffer.from(JSON.stringify({commit:buildCommit})).toString('base64')])+',');}closeShard();
let api=['feed-api.mjs','exchange-api.mjs','forum-api.mjs','community-api.mjs','portal-api.mjs'].map(file=>readFileSync(path.join(root,'worker',file),'utf8').replace(/export /g,'')).join('\n');let runtime=readFileSync(path.join(root,'worker/runtime.mjs'),'utf8').replace(/^import .*;$/gm,'');

View file

@ -0,0 +1,17 @@
import test from 'node:test';import assert from 'node:assert/strict';
import {renderNewsBody,validateNewsContent,newsBBCode,newsPlainText} from '../web/news-format.mjs';
import {forumNewsRevision} from '../node/forum-news.mjs';
const article='# A dispatch\n\nOur **House** uses *care* and `code`. Read [the report](https://www.dunerealms.com/news).\n\n1. First item\n2. Second item\n\n- One\n- Two\n\n![House seal](https://www.dunerealms.com/assets/seals/house-seal.webp)';
test('one article retains formatting, link labels, ordered lists and image alt text across website, forum and plain delivery',()=>{
assert.equal(validateNewsContent(article),article);const html=renderNewsBody(article),forum=newsBBCode(article),plain=newsPlainText(article);
for(const expected of ['<h3>A dispatch</h3>','<strong>House</strong>','<em>care</em>','<code>code</code>','<ol><li>First item</li>','<ul><li>One</li>','alt="House seal"','rel="noopener noreferrer"'])assert.ok(html.includes(expected),expected);
for(const expected of ['[b]House[/b]','[i]care[/i]','[list=1]','[url=https://www.dunerealms.com/news]the report[/url]','[img]https://www.dunerealms.com/assets/seals/house-seal.webp[/img]'])assert.ok(forum.includes(expected),expected);
assert.match(plain,/Our House uses care and code\. Read the report/);assert.ok(!plain.includes('**'));assert.ok(plain.includes('House seal'));
const post=forumNewsRevision({id:'id',status:'published',published_at:1,title:'Title',body:article,category:'news',author_name:'Author'},2);assert.equal(post.format_version,3);assert.equal(post.body_bbcode,forum);assert.equal(post.author_name,'Author');
});
test('unsafe schemes, credentials, HTML and remote images fail validation; renderers cannot turn legacy input into active code',()=>{
for(const body of ['<script>alert(1)</script>','[click](javascript:alert(1))','[click](data:text/html,hello)','[click](https://user:pass@example.com)','![track](https://example.com/image.png)','![](https://www.dunerealms.com/assets/image.png)'])assert.throws(()=>validateNewsContent(body),body);
const html=renderNewsBody('<img src=x onerror=alert(1)>\n\n[click](javascript:alert(1))\n\n![track](https://evil.example/x.png)');assert.ok(!html.includes('<img'));assert.ok(!html.includes('href="javascript:'));assert.match(html,/&lt;img/);
const bb=newsBBCode('[img]https://evil.example/x.png[/img]\n\n<script>bad</script>');assert.ok(!bb.includes('[img]'));assert.ok(!bb.includes('<script>'));
});
test('public video artwork and existing plain articles retain supported rendering',()=>{assert.equal(renderNewsBody('A plain article.'),'<p>A plain article.</p>');assert.match(renderNewsBody('[Epic soundtrack](https://www.dunerealms.com/assets/video/epic.mp4)'),/<video controls autoplay muted loop/);});

View file

@ -26,3 +26,13 @@ test('stale confirmation and revoked evidence cannot transfer a deed or consume
assert.equal((await f.db.first('SELECT outcome FROM political_office_terms WHERE id=?',[f.term])).outcome,'winner');
}finally{f.db.close();}
});
test('a request UUID from an earlier season cannot create an orphan declaration key',async()=>{
const f=await fixture();try{
await f.service.declare(f.winner,f.input);const before=(await f.keys.list(f.winner.id)).length;
await f.db.query("UPDATE jarvis_pol_progression_seasons SET state='closed' WHERE season_id='S01'");
await f.db.query("INSERT INTO jarvis_pol_progression_seasons(season_id,starts_at,ends_at,level_cap,curve_base,state) VALUES('S02',0,?,0,25,'active')",[f.now()+100000]);
await assert.rejects(f.service.declare(f.winner,f.input),/reference conflict/);
assert.equal((await f.keys.list(f.winner.id)).length,before);
}finally{f.db.close();}
});

View file

@ -8,20 +8,8 @@ function newsModule(root,kind){let page=1,generation=0;const archive=root.datase
}
for(const root of document.querySelectorAll('[data-news-module]'))newsModule(root,root.dataset.newsModule);
const fullPost=document.getElementById('news-full-post'),postId=new URLSearchParams(location.search).get('post');
function formatNewsBody(root,value){
let paragraph=[],list=null;
const flush=()=>{if(paragraph.length){root.append(newsEl('p',paragraph.join(' ')));paragraph=[];}list=null;};
const lines=String(value).replace(/\r/g,'').split('\n');
for(let i=0;i<lines.length;i++){
const line=lines[i].trim();if(!line){flush();continue;}
const bullet=line.match(/^(?:[•*-]|\d+[.)])\s+(.+)$/);
if(bullet){if(paragraph.length)flush();if(!list){list=newsEl('ul');root.append(list);}list.append(newsEl('li',bullet[1]));continue;}
const heading=line.match(/^#{1,4}\s+(.+)$/),next=lines.slice(i+1).find(x=>x.trim());
if(heading||(!paragraph.length&&line.length<80&&/^[•*-]\s/.test(next?.trim()||''))){flush();root.append(newsEl('h3',heading?heading[1]:line));continue;}
if(list)flush();paragraph.push(line);
}
flush();
}
function formatNewsBody(root,value){root.textContent=value;void import('/news-format.mjs').then(({renderNewsBody})=>{root.innerHTML=renderNewsBody(value);}).catch(()=>{root.textContent=value;});}
if(fullPost&&postId){
document.body.classList.add('news-article-page');const archive=document.getElementById('archive-news');if(archive)archive.hidden=true;fullPost.hidden=false;
newsFetch('/api/news/'+encodeURIComponent(postId)).then(({post})=>{

View file

@ -0,0 +1,41 @@
// Shared safe news grammar for editorial preview, website and native delivery.
const esc=v=>String(v).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const bb=v=>String(v).replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('[','&#91;').replaceAll(']','&#93;');
export function newsLink(value){try{const u=new URL(value);return u.protocol==='https:'&&!u.username&&!u.password?u.href:null;}catch{return null;}}
export function newsImage(value){const u=newsLink(value);return u&&/^https:\/\/www\.dunerealms\.com\/assets\/(?:[a-z0-9_-]+\/)*[a-z0-9_-]+\.(?:png|webp|jpe?g)$/i.test(u)?u:null;}
export function validateNewsContent(value){
if(typeof value!=='string'||value.trim().length<10||value.length>12000||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(value))throw Error('Use article content of 10–12,000 characters.');
if(/<\s*\/?[a-z][^>]*>/i.test(value))throw Error('Use the formatting controls instead of HTML.');
for(const m of value.matchAll(/(!?)\[([^\]\n]*)\]\(([^\n)]*)\)/g))if(!m[2].trim()||m[2].length>200||!(m[1]?newsImage(m[3]):newsLink(m[3])))throw Error(m[1]?'Images need alt text and an HTTPS image from the DuneRealms assets folder.':'Links need a label and a valid HTTPS address without login details.');
return value.replace(/\r\n?/g,'\n').trim();
}
function inline(value,mode){
const text=mode==='html'?esc:mode==='bbcode'?bb:v=>v;let out='',from=0;
for(const m of value.matchAll(/\[([^\]\n]{1,200})\]\(([^\s)]+)\)|\*\*([^*\n]+)\*\*|\*([^*\n]+)\*|`([^`\n]+)`/g)){
out+=text(value.slice(from,m.index));const url=m[1]&&newsLink(m[2]);
if(m[1])out+=url?(mode==='html'?'<a class="dispatch-read-more" href="'+esc(url)+'" rel="noopener noreferrer">'+text(m[1])+'</a>':mode==='bbcode'?'[url='+bb(url)+']'+text(m[1])+'[/url]':m[1]):text(m[0]);
else{const content=m[3]||m[4]||m[5],tag=m[3]?'strong':m[4]?'em':'code',btag=m[3]?'b':m[4]?'i':'font=monospace';out+=mode==='html'?'<'+tag+'>'+text(content)+'</'+tag+'>':mode==='bbcode'?'['+btag+']'+text(content)+'[/'+btag.split('=')[0]+']':content;}
from=m.index+m[0].length;
}return out+text(value.slice(from));
}
export function newsBlocks(value){
const blocks=[];let paragraph=[],list=null;const flush=()=>{if(paragraph.length){blocks.push({kind:'paragraph',text:paragraph.join(' ')});paragraph=[];}list=null;};
for(const raw of String(value).replace(/\r/g,'').split('\n')){
const line=raw.trim();if(!line){flush();continue;}
const image=line.match(/^!\[([^\]\n]{1,200})\]\(([^\s)]+)\)$/),video=line.match(/^\[([^\]\n]{1,200})\]\((https:\/\/www\.dunerealms\.com\/assets\/video\/[a-z0-9-]+\.mp4)\)$/i);
if(image&&newsImage(image[2])){flush();blocks.push({kind:'image',alt:image[1],url:newsImage(image[2])});continue;}
if(video){flush();blocks.push({kind:'video',alt:video[1],url:video[2]});continue;}
const heading=line.match(/^#{1,4}\s+(.+)$/),bullet=line.match(/^(?:([-*•])|(\d+)[.)])\s+(.+)$/);
if(heading){flush();blocks.push({kind:'heading',text:heading[1]});}
else if(bullet){if(paragraph.length)flush();const kind=bullet[2]?'ordered':'unordered';if(!list||list.kind!==kind){list={kind,items:[]};blocks.push(list);}list.items.push(bullet[3]);}
else{list=null;paragraph.push(line);}
}flush();return blocks;
}
export function renderNewsBody(value){return newsBlocks(value).map(b=>{
if(b.kind==='image')return '<link rel="stylesheet" href="/news-images.css?v=20261108"><figure class="article-picture'+(b.url.includes('/seals/')?' article-seal':'')+'"><img loading="lazy" src="'+esc(b.url)+'" alt="'+esc(b.alt)+'"><figcaption>'+esc(b.alt)+'</figcaption></figure>';
if(b.kind==='video')return '<link rel="stylesheet" href="/news-video.css?v=20261107"><figure class="article-video"><video controls autoplay muted loop playsinline preload="metadata" aria-label="'+esc(b.alt)+'" poster="'+esc(b.url.replace(/\.mp4$/i,'-poster.png'))+'"><source src="'+esc(b.url)+'" type="video/mp4">Your browser does not support embedded video.</video><figcaption>Enable sound in the player for the original epic soundtrack.</figcaption></figure>';
if(b.items){const tag=b.kind==='ordered'?'ol':'ul';return '<'+tag+'>'+b.items.map(t=>'<li>'+inline(t,'html')+'</li>').join('')+'</'+tag+'>';}
const tag=b.kind==='heading'?'h3':'p';return '<'+tag+'>'+inline(b.text,'html')+'</'+tag+'>';
}).join('');}
export function newsBBCode(value){return newsBlocks(value).map(b=>b.kind==='image'?'[img]'+bb(b.url)+'[/img]\n'+bb(b.alt):b.kind==='video'?'[url='+bb(b.url)+']'+bb(b.alt)+'[/url]':b.items?'[list'+(b.kind==='ordered'?'=1':'')+']\n'+b.items.map(t=>'[*]'+inline(t,'bbcode')).join('\n')+'\n[/list]':b.kind==='heading'?'[b]'+inline(b.text,'bbcode')+'[/b]':inline(b.text,'bbcode')).join('\n\n');}
export function newsPlainText(value){return newsBlocks(value).map(b=>b.alt||b.items?.map(t=>inline(t,'text')).join(' ')||inline(b.text,'text')).join(' ').replace(/<[^>]*>/g,'').replace(/\s+/g,' ').trim();}