web/website/scripts/bootstrap-organisation-policies.mjs
2026-11-27 23:43:05 +00:00

32 lines
2.7 KiB
JavaScript

import {randomUUID} from 'node:crypto';
import {fileURLToPath} from 'node:url';
import {resolve} from 'node:path';
import {openDatabase} from '../node/mysql.mjs';
import {initializeOrganisation} from '../node/organisation-model.mjs';
import {defaultOrganisationPolicies} from '../node/organisation-default-policies.mjs';
export async function bootstrapPolicies(db,{actorId,apply=false,clock=Date.now}={}){
if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(actorId||''))throw Error('An existing control actor UUID is required.');
const templates=defaultOrganisationPolicies();
if(!apply)return {applied:false,templates,permissionsChanged:false};
return db.transaction(async tx=>{
const actor=await tx.first("SELECT a.id,p.principal_kind FROM site_accounts a JOIN org_control_principals p ON p.user_id=a.id WHERE a.id=? AND a.password_hash NOT LIKE '!%' FOR SHARE",[actorId]);
if(!actor||!['owner','executive','service'].includes(actor.principal_kind))throw Error('Current control principal required.');
let created=0,retained=0;
for(const p of templates){
await tx.query('INSERT IGNORE INTO org_scope_versions(scope_type,scope_key,version) VALUES(?,?,1)',[p.scopeType,p.scopeKey]);
await tx.first('SELECT version FROM org_scope_versions WHERE scope_type=? AND scope_key=? FOR UPDATE',[p.scopeType,p.scopeKey]);
const existing=await tx.first('SELECT version FROM org_role_policies WHERE scope_type=? AND scope_key=? AND role_key=? FOR UPDATE',[p.scopeType,p.scopeKey,p.role]);
if(existing){retained++;continue;}
const now=clock();
await tx.query('INSERT INTO org_role_policies(scope_type,scope_key,role_key,permissions_json,version,updated_by,updated_at) VALUES(?,?,?,?,1,?,?)',[p.scopeType,p.scopeKey,p.role,JSON.stringify(p.nodes),actorId,now]);
await tx.query('UPDATE org_scope_versions SET version=version+1 WHERE scope_type=? AND scope_key=?',[p.scopeType,p.scopeKey]);
await tx.query('INSERT INTO org_assignment_events(id,user_id,actor_id,action,scope_type,scope_key,reason,after_json,created_at) VALUES(?,?,?,?,?,?,?,?,?)',[randomUUID(),null,actorId,'policy-baseline',p.scopeType,p.scopeKey,'Owner-approved Great Migration explicit function mapping',JSON.stringify({role:p.role,nodes:p.nodes,permissionsChanged:false}),now]);
created++;
}
return {applied:true,created,retained,permissionsChanged:false,enforcement:'preparing'};
});
}
if(process.argv[1]&&fileURLToPath(import.meta.url)===resolve(process.argv[1])){
const db=await openDatabase(process.env);
try{await initializeOrganisation(db);console.log(JSON.stringify(await bootstrapPolicies(db,{actorId:process.argv.find(a=>a.startsWith('--actor='))?.slice(8),apply:process.argv.includes('--apply')})));}finally{await db.close();}
}