import {createHash} from 'node:crypto'; import {identity} from './auth.mjs'; import {accessFor} from './permissions.mjs'; import {readCompanyDeed,companyDeedView,companyId} from './company-deeds.mjs'; import {separateCompanyMailboxId} from './company-royal-mail.mjs'; const fault=(message,status=409)=>Object.assign(Error(message),{status}); function reader(tx){return{prepare(sql){let args=[];return{bind(...values){args=values;return this;},first:()=>tx.first(sql,args),all:async()=>({results:await tx.query(sql,args)})};}};} const validKeySQL="SELECT id FROM organisation_keys WHERE target_id=? AND key_type IN ('staff-company-royal','political-appointment') AND used_at IS NOT NULL AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at>?) ORDER BY created_at DESC,id"; export function createCompanyMailboxSettings(db,{origin='https://cp.dunerealms.com',authenticate=r=>identity(r,db),access=u=>accessFor(db,u),clock=Date.now}={}){return async request=>{ const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}}),url=new URL(request.url),match=/^\/api\/companies\/([a-f0-9-]{36})\/mailbox$/i.exec(url.pathname); if(!match||!companyId(match[1])||url.search)return reply({message:'Company mailbox settings not found.'},404); if(!['GET','POST'].includes(request.method))return reply({message:'Method not allowed.'},405); const user=await authenticate(request);if(!user)return reply({message:'Sign in to manage Company correspondence.'},401); if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403); const id=match[1]; async function view(replayed=false){const deed=await readCompanyDeed(db,id);if(!companyDeedView(deed,user.id).canManage||deed.company.status!=='active')throw fault('Current Company management is required.',403);const row=await db.prepare('SELECT royal_key_id,state,updated_at FROM site_company_royal_mail WHERE company_id=?').bind(id).first(),{results:keys}=await db.prepare(validKeySQL).bind(id,clock()).all(),eligible=deed.company.charter_kind==='royal'&&keys.length>0;return{companyId:id,mode:row&&row.state!=='shared'?'separate':'shared',state:row?.state||'shared',version:Number(row?.updated_at||0),royalEligible:eligible,replayed};} try{ if(request.method==='GET')return reply(await view()); if(request.headers.get('origin')!==new URL(origin).origin)throw fault('Origin rejected.',403); if(!/^application\/json(?:\s*;|$)/i.test(request.headers.get('content-type')||''))throw fault('JSON required.',415); const raw=await request.text();if(raw.length>2048)throw fault('Request too large.',413);let body;try{body=JSON.parse(raw);}catch{throw fault('Invalid mailbox instruction.',400);} if(!body||Object.keys(body).some(k=>!['mode','version','requestId','confirmed'].includes(k))||!['shared','separate'].includes(body.mode)||!companyId(body.requestId)||!Number.isSafeInteger(body.version)||body.version<0||body.confirmed!==true)throw fault('Choose and confirm a mailbox mode.',400); const fingerprint=createHash('sha256').update(JSON.stringify([id,user.id,body.mode,body.version])).digest('hex'); const replayed=await db.transaction(async tx=>{ await tx.first('SELECT id FROM corrino_companies WHERE id=? FOR UPDATE',[id]);await tx.first('SELECT company_id FROM site_company_deeds WHERE company_id=? FOR UPDATE',[id]); const fresh=await authenticate(request);if(fresh?.id!==user.id||!(await access(fresh)).nodes.includes('web.menu.game'))throw fault('Your session changed.',403); const deed=await readCompanyDeed(reader(tx),id);if(!companyDeedView(deed,user.id).canManage||deed.company.status!=='active')throw fault('Company authority changed.',403); const event=await tx.first('SELECT company_id,actor_id,action,details_json FROM corrino_company_events WHERE id=?',[body.requestId]);if(event){const details=JSON.parse(event.details_json||'{}');if(event.company_id!==id||event.actor_id!==user.id||event.action!=='mailbox-preference'||details.fingerprint!==fingerprint)throw fault('This instruction reference was already used.');return true;} const previous=await tx.first('SELECT state,royal_key_id,mailbox_id,updated_at FROM site_company_royal_mail WHERE company_id=? FOR UPDATE',[id]);if(Number(previous?.updated_at||0)!==body.version)throw fault('Mailbox settings changed. Refresh first.'); const now=Math.max(clock(),body.version+1);let keyId=previous?.royal_key_id||null,state='shared'; if(body.mode==='separate'){ const key=await tx.first(validKeySQL+' FOR UPDATE',[id,clock()]);if(deed.company.charter_kind!=='royal'||!key)throw fault('A Royal Company deed with a valid applied Royal key is required.',403);keyId=key.id;state=previous?.state==='active'&&previous.royal_key_id===keyId?'active':'pending'; } if(previous)await tx.query('UPDATE site_company_royal_mail SET royal_key_id=?,state=?,updated_at=? WHERE company_id=?',[keyId,state,now,id]); else if(body.mode==='separate')await tx.query('INSERT INTO site_company_royal_mail(company_id,royal_key_id,mailbox_id,state,updated_at) VALUES(?,?,?,?,?)',[id,keyId,separateCompanyMailboxId(id),state,now]); await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[body.requestId,id,'mailbox-preference',user.id,JSON.stringify({fingerprint,mode:body.mode,keyId}),now]);return false; });return reply(await view(replayed)); }catch(error){return reply({message:error.status?error.message:'Company mailbox settings are temporarily unavailable.'},error.status||503);} };}