import {gameAuthorized} from './game-link.mjs'; import {createQuestActivityEvents} from './quest-activity-events.mjs'; export function createQuestActivityAPI(db,keys,settings,{clock=Date.now,namespace}={}){ if(!['pol','personal'].includes(namespace))throw TypeError('Fixed activity namespace required'); const producer={},events=keys?createQuestActivityEvents(db,keys,{namespace,clock,authorizeProducer:async actor=>actor===producer}):null; const reply=(value,status=200)=>Response.json(value,{status,headers:{'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}}); return async request=>{ if(!gameAuthorized(request,settings))return reply({message:'Unauthorized'},401); const url=new URL(request.url);if(url.pathname!=='/internal/progression/'+namespace+'/event'||request.method!=='POST')return reply({message:'Activity route not found.'},404); if(url.search)return reply({message:'Activity identity overrides are not accepted.'},400); if(!events)return reply({message:'Activity keys are unavailable.'},503); 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:'Activity evidence required.'},400);let size=0;const chunks=[]; try{while(true){const {done,value}=await reader.read();if(done)break;size+=value.length;if(size>4096){await reader.cancel();return reply({message:'Activity event exceeds its bound.'},413);}chunks.push(value);}return reply(await events.record(producer,JSON.parse(Buffer.concat(chunks).toString('utf8'))));} catch{return reply({message:'The activity receipt could not be verified. No objective was credited.'},409);}finally{reader.releaseLock();} }; }