web/website/node/rebellion-api.mjs

24 lines
2.6 KiB
JavaScript

import {identity} from './auth.mjs';import {accessFor} from './permissions.mjs';
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
export function createRebellionAPI(central,service,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,central),access=u=>accessFor(central,u)}={}){
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
return async request=>{try{
if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405);
const actor=await authenticate(request);if(!actor)return reply({message:'Sign in first.'},401);if(!(await access(actor)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403);
if(!service)return reply({message:'Rebellion decisions are unavailable.'},503);
const url=new URL(request.url);
if(request.method==='GET'){
if([...url.searchParams.keys()].some(k=>k!=='clanId')||url.searchParams.getAll('clanId').length>1)return reply({message:'Choose one clan.'},400);
const clanId=url.searchParams.get('clanId')||(await central.prepare("SELECT clan_id FROM site_clan_members WHERE user_id=? AND clan_role='owner'").bind(actor.id).first())?.clan_id;
if(!uuid(clanId))return reply({message:'The clan leader starts rebellion decisions.'},403);
return reply({clanId,choices:await service.options(actor,clanId),quests:await service.list(actor,clanId),gameProducerConnected:false});
}
if(url.search||request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403);
const raw=await request.text();if(raw.length>4000)return reply({message:'Request too large.'},413);let input;try{input=JSON.parse(raw);}catch{return reply({message:'Invalid rebellion decision.'},400);}
if(!input||typeof input!=='object'||Array.isArray(input))return reply({message:'Invalid rebellion decision.'},400);
const fresh=await authenticate(request);if(fresh?.id!==actor.id||!(await access(fresh)).nodes.includes('web.menu.game'))return reply({message:'Your session changed.'},403);
const {action,...fields}=input;if(action==='declare')return reply({ok:true,quest:await service.declare(fresh,fields)},201);
if(action==='cancel'&&Object.keys(fields).length===1&&uuid(fields.questKeyId))return reply({ok:true,...await service.cancel(fresh,fields)});
return reply({message:'Unknown rebellion decision. Victory keys are accepted only through the trusted game adapter.'},400);
}catch(error){return reply({message:error.status?error.message:'The rebellion decision could not be verified.'},error.status||503);}};
}