web/website/node/server-project-api.mjs

29 lines
3.1 KiB
JavaScript

import {identity} from './auth.mjs';
export function createServerProjectAPI(db,service,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),clock=Date.now}={}){
const attempts=new Map();
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 user=await authenticate(request);if(!user)return reply({message:'Sign in to open server projects.'},401);
if(!service)return reply({message:'The project service is unavailable.'},503);
const url=new URL(request.url),actor={...user,revalidate:()=>authenticate(request)};
if(url.search)return reply({message:'Account and project overrides are not accepted.'},400);
try{
if(request.method==='GET')return url.pathname==='/api/projects'?reply(await service.list(actor)):reply({message:'Project route not found.'},404);
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
if(request.headers.get('origin')!==origin)return reply({message:'Origin rejected.'},403);
const now=clock();for(const[id,row]of attempts)if(row.until<=now)attempts.delete(id);
let attempt=attempts.get(user.id);if(!attempt){if(attempts.size>=5000)return reply({message:'Project requests are busy. Retry shortly.'},429);attempt={count:0,until:now+60000};attempts.set(user.id,attempt);}
if(++attempt.count>20)return reply({message:'Wait a minute before sending more project actions.'},429);
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
let body;try{const reader=request.body?.getReader();if(!reader)throw Error();const chunks=[];let size=0;while(true){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>65536){await reader.cancel();return reply({message:'Project request too large.'},413);}chunks.push(value);}body=JSON.parse(Buffer.concat(chunks).toString('utf8'));}catch{return reply({message:'Invalid project request.'},400);}
if(!body||typeof body!=='object'||Array.isArray(body)||body.confirmed!==true)return reply({message:'Confirm the selected project action.'},400);
const routes={'/api/projects/submit':['submit',['requestId','title','proposal','requestedMinor','confirmed']],'/api/projects/review':['review',['projectId','requestId','version','approve','approvedMinor','note','confirmed']],'/api/projects/complete':['complete',['projectId','requestId','version','confirmed']]};
const route=routes[url.pathname];if(!route)return reply({message:'Project route not found.'},404);
if(Object.keys(body).some(k=>!route[1].includes(k))||route[0]==='review'&&typeof body.approve!=='boolean')return reply({message:'Choose a valid project action.'},400);
const result=await service[route[0]](actor,body);return reply({ok:true,...result});
}catch(error){
const safe=/^(Project |Current project|Approved project|Active project|Review the project|Approve a budget|A review note|Invalid project)/.test(error.message||'');
return reply({message:safe?error.message:'The project action could not be confirmed. Reload before retrying.'},safe?409:503);
}
};
}