import {identity} from '../node/auth.mjs'; import {can} from '../node/permissions.mjs'; import {createItemDesigns} from '../node/item-designs.mjs'; export function createItemDesignAPI(db,keys,settings={},dependencies={}){ const authenticate=dependencies.authenticate||(request=>identity(request,db)); const allowed=dependencies.allowed||(async(actor,store)=>{ const fresh=(await store.query("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[actor.id]))[0]; return !!fresh&&await can(db,fresh,'web.items.manage'); }); const service=keys?createItemDesigns(db,keys,{authorize:allowed}):null; const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}}); return async request=>{ const url=new URL(request.url);if(url.pathname!=='/api/items/designs'||url.search)return reply({message:'Use the item definition register without identity overrides.'},400); 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 allowed(actor,db))return reply({message:'Item definition management required.'},403); if(!service)return reply({message:'The item definition key service is unavailable.'},503); if(request.method==='GET')return reply({definitions:await service.list(actor)}); if(request.headers.get('origin')!==new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin)return reply({message:'Origin 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:'Item definition required.'},400); let input;try{const chunks=[];let length=0;while(true){const {value,done}=await reader.read();if(done)break;length+=value.byteLength;if(length>16384){await reader.cancel();return reply({message:'Item definition exceeds its bound.'},413);}chunks.push(value);}input=JSON.parse(Buffer.concat(chunks).toString('utf8'));} catch{return reply({message:'Invalid item definition.'},400);}finally{reader.releaseLock();} if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).length!==4||!['action','id','revision','design'].every(key=>Object.hasOwn(input,key))||input.action!=='save')return reply({message:'Use the selected item, current revision and complete design.'},400); try{const saved=await service.save(actor,input);return reply(saved,saved.revision===1&&!saved.replayed?201:200);} catch(error){if(error instanceof TypeError)return reply({message:error.message},400);if(error.message==='Item definition management required.')return reply({message:error.message},403);if(/^Item definition (?:changed|revision conflict)/.test(error.message))return reply({message:error.message},409);throw error;} }; }