MC/website/node/postbank-authority.mjs

46 lines
5 KiB
JavaScript

import {delegatedAuthority} from './postbank-authorisations.mjs';
import {createHash} from 'node:crypto';
import {accessFor} from './permissions.mjs';
const STAFF_ROLES=new Set(['owners','web_net_admin','network_admin','web_network','web_support','web_net_owner','corestaff','web_admin','web_dev']);
export const HOUSES=Object.freeze({atreides:'House Aerdrecht',harkonnen:'House Harkveen',corrino:'House Korenholt',ordos:'House Oordwijk',fremen:'Vrijduin',veiled_concord:'Veiled Concord',spacing_guild:'Vaerkring'});
export function entityId(kind,key){const h=createHash('sha256').update('postbank:entity:'+kind+':'+key).digest('hex');return `${h.slice(0,8)}-${h.slice(8,12)}-5${h.slice(13,16)}-a${h.slice(17,20)}-${h.slice(20,32)}`;}
const can= (rights,key)=>rights.nodes.includes(key);
// Central identity/organisation records are read-only sources. No gameplay bank,
// bearer gateway, old balance or historical bank transaction is read here.
export function createPostbankAuthority(central,{clock=Date.now,rightsFor=accessFor,bank=null}={}){
const rows=async(sql,args=[])=>(await central.prepare(sql).bind(...args).all()).results||[];
return async (user,{bank:store=bank}={})=>{
const rights=await rightsFor(central,user),readAdmin=can(rights,'web.bank.staff.view'),manageAdmin=can(rights,'web.bank.staff.manage'),now=clock();
const sources=[],operatorRoles=new Set(['owner','officer','admin','leader']);
// Administrative inspection belongs to separate admin routes, never personal activation cards.
const add=(kind,key,name,operators=[],viewers=[],expiresAt=null)=>sources.push({id:entityId(kind,key),kind,key,name,canView:operators.includes(user.id)||viewers.includes(user.id),canActivate:operators.includes(user.id),canPay:operators.includes(user.id),expiresAt});
const policy=await central.prepare('SELECT game_link_exempt FROM site_account_policies WHERE user_id=?').bind(user.id).first();
if(!policy?.game_link_exempt&&!['memorial','official_account'].includes(user.role))add('person',user.id,user.username,[user.id]);
const clans=await rows('SELECT id,name,owner_id FROM site_clans WHERE active=1');
const members=await rows('SELECT clan_id,user_id,clan_role FROM site_clan_members');
for(const clan of clans)add('clan',clan.id,clan.name,[clan.owner_id,...members.filter(m=>m.clan_id===clan.id&&operatorRoles.has(m.clan_role)).map(m=>m.user_id)],members.filter(m=>m.clan_id===clan.id).map(m=>m.user_id));
const companies=await rows("SELECT id,name,founded_by,ceo_account_id FROM corrino_companies WHERE status='active'");
for(const company of companies)add('company',company.id,company.name,[company.founded_by,company.ceo_account_id].filter(Boolean));
const terms=await rows("SELECT user_id,office,faction,expires_at FROM political_office_terms WHERE outcome='winner' AND starts_at<=? AND expires_at>?",[now,now]);
const bootstrap=await rows('SELECT website_id,roles_json,expires_at FROM drforum_dune_political_roles WHERE expires_at>?',[Math.floor(now/1000)]);
const bootstrapRoles=bootstrap.map(b=>{let roles=[];try{roles=JSON.parse(b.roles_json);}catch{}return {...b,roles:Array.isArray(roles)?roles:[]};});
for(const [key,name]of Object.entries(HOUSES)){
const current=terms.filter(t=>t.faction===key&&['house_leader','reverent_mother'].includes(t.office));
add('house',key,name,current.map(t=>t.user_id),[],current.length?Math.min(...current.map(t=>Number(t.expires_at))):null);
}
const emperors=terms.filter(t=>t.office==='emperor'),beforeFirstHandover=now<Date.parse('2026-11-15T18:00:00Z');
const provisional=beforeFirstHandover?bootstrapRoles.filter(b=>b.roles.includes('emperor')):[];
const emperorActors=[...emperors.map(t=>t.user_id),...provisional.map(b=>b.website_id)];
const emperorExpiry=emperors.length?Math.min(...emperors.map(t=>Number(t.expires_at))):provisional.length?Math.min(...provisional.map(b=>Number(b.expires_at)*1000),Date.parse('2026-11-15T18:00:00Z')):null;
add('office','emperor','Office of the Emperor',emperorActors,[],emperorExpiry);
for(const [key,name]of Object.entries(HOUSES)){
const current=terms.filter(t=>t.faction===key&&['house_leader','reverent_mother'].includes(t.office));
add('office','leader:'+key,key==='veiled_concord'?'Office of the Reverent Mother':name+' Leadership',current.map(t=>t.user_id),[],current.length?Math.min(...current.map(t=>Number(t.expires_at))):null);
}
// Staff eligibility follows current central access roles, not cosmetic honours.
const staff=await rows("SELECT a.id,a.username,a.role FROM site_accounts a LEFT JOIN site_account_policies p ON p.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND COALESCE(p.game_link_exempt,0)=0");
const eligibleStaff=staff.filter(a=>STAFF_ROLES.has(a.role));
for(const actor of eligibleStaff)add('staff',actor.id,actor.username+' · Staff',[actor.id]);
return delegatedAuthority({entities:sources,readAdmin,manageAdmin,rankKeys:rights.ranks||[user.role],eligibleStaff:eligibleStaff.map(a=>({id:a.id,username:a.username})),server:{state:'not_linked',name:'Game server account'}},user,store,now);
};
}