forked from unimatrix/web
Validate cross-organisation parent deeds and derive political control from current office terms
This commit is contained in:
parent
5619d005e7
commit
7fddf78351
3 changed files with 85 additions and 0 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import {ENTITY_RELATION_SCHEMA,ENTITY_RELATION_GUARD_SCHEMA,entityParent,entityControllers} from './entity-relations.mjs';
|
||||
import {COMPANY_ROYAL_MAIL_SCHEMA} from './company-royal-mail.mjs';
|
||||
import {CLAIM_REGISTRY_SCHEMA} from './claim-registry.mjs';
|
||||
import {JARVIS_COMPANY_REQUEST_SCHEMA} from './jarvis-request-domains.mjs';
|
||||
|
|
@ -6,6 +7,8 @@ import {OrganisationKeyError} from './organisation-keys.mjs';
|
|||
import {clanMemberLimit} from './clan-membership-policy.mjs';
|
||||
|
||||
export const COMPANY_DEED_SCHEMA=[
|
||||
ENTITY_RELATION_SCHEMA,
|
||||
ENTITY_RELATION_GUARD_SCHEMA,
|
||||
`CREATE TABLE IF NOT EXISTS site_company_institutions(company_id CHAR(36) PRIMARY KEY,institution_key VARCHAR(40) NOT NULL UNIQUE,FOREIGN KEY(company_id) REFERENCES corrino_companies(id))`,
|
||||
CLAIM_REGISTRY_SCHEMA,
|
||||
COMPANY_ROYAL_MAIL_SCHEMA,
|
||||
|
|
@ -30,6 +33,7 @@ export async function recordInitialCompanyDeed(tx,company,now){
|
|||
}
|
||||
export async function initializeCompanyDeeds(db,{mysql=true,clock=Date.now}={}){
|
||||
for(const sql of COMPANY_DEED_SCHEMA)await db.prepare(sql+(mysql?' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4':'')).run();
|
||||
await db.query('INSERT INTO jarvis_entity_relation_guard(id) VALUES(1) ON DUPLICATE KEY UPDATE id=VALUES(id)');
|
||||
await db.transaction(async tx=>{const companies=await tx.query("SELECT c.id,c.founded_by,c.created_at FROM corrino_companies c JOIN site_accounts a ON a.id=c.founded_by LEFT JOIN site_company_deeds d ON d.company_id=c.id WHERE c.status IN ('active','pending') AND d.company_id IS NULL ORDER BY c.id FOR UPDATE");for(const company of companies)await recordInitialCompanyDeed(tx,company,clock());});
|
||||
// Pin existing companies to their original founder's single Clan mailbox.
|
||||
// Later acquisitions never rewrite this origin or migrate messages.
|
||||
|
|
@ -67,6 +71,7 @@ export async function upgradeOriginalCompany(db,keys,user,input){
|
|||
|
||||
// Derived control follows current parent deeds; it never changes membership or title ownership.
|
||||
export async function companyHierarchyControllers(db,id){
|
||||
if(await entityParent(db,'company',id))return entityControllers(db,'company',id);
|
||||
const users=new Set(),seen=new Set([id]);let current=id;
|
||||
for(let depth=0;depth<32;depth++){
|
||||
const row=await db.prepare("SELECT c.id,c.status,d.owner_account_id,d.charter_kind FROM site_company_relations r JOIN corrino_companies c ON c.id=r.parent_company_id JOIN site_company_deeds d ON d.company_id=c.id WHERE r.company_id=?").bind(current).first();
|
||||
|
|
|
|||
39
website/node/entity-relations.mjs
Normal file
39
website/node/entity-relations.mjs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import {randomUUID} from 'node:crypto';import {PUBLIC_OFFICES} from './public-government.mjs';
|
||||
export const ENTITY_RELATION_SCHEMA=`CREATE TABLE IF NOT EXISTS jarvis_entity_relations(child_kind VARCHAR(12) NOT NULL,child_id CHAR(36) NOT NULL,parent_kind VARCHAR(12) NOT NULL,parent_id VARCHAR(36) NOT NULL,relation_origin VARCHAR(16) NOT NULL,key_id CHAR(36) NOT NULL,request_id CHAR(36) NOT NULL UNIQUE,actor_id CHAR(36) NOT NULL,created_at BIGINT NOT NULL,PRIMARY KEY(child_kind,child_id))`;
|
||||
export const ENTITY_RELATION_GUARD_SCHEMA='CREATE TABLE IF NOT EXISTS jarvis_entity_relation_guard(id INTEGER PRIMARY KEY)';
|
||||
const first=(db,sql,args=[])=>db.first?db.first(sql,args):db.prepare(sql).bind(...args).first();
|
||||
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v);
|
||||
export async function currentOfficeController(db,key,now=Date.now()){
|
||||
const o=PUBLIC_OFFICES.find(o=>o.key===key);if(!o)return null;
|
||||
const kinds=o.kind==='bene'?['bene','house']:o.kind==='guild'?['guild','court']:[o.kind];
|
||||
const args=[o.faction,o.office,now,now,...kinds],sql="SELECT t.id,t.user_id FROM political_office_terms t JOIN site_accounts a ON a.id=t.user_id AND a.password_hash NOT LIKE '!%' WHERE t.faction=? AND t.office=? AND t.outcome='winner' AND t.starts_at<=? AND t.expires_at>? AND t.kind IN ("+kinds.map(()=>'?').join(',')+")";
|
||||
const rows=db.query?await db.query(sql,args):(await db.prepare(sql).bind(...args).all()).results;return rows.length===1?{userId:rows[0].user_id,termId:rows[0].id}:null;
|
||||
}
|
||||
export async function entityParent(db,kind,id){return first(db,'SELECT * FROM jarvis_entity_relations WHERE child_kind=? AND child_id=?',[kind,id]);}
|
||||
export async function entityControllers(db,kind,id,{clock=Date.now}={}){
|
||||
const users=new Set(),seen=new Set();let current={kind,id};
|
||||
for(let n=0;n<32;n++){
|
||||
const identity=current.kind+':'+current.id;if(seen.has(identity))throw Error('Entity hierarchy cycle');seen.add(identity);
|
||||
if(current.kind==='politics'){const office=await currentOfficeController(db,current.id,clock());if(office)users.add(office.userId);return [...users];}
|
||||
let parent=await entityParent(db,current.kind,current.id);
|
||||
if(!parent&¤t.kind==='company'){const old=await first(db,'SELECT parent_company_id FROM site_company_relations WHERE company_id=?',[current.id]);if(old)parent={parent_kind:'company',parent_id:old.parent_company_id};}
|
||||
if(!parent&¤t.kind==='clan'){const old=await first(db,'SELECT parent_clan_id FROM site_clan_deeds WHERE clan_id=?',[current.id]);if(old?.parent_clan_id)parent={parent_kind:'clan',parent_id:old.parent_clan_id};}
|
||||
if(!parent)return [...users];current={kind:parent.parent_kind,id:parent.parent_id};
|
||||
if(current.kind==='company'){const owner=await first(db,"SELECT d.owner_account_id,c.status,d.charter_kind FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id WHERE c.id=?",[current.id]);if(!owner||owner.status!=='active'||!['original','royal'].includes(owner.charter_kind))return [...users];if(!await first(db,"SELECT m.user_id FROM site_company_members m JOIN site_accounts a ON a.id=m.user_id AND a.password_hash NOT LIKE '!%' WHERE m.company_id=? AND m.user_id=?",[current.id,owner.owner_account_id]))throw Error('Parent company deed requires review');users.add(owner.owner_account_id);}
|
||||
else if(current.kind==='clan'){const owner=await first(db,"SELECT c.owner_id FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id AND m.user_id=c.owner_id JOIN site_game_links l ON l.user_id=m.user_id AND l.minecraft_uuid=m.minecraft_uuid JOIN site_accounts a ON a.id=m.user_id AND a.password_hash NOT LIKE '!%' WHERE c.id=? AND c.active=1",[current.id]);if(!owner)return [...users];users.add(owner.owner_id);}
|
||||
}
|
||||
throw Error('Entity hierarchy exceeds supported depth');
|
||||
}
|
||||
// Internal transaction primitive: the caller must validate its deed/key and both parties.
|
||||
export async function setEntityParent(tx,{childKind,childId,parentKind,parentId,origin,keyId,requestId,actorId,now=Date.now()}){
|
||||
if(!['company','clan'].includes(childKind)||!['company','clan','politics'].includes(parentKind)||!uuid(childId)||!uuid(keyId)||!uuid(requestId)||!uuid(actorId)||!['created','purchase','submission','conquest','staff'].includes(origin)||parentKind!=='politics'&&!uuid(parentId)||parentKind==='politics'&&!PUBLIC_OFFICES.some(o=>o.key===parentId))throw TypeError('Invalid parent deed instruction');
|
||||
if(!await tx.first('SELECT id FROM jarvis_entity_relation_guard WHERE id=1 FOR UPDATE'))throw Error('Entity relation guard unavailable');
|
||||
const lock=await tx.first(childKind==='company'?'SELECT owner_account_id FROM site_company_deeds WHERE company_id=? FOR UPDATE':'SELECT owner_id FROM site_clans WHERE id=? AND active=1 FOR UPDATE',[childId]);if(!lock)throw Error('Child deed unavailable');
|
||||
let next={kind:parentKind,id:parentId};const seen=new Set([childKind+':'+childId]);
|
||||
for(let n=0;n<32;n++){const node=next.kind+':'+next.id;if(seen.has(node))throw Error('Parent deed would create a cycle');seen.add(node);if(next.kind==='politics')break;const valid=await tx.first(next.kind==='company'?"SELECT c.id FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id WHERE c.id=? AND c.status='active' AND d.charter_kind IN ('original','royal') FOR UPDATE":"SELECT c.id FROM site_clans c JOIN site_clan_charters d ON d.clan_id=c.id WHERE c.id=? AND c.active=1 AND d.charter_kind IN ('original','royal') FOR UPDATE",[next.id]);if(!valid)throw Error('Parent deed unavailable');let p=await tx.first('SELECT * FROM jarvis_entity_relations WHERE child_kind=? AND child_id=? FOR UPDATE',[next.kind,next.id]);if(!p&&next.kind==='company'){const old=await tx.first('SELECT parent_company_id FROM site_company_relations WHERE company_id=?',[next.id]);if(old)p={parent_kind:'company',parent_id:old.parent_company_id};}if(!p&&next.kind==='clan'){const old=await tx.first('SELECT parent_clan_id FROM site_clan_deeds WHERE clan_id=?',[next.id]);if(old?.parent_clan_id)p={parent_kind:'clan',parent_id:old.parent_clan_id};}if(!p)break;if(n===31)throw Error('Parent hierarchy too deep');next={kind:p.parent_kind,id:p.parent_id};}
|
||||
const old=await entityParent(tx,childKind,childId);if(old?.request_id===requestId){if(old.parent_kind!==parentKind||old.parent_id!==parentId||old.key_id!==keyId)throw Error('Parent instruction reference conflict');return {replayed:true};}
|
||||
await tx.query('INSERT INTO jarvis_entity_relations(child_kind,child_id,parent_kind,parent_id,relation_origin,key_id,request_id,actor_id,created_at) VALUES(?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE parent_kind=VALUES(parent_kind),parent_id=VALUES(parent_id),relation_origin=VALUES(relation_origin),key_id=VALUES(key_id),request_id=VALUES(request_id),actor_id=VALUES(actor_id),created_at=VALUES(created_at)',[childKind,childId,parentKind,parentId,origin,keyId,requestId,actorId,now]);
|
||||
if(childKind==='company'){await tx.query('DELETE FROM site_company_relations WHERE company_id=?',[childId]);if(parentKind==='company')await tx.query('INSERT INTO site_company_relations(company_id,parent_company_id,relation_origin,updated_at) VALUES(?,?,?,?)',[childId,parentId,origin,now]);await tx.query('UPDATE site_company_deeds SET version=version+1,updated_at=? WHERE company_id=?',[now,childId]);}
|
||||
else await tx.query('UPDATE site_clan_deeds SET parent_clan_id=?,version=version+1,updated_at=? WHERE clan_id=?',[parentKind==='clan'?parentId:null,now,childId]);
|
||||
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actorId,'entity-parent-changed',JSON.stringify({childKind,childId,parentKind,parentId,origin,keyId,requestId}),now]);return {replayed:false};
|
||||
}
|
||||
41
website/tests/entity-relations.test.mjs
Normal file
41
website/tests/entity-relations.test.mjs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {companyFixture} from './company-deed-fixture.mjs';
|
||||
import {entityControllers,currentOfficeController} from '../node/entity-relations.mjs';
|
||||
test('parent company control requires a current eligible deed and owner membership',async()=>{
|
||||
const f=await companyFixture();try{
|
||||
const parent=await f.create(),child=randomUUID();
|
||||
await f.db.query("UPDATE site_company_deeds SET charter_kind='royal' WHERE company_id=?",[parent]);
|
||||
await f.db.query('INSERT INTO jarvis_entity_relations VALUES(?,?,?,?,?,?,?,?,?)',['company',child,'company',parent,'staff',randomUUID(),randomUUID(),f.people.Owner.id,Date.now()]);
|
||||
assert.deepEqual(await entityControllers(f.db,'company',child),[f.people.Owner.id]);
|
||||
await f.db.query('DELETE FROM site_company_members WHERE company_id=?',[parent]);
|
||||
await assert.rejects(entityControllers(f.db,'company',child),/requires review/);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
test('political parent authority follows the current unambiguous office term and expires',async()=>{
|
||||
const f=await companyFixture();try{
|
||||
f.db.sqlite.exec('ALTER TABLE political_office_terms ADD COLUMN id TEXT;ALTER TABLE political_office_terms ADD COLUMN kind TEXT;');
|
||||
const now=Date.now(),term=randomUUID();
|
||||
await f.db.query("INSERT INTO political_office_terms(id,kind,user_id,office,faction,starts_at,expires_at,outcome) VALUES(?,'imperial',?,'emperor','imperium',?,?,'winner')",[term,f.people.Owner.id,now-1000,now+1000]);
|
||||
assert.equal((await currentOfficeController(f.db,'emperor',now)).userId,f.people.Owner.id);
|
||||
assert.equal(await currentOfficeController(f.db,'emperor',now+1000),null);
|
||||
await f.db.query("INSERT INTO political_office_terms(id,kind,user_id,office,faction,starts_at,expires_at,outcome) VALUES(?,'imperial',?,'emperor','imperium',?,?,'winner')",[randomUUID(),f.people.Other.id,now-1000,now+1000]);
|
||||
assert.equal(await currentOfficeController(f.db,'emperor',now),null);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
import {setEntityParent} from '../node/entity-relations.mjs';
|
||||
test('parent changes serialize, reject cycles, preserve ownership and replay one instruction',async()=>{
|
||||
const f=await companyFixture();try{
|
||||
f.db.sqlite.exec('CREATE TABLE account_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,details TEXT,created_at INTEGER)');
|
||||
const child=await f.create(),parent=randomUUID(),now=Date.now();
|
||||
await f.db.query("INSERT INTO corrino_companies(id,slug,name,description,founded_by,status,created_at,updated_at) VALUES(?,'parent','Parent','Parent',?,'active',?,?)",[parent,f.people.Other.id,now,now]);
|
||||
await f.db.query("INSERT INTO site_company_deeds(company_id,owner_account_id,charter_kind,version,created_at,updated_at) VALUES(?,?,'royal',1,?,?)",[parent,f.people.Other.id,now,now]);
|
||||
const instruction={childKind:'company',childId:child,parentKind:'company',parentId:parent,origin:'staff',keyId:randomUUID(),requestId:randomUUID(),actorId:f.people.Owner.id};
|
||||
assert.equal((await f.db.transaction(tx=>setEntityParent(tx,instruction))).replayed,false);
|
||||
assert.equal((await f.db.transaction(tx=>setEntityParent(tx,instruction))).replayed,true);
|
||||
await f.db.query("UPDATE site_company_deeds SET charter_kind='royal' WHERE company_id=?",[child]);
|
||||
await assert.rejects(f.db.transaction(tx=>setEntityParent(tx,{...instruction,childId:parent,parentId:child,requestId:randomUUID()})),/cycle/);
|
||||
assert.equal((await f.db.first('SELECT owner_account_id FROM site_company_deeds WHERE company_id=?',[child])).owner_account_id,f.people.Owner.id);
|
||||
}finally{f.db.close();}
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff