web/website/node/political-office-charters.mjs

32 lines
2.5 KiB
JavaScript

import {createHash} from 'node:crypto';
import {PUBLIC_OFFICES} from './public-government.mjs';
import {STAFF_OFFICE_ACCOUNT_ID,OrganisationKeyError} from './organisation-keys.mjs';
export const POLITICAL_OFFICE_CHARTER_SCHEMA=`CREATE TABLE IF NOT EXISTS political_office_charters (office_key VARCHAR(32) PRIMARY KEY,organisation_id CHAR(36) NOT NULL UNIQUE,charter_kind VARCHAR(12) NOT NULL,staff_key_id CHAR(36) NOT NULL UNIQUE,applied_at BIGINT NOT NULL)`;
export function politicalOfficeId(key){
if(!PUBLIC_OFFICES.some(o=>o.key===key))throw new TypeError('Unknown protected political office');
const hex=createHash('sha256').update('dunerealms:protected-office:'+key).digest('hex');
return hex.slice(0,8)+'-'+hex.slice(8,12)+'-4'+hex.slice(13,16)+'-8'+hex.slice(17,20)+'-'+hex.slice(20,32);
}
// Internal system reconciliation, never a user redemption or a personal founding grant.
// Royal standing belongs to the office; membership still follows the current office deed.
export async function ensurePoliticalOfficeCharters(db,keys,{clock=Date.now}={}){
if(!keys)throw new TypeError('The organisation key service is required');
await db.query(POLITICAL_OFFICE_CHARTER_SCHEMA);
let applied=0;
for(const office of PUBLIC_OFFICES){
const targetId=politicalOfficeId(office.key),scopeId='office:'+office.key;
const grant=await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'staff-office-royal',scopeId,authorize:async()=>{politicalOfficeId(office.key);}});
const 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-office-royal',code:key.code,targetId,requestId:targetId,apply:async(tx,context)=>{
if(context.scopeId!==scopeId)throw new OrganisationKeyError('Staff key does not match this office');
await tx.query('INSERT INTO political_office_charters(office_key,organisation_id,charter_kind,staff_key_id,applied_at) VALUES(?,?,?,?,?)',[office.key,targetId,'royal',context.keyId,clock()]);
}});applied++;
}
const row=await db.prepare('SELECT organisation_id,charter_kind,staff_key_id FROM political_office_charters WHERE office_key=?').bind(office.key).first();
if(key?.status!=='available'&&key?.status!=='used'||!row||row.organisation_id!==targetId||row.charter_kind!=='royal'||row.staff_key_id!==grant.id||key?.status==='used'&&key.targetId!==targetId)throw new OrganisationKeyError('Protected office staff charter requires review');
}
db.politicalOfficeChartersEnabled=true;
return{offices:PUBLIC_OFFICES.length,applied};
}