diff --git a/tools/install-shared-chrome-publication.py b/tools/install-shared-chrome-publication.py new file mode 100644 index 00000000..81d03407 --- /dev/null +++ b/tools/install-shared-chrome-publication.py @@ -0,0 +1,40 @@ +"""Install the existing canonical chrome publisher after successful promotion.""" +from pathlib import Path +import argparse +import os +import subprocess + +CURRENT = Path('/home/dunerealms/apps/dunerealms/current') +RELEASES = Path('/home/dunerealms/apps/dunerealms/releases') +DROPIN = Path('/etc/systemd/system/dunerealms-ci-promote.service.d/30-shared-chrome.conf') + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--apply', action='store_true') + args = parser.parse_args() + release = CURRENT.resolve(strict=True) + if not release.is_relative_to(RELEASES) or not release.name.startswith('ci-'): + raise RuntimeError('Unexpected live release directory') + publisher = release / 'scripts/publish-shared-chrome.py' + if not publisher.is_file(): + raise RuntimeError('Canonical publisher missing from live release') + if not args.apply: + print('Publish canonical navigation and keep native headers current after deployment.') + return + if os.geteuid() != 0: + raise RuntimeError('Deployment operator required') + # This is the existing file publisher: no application restart or DB write. + subprocess.run(['/usr/bin/python3', str(publisher), '--apply'], check=True) + DROPIN.parent.mkdir(parents=True, exist_ok=True) + command = '[Service]\nExecStartPost=/usr/bin/python3 ' + str(CURRENT / 'scripts/publish-shared-chrome.py') + ' --apply\n' + if DROPIN.exists() and DROPIN.read_text() != command: + raise RuntimeError('Existing publication override differs; inspect before replacing') + temporary = DROPIN.with_suffix('.new') + temporary.write_text(command) + temporary.chmod(0o644) + os.replace(temporary, DROPIN) + subprocess.run(['/usr/bin/systemctl', 'daemon-reload'], check=True) + print('Shared forum/support navigation published; future promotions will refresh it.') + +if __name__ == '__main__': + main() diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index a92c0a06..01a9c107 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,3 +1,4 @@ +import {GAZETTE_SCHEMA} from '../node/jarvis-gazette.mjs'; import {ECONOMIC_SNAPSHOT_SCHEMA} from '../node/jarvis-economic-snapshots.mjs'; import {initializeProgression} from '../node/progression-schema.mjs'; import {ensureProgressionPolicy} from '../node/progression-policy.mjs'; @@ -424,9 +425,9 @@ export async function startPanel(settings=process.env){ inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); } const bankDatabase=await openPostbankDatabase(settings); - const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys);await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await ensureProgressionPolicy(db,organisationKeys);const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const handle=createPanel(db,settings,{inventoryPool,bankDatabase,organisationKeys,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const db=await openDatabase(settings);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys);await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;await initializeProgression(db);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const handle=createPanel(db,settings,{inventoryPool,bankDatabase,organisationKeys,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; await initializeInternalMailAccess(db);const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db); - const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:bankDatabase?[{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:()=>progressionRuntime.quests.processCompletions()},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[]}); + const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:bankDatabase?[{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[]}); const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':"default-src 'self'; script-src 'self' https://www.dunerealms.com; style-src 'self' https://www.dunerealms.com https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://www.dunerealms.com; img-src 'self' data: https://www.dunerealms.com https://support.dunerealms.com; frame-src 'self' https://luckperms.net https://www.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com https://clans.dunerealms.com https://corp.dunerealms.com https://wiki.dunerealms.com; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://clans.dunerealms.com"}; const server=createServer(async(req,res)=>{try{ req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);} diff --git a/website/node/discord-news.mjs b/website/node/discord-news.mjs index bb6ed5cb..e213e66e 100644 --- a/website/node/discord-news.mjs +++ b/website/node/discord-news.mjs @@ -1,4 +1,5 @@ import {readFile} from 'node:fs/promises'; +import {GAZETTE_NAME} from './jarvis-gazette.mjs'; import {randomUUID} from 'node:crypto'; import {newsPath} from './search-visibility.mjs'; const ORIGIN='https://www.dunerealms.com'; @@ -6,7 +7,7 @@ const categories=new Set(['world','news','maintenance','changelogs','events','co 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',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')+' • DuneRealms'},timestamp:new Date(Number(post.published_at)).toISOString()}]}; + 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'}={}){ 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!==channelId||config.guildId!=='1567229433033531462')throw Error('Invalid news webhook configuration'); diff --git a/website/node/forum-news.mjs b/website/node/forum-news.mjs index d1a3b020..6f4e904c 100644 --- a/website/node/forum-news.mjs +++ b/website/node/forum-news.mjs @@ -1,4 +1,5 @@ import {execFile} from 'node:child_process'; +import {GAZETTE_NAME} from './jarvis-gazette.mjs'; import {existsSync} from 'node:fs'; import {createHash,randomUUID} from 'node:crypto'; export async function initializeForumNews(db){ @@ -9,7 +10,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',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:2} :{id:row.id,status:'archived'}; return {...post,revision:createHash('sha256').update(JSON.stringify(post)).digest('hex')}; } diff --git a/website/node/jarvis-gazette.mjs b/website/node/jarvis-gazette.mjs new file mode 100644 index 00000000..985d413b --- /dev/null +++ b/website/node/jarvis-gazette.mjs @@ -0,0 +1,36 @@ +import {createHash} from 'node:crypto'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +import {OFFICIAL_ACCOUNT} from './official-account.mjs'; +export const GAZETTE_NAME='J.A.R.V.I.S. Gazette'; +// Domain adapters publish confirmed public facts, never arbitrary audit rows. +export const GAZETTE_EVENT_TYPES=Object.freeze([ + 'project-approved','election-announced','election-result','war-declared','peace-agreed', + 'clan-ownership','company-ownership','server-event','progression-milestone' +]); +export function gazetteEventEligible(event){ + return !!event&&GAZETTE_EVENT_TYPES.includes(event.type)&&event.visibility==='public'&&event.confirmed===true&&typeof event.sourceId==='string'&&event.sourceId.length>0; +} +export const GAZETTE_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_gazette_records(id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,event_type VARCHAR(32) NOT NULL,source_id VARCHAR(160) NOT NULL,post_id CHAR(36) NOT NULL UNIQUE,payload_json TEXT NOT NULL,payload_hash CHAR(64) NOT NULL,created_at BIGINT NOT NULL,UNIQUE KEY gazette_source(event_type,source_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`; +const hash=value=>createHash('sha256').update(value).digest('hex'); +const recordId=(type,source)=>{const h=hash(JSON.stringify([type,source]));return h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);}; +// The trusted domain adapter supplies a public projection of confirmed facts. +// Existing editorial workers handle delivery; this creates no second outbox. +export function createGazettePublisher(db,keys,{authorize,resolve,clock=Date.now}){ + if(typeof authorize!=='function'||typeof resolve!=='function')throw TypeError('Gazette domain adapters required'); + return Object.freeze({async publish(actor,event){ + if(!gazetteEventEligible(event)||event.sourceId.length>160)throw TypeError('Confirmed public Gazette event required'); + const id=recordId(event.type,event.sourceId); + const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'gazette-news',scopeId:'news:'+id+':v1',authorize:async(tx,{keyId})=>{ + if(!await authorize(actor,event,tx))throw Error('Gazette publication authority required'); + const existing=await tx.first('SELECT payload_json,payload_hash FROM jarvis_gazette_records WHERE id=? FOR UPDATE',[id]); + if(existing){if(hash(existing.payload_json)!==existing.payload_hash)throw Error('Gazette record integrity check failed');return;} + const fact=await resolve(event,tx),now=clock(); + if(!fact||typeof fact.title!=='string'||!fact.title.trim()||fact.title.length>120||typeof fact.body!=='string'||!fact.body.trim()||fact.body.length>12000||!['news','world','events','community'].includes(fact.category)||!Number.isSafeInteger(fact.occurredAt)||fact.occurredAt<0||fact.occurredAt>now)throw Error('Gazette source is not a confirmed public fact'); + const payload={type:event.type,sourceId:event.sourceId,title:fact.title,body:fact.body,category:fact.category,occurredAt:fact.occurredAt,publisher:GAZETTE_NAME}; + const json=JSON.stringify(payload); + await tx.query('INSERT INTO website_posts(id,source_key,category,title,body,status,author_id,created_at,updated_at,published_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,1)',[id,'gazette:'+id,fact.category,fact.title,fact.body,'published',OFFICIAL_ACCOUNT.id,now,now,now]); + await tx.query('INSERT INTO jarvis_gazette_records(id,key_id,event_type,source_id,post_id,payload_json,payload_hash,created_at) VALUES(?,?,?,?,?,?,?,?)',[id,keyId,event.type,event.sourceId,id,json,hash(json),now]); + }}); + return {postId:id,keyId:grant.id,created:grant.created,sealed:true}; + }}); +} diff --git a/website/node/jarvis-promotions.mjs b/website/node/jarvis-promotions.mjs index db8500e4..ae0db855 100644 --- a/website/node/jarvis-promotions.mjs +++ b/website/node/jarvis-promotions.mjs @@ -1,4 +1,5 @@ import {mirrorPublicServerEvents} from './jarvis-event-publication.mjs'; +import {GAZETTE_NAME} from './jarvis-gazette.mjs'; import {currentCodexEdition} from './organisation-key-service.mjs'; import {campaignDestination} from './election-campaigns.mjs'; import {readFile} from 'node:fs/promises';import {execFile} from 'node:child_process';import {fileURLToPath} from 'node:url';import {createHash,randomUUID} from 'node:crypto'; @@ -15,7 +16,7 @@ export function createPromotionDelivery(central,bank,{config=null,sendForum=nati for(const row of rows){if(attempted>=5)break;if(!channels.includes(row.channel))continue;let closed=row.state!=='open'||row.campaign_end!=null&&Number(row.campaign_end)<=now||row.job_end!=null&&Number(row.job_end)<=now;if(!closed&&row.source_term_id)closed=!await central.prepare("SELECT id FROM political_office_terms WHERE id=? AND outcome='winner' AND starts_at<=? AND expires_at>?").bind(row.source_term_id,now,now).first();const payload=promotionPayload(row,closed);if(row.revision_hash===payload.revision){await bank.query("UPDATE jarvis_promotion_jobs SET next_attempt=? WHERE id=? AND state='sent'",[now+60000,row.job_id]);continue;}if(closed&&!row.reference_id){await bank.query("UPDATE jarvis_promotion_jobs SET state='cancelled' WHERE id=? AND state IN ('queued','retry')",[row.job_id]);continue;}const token=randomUUID(); const claimed=await bank.transaction(async tx=>{const job=await tx.first('SELECT state FROM jarvis_promotion_jobs WHERE id=? FOR UPDATE',[row.job_id]);if(!job||!['queued','retry','sent'].includes(job.state))return false;const delivered=await tx.first('SELECT reference_id,revision_hash FROM jarvis_promotion_delivery WHERE job_id=? FOR UPDATE',[row.job_id]);if(delivered?.revision_hash===payload.revision)return false;if(delivered?.reference_id)row.reference_id=delivered.reference_id;await tx.query("INSERT INTO jarvis_promotion_delivery(job_id,claim_token,claimed_at) VALUES(?,?,?) ON DUPLICATE KEY UPDATE claim_token=VALUES(claim_token),claimed_at=VALUES(claimed_at)",[row.job_id,token,now]);await tx.query("UPDATE jarvis_promotion_jobs SET state='sending',attempts=attempts+1 WHERE id=?",[row.job_id]);return true;});if(!claimed)continue;attempted++; const finish=async(state,{reference=row.reference_id||'',hash=row.revision_hash||'',error='',next=now}={})=>bank.transaction(async tx=>{const own=await tx.first('SELECT claim_token FROM jarvis_promotion_delivery WHERE job_id=? FOR UPDATE',[row.job_id]);if(own?.claim_token!==token)return;await tx.query('UPDATE jarvis_promotion_delivery SET reference_id=?,revision_hash=?,last_error=?,claim_token=\'\' WHERE job_id=?',[reference,hash,error,row.job_id]);await tx.query('UPDATE jarvis_promotion_jobs SET state=?,next_attempt=? WHERE id=?',[state,next,row.job_id]);}); - try{let reference;if(row.channel==='boards'){const result=await sendForum({action:'publish',...payload,jobId:row.job_id});if(!Number.isSafeInteger(result.threadId)||result.threadId<1||result.revision!==payload.revision)throw Error('Unconfirmed forum post');reference=String(result.threadId);}else{const endpoint=webhook+(row.reference_id?'/messages/'+row.reference_id:'?wait=true'),body={username:'Jarvis · DuneRealms Starport',allowed_mentions:{parse:[]},embeds:[{title:(closed?'[CLOSED] ':'')+payload.title,description:payload.message.slice(0,1800),url:payload.url,color:0xc6a551,footer:{text:payload.owner+' · J.A.R.V.I.S.'}}]};if(row.reference_id)delete body.username;const response=await fetcher(endpoint,{method:row.reference_id?'PATCH':'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body),signal:AbortSignal.timeout(15000),redirect:'error'});if(response.status===429){const result=await response.json().catch(()=>({}));await finish('retry',{error:'Rate limited',next:now+Math.max(1000,Math.min(3600000,Number(result.retry_after||60)*1000))});continue;}if(!response.ok){await finish(response.status>=500?'uncertain':'failed',{error:'Discord HTTP '+response.status});failed++;continue;}const result=await response.json();if(!/^\d+$/.test(String(result.id||'')))throw Error('Unconfirmed Discord response');reference=String(result.id);} + try{let reference;if(row.channel==='boards'){const result=await sendForum({action:'publish',...payload,jobId:row.job_id});if(!Number.isSafeInteger(result.threadId)||result.threadId<1||result.revision!==payload.revision)throw Error('Unconfirmed forum post');reference=String(result.threadId);}else{const endpoint=webhook+(row.reference_id?'/messages/'+row.reference_id:'?wait=true'),body={username:GAZETTE_NAME,allowed_mentions:{parse:[]},embeds:[{title:(closed?'[CLOSED] ':'')+payload.title,description:payload.message.slice(0,1800),url:payload.url,color:0xc6a551,footer:{text:payload.owner+' · '+GAZETTE_NAME}}]};if(row.reference_id)delete body.username;const response=await fetcher(endpoint,{method:row.reference_id?'PATCH':'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body),signal:AbortSignal.timeout(15000),redirect:'error'});if(response.status===429){const result=await response.json().catch(()=>({}));await finish('retry',{error:'Rate limited',next:now+Math.max(1000,Math.min(3600000,Number(result.retry_after||60)*1000))});continue;}if(!response.ok){await finish(response.status>=500?'uncertain':'failed',{error:'Discord HTTP '+response.status});failed++;continue;}const result=await response.json();if(!/^\d+$/.test(String(result.id||'')))throw Error('Unconfirmed Discord response');reference=String(result.id);} await finish(closed?'closed':'sent',{reference,hash:payload.revision,next:now+60000});sent++; }catch{await finish(row.channel==='boards'?'retry':'uncertain',{error:row.channel==='boards'?'Native forum reconciliation pending':'Outcome unknown; review before retry',next:now+60000});failed++;} }return{sent,failed}; diff --git a/website/node/news.mjs b/website/node/news.mjs index 8828fce2..39328508 100644 --- a/website/node/news.mjs +++ b/website/node/news.mjs @@ -1,4 +1,5 @@ import {nativeForumFeed} from './native-forum-feed.mjs'; +import {GAZETTE_NAME} from './jarvis-gazette.mjs'; import {randomUUID} from 'node:crypto'; import {readFile} from 'node:fs/promises'; import {json} from './game-link.mjs'; @@ -27,11 +28,11 @@ export function createPublicNews(db){return async request=>{ try{return json(await nativeForumFeed(page));}catch{return json({message:'Forum updates are temporarily unavailable.'},503);} } const match=url.pathname.match(/^\/api\/news\/([0-9a-f-]{36})$/i); - if(match){const post=await db.prepare("SELECT p.id,p.title,p.body,p.category,p.published_at,c.label,c.artwork,COALESCE(a.display_name,a.username,'DuneRealms') AS author_name FROM website_posts p JOIN website_post_categories c ON c.category_key=p.category LEFT JOIN site_accounts a ON a.id=p.author_id WHERE p.id=? AND p.status='published' AND p.published_at<=?").bind(match[1],Date.now()).first();return post?json({post:(await forumLinks(db,[post]))[0]}):json({message:'Post not found'},404);} + if(match){const post=await db.prepare("SELECT p.id,p.title,p.body,p.category,p.published_at,c.label,c.artwork,COALESCE(a.display_name,a.username,'DuneRealms') AS author_name FROM website_posts p JOIN website_post_categories c ON c.category_key=p.category LEFT JOIN site_accounts a ON a.id=p.author_id WHERE p.id=? AND p.status='published' AND p.published_at<=?").bind(match[1],Date.now()).first();return post?json({post:(await forumLinks(db,[{...post,publisher:GAZETTE_NAME}]))[0]}):json({message:'Post not found'},404);} if(url.pathname!=='/api/news')return json({message:'Not found'},404); const page=Number(url.searchParams.get('page')||1),archive=url.searchParams.get('surface')==='archive',size=archive?25:5; if(!Number.isSafeInteger(page)||page<1||page>1000000)return json({message:'Invalid page'},400); const count=await db.prepare("SELECT COUNT(*) AS count FROM website_posts WHERE status='published' AND published_at<=?").bind(Date.now()).first(); const {results}=await db.prepare("SELECT p.id,p.title,p.body,p.category,p.published_at,c.label,c.artwork,COALESCE(a.display_name,a.username,'DuneRealms') AS author_name FROM website_posts p JOIN website_post_categories c ON c.category_key=p.category LEFT JOIN site_accounts a ON a.id=p.author_id WHERE p.status='published' AND p.published_at<=? ORDER BY p.published_at DESC,p.id DESC LIMIT ? OFFSET ?").bind(Date.now(),size,(page-1)*size).all(); - return json({posts:await forumLinks(db,results.map(p=>({...p,body:publicNewsExcerpt(p.body)}))),page,pages:Math.max(1,Math.ceil(Number(count.count)/size)),total:Number(count.count)}); + return json({posts:await forumLinks(db,results.map(p=>({...p,publisher:GAZETTE_NAME,body:publicNewsExcerpt(p.body)}))),page,pages:Math.max(1,Math.ceil(Number(count.count)/size)),total:Number(count.count)}); };} diff --git a/website/node/progression-milestone-news.mjs b/website/node/progression-milestone-news.mjs new file mode 100644 index 00000000..72513369 --- /dev/null +++ b/website/node/progression-milestone-news.mjs @@ -0,0 +1,18 @@ +import {createGazettePublisher} from './jarvis-gazette.mjs'; +export function createProgressionMilestoneNews(db,keys,{clock=Date.now}={}){ + const publisherIdentity=Object.freeze({source:'progression-milestones'}); + const publisher=createGazettePublisher(db,keys,{clock,authorize:async actor=>actor===publisherIdentity,resolve:async(event,tx)=>{ + const row=await tx.first("SELECT o.account_id,o.season_id,o.purpose,o.created_at,a.username,a.display_name,p.level_no,s.level_cap FROM jarvis_progression_outbox o JOIN site_accounts a ON a.id=o.account_id JOIN jarvis_progression_accounts p ON p.account_id=o.account_id JOIN jarvis_progression_seasons s ON s.season_id=o.season_id WHERE o.id=? FOR UPDATE",[event.sourceId]); + if(!row)return null;const level=Number(row.purpose.slice(6));if(!['level-'+Math.max(1,Math.floor(Number(row.level_cap)/2)),'level-'+row.level_cap].includes(row.purpose)||Number(row.level_no){ + for(const type of GAZETTE_EVENT_TYPES)assert(gazetteEventEligible({type,visibility:'public',confirmed:true,sourceId:'reference'})); + assert(!gazetteEventEligible({type:'election-result',visibility:'private',confirmed:true,sourceId:'reference'})); + assert(!gazetteEventEligible({type:'election-result',visibility:'public',confirmed:'true',sourceId:'reference'})); + assert(!gazetteEventEligible({type:'private-support-case',visibility:'public',confirmed:true,sourceId:'reference'})); +}); + +test('confirmed Gazette facts reuse the editorial register and have one sealed, nonredeemable news instrument',async()=>{ + const f=await companyFixture();try{ + await f.db.query(GAZETTE_SCHEMA);await f.db.query('CREATE TABLE website_posts(id TEXT PRIMARY KEY,source_key TEXT UNIQUE,category TEXT,title TEXT,body TEXT,status TEXT,author_id TEXT,created_at INT,updated_at INT,published_at INT,version INT)'); + const actor={},event={type:'project-approved',sourceId:randomUUID(),visibility:'public',confirmed:true};let resolveCount=0; + const service=createGazettePublisher(f.db,f.keys,{clock:()=>2000,authorize:async who=>who===actor,resolve:async()=>{resolveCount++;return{title:'A new server project',body:'A confirmed public project.',category:'news',occurredAt:1000};}}); + await assert.rejects(service.publish({},event),/authority/);assert.equal((await f.db.query('SELECT id FROM website_posts')).length,0); + const first=await service.publish(actor,event),again=await service.publish(actor,event); + assert.equal(first.created,true);assert.equal(again.created,false);assert.equal(first.postId,again.postId);assert.equal(resolveCount,1);assert.equal(first.code,undefined); + assert.equal((await f.db.query('SELECT id FROM website_posts')).length,1);assert.equal((await f.db.query('SELECT id FROM jarvis_gazette_records')).length,1); + await assert.rejects(f.keys.consume({keyType:'gazette-news'}),/sealed system records/i); + }finally{f.db.close();} +}); + +test('unconfirmed or private facts cannot create news; invalid domain projections roll back their keys',async()=>{ + const f=await companyFixture();try{ + await f.db.query(GAZETTE_SCHEMA);const service=createGazettePublisher(f.db,f.keys,{authorize:async()=>true,resolve:async()=>null}); + await assert.rejects(service.publish({}, {type:'election-result',sourceId:'one',visibility:'private',confirmed:true}),/Confirmed public/); + await assert.rejects(service.publish({}, {type:'election-result',sourceId:'one',visibility:'public',confirmed:true}),/confirmed public fact/); + assert.equal((await f.db.query("SELECT id FROM organisation_keys WHERE key_type='gazette-news'")).length,0); + }finally{f.db.close();} +}); +test('Gazette branding retains human author attribution and blocks mentions',()=>{ + const payload=newsWebhookPayload({id:'test',title:'Confirmed project',body:'Public facts',category:'news',published_at:1,author_name:'Editor'}); + assert.equal(payload.username,GAZETTE_NAME);assert.match(payload.embeds[0].footer.text,/Editor/);assert.match(payload.embeds[0].footer.text,/Gazette/);assert.deepEqual(payload.allowed_mentions,{parse:[]}); +}); diff --git a/website/tests/progression-milestone-news.test.mjs b/website/tests/progression-milestone-news.test.mjs new file mode 100644 index 00000000..b1e50ccc --- /dev/null +++ b/website/tests/progression-milestone-news.test.mjs @@ -0,0 +1,19 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs'; +import {initializeProgression} from '../node/progression-schema.mjs'; +import {GAZETTE_SCHEMA} from '../node/jarvis-gazette.mjs'; +import {createProgressionMilestoneNews} from '../node/progression-milestone-news.mjs'; +test('halfway and completion publish once through existing news, while ordinary levels never become public',async()=>{ + const f=await companyFixture();try{ + await initializeProgression(f.db);await f.db.query(GAZETTE_SCHEMA); + await f.db.query('CREATE TABLE website_posts(id TEXT PRIMARY KEY,source_key TEXT UNIQUE,category TEXT,title TEXT,body TEXT,status TEXT,author_id TEXT,created_at INT,updated_at INT,published_at INT,version INT)'); + await f.db.query("INSERT INTO jarvis_progression_seasons(season_id,starts_at,ends_at,level_cap,curve_base,state) VALUES('S01',0,10000,70,25,'active')"); + await f.db.query('INSERT INTO jarvis_progression_accounts(account_id,total_xp,effective_xp,level_no,version,updated_at) VALUES(?,60375,60375,70,1,1000)',[f.people.Member.id]); + for(const purpose of ['level-35','level-70','level-3'])await f.db.query("INSERT INTO jarvis_progression_outbox(id,account_id,season_id,purpose,payload_json,state,created_at) VALUES(?,?,'S01',?,'{}','queued',1000)",[randomUUID(),f.people.Member.id,purpose]); + const worker=createProgressionMilestoneNews(f.db,f.keys,{clock:()=>2000}); + assert.deepEqual(await worker.drain(),{published:2,failed:1}); + assert.deepEqual(await worker.drain(),{published:0,failed:1}); + const posts=await f.db.query('SELECT title,body FROM website_posts');assert.equal(posts.length,2);assert(posts.some(p=>p.title.endsWith('level 35')));assert(posts.some(p=>p.title.endsWith('level 70'))); + assert(posts.every(p=>!p.body.includes(f.people.Member.id)));assert.equal((await f.db.query('SELECT id FROM jarvis_gazette_records')).length,2); + }finally{f.db.close();} +}); diff --git a/website/web/exchange.html b/website/web/exchange.html index f9f23735..8cfa8019 100644 --- a/website/web/exchange.html +++ b/website/web/exchange.html @@ -1 +1 @@ -Interplanetary Exchange — dunerealms.com

Opening the Exchange…

+Interplanetary Exchange — dunerealms.com

Opening the Exchange…

J.A.R.V.I.S. Gazette

Confirmed milestones and news from across the realm.

diff --git a/website/web/home-news.js b/website/web/home-news.js index 2bca39d0..40139ed5 100644 --- a/website/web/home-news.js +++ b/website/web/home-news.js @@ -1,7 +1,7 @@ const newsEl=(tag,text)=>{const el=document.createElement(tag);if(text!==undefined)el.textContent=text;return el;}; const newsDate=n=>new Date(Number(n)).toLocaleDateString(undefined,{year:'numeric',month:'short',day:'numeric'}); async function newsFetch(path){const response=await fetch(path,{cache:'no-store'});if(!response.ok)throw Error('Updates are temporarily unavailable. Please try again later.');return response.json();} -function newsCard(post,forum=false){const card=newsEl('article');card.className='dispatch-card';const image=newsEl('img');image.src=forum?'assets/nav-boards-full-v2.webp':'assets/nav-discord-full-v2.webp';image.alt='';image.loading='lazy';image.width=1672;image.height=941;const content=newsEl('div');content.className='dispatch-copy';content.append(newsEl('span',forum?'COMMUNITY':post.label),newsEl('small',newsDate(forum?post.last_activity_at:post.published_at)));const title=newsEl('h3'),link=newsEl('a',post.title);link.title=post.title;link.href=forum?post.url:'news-archive.html?post='+post.id;title.append(link);content.append(title,newsEl('p',forum?post.excerpt:post.body.split(/\n\s*\n/)[0]));const more=newsEl('a',forum?'Read discussion →':'Read more →');more.className='dispatch-read-more';more.href=link.href;content.append(more);card.append(image,content);return card;} +function newsCard(post,forum=false){const card=newsEl('article');card.className='dispatch-card';const image=newsEl('img');image.src=forum?'assets/nav-boards-full-v2.webp':'assets/nav-discord-full-v2.webp';image.alt='';image.loading='lazy';image.width=1672;image.height=941;const content=newsEl('div');content.className='dispatch-copy';content.append(newsEl('span',forum?'COMMUNITY':post.label),newsEl('small',newsDate(forum?post.last_activity_at:post.published_at)));const title=newsEl('h3'),link=newsEl('a',post.title);link.title=post.title;link.href=forum?post.url:'news-archive.html?post='+post.id;title.append(link);content.append(title,newsEl('p',forum?post.excerpt:post.body.split(/\n\s*\n/)[0]));if(!forum&&post.publisher)content.append(newsEl('small',post.publisher));const more=newsEl('a',forum?'Read discussion →':'Read more →');more.className='dispatch-read-more';more.href=link.href;content.append(more);card.append(image,content);return card;} function newsModule(root,kind){let page=1,generation=0;const archive=root.dataset.archive==='true',grid=newsEl('div');grid.className='dispatch-grid';grid.setAttribute('aria-live','polite');const controls=newsEl('nav');controls.className='dispatch-pagination';controls.setAttribute('aria-label',kind==='forum'?'Latest forum posts pages':'News pages');const prev=newsEl('button','← Previous'),state=newsEl('span'),next=newsEl('button','Next →');prev.type=next.type='button';controls.append(prev,state,next);root.append(grid,controls); async function load(){const token=++generation;prev.disabled=next.disabled=true;state.textContent='Loading…';try{const data=await newsFetch(kind==='forum'?'/api/home/forum?page='+page:'/api/news?'+new URLSearchParams({page,surface:archive?'archive':'home'}));if(token!==generation)return;root.querySelector('[data-server-news]')?.remove();grid.replaceChildren();for(const post of data.posts)grid.append(newsCard(post,kind==='forum'));if(!data.posts.length)grid.append(newsEl('p',kind==='forum'?'No public discussions yet. Start one in the forums.':'No published news yet. Updates will appear here when released.'));state.textContent='Page '+page+' of '+Math.max(1,data.pages);prev.disabled=page<=1;next.disabled=page>=data.pages;}catch(error){if(token===generation){grid.replaceChildren(newsEl('p',error.message));state.textContent='Unavailable';}}} prev.onclick=()=>{page--;load();};next.onclick=()=>{page++;load();};root.addEventListener('keydown',event=>{if(event.target instanceof HTMLInputElement||event.target instanceof HTMLTextAreaElement)return;if(event.key==='ArrowLeft'&&!prev.disabled){event.preventDefault();prev.click();}if(event.key==='ArrowRight'&&!next.disabled){event.preventDefault();next.click();}});load(); @@ -29,7 +29,7 @@ if(fullPost&&postId){ const back=newsEl('a','← News archive');back.href='news-archive.html';back.className='article-back'; const head=newsEl('div');head.className='article-heading';const copy=newsEl('div'); const category=newsEl('span',post.label);category.className='article-category';const date=newsEl('time',newsDate(post.published_at));date.dateTime=new Date(Number(post.published_at)).toISOString(); - const meta=newsEl('div');meta.className='article-meta';meta.append(category,date);meta.append(newsEl('span','Written by '+(post.author_name||'DuneRealms')));copy.append(meta,newsEl('h1',post.title)); + const meta=newsEl('div');meta.className='article-meta';meta.append(category,date);meta.append(newsEl('span','Written by '+(post.author_name||'DuneRealms')));if(post.publisher)meta.append(newsEl('span',post.publisher));copy.append(meta,newsEl('h1',post.title)); const image=newsEl('img');const artKeys=['world','news','maintenance','changelogs','events','community'];image.src='assets/news-'+(artKeys.includes(post.category_key||post.category)?(post.category_key||post.category):'news')+'.webp';image.alt='Imperial dispatch artwork';image.width=360;image.height=240;head.append(copy,image); const body=newsEl('div');body.className='dispatch-full-body';formatNewsBody(body,post.body); const foot=newsEl('div');foot.className='article-actions';const all=newsEl('a','Browse all news →');all.href='news-archive.html';all.className='dispatch-read-more';foot.append(all);if(post.forum_url){const forum=newsEl('a','Go to forum post →');forum.href=post.forum_url;forum.className='dispatch-read-more';foot.append(forum);}