web/website/node/postbank-authority.mjs
unimatrixgit 57d4eadabb Add parallel faith office and compact quest dossiers
Reuse political elections and appointments for the New Faith, with Church-only artwork and theme. Deny faith-office conquest, enforce repeatable reward cooldowns, and open quest and decision details in accessible in-page dialogs. Compact item listings while preserving their lore previews.
2026-11-22 09:03:13 +01:00

53 lines
7.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {companyDeedOperators} from './company-deeds.mjs';
import {passiveOrderRecords} from './political-passive-orders.mjs';
import {clanBankingEligible,restrictBasicClanBanking} from './clan-banking-policy.mjs';
import {clanDeedOperators} from './clan-deeds.mjs';
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',muad_dib:'Church of Muad’Dib',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'),basicIds=new Set();if(central.clanDeedsEnabled){const eligibility=await rows('SELECT c.id,ch.charter_kind,i.institution_key FROM site_clans c LEFT JOIN site_clan_charters ch ON ch.clan_id=c.id LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.active=1');for(const row of eligibility)if(!clanBankingEligible(row))basicIds.add(entityId('clan',row.id));}
const members=await rows('SELECT clan_id,user_id,clan_role FROM site_clan_members'),deedOperators=await clanDeedOperators(central);
for(const clan of clans)add('clan',clan.id,clan.name,[clan.owner_id,...(deedOperators.get(clan.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(central.companyDeedsEnabled?"SELECT c.id,c.name,d.owner_account_id AS founded_by,c.ceo_account_id,d.charter_kind FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id WHERE c.status='active'":"SELECT id,name,founded_by,ceo_account_id FROM corrino_companies WHERE status='active'");if(central.companyDeedsEnabled)for(const company of companies)if(!['original','royal'].includes(company.charter_kind))basicIds.add(entityId('company',company.id));
const companyOperators=await companyDeedOperators(central);for(const company of companies)add('company',company.id,company.name,[company.founded_by,company.ceo_account_id,...(companyOperators.get(company.id)||[])].filter(Boolean));
for(const order of await passiveOrderRecords(central,{actor:user,clock}))if(order.capabilities.viewAccount)sources.push({id:entityId('company',order.bankLegacyId),kind:'company',key:order.bankLegacyId,name:order.name,organisationType:'passive-order',canView:true,canPay:order.capabilities.payFromAccount,canActivate:order.role==='fixed-leader',expiresAt:null});
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','doci'].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','doci'].includes(t.office));
add('office','leader:'+key,key==='veiled_concord'?'Office of the Mother Superior':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 currentStaff=central.organisationAccessEnabled?await rows("SELECT DISTINCT user_id FROM org_assignments WHERE scope_type IN ('organisation','department','branch') AND status='active' AND starts_at<=? AND (ends_at IS NULL OR ends_at>?)",[now,now]):null;
const currentStaffIds=currentStaff?new Set(currentStaff.map(a=>a.user_id)):null;
const eligibleStaff=staff.filter(a=>currentStaffIds?currentStaffIds.has(a.id):STAFF_ROLES.has(a.role));
for(const actor of eligibleStaff)add('staff',actor.id,actor.username+' · Staff',[actor.id]);
return restrictBasicClanBanking(await delegatedAuthority({entities:sources,readAdmin,manageAdmin,manageClients:manageAdmin||can(rights,'web.bank.staff.clients'),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),basicIds,{requirements:new Map(companies.map(c=>[entityId('company',c.id),'company_key']))});
};
}