MC/website/node/company-royal-mail.mjs
2026-11-27 23:43:05 +00:00

38 lines
5.2 KiB
JavaScript

import {createHash,randomUUID} from 'node:crypto';
import {STAFF_OFFICE_ACCOUNT_ID,OrganisationKeyError} from './organisation-keys.mjs';
export const COMPANY_ROYAL_MAIL_SCHEMA=`CREATE TABLE IF NOT EXISTS site_company_royal_mail (company_id CHAR(36) PRIMARY KEY,royal_key_id CHAR(36) NOT NULL UNIQUE,mailbox_id CHAR(36) NOT NULL UNIQUE,state VARCHAR(12) NOT NULL,updated_at BIGINT NOT NULL)`;
export function separateCompanyMailboxId(id){const h=createHash('sha256').update('dunerealms:royal-company-mail:'+id).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-4'+h.slice(13,16)+'-8'+h.slice(17,20)+'-'+h.slice(20,32);}
const targetSql="SELECT c.id,c.name,c.slug,c.status,d.owner_account_id,d.charter_kind,d.original_key_id FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id JOIN site_accounts a ON a.id=d.owner_account_id WHERE LOWER(c.name)='unicorp' AND LOWER(a.username)='unimatrix999' AND a.password_hash NOT LIKE '!%'";
const first=(db,sql,args=[])=>typeof db.first==='function'?db.first(sql,args):db.prepare(sql).bind(...args).first();
async function verifyOriginal(tx,c){
const original=c&&await first(tx,"SELECT id FROM organisation_keys WHERE id=? AND key_type='company-founding' AND target_id=? AND used_at IS NOT NULL AND revoked_at IS NULL",[c.original_key_id,c.id]);
if(!c||c.status!=='active'||!['original','royal'].includes(c.charter_kind)||!original)throw new OrganisationKeyError('The active Unicorp original Company deed must match before the authorised Royal upgrade');
}
// One explicitly requested rollout. No other company, account, personal key or
// old mailbox is promoted, moved, deleted or granted staff access.
export async function applyUnicorpRoyalMailbox(db,keys,{apply=false,clock=Date.now}={}){
const rows=await db.query(targetSql);if(!rows.length)return{state:'not_found',changed:false};if(rows.length!==1)throw new OrganisationKeyError('Unicorp identity is ambiguous');const c=rows[0];
await verifyOriginal(db,c);if(!apply)return{state:'ready',companyId:c.id,name:c.name,currentCharter:c.charter_kind,desiredCharter:'royal',mailbox:'separate',changed:false};
await db.query(COMPANY_ROYAL_MAIL_SCHEMA);
const scopeId='company:'+c.id,grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-company-royal',scopeId,authorize:async tx=>{await verifyOriginal(tx,await tx.first(targetSql+' FOR UPDATE'));}}),key=(await keys.list(STAFF_OFFICE_ACCOUNT_ID)).find(k=>k.id===grant.id);
if(key?.status==='available')await keys.consume({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-company-royal',code:key.code,targetId:c.id,requestId:c.id,apply:async(tx,context)=>{
const current=await tx.first(targetSql+' FOR UPDATE');await verifyOriginal(tx,current);if(current.id!==c.id||context.scopeId!==scopeId)throw new OrganisationKeyError('The Company deed changed');const now=clock();
await tx.query("UPDATE site_company_deeds SET charter_kind='royal',version=version+1,updated_at=? WHERE company_id=?",[now,c.id]);
await tx.query("INSERT INTO site_company_royal_mail(company_id,royal_key_id,mailbox_id,state,updated_at) VALUES(?,?,?,'pending',?)",[c.id,context.keyId,separateCompanyMailboxId(c.id),now]);
await tx.query('INSERT INTO corrino_company_events(id,company_id,action,actor_id,details_json,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),c.id,'staff-royal-upgrade',STAFF_OFFICE_ACCOUNT_ID,JSON.stringify({keyId:context.keyId,reason:'Explicit owner request: Royal Unicorp and separate mailbox',mailbox:'separate'}),now]);
}});
const record=await first(db,'SELECT royal_key_id,mailbox_id,state FROM site_company_royal_mail WHERE company_id=?',[c.id]);
if(!record||record.royal_key_id!==grant.id||key?.status!=='available'&&(key?.status!=='used'||key.targetId!==c.id))throw new OrganisationKeyError('Unicorp Royal staff key requires review');
return{state:record.state,companyId:c.id,name:c.name,charter:'royal',changed:key.status==='available'};
}
export async function readRoyalCompanyMailbox(db,id,now=Date.now()){
return first(db,"SELECT m.mailbox_id,m.state,c.id,c.name,c.slug FROM site_company_royal_mail m JOIN corrino_companies c ON c.id=m.company_id JOIN site_company_deeds d ON d.company_id=c.id JOIN organisation_keys k ON k.id=m.royal_key_id WHERE c.id=? AND c.status='active' AND d.charter_kind='royal' AND k.key_type IN ('staff-company-royal','political-appointment') AND k.used_at IS NOT NULL AND k.target_id=c.id AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>?)",[id,now]);
}
export async function reconcileRoyalCompanyMail(db,broker){
await db.query(COMPANY_ROYAL_MAIL_SCHEMA);const rows=await db.query("SELECT company_id FROM site_company_royal_mail WHERE state='pending' ORDER BY company_id");let activated=0;
for(const row of rows){const source=await readRoyalCompanyMailbox(db,row.company_id);if(!source)continue;
await broker({action:'internal_ensure',userId:source.mailbox_id,eligible:true,mailboxKind:'clan',resourceId:source.id,localPart:'company-'+source.slug+'.internal'});
if(!await readRoyalCompanyMailbox(db,row.company_id))continue;
await db.query("UPDATE site_company_royal_mail SET state='active',updated_at=? WHERE company_id=? AND mailbox_id=? AND state='pending'",[Date.now(),source.id,source.mailbox_id]);activated++;
}return{activated};
}