web/website/node/clandestine-institutions.mjs
2026-11-27 23:43:05 +00:00

48 lines
8.2 KiB
JavaScript

import {randomUUID} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs';
import {createSystemCharacters} from './system-characters.mjs';
import {recordInitialCompanyDeed} from './company-deeds.mjs';
import {SMUGGLER_CLAN_ID,SMUGGLER_COMPANY_ID} from './clandestine-identity.mjs';
const scope='institution:smugglers:v1',requestId='f905b561-73e4-59c3-a5cf-c06e82100fc1';
export const SECONDARY_AFFILIATION_SCHEMA='CREATE TABLE IF NOT EXISTS jarvis_secondary_affiliations(account_id CHAR(36) NOT NULL,organisation_kind VARCHAR(12) NOT NULL,organisation_id CHAR(36) NOT NULL,source_key_id CHAR(36) NOT NULL,joined_at BIGINT NOT NULL,PRIMARY KEY(account_id,organisation_kind,organisation_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4';
export async function initializeSecondaryAffiliations(db){await db.query(SECONDARY_AFFILIATION_SCHEMA);db.secondaryAffiliationsEnabled=true;}
const first=async(db,sql,args=[])=>(await db.query(sql,args))[0]||null;
async function custodian(store,keys){const identity=await createSystemCharacters(store,keys,{authorizeOperator:async()=>false}).inspect('esmar_tuek');if(!identity?.capabilities.includes('quest.issue'))throw Error('Current smuggler system identity required');return identity;}
export async function readSmugglerInstitutions(store,keys,{lock=false}={}){
const identity=await custodian(store,keys),row=await first(store,"SELECT k.id,k.used_at,k.revoked_at FROM organisation_keys k JOIN site_clan_charters ch ON ch.key_id=k.id AND ch.clan_id=? JOIN site_clan_institutions ci ON ci.clan_id=ch.clan_id AND ci.institution_key='smugglers' JOIN site_company_deeds d ON d.original_key_id=k.id AND d.company_id=? JOIN site_company_institutions i ON i.company_id=d.company_id AND i.institution_key='smugglers' JOIN site_clans c ON c.id=ch.clan_id AND c.active=1 JOIN corrino_companies co ON co.id=d.company_id AND co.status='active' WHERE k.account_id=? AND k.key_type='staff-parent-link' AND k.scope_id=? AND k.expires_at IS NULL AND ch.charter_kind='royal' AND d.charter_kind='royal' AND k.target_id=? AND c.owner_id=? AND ci.custodian_user_id=? AND d.owner_account_id=?"+(lock?' FOR UPDATE':''),[SMUGGLER_CLAN_ID,SMUGGLER_COMPANY_ID,STAFF_OFFICE_ACCOUNT_ID,scope,SMUGGLER_CLAN_ID,identity.id,identity.id,identity.id]);
if(!row||row.used_at===null||row.revoked_at!==null)return null;return {keyId:row.id,custodianId:identity.id,clanId:SMUGGLER_CLAN_ID,companyId:SMUGGLER_COMPANY_ID,hidden:true,protected:true};
}
export function createClandestineInstitutions(db,keys,{authorizeOperator,clock=Date.now}={}){
if(typeof authorizeOperator!=='function')throw TypeError('Current institution operator required');
return Object.freeze({async provision(actor){
const verify=async tx=>{if(await authorizeOperator(actor,tx)!==true)throw Error('Current institution operator required');const identity=await custodian(tx,keys);const key=await tx.first('SELECT revoked_at FROM organisation_keys WHERE id=? FOR UPDATE',[identity.keyId]);if(!key||key.revoked_at!==null)throw Error('System custodian changed');return identity;};
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',scopeId:scope,authorize:verify}),key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id);
let applied=false;if(key?.status==='available'){const result=await keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-parent-link',code:key.code,targetId:SMUGGLER_CLAN_ID,requestId,apply:async tx=>{
const identity=await verify(tx),now=clock();
if(await tx.first("SELECT id FROM site_clans WHERE id=? OR name_key='the unmarked caravan' OR tag='SMUG' FOR UPDATE",[SMUGGLER_CLAN_ID])||await tx.first("SELECT id FROM corrino_companies WHERE id=? OR slug='tuek-hidden-exchange' FOR UPDATE",[SMUGGLER_COMPANY_ID]))throw Error('Reserved institution identity collision; nothing was adopted');
if(await tx.first('SELECT clan_id FROM site_clan_members WHERE user_id=? FOR UPDATE',[identity.id]))throw Error('System custodian already has a primary clan');
await tx.query("INSERT INTO site_clans(id,name,name_key,tag,description,owner_id,active,version,created_at,updated_at,home_world) VALUES(?,'The Unmarked Caravan','the unmarked caravan','SMUG','Protected hidden smuggler institution. Secondary quest affiliations confer no ordinary clan authority.',?,1,1,?,?,'arrakduin')",[SMUGGLER_CLAN_ID,identity.id,now,now]);
await tx.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',?)",[identity.id,identity.minecraftUuid,SMUGGLER_CLAN_ID,now]);
await tx.query('INSERT INTO site_clan_deeds(clan_id,updated_at) VALUES(?,?)',[SMUGGLER_CLAN_ID,now]);
await tx.query("INSERT INTO site_clan_charters(clan_id,original_account_id,key_id,charter_kind,created_at) VALUES(?,?,?,'royal',?)",[SMUGGLER_CLAN_ID,identity.id,grant.id,now]);
await tx.query("INSERT INTO site_clan_institutions(clan_id,institution_key,member_limit,franchise_terms,recruitment_open,custodian_user_id) VALUES(?,'smugglers',5,5,0,?)",[SMUGGLER_CLAN_ID,identity.id]);
await tx.query("INSERT INTO corrino_companies(id,slug,name,description,founded_by,ceo_account_id,status,created_at,updated_at) VALUES(?,'tuek-hidden-exchange','Tuek Hidden Exchange','Protected hidden smuggler company. Secondary affiliations grant no PvP or bank authority.',?,NULL,'active',?,?)",[SMUGGLER_COMPANY_ID,identity.id,now,now]);
await recordInitialCompanyDeed(tx,{id:SMUGGLER_COMPANY_ID,founded_by:identity.id,created_at:now},now);
await tx.query("UPDATE site_company_deeds SET charter_kind='royal',original_key_id=? WHERE company_id=?",[grant.id,SMUGGLER_COMPANY_ID]);
await tx.query("INSERT INTO site_company_institutions(company_id,institution_key) VALUES(?,'smugglers')",[SMUGGLER_COMPANY_ID]);
await tx.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'hidden-smuggler-institutions',JSON.stringify({keyId:grant.id,clanId:SMUGGLER_CLAN_ID,companyId:SMUGGLER_COMPANY_ID,systemCustodian:identity.id,ticketId:412,ordinaryAccountsMoved:0}),now]);
}});applied=!result.replayed;}
const current=await readSmugglerInstitutions(db,keys);if(!current||current.keyId!==grant.id)throw Error('Protected institution charter requires review');return {...current,created:applied};
}});
}
export async function grantSmugglerAffiliations(tx,keys,actor,{clock=Date.now}={}){
const institutions=await readSmugglerInstitutions(tx,keys,{lock:true});if(!institutions)throw Error('Protected smuggler institutions are unavailable');
const quest=await first(tx,"SELECT s.key_id FROM jarvis_pol_quest_states s JOIN organisation_keys k ON k.id=s.key_id WHERE s.account_id=? AND s.definition_id='POL-SMUGGLERS-01' AND k.key_type='quest' AND k.account_id=s.account_id AND k.scope_id=CONCAT(s.season_id,':POL_POL-SMUGGLERS-01') AND k.revoked_at IS NULL FOR UPDATE",[actor.id]);if(!quest)throw Error('Bound smuggler introduction quest required');
for(const [kind,id]of [['clan',SMUGGLER_CLAN_ID],['company',SMUGGLER_COMPANY_ID]])await tx.query('INSERT INTO jarvis_secondary_affiliations(account_id,organisation_kind,organisation_id,source_key_id,joined_at) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE account_id=VALUES(account_id)',[actor.id,kind,id,quest.key_id,clock()]);
return {sourceKeyId:quest.key_id,primaryAffiliationChanged:false};
}
export async function readSmugglerAffiliations(db,keys,accountId){
const rows=await db.query("SELECT a.organisation_kind,a.organisation_id,a.joined_at FROM jarvis_secondary_affiliations a JOIN organisation_keys k ON k.id=a.source_key_id AND k.account_id=a.account_id AND k.key_type='quest' AND k.used_at IS NOT NULL AND k.revoked_at IS NULL JOIN jarvis_pol_quest_claims q ON q.key_id=k.id AND q.account_id=a.account_id JOIN jarvis_pol_quest_states s ON s.key_id=k.id AND s.definition_id='POL-SMUGGLERS-01' WHERE a.account_id=? AND ((a.organisation_kind='clan' AND a.organisation_id=?) OR (a.organisation_kind='company' AND a.organisation_id=?)) ORDER BY a.organisation_kind",[accountId,SMUGGLER_CLAN_ID,SMUGGLER_COMPANY_ID]);
if(!rows.length||!await readSmugglerInstitutions(db,keys))return [];
return rows.map(r=>({kind:r.organisation_kind,id:r.organisation_id,secondary:true,hidden:true,capabilities:['quest.smuggling'],pvp:false,bankManagement:false,joinedAt:Number(r.joined_at)}));
}