import {identity} from './auth.mjs'; import {manageManualSeal} from './manual-seal-admin.mjs'; import {accessFor} from './permissions.mjs'; import {MANUAL_SEALS} from './seal-entitlements.mjs'; import {activeSealEntitlements} from './seal-entitlement-store.mjs'; import {AWARD_LABELS} from './recognition.mjs'; import {nativeSyncChange} from './native-sync-outbox.mjs'; export function createManualSealRoute(db,origin,{authenticate=identity,manage=manageManualSeal,readAccess=accessFor,queue=()=>nativeSyncChange(db).run()}={}){return async request=>{ const actor=await authenticate(request,db); if(!actor)return Response.json({message:'Sign in first.'},{status:401}); if(request.method==='GET'){ const rights=await readAccess(db,actor); if(!rights.nodes.includes('web.accounts.view'))return Response.json({message:'Account directory permission required.'},{status:403}); const id=new URL(request.url).searchParams.get('userId');if(!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id||''))return Response.json({message:'Select a citizen.'},{status:400}); const labels={'alpha-tester':'Alpha Tester','beta-tester':'Beta Tester','launch-contributor':'Launch Contributor','dedicated-tester':'Dedicated Tester','season-tavren-ii':'Season Tavren II','dunegit-owner':'DuneGit Owner',...AWARD_LABELS}; const entitlements=(await activeSealEntitlements(db,id)).map(({id,key,source,grantedAt})=>({id,key,source,grantedAt})); return Response.json({catalogue:[...MANUAL_SEALS].map(key=>({key,label:labels[key]||key,file:key+'-150.png'})),entitlements,canManage:actor.id!==id&&rights.nodes.includes('web.accounts.assign')},{headers:{'Cache-Control':'no-store'}}); } if(request.method!=='POST')return Response.json({message:'Method not allowed.'},{status:405}); if(request.headers.get('origin')!==origin)return Response.json({message:'Origin rejected.'},{status:403}); let body;try{body=await request.json();}catch{return Response.json({message:'Invalid JSON.'},{status:400});} if(!body||typeof body!=='object'||Array.isArray(body)||!['grant','revoke'].includes(body.action)||typeof body.targetId!=='string'||typeof body.seal!=='string'||typeof body.reason!=='string'||body.reason.trim().length<3||body.reason.length>500)return Response.json({message:'Action, recipient, seal and reason required.'},{status:400}); const result=await manage(db,actor,body); // Retrying an already saved grant also retries its derived native signature refresh. if(result.ok)await queue(); return Response.json(result,{status:result.ok?200:result.status||400,headers:{'Cache-Control':'no-store'}}); };}