forked from unimatrix/web
51 lines
5.5 KiB
JavaScript
51 lines
5.5 KiB
JavaScript
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;if(kind==='company'&&!uuid.test(id)||kind==='politics'&&!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);}
|
|
return await db.transaction(async tx=>{
|
|
const fresh=await authenticate(request);if(fresh?.id!==user.id)throw failure('Your session changed.',403);
|
|
let organisation;
|
|
if(kind==='company'){
|
|
organisation=await tx.first("SELECT id,name,description,updated_at,founded_by,ceo_account_id FROM corrino_companies WHERE id=? AND status IN ('active','pending') FOR UPDATE",[id]);
|
|
if(!organisation||![organisation.founded_by,organisation.ceo_account_id].includes(user.id))throw failure('Company management authority required.',403);
|
|
}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'});
|
|
}
|
|
}
|
|
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'});
|
|
});
|
|
}catch(error){return reply({message:error.status?error.message:'Organisation settings are temporarily unavailable.'},error.status||503);}
|
|
};}
|

Staff