MC/website/node/jarvis-events.mjs
2026-11-27 23:43:05 +00:00

14 lines
6.4 KiB
JavaScript

import {createRealmEventRecord} from './realm-event-records.mjs';
import {randomUUID} from 'node:crypto';import {identity} from './auth.mjs';import {can} from './permissions.mjs';import {clanDeedAuthority} from './clan-deeds.mjs';import {readCompanyDeed,companyDeedView} from './company-deeds.mjs';import {createJarvisOrganisationContext} from './jarvis-organisation-context.mjs';
export const EVENT_SCHEMA=[`CREATE TABLE IF NOT EXISTS jarvis_events(id CHAR(36) PRIMARY KEY,request_id CHAR(36) NOT NULL UNIQUE,reference VARCHAR(40) NOT NULL UNIQUE,scope_kind VARCHAR(16) NOT NULL,scope_id VARCHAR(36) NOT NULL,title VARCHAR(100) NOT NULL,description TEXT NOT NULL,starts_at BIGINT NOT NULL,ends_at BIGINT NOT NULL,state VARCHAR(16) NOT NULL,revision INT NOT NULL,actor_id CHAR(36) NOT NULL,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,`CREATE TABLE IF NOT EXISTS jarvis_event_history(id CHAR(36) PRIMARY KEY,event_id CHAR(36) NOT NULL,actor_id CHAR(36) NOT NULL,action VARCHAR(16) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`];
export const EVENT_INSTRUMENT=Object.freeze({prefix:'EVT',purpose:'scheduled-event',redeemable:false,states:['scheduled','cancelled'],promotionPurpose:'event-publication'});
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
export function eventInput(body){if(!body||!['clan','company','politics','server'].includes(body.kind)||typeof body.scopeId!=='string'||!/^[a-z0-9_-]{1,36}$/i.test(body.scopeId)||!uuid(body.requestId)||body.confirmed!==true||typeof body.title!=='string'||body.title.trim().length<3||body.title.length>100||typeof body.description!=='string'||body.description.length>2000||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(body.title+body.description)||!Number.isSafeInteger(body.startsAt)||!Number.isSafeInteger(body.endsAt)||body.startsAt<0||body.endsAt<=body.startsAt)throw Object.assign(Error('Review the event title, dates and confirmation.'),{status:400});return{...body,title:body.title.trim()};}
export function createEventAuthority(central){const political=createJarvisOrganisationContext(central);return async(user,kind,id)=>{if(kind==='server')return id==='realm'&&await can(central,user,'cp.menu.administration');if(kind==='clan'){const r=await clanDeedAuthority(central,user.id,id);return !!r.canManage;}if(kind==='company')return companyDeedView(await readCompanyDeed(central,id),user.id).canManage;if(kind==='politics'){try{return (await political(user,{kind,id})).membershipSource==='active-office-deed';}catch{return false;}}return false;};}
const project=r=>({id:r.id,reference:r.reference,kind:r.scope_kind,scopeId:r.scope_id,title:r.title,description:r.description,startsAt:Number(r.starts_at),endsAt:Number(r.ends_at),state:r.state,revision:Number(r.revision)});
export function createRealmEvents(central,store,{authenticate=r=>identity(r,central),authorize=createEventAuthority(central),origin='https://cp.dunerealms.com',clock=Date.now,isManagedEvent=async()=>false}={}){const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});return async request=>{try{const user=await authenticate(request);if(!user)return reply({message:'Sign in to view events.'},401);if(!store)return reply({message:'J.A.R.V.I.S. event records are unavailable.'},503);const url=new URL(request.url);
if(request.method==='GET'){if([...url.searchParams.keys()].some(k=>!['kind','id'].includes(k)))return reply({message:'Invalid event scope.'},400);const kind=url.searchParams.get('kind'),id=url.searchParams.get('id');if(kind&&!['clan','company','politics','server'].includes(kind)||kind&&(!id||!/^[a-z0-9_-]{1,36}$/i.test(id)))return reply({message:'Choose an event scope.'},400);const rows=await store.query('SELECT * FROM jarvis_events WHERE ends_at>=?'+(kind?' AND scope_kind=? AND scope_id=?':'')+' ORDER BY starts_at,id LIMIT 501',[clock()-30*86400000,...(kind?[kind,id]:[])]);if(rows.length>500)return reply({message:'Narrow the calendar to an organisation.'},409);return reply({events:rows.map(project),canManage:kind?await authorize(user,kind,id):false,promotionChannels:[],instrument:EVENT_INSTRUMENT});}
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);if(url.search||request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);const raw=await request.text();if(raw.length>12000)return reply({message:'Event is too large.'},413);let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid event.'},400);}const input=eventInput(body);if(!await authorize(user,input.kind,input.scopeId))return reply({message:'Current organisation deed or staff authority required.'},403);if(input.promotions?.length)return reply({message:'Event promotion delivery is not configured. Nothing was charged.'},503);
return reply(await store.transaction(async tx=>{if(input.action==='create'){const result=await createRealmEventRecord(tx,user,input,clock());return {event:project(await tx.first('SELECT * FROM jarvis_events WHERE id=?',[result.eventId])),replayed:result.replayed};}
if(!['update','cancel'].includes(input.action)||!uuid(input.id)||!Number.isSafeInteger(input.revision))throw Object.assign(Error('Choose a current event.'),{status:400});const row=await tx.first('SELECT * FROM jarvis_events WHERE id=? FOR UPDATE',[input.id]);if(!row||row.scope_kind!==input.kind||row.scope_id!==input.scopeId||Number(row.revision)!==input.revision||row.state!=='scheduled')throw Object.assign(Error('The event changed. Refresh before editing.'),{status:409});if(await isManagedEvent(row.id))throw Object.assign(Error('Use the War Exchange to change this agreed calendar booking.'),{status:409});await tx.query('UPDATE jarvis_events SET title=?,description=?,starts_at=?,ends_at=?,state=?,revision=revision+1,updated_at=? WHERE id=?',[input.title,input.description,input.startsAt,input.endsAt,input.action==='cancel'?'cancelled':'scheduled',clock(),row.id]);await tx.query('INSERT INTO jarvis_event_history VALUES(?,?,?,?,?)',[randomUUID(),row.id,user.id,input.action,clock()]);return{event:project(await tx.first('SELECT * FROM jarvis_events WHERE id=?',[row.id]))};}));
}catch(error){return reply({message:error.status?error.message:'The event action was not confirmed. Refresh to check its state.'},error.status||503);}};}