import {identity} from './auth.mjs';import {jarvisGeneratorCan} from './jarvis-generator-access.mjs';import {createMasterKeyGenerator} from './jarvis-master-generator.mjs'; import {testIdentityTargets,TEST_IDENTITY_ACTION,TEST_IDENTITY_PERMISSION} from './account-test-identity.mjs'; export function createMasterKeyGeneratorAPI(db,keys,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),authorize=(u,node)=>jarvisGeneratorCan(db,u,node)}={}){ const service=keys?createMasterKeyGenerator(db,keys,{authorize}):null; const reply=(d,s=200)=>Response.json(d,{status:s,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 use J.A.R.V.I.S.'},401); const url=new URL(request.url),options=url.pathname.endsWith('/options');if(url.search&&!options)return reply({message:'Query overrides are not accepted.'},400); if(!await authorize(user,'web.jarvis.keys.view'))return reply({message:'Masterkey access required.'},403); if(!service)return reply({message:'The key service is unavailable.'},503); try{ if(request.method==='GET'){ if(options){ if([...url.searchParams.keys()].some(k=>!['actionId','q'].includes(k))||['actionId','q'].some(k=>url.searchParams.getAll(k).length!==1)||url.searchParams.get('actionId')!==TEST_IDENTITY_ACTION)return reply({message:'Choose a connected account action.'},400); if(!await authorize(user,TEST_IDENTITY_PERMISSION))return reply({message:'Masterkey target authority required.'},403); const q=url.searchParams.get('q');if(!/^[A-Za-z0-9_]{2,32}$/.test(q||''))return reply({message:'Enter at least two account-name characters.'},400); const targets=await testIdentityTargets(db,q),fresh=await authenticate(request); if(fresh?.id!==user.id||!await authorize(fresh,TEST_IDENTITY_PERMISSION)||!await authorize(fresh,'web.jarvis.keys.view'))return reply({message:'Your session or authority changed.'},403); return reply({targets,selectionGrantsAuthority:false}); } if(url.pathname.endsWith('/history')){const rows=(await db.prepare('SELECT action_id,template_version,state,created_at FROM jarvis_generated_instructions WHERE account_id=? ORDER BY created_at DESC LIMIT 100').bind(user.id).all()).results;return reply({records:rows});} return reply(await service.catalogue(user)); } if(request.method!=='POST')return reply({message:'Method not allowed.'},405); if(options)return reply({message:'Target suggestions are read-only.'},405); if(request.headers.get('origin')!==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(),parts=[];let size=0;if(!reader)return reply({message:'Instruction required.'},400); while(true){const r=await reader.read();if(r.done)break;size+=r.value.byteLength;if(size>8192){await reader.cancel();return reply({message:'Instruction too large.'},413);}parts.push(r.value);} let input;try{input=JSON.parse(Buffer.concat(parts).toString('utf8'));}catch{return reply({message:'Invalid instruction.'},400);} const redeem=url.pathname.endsWith('/redeem'),fields=redeem?['code','requestId','confirmed']:['actionId','templateVersion','values','requestId','confirmed']; if(!input||Array.isArray(input)||input.confirmed!==true||Object.keys(input).some(k=>!fields.includes(k)))return reply({message:'Review and confirm the instruction.'},400); const fresh=await authenticate(request);if(fresh?.id!==user.id||!await authorize(fresh,'web.jarvis.keys.view'))return reply({message:'Your session or authority changed.'},403); return reply({ok:true,...await service[redeem?'redeem':'issue'](fresh,input)}); }catch(error){const message=error.message||'';const safe=/^(Devkeys|Masterkey|Choose |Invalid |Unknown |Instruction |Protected |Clan inventory|Key unavailable|Enter |Dossier)/.test(message);return reply({message:safe?message:'The instruction could not be confirmed. Reload before retrying.'},/authority/.test(message)?403:409);} }; }