import {companyHierarchyControllers} from './company-deeds.mjs'; import {readPassiveOrder,passiveOrderAuthority} from './political-passive-orders.mjs'; import {randomUUID} from 'node:crypto'; import {identity} from './auth.mjs'; import {accessFor} from './permissions.mjs'; import {PUBLIC_OFFICES} from './public-government.mjs'; import {validateMotd} from './organisation-motd.mjs'; const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i; const failure=(message,status)=>Object.assign(Error(message),{status}); export function createOrganisationSettingsRoute(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\/organisations\/(company|politics)\/([a-z0-9_-]{1,36})\/settings$/i.exec(url.pathname); if(!match||url.search)return reply({message:'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 organisation settings.'},401); if(!(await access(user)).nodes.includes('web.menu.game'))return reply({message:'Game account access required.'},403); const [,kind,id]=match; const passive=kind==='politics'&&db.passiveOrdersEnabled?await readPassiveOrder(db,id):null; if(kind==='company'&&!uuid.test(id)||kind==='politics'&&!passive&&!PUBLIC_OFFICES.some(o=>o.key===id))return reply({message:'Organisation not found.'},404); if(request.method==='POST'&&request.headers.get('origin')!==origin)return reply({message:'Request origin rejected.'},403); try{ let input;if(request.method==='POST'){const text=await request.text();if(text.length>6000)throw failure('Settings request too large.',413);try{input=JSON.parse(text);}catch{throw failure('Invalid settings.',400);}if(!input||!['motd','identity'].includes(input.action)||!Number.isSafeInteger(input.revision)||input.revision<0)throw failure('Refresh and review the current settings.',400);} // Revalidate before acquiring a transaction connection; authentication uses the same pool. const fresh=await authenticate(request);if(fresh?.id!==user.id||!(await access(fresh)).nodes.includes('web.menu.game'))throw failure('Your session changed.',403); return await db.transaction(async tx=>{ let organisation,canEdit=true; if(kind==='company'){ organisation=await tx.first(db.companyDeedsEnabled?"SELECT c.id,c.name,c.description,c.updated_at,d.owner_account_id AS founded_by,c.ceo_account_id FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id WHERE c.id=? AND c.status IN ('active','pending') FOR UPDATE":"SELECT id,name,description,updated_at,founded_by,ceo_account_id FROM corrino_companies WHERE id=? AND status IN ('active','pending') FOR UPDATE",[id]); canEdit=!!organisation&&[organisation.founded_by,organisation.ceo_account_id,...(db.companyDeedsEnabled?await companyHierarchyControllers({prepare(sql){let args=[];return{bind(...v){args=v;return this;},first:()=>tx.first(sql,args)};}},id):[])].includes(user.id);if(!canEdit&&(input||!db.companyDeedsEnabled||!await tx.first('SELECT user_id FROM site_company_members WHERE company_id=? AND user_id=?',[id,user.id])))throw failure('Company management authority required.',403);if(!organisation)throw failure('Company not found.',404); }else if(passive){ await tx.first('SELECT id FROM political_passive_orders WHERE id=? FOR UPDATE',[passive.id]); const reader={passiveOrdersEnabled:true,query:tx.query.bind(tx),prepare(sql){let values=[];return{bind(...args){values=args;return this;},first:()=>tx.first(sql,values),all:async()=>({results:await tx.query(sql,values)})};}}; let authority=await passiveOrderAuthority(reader,user,id,{clock}); if(authority?.parentOfficeholder){await tx.first('SELECT id FROM political_office_terms WHERE id=? FOR UPDATE',[authority.parentTermId]);authority=await passiveOrderAuthority(reader,user,id,{clock});} if(!authority||!authority.member&&!authority.capabilities.editMotd)throw failure('Current Order membership or scoped MOTD authority required.',403); canEdit=authority.capabilities.editMotd; if(input&&(!canEdit||input.action!=='motd'))throw failure('This Order deed permits only its scoped MOTD action.',403); organisation={name:authority.order.name,description:authority.order.description,updated_at:0}; }else{ const office=PUBLIC_OFFICES.find(o=>o.key===id),kinds=office.kind==='bene'?['bene','house']:office.kind==='guild'?['guild','court']:[office.kind],now=clock(); const terms=await tx.query("SELECT user_id,kind FROM political_office_terms WHERE faction=? AND office=? AND outcome='winner' AND starts_at<=? AND expires_at>? FOR UPDATE",[office.faction,office.office,now,now]); const valid=terms.filter(t=>kinds.includes(t.kind));if(valid.length!==1||valid[0].user_id!==user.id)throw failure('A current unambiguous office deed is required.',403); organisation={name:office.scope,description:office.description,updated_at:0}; } const message=await tx.first('SELECT message,updated_at FROM organisation_motd WHERE organisation_kind=? AND organisation_id=? FOR UPDATE',[kind,id]); if(input){ if(input.action==='identity'){ if(kind!=='company')throw failure('Protected office identity follows the office register.',403); const name=typeof input.name==='string'?input.name.trim():'',description=typeof input.description==='string'?input.description.trim():''; if(!name||name.length>120||description.length>1000||/[\x00-\x1f\x7f]/.test(name)||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(description))throw failure('Enter a name up to 120 characters and description up to 1,000.',400); if(input.revision!==Number(organisation.updated_at))throw failure('The identity changed. Refresh before saving.',409); const now=Math.max(clock(),Number(organisation.updated_at)+1);await tx.query('UPDATE corrino_companies SET name=?,description=?,updated_at=? WHERE id=?',[name,description,now,id]);organisation={...organisation,name,description,updated_at:now}; }else{ if(input.revision!==Number(message?.updated_at||0))throw failure('The message changed. Refresh before saving.',409); let text;try{text=validateMotd(input.message);}catch(e){throw failure(e.message,400);} const now=Math.max(clock(),Number(message?.updated_at||0)+1); await tx.query('INSERT INTO organisation_motd(organisation_kind,organisation_id,message,updated_by,updated_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE message=VALUES(message),updated_by=VALUES(updated_by),updated_at=VALUES(updated_at)',[kind,id,text,user.id,now]); await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),user.id,'organisation-motd',JSON.stringify({kind,id}),now]); return reply({name:organisation.name,description:organisation.description,identityRevision:Number(organisation.updated_at),motd:text,motdRevision:now,canEditIdentity:kind==='company'&&canEdit,canEditMotd:canEdit}); } } if(input)await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),user.id,'organisation-identity',JSON.stringify({kind,id}),clock()]); return reply({name:organisation.name,description:organisation.description,identityRevision:Number(organisation.updated_at),motd:message?.message||'',motdRevision:Number(message?.updated_at||0),canEditIdentity:kind==='company'&&canEdit,canEditMotd:canEdit}); }); }catch(error){return reply({message:error.status?error.message:'Organisation settings are temporarily unavailable.'},error.status||503);} };}