diff --git a/website/node/discord-news.mjs b/website/node/discord-news.mjs new file mode 100644 index 00000000..f019541e --- /dev/null +++ b/website/node/discord-news.mjs @@ -0,0 +1,51 @@ +import {readFile} from 'node:fs/promises'; +import {randomUUID} from 'node:crypto'; +import {newsPath} from './search-visibility.mjs'; +const ORIGIN='https://www.dunerealms.com'; +const categories=new Set(['world','news','maintenance','changelogs','events','community']); +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); + return {username:'DuneRealms Dispatches',avatar_url:'https://cdn.discordapp.com/avatars/1567239700610285618/dc3ff7eb9f86481f52b4293affa3bbfd.png',allowed_mentions:{parse:[]},embeds:[{title:(test?'[TEST] ':'')+String(post.title).slice(0,240),description:summary,url:ORIGIN+newsPath(post),color:0xc6a551,image:{url:ORIGIN+'/assets/news-'+category+'.webp'},footer:{text:test?'Integration test — not a new published article':'DuneRealms • The Quest for Tavren II Aedrecht'},timestamp:new Date(Number(post.published_at)).toISOString()}]}; +} +export function validateNewsWebhook(config){ + const url=new URL(config.url);if(url.protocol!=='https:'||url.hostname!=='discord.com'||!/^\/api(?:\/v10)?\/webhooks\/\d+\/[A-Za-z0-9_.-]+$/.test(url.pathname)||url.search||url.hash||url.username||url.password||config.channelId!=='1567237542040834250'||config.guildId!=='1567229433033531462')throw Error('Invalid news webhook configuration'); + return url.href; +} +export async function initializeDiscordNews(db,now=Date.now()){ + await db.prepare("CREATE TABLE IF NOT EXISTS discord_news_meta (marker VARCHAR(40) PRIMARY KEY,created_at BIGINT NOT NULL)").run(); + await db.prepare("CREATE TABLE IF NOT EXISTS discord_news_delivery (post_id CHAR(36) PRIMARY KEY,state VARCHAR(16) NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,next_at BIGINT NOT NULL DEFAULT 0,claimed_at BIGINT NOT NULL DEFAULT 0,claim_token CHAR(36) NOT NULL DEFAULT '',message_id VARCHAR(30) NOT NULL DEFAULT '',last_error VARCHAR(80) NOT NULL DEFAULT '')").run(); + await db.batch([ + db.prepare("INSERT INTO discord_news_delivery(post_id,state) SELECT id,'baseline' FROM website_posts WHERE status='published' AND published_at<=? AND NOT EXISTS(SELECT 1 FROM discord_news_meta WHERE marker='initialized') ON CONFLICT(post_id) DO UPDATE SET post_id=excluded.post_id").bind(now), + db.prepare("INSERT INTO discord_news_meta(marker,created_at) VALUES('initialized',?) ON CONFLICT(marker) DO UPDATE SET marker=excluded.marker").bind(now) + ]); +} +export async function drainDiscordNews(db,config,{fetcher=fetch,now=Date.now}={}){ + const webhook=validateNewsWebhook(config),time=now(); + // A timeout/crash after sending may already have posted. Never blindly duplicate it. + await db.prepare("UPDATE discord_news_delivery SET state='uncertain',last_error='Interrupted delivery requires review' WHERE state='sending' AND claimed_at{await db.prepare('UPDATE discord_news_delivery SET state=?,message_id=?,next_at=?,last_error=? WHERE post_id=? AND claim_token=?').bind(state,message,next,error,job.post_id,token).run();states.push(state);}; + if(!post){await finish('withdrawn');continue;} + try{ + const response=await fetcher(webhook+'?wait=true',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(newsWebhookPayload(post)),signal:AbortSignal.timeout(15000),redirect:'error'}); + if(response.status===429){let seconds=60;try{seconds=Math.max(1,Math.min(3600,Number((await response.json()).retry_after)||60));}catch{}await finish('retry','',time+seconds*1000,'Rate limited');continue;} + if(!response.ok){await finish(response.status>=500?'uncertain':'failed','','0','Discord HTTP '+response.status);continue;} + let result;try{result=await response.json();}catch{} + if(!/^\d+$/.test(String(result?.id||''))){await finish('uncertain','','0','No confirmed message ID');continue;} + await finish('sent',String(result.id)); + }catch{await finish('uncertain','','0','Delivery outcome unknown; review before retry');} + } + return states; +} +export async function startDiscordNewsWorker(db,settings=process.env,{logger=console}={}){ + const file=settings.DISCORD_NEWS_CONFIG_FILE;if(!file)return()=>{}; + let config;try{config=JSON.parse(await readFile(file,'utf8'));validateNewsWebhook(config);await initializeDiscordNews(db);}catch{logger.warn('Discord news worker unavailable; check private configuration');return()=>{};} + let stopped=false,busy=false;const tick=async()=>{if(stopped||busy)return;busy=true;try{await drainDiscordNews(db,config);}catch{logger.warn('Discord news queue check failed');}finally{busy=false;}}; + const timer=setInterval(tick,10000);timer.unref?.();void tick();return()=>{stopped=true;clearInterval(timer);}; +} diff --git a/website/node/server.mjs b/website/node/server.mjs index 5e0eb10f..8064b0e3 100644 --- a/website/node/server.mjs +++ b/website/node/server.mjs @@ -1,3 +1,4 @@ +import {startDiscordNewsWorker} from './discord-news.mjs'; import {createPublicKitMarket} from './kit-catalogue.mjs'; import {retiredTicketResponse} from './retired-tickets.mjs'; import {startNativeSyncRetryWorker} from './native-sync-outbox.mjs'; @@ -76,6 +77,7 @@ export function createApplication(db,settings={}) { } export async function start(settings=process.env) { const db=await openDatabase(settings);await initializeGitIdentities(db);await initializeMailIdentities(db);await initializeRanks(db);await initializeBadges(db);await initializeNews(db);const handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin; + const stopDiscordNews=await startDiscordNewsWorker(db,settings); const stopGitSync=startGitIdentitySync(db,settings),stopMailSync=startStaffMailSync(db),stopNativeSync=startNativeSyncRetryWorker(db); const forgejo=createForgejoProxy(settings,gitProxyIdentity(db,settings)); const server=createServer(async(req,res)=>{ @@ -91,7 +93,7 @@ export async function start(settings=process.env) { server.requestTimeout=300000;server.headersTimeout=10000; await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(Number(settings.PORT||3000),'127.0.0.1',resolve);}); console.log('DuneRealms website running on localhost:'+Number(settings.PORT||3000)+'; MySQL connected.'); - const shutdown=()=>{stopGitSync();stopMailSync();stopNativeSync();server.close(async()=>{await db.close();process.exit(0);});};process.once('SIGTERM',shutdown);process.once('SIGINT',shutdown); + const shutdown=()=>{stopDiscordNews();stopGitSync();stopMailSync();stopNativeSync();server.close(async()=>{await db.close();process.exit(0);});};process.once('SIGTERM',shutdown);process.once('SIGINT',shutdown); return server; } if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)await start(); diff --git a/website/tests/discord-news.test.mjs b/website/tests/discord-news.test.mjs new file mode 100644 index 00000000..fcca153b --- /dev/null +++ b/website/tests/discord-news.test.mjs @@ -0,0 +1,15 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {LocalD1}from './d1-adapter.mjs'; +import {initializeDiscordNews,drainDiscordNews,newsWebhookPayload,validateNewsWebhook}from '../node/discord-news.mjs'; +const config={url:'https://discord.com/api/webhooks/123/fake_token',channelId:'1567237542040834250',guildId:'1567229433033531462'}; +function db(){return new LocalD1('CREATE TABLE website_posts(id CHAR(36) PRIMARY KEY,title TEXT,body TEXT,category TEXT,status TEXT,published_at BIGINT)');} +async function post(d,id,status='published',date=1000){await d.prepare('INSERT INTO website_posts VALUES(?,?,?,?,?,?)').bind(id,'A public article','A short summary for the community.','news',status,date).run();} +const sent=()=>Response.json({id:'123456789012345678'}); +test('old posts baseline once; new publication sends once despite edits/restarts',async()=>{const d=db();try{await post(d,'old');await initializeDiscordNews(d,2000);await post(d,'new');let calls=0;const opt={now:()=>3000,fetcher:async()=>{calls++;return sent();}};assert.deepEqual(await drainDiscordNews(d,config,opt),['sent']);await initializeDiscordNews(d,4000);await d.prepare("UPDATE website_posts SET title='Edited' WHERE id='new'").run();await drainDiscordNews(d,config,opt);assert.equal(calls,1);assert.equal((await d.prepare("SELECT state FROM discord_news_delivery WHERE post_id='old'").first()).state,'baseline');}finally{d.close();}}); +test('draft, archived, future and withdrawn articles are not posted',async()=>{const d=db();try{await initializeDiscordNews(d,0);for(const status of ['draft','archived','deleted'])await post(d,status,status);await post(d,'future','published',5000);let calls=0;await drainDiscordNews(d,config,{now:()=>2000,fetcher:async()=>{calls++;return sent();}});assert.equal(calls,0);await d.prepare("UPDATE website_posts SET status='published' WHERE id='draft'").run();assert.deepEqual(await drainDiscordNews(d,config,{now:()=>2000,fetcher:async()=>{calls++;return sent();}}),['sent']);assert.equal(calls,1);}finally{d.close();}}); +test('concurrent drainers claim one delivery',async()=>{const d=db();try{await initializeDiscordNews(d,0);await post(d,'new');let calls=0;const opt={now:()=>2000,fetcher:async()=>{calls++;return sent();}};await Promise.all([drainDiscordNews(d,config,opt),drainDiscordNews(d,config,opt)]);assert.equal(calls,1);}finally{d.close();}}); +test('429 honours retry delay; uncertain outcomes never automatically duplicate',async()=>{const d=db();try{await initializeDiscordNews(d,0);await post(d,'rate');let calls=0;let clock=2000;const opt={now:()=>clock,fetcher:async()=>{calls++;return calls===1?Response.json({retry_after:2},{status:429}):sent();}};assert.deepEqual(await drainDiscordNews(d,config,opt),['retry']);await drainDiscordNews(d,config,opt);assert.equal(calls,1);clock=4001;assert.deepEqual(await drainDiscordNews(d,config,opt),['sent']);await post(d,'uncertain');await drainDiscordNews(d,config,{now:()=>5000,fetcher:async()=>{throw Error('timeout secret URL must not be stored');}});await drainDiscordNews(d,config,{now:()=>9000,fetcher:async()=>{throw Error('must not retry');}});const row=await d.prepare("SELECT * FROM discord_news_delivery WHERE post_id='uncertain'").first();assert.equal(row.state,'uncertain');assert.equal(row.attempts,1);assert(!row.last_error.includes('secret'));}finally{d.close();}}); +test('HTTP failures and unconfirmed success do not claim delivered',async()=>{for(const [response,state]of [[new Response('',{status:403}),'failed'],[new Response('',{status:503}),'uncertain'],[Response.json({}),'uncertain']]){const d=db();try{await initializeDiscordNews(d,0);await post(d,'n');assert.deepEqual(await drainDiscordNews(d,config,{now:()=>2000,fetcher:async()=>response}),[state]);}finally{d.close();}}}); +test('interrupted sends become uncertain; withdrawn queued post stays private',async()=>{const d=db();try{await initializeDiscordNews(d,0);await post(d,'a','draft');await d.prepare("INSERT INTO discord_news_delivery(post_id,state,claimed_at) VALUES('crash','sending',1)").run();await d.prepare("INSERT INTO discord_news_delivery(post_id,state) VALUES('a','queued')").run();assert.deepEqual(await drainDiscordNews(d,config,{now:()=>200000,fetcher:async()=>{throw Error('No send expected');}}),['withdrawn']);assert.equal((await d.prepare("SELECT state FROM discord_news_delivery WHERE post_id='crash'").first()).state,'uncertain');}finally{d.close();}}); +test('payload suppresses mentions and uses canonical public artwork/article URLs',()=>{const body=newsWebhookPayload({id:'00000000-0000-4000-8000-000000000001',title:'New @everyone dispatch',body:' **Hello** [traveller](https://example.com)',category:'../../private',published_at:1000});assert.deepEqual(body.allowed_mentions,{parse:[]});assert(body.embeds[0].url.startsWith('https://www.dunerealms.com/news/'));assert.equal(body.embeds[0].image.url,'https://www.dunerealms.com/assets/news-news.webp');assert(!body.embeds[0].description.includes('