web/website/node/progression-api.mjs

49 lines
4.9 KiB
JavaScript

import {identity} from './auth.mjs';
import {parseOrganisationCode} from '../control-panel/public/codex-code-format.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 createProgressionAPI(db,{quests,xp,collect=async()=>{},authenticate=r=>identity(r,db),origin='https://cp.dunerealms.com'}={}){
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}});
return async request=>{
const url=new URL(request.url),user=await authenticate(request);if(!user)return reply({message:'Sign in to open your mission journal.'},401);
const actor={...user,revalidate:async()=>authenticate(request)};
if(!quests)return reply({message:'The quest service is not available.'},503);
try{
if(request.method==='GET'){
if(url.pathname==='/api/progression'&&!url.search){const sources=await collect(actor);return reply({...await quests.list(actor),sources});}
if(url.pathname==='/api/progression/history'){
if([...url.searchParams.keys()].some(k=>k!=='page')||url.searchParams.getAll('page').length>1||!/^\d{1,4}$/.test(url.searchParams.get('page')||'1'))return reply({message:'Choose a valid history page.'},400);
const page=Number(url.searchParams.get('page')||1);if(page<1)return reply({message:'Choose a valid history page.'},400);
const rows=await db.query('SELECT key_id,action,details_json,created_at FROM jarvis_progression_history WHERE account_id=? ORDER BY created_at DESC,id DESC LIMIT 26 OFFSET '+((page-1)*25),[user.id]);
return reply({page,hasMore:rows.length>25,records:rows.slice(0,25).map(r=>({keyId:r.key_id,action:r.action,details:JSON.parse(r.details_json),createdAt:Number(r.created_at)}))});
}
return reply({message:'Mission route not found.'},404);
}
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin||url.search)return reply({message:'Origin or account override rejected.'},403);
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
const reader=request.body?.getReader();if(!reader)return reply({message:'Request body required.'},400);let raw='',size=0;const decoder=new TextDecoder();
while(true){const {done,value}=await reader.read();if(done)break;size+=value.length;if(size>4096){await reader.cancel();return reply({message:'Request too large.'},413);}raw+=decoder.decode(value,{stream:true});}raw+=decoder.decode();
let body;try{body=JSON.parse(raw);}catch{return reply({message:'Invalid mission request.'},400);}
if(!body||typeof body!=='object'||Array.isArray(body)||body.confirmed!==true)return reply({message:'Confirm the selected action.'},400);
if(url.pathname==='/api/progression/start'){
if(Object.keys(body).some(k=>!['definitionId','confirmed'].includes(k))||typeof body.definitionId!=='string')return reply({message:'Choose a mission.'},400);
await collect(actor);const result=await quests.start(actor,body);return reply({ok:true,keyId:result.id,created:result.created});
}
if(url.pathname==='/api/progression/claim'){
if(Object.keys(body).some(k=>!['definitionId','requestId','revision','confirmed'].includes(k))||typeof body.definitionId!=='string'||!uuid(body.requestId)||!Number.isSafeInteger(body.revision)||body.revision<1)return reply({message:'Review the current mission reward.'},400);
await collect(actor);const result=await quests.claim(actor,body);await quests.processCompletions({accountId:user.id});return reply({ok:true,...result});
}
if(url.pathname==='/api/progression/xp/redeem'){
if(!xp||Object.keys(body).some(k=>!['code','requestId','confirmed'].includes(k))||typeof body.code!=='string'||!uuid(body.requestId))return reply({message:'Provide a complete XP instrument.'},400);
let parsed;try{parsed=parseOrganisationCode(body.code);}catch{return reply({message:'Provide a complete XP instrument.'},400);}
const keyType=parsed.prefix==='XPC'?'xp-correction':parsed.prefix==='XPX'?'xp-transfer':null;if(!keyType)return reply({message:'This instrument is not a player XP key.'},400);
const fresh=await authenticate(request);if(fresh?.id!==user.id)return reply({message:'Your session changed.'},403);
const result=await xp.redeem(actor,{code:body.code,keyType,requestId:body.requestId});await quests.processCompletions({accountId:user.id});return reply({ok:true,...result});
}
return reply({message:'Mission route not found.'},404);
}catch(error){
const safe=/^(Quest|XP |Season|Unknown quest|Current player|A single matching|An approved matching|Trusted observation|Verified deed|No reserved|Source season|Mandatory reward)/.test(error.message||'');
return reply({message:safe?error.message:'The mission service could not confirm this action. Reload before retrying.'},safe?409:503);
}
};
}