web/website/node/starter-kit-api.mjs
2026-11-21 20:22:37 +01:00

18 lines
2 KiB
JavaScript

import {gameAuthorized} from './game-link.mjs';
import {createStarterKitEvents} from './starter-kit-events.mjs';
import {STARTER_KIT_POLICY,STARTER_REPAIR_PARTS} from '../control-panel/public/starter-kit-policy.mjs';
export function createStarterKitEventAPI(db,keys,settings,{clock=Date.now}={}){
const producer={},events=keys?createStarterKitEvents(db,keys,{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.search)return reply({message:'Equipment event query overrides are not accepted.'},400);
if(url.pathname==='/internal/equipment/starter-policy'&&request.method==='GET')return reply({policy:STARTER_KIT_POLICY,parts:STARTER_REPAIR_PARTS,minecraftProducerIncluded:false});
if(url.pathname!=='/internal/equipment/starter-event'||request.method!=='POST')return reply({message:'Equipment route not found.'},404);
if(!events)return reply({message:'The equipment key service is 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:'Equipment event required.'},400);let bytes=0;const chunks=[];
try{while(true){const {done,value}=await reader.read();if(done)break;bytes+=value.byteLength;if(bytes>32768){await reader.cancel();return reply({message:'Equipment event exceeds its bound.'},413);}chunks.push(value);}const body=JSON.parse(Buffer.concat(chunks).toString('utf8'));return reply(await events.record(producer,body));}
catch(error){return reply({message:error instanceof TypeError?'Review the equipment event fields.':'The equipment receipt could not be verified. No replacement was delivered.'},409);}finally{reader.releaseLock();}
};
}