diff --git a/website/node/postbank-authority.mjs b/website/node/postbank-authority.mjs index 73fe49e2..f3ffad13 100644 --- a/website/node/postbank-authority.mjs +++ b/website/node/postbank-authority.mjs @@ -5,6 +5,7 @@ import {clanDeedOperators} from './clan-deeds.mjs'; import {delegatedAuthority} from './postbank-authorisations.mjs'; import {createHash} from 'node:crypto'; import {accessFor} from './permissions.mjs'; +import {currentOfficeController} from './entity-relations.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)}`;} @@ -29,8 +30,9 @@ export function createPostbankAuthority(central,{clock=Date.now,rightsFor=access 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:[]};}); + const canonicalOffice=async(key,office,faction)=>{if(!terms.some(t=>t.office===office&&t.faction===faction))return[];const holder=await currentOfficeController(central,key,now);if(!holder)return[];const term=await central.prepare('SELECT expires_at FROM political_office_terms WHERE id=?').bind(holder.termId).first();return term?[{user_id:holder.userId,expires_at:term.expires_at}]:[];},leadership=new Map(); for(const [key,name]of Object.entries(HOUSES)){ - const current=terms.filter(t=>t.faction===key&&['house_leader','reverent_mother','doci'].includes(t.office)); + const current=key==='spacing_guild'?await canonicalOffice('spacing_guild','guild_leader','spacing_guild'):terms.filter(t=>t.faction===key&&['house_leader','reverent_mother','doci'].includes(t.office));leadership.set(key,current); 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=nowNumber(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)); + const current=leadership.get(key); 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); } + const delegates=await canonicalOffice('clan_delegate','clan_delegate','clans');add('office','leader:clan_delegate','Office of the Clan Delegate',delegates.map(t=>t.user_id),[],delegates.length?Number(delegates[0].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; diff --git a/website/tests/postbank-political-mandates.test.mjs b/website/tests/postbank-political-mandates.test.mjs new file mode 100644 index 00000000..240b04d2 --- /dev/null +++ b/website/tests/postbank-political-mandates.test.mjs @@ -0,0 +1,46 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs'; +import {createPostbankAuthority,entityId} from '../node/postbank-authority.mjs'; +import {PostbankService} from '../node/postbank-service.mjs'; +import {BANK_VERSION} from '../node/postbank-catalogue.mjs'; +import {PUBLIC_OFFICES} from '../node/public-government.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from '../node/organisation-keys.mjs'; +import {POLITICAL_DECISION_SCHEMA,createPoliticalDecisions} from '../node/political-decisions.mjs'; +import {initializePOLProgression,polProgressionStore} from '../node/progression-pol.mjs'; +async function fixture(office='spacing_guild',kind=null){ + const f=await companyFixture(),original=f.db.query.bind(f.db);f.db.query=(sql,args=[])=>original(sql.replace(/,\s*KEY \w+\([^)]*\)/g,''),args);f.db.sqlite.function('CONCAT',{varargs:true},(...args)=>args.join('')); + f.db.sqlite.exec('ALTER TABLE political_office_terms ADD COLUMN id TEXT;ALTER TABLE political_office_terms ADD COLUMN kind TEXT;CREATE TABLE political_office_charters(office_key TEXT PRIMARY KEY,charter_kind TEXT,staff_key_id TEXT);CREATE TABLE political_proclamations(id TEXT PRIMARY KEY,request_id TEXT,scope TEXT,title TEXT,body TEXT,author_id TEXT,created_at INT,version INT)'); + await f.db.query(POLITICAL_DECISION_SCHEMA);await initializePOLProgression(f.db);const pol=polProgressionStore(f.db);await pol.query("INSERT INTO jarvis_progression_seasons VALUES('S01',0,9999999999,0,25,'active',1)");await pol.query('INSERT INTO jarvis_progression_accounts VALUES(?,50000,50000,63,1,0)',[f.people.Owner.id]); + let now=1000;const o=PUBLIC_OFFICES.find(o=>o.key===office),termId=randomUUID();await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at) VALUES(?,?,?,?,?,'winner',0,9999999999)",[termId,f.people.Owner.id,kind||o.kind,o.faction,o.office]); + const charter=await f.keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId:'office:'+office,authorize:async()=>true});await f.keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',code:charter.code,targetId:randomUUID(),requestId:randomUUID(),apply:(tx,{keyId})=>tx.query('INSERT INTO political_office_charters VALUES(?,?,?)',[office,'royal',keyId])}); + const authority=createPostbankAuthority(f.db,{clock:()=>now,bank:f.db,rightsFor:async()=>({nodes:['web.menu.game'],ranks:[]})}),officeId=entityId('office','leader:'+office);return{...f,pol,authority,officeId,termId,o,clock:()=>now,setTime:n=>now=n}; +} +test('canonical Guild and supported court mandates activate and fund real political decisions through the default bank authority',async()=>{ + for(const kind of ['guild','court']){const f=await fixture('spacing_guild',kind);try{ + const authority=await f.authority(f.people.Owner),source=authority.entities.find(e=>e.id===f.officeId);assert.equal(source.canPay,true);assert.equal(source.canActivate,true);assert.equal(source.expiresAt,9999999999); + await new PostbankService(f.db,f.authority,{clock:f.clock}).activate(f.people.Owner,{entityId:f.officeId,packageKey:'pb_civic',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const account=await f.db.first("SELECT * FROM pb_accounts WHERE type_code='107'");await f.db.query('UPDATE pb_accounts SET balance_minor=2000000 WHERE id=?',[account.id]);await f.db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_tax_treasury','979','Tax',0,'active',1)"); + const service=createPoliticalDecisions(f.db,f.db,f.keys,{clock:f.clock,authority:f.authority,verifyStorage:async()=>null}),view=await service.read(f.people.Owner,'SG-PROCLAIM');assert.equal(view.canExecute,true);assert(view.accounts.some(a=>a.id===String(account.id))); + const input={decisionId:'SG-PROCLAIM',requestId:randomUUID(),sourceAccount:String(account.id),title:'Verified Guild bulletin',body:'A funded Guild bulletin from its actual elected mandate.',confirmed:true};await service.execute(f.people.Owner,input);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[account.id])).balance_minor,1950000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1); + }finally{f.db.close();}} +}); +test('legacy Guild house roles, ambiguous mandates and expired holders do not acquire Guild bank powers',async()=>{ + const f=await fixture();try{ + const old=randomUUID();await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at) VALUES(?,?,'house','spacing_guild','house_leader','winner',0,9999999999)",[old,f.people.Other.id]);assert.equal((await f.authority(f.people.Owner)).entities.find(e=>e.id===f.officeId).canPay,true);assert.equal((await f.authority(f.people.Other)).entities.find(e=>e.id===f.officeId).canPay,false); + const duplicate=randomUUID();await f.db.query("INSERT INTO political_office_terms(id,user_id,kind,faction,office,outcome,starts_at,expires_at) VALUES(?,?,'guild','spacing_guild','guild_leader','winner',0,9999999999)",[duplicate,f.people.Other.id]);for(const actor of [f.people.Owner,f.people.Other])assert.equal((await f.authority(actor)).entities.find(e=>e.id===f.officeId).canPay,false); + await f.db.query('DELETE FROM political_office_terms WHERE id=?',[duplicate]);f.setTime(9999999999);assert.equal((await f.authority(f.people.Owner)).entities.find(e=>e.id===f.officeId).canPay,false); + }finally{f.db.close();} +}); +test('Guild succession changes operators on the same office identity without resetting its account or balance',async()=>{ + const f=await fixture();try{ + await new PostbankService(f.db,f.authority,{clock:f.clock}).activate(f.people.Owner,{entityId:f.officeId,packageKey:'pb_civic',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const before=await f.db.first("SELECT * FROM pb_accounts WHERE type_code='107'");await f.db.query('UPDATE pb_accounts SET balance_minor=123456 WHERE id=?',[before.id]);await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Other.id,f.termId]);assert.equal((await f.authority(f.people.Owner)).entities.find(e=>e.id===f.officeId).canPay,false);assert.equal((await f.authority(f.people.Other)).entities.find(e=>e.id===f.officeId).canPay,true);const after=await f.db.first('SELECT * FROM pb_accounts WHERE id=?',[before.id]);assert.equal(after.account_number,before.account_number);assert.equal(after.balance_minor,123456);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_clients')).n,1); + }finally{f.db.close();} +}); +test('the elected Clan Delegate gets its own office scope without a House, staff override or another holder’s rights',async()=>{ + const f=await fixture('clan_delegate');try{ + const mine=await f.authority(f.people.Owner),other=await f.authority(f.people.Other);assert.equal(mine.entities.find(e=>e.id===f.officeId).canPay,true);assert.equal(mine.entities.some(e=>e.kind==='house'&&e.key==='clans'),false);assert.equal(other.entities.find(e=>e.id===f.officeId).canPay,false); + await new PostbankService(f.db,f.authority,{clock:f.clock}).activate(f.people.Owner,{entityId:f.officeId,packageKey:'pb_civic',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE type_code='107'")).balance_minor,0); + f.setTime(9999999999);assert.equal((await f.authority(f.people.Owner)).entities.find(e=>e.id===f.officeId).canActivate,false); + }finally{f.db.close();} +});