From 22a1ec94de9108113f683ec4905ab029c646fdb8 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:36:23 +0100 Subject: [PATCH 1/3] Reject cross-season reuse of rebellion declaration request IDs --- website/node/rebellion-quests.mjs | 2 +- website/tests/rebellion-quests.test.mjs | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/website/node/rebellion-quests.mjs b/website/node/rebellion-quests.mjs index 94ca0a5b..4d69546e 100644 --- a/website/node/rebellion-quests.mjs +++ b/website/node/rebellion-quests.mjs @@ -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'}); diff --git a/website/tests/rebellion-quests.test.mjs b/website/tests/rebellion-quests.test.mjs index 9e66089e..24a93a29 100644 --- a/website/tests/rebellion-quests.test.mjs +++ b/website/tests/rebellion-quests.test.mjs @@ -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();} +}); From 22f08a83cf2cbe2773abea2fffdce7a9afdc3821 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:36:24 +0100 Subject: [PATCH 2/3] Extend the existing newsroom with shared safe formatting and media previews --- docs/design/NEWSROOM-FORMATTING.md | 29 ++++++++ website/control-panel/community-admin.mjs | 2 + .../public/cp-v2/cp-v2-newsroom.mjs | 12 ++-- website/control-panel/public/cp-v2/v2.css | 2 + website/control-panel/public/news-format.mjs | 2 + website/control-panel/server.mjs | 1 + website/integrations/mybb/forum-news.php | 72 +++++++++++++++++++ website/node/discord-news.mjs | 3 +- website/node/forum-news.mjs | 3 +- website/node/news-format.mjs | 9 +-- website/node/server.mjs | 2 +- website/scripts/build.mjs | 2 +- website/tests/news-format.test.mjs | 17 +++++ website/web/home-news.js | 16 +---- 14 files changed, 142 insertions(+), 30 deletions(-) create mode 100644 docs/design/NEWSROOM-FORMATTING.md create mode 100644 website/control-panel/public/news-format.mjs create mode 100644 website/integrations/mybb/forum-news.php create mode 100644 website/tests/news-format.test.mjs diff --git a/docs/design/NEWSROOM-FORMATTING.md b/docs/design/NEWSROOM-FORMATTING.md new file mode 100644 index 00000000..30847fef --- /dev/null +++ b/docs/design/NEWSROOM-FORMATTING.md @@ -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. diff --git a/website/control-panel/community-admin.mjs b/website/control-panel/community-admin.mjs index 6631c595..60545c16 100644 --- a/website/control-panel/community-admin.mjs +++ b/website/control-panel/community-admin.mjs @@ -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); diff --git a/website/control-panel/public/cp-v2/cp-v2-newsroom.mjs b/website/control-panel/public/cp-v2/cp-v2-newsroom.mjs index f2dc3bf9..36f48b90 100644 --- a/website/control-panel/public/cp-v2/cp-v2-newsroom.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-newsroom.mjs @@ -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); diff --git a/website/control-panel/public/cp-v2/v2.css b/website/control-panel/public/cp-v2/v2.css index 8b01421a..9507a17b 100644 --- a/website/control-panel/public/cp-v2/v2.css +++ b/website/control-panel/public/cp-v2/v2.css @@ -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} diff --git a/website/control-panel/public/news-format.mjs b/website/control-panel/public/news-format.mjs new file mode 100644 index 00000000..56fe4ae1 --- /dev/null +++ b/website/control-panel/public/news-format.mjs @@ -0,0 +1,2 @@ +// Node-side imports of the editor use the same authored browser formatter. +export * from '../../web/news-format.mjs'; diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 779d294c..ea91db93 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -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); diff --git a/website/integrations/mybb/forum-news.php b/website/integrations/mybb/forum-news.php new file mode 100644 index 00000000..bfc91546 --- /dev/null +++ b/website/integrations/mybb/forum-news.php @@ -0,0 +1,72 @@ +(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(['[',']'],['[',']'],(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'=>''.htmlspecialchars_uni($label).'','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}')");} diff --git a/website/node/discord-news.mjs b/website/node/discord-news.mjs index e213e66e..e0fa2969 100644 --- a/website/node/discord-news.mjs +++ b/website/node/discord-news.mjs @@ -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'}={}){ diff --git a/website/node/forum-news.mjs b/website/node/forum-news.mjs index 6f4e904c..1b55597e 100644 --- a/website/node/forum-news.mjs +++ b/website/node/forum-news.mjs @@ -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')}; } diff --git a/website/node/news-format.mjs b/website/node/news-format.mjs index b347edb5..bfa604d1 100644 --- a/website/node/news-format.mjs +++ b/website/node/news-format.mjs @@ -1,8 +1 @@ -const esc=v=>String(v).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[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:'?''+esc(m[1])+'':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+='

'+inline(paragraph.join(' '))+'

';paragraph=[];}if(list){html+='';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+='
'+esc(picture[1])+'
'+esc(picture[1])+'
';continue;} - const video=line.match(/^\[([^\]\n]{1,200})\]\((https:\/\/www\.dunerealms\.com\/assets\/video\/[a-z0-9-]+\.mp4)\)$/i); - if(video){flush();html+='
Enable sound in the player for the original epic soundtrack.
';continue;} - const heading=line.match(/^#{1,3}\s+(.+)$/),bullet=line.match(/^[-*]\s+(.+)$/);if(heading){flush();html+='

'+inline(heading[1])+'

';}else if(bullet){if(paragraph.length)flush();if(!list){html+='