MC/website/scripts/create-alpha1009-clans.mjs

57 lines
8.2 KiB
JavaScript

// Explicit operator bootstrap requested by the owner. No game factions, bank
// accounts, voting records, companies or external messages are changed here.
import {randomUUID,randomInt} from 'node:crypto';
import {readFile,mkdir,writeFile} from 'node:fs/promises';
import {execFileSync} from 'node:child_process';
import {fileURLToPath} from 'node:url';
import {pathToFileURL} from 'node:url';
const root=new URL('../',import.meta.url),seed='alpha1009-clan-bootstrap-v1';
const names=['House Veyr','Veiled Concord','Vaerkring'];
const shuffle=items=>{const result=[...items];for(let i=result.length-1;i>0;i--){const j=randomInt(i+1);[result[i],result[j]]=[result[j],result[i]];}return result;};
export function chooseClanRosters(eligible){
const required=['halobeau143','racoonvibz','yooshi'],byName=new Map(eligible.map(p=>[p.username.toLowerCase(),p]));
if(required.some(n=>!byName.has(n)))throw Error('A requested player is no longer eligible or clanless.');
const rest=shuffle(eligible.filter(p=>!required.includes(p.username.toLowerCase())));if(rest.length<5)throw Error('Not enough clanless linked players for an officer/leader in both institutions.');
const house=[...required.map(n=>byName.get(n)),rest.shift()],institutions=[[],[]];
for(const player of rest){const target=institutions[0].length<=institutions[1].length?0:1;if(institutions[target].length<5)institutions[target].push(player);if(institutions.every(r=>r.length===5))break;}
return {house,institutions};
}
function image(relative){
// Operator assets are trusted repository files, not public uploads. Keep the
// same pixel/dimension/animation restrictions and bounded WebP storage format.
const python=`import io,sys,warnings\nfrom PIL import Image\nImage.MAX_IMAGE_PIXELS=4194304\nwarnings.simplefilter('error',Image.DecompressionBombWarning)\nb=sys.stdin.buffer.read(3145729)\nassert 0<len(b)<=3145728\ni=Image.open(io.BytesIO(b))\nassert i.format=='PNG' and getattr(i,'n_frames',1)==1 and min(i.size)>=32 and max(i.size)<=4096\ni.verify()\ni=Image.open(io.BytesIO(b)).convert('RGBA')\ni.thumbnail((512,512),Image.Resampling.LANCZOS)\ni.save(sys.stdout.buffer,'WEBP',quality=90,method=6)`;
return readFile(new URL('web/assets/clans/'+relative,root)).then(bytes=>{const output=execFileSync('python3',['-c',python],{input:bytes,maxBuffer:1048576,timeout:10000});if(!output.length||output.length>1048576)throw Error('Invalid emblem');return output;});
}
async function main(apply){
const mysql=(await import('mysql2/promise')).default,db=await mysql.createConnection({user:'root',socketPath:'/var/run/mysqld/mysqld.sock',database:'website',charset:'utf8mb4'});
try{
const [prior]=await db.query("SELECT id FROM account_audit WHERE action='clan-bootstrap' AND details LIKE ?",['%'+seed+'%']);if(prior.length){console.log('Already bootstrapped. Existing clans and later progress will not be overwritten.');return;}
const [existing]=await db.query('SELECT id FROM site_clans WHERE name IN (?,?,?) OR tag IN (?,?,?)',[...names,'VEYR','VEIL','VAER']);if(existing.length)throw Error('A requested clan already exists; operator review required.');
const [eligible]=await db.query("SELECT a.id,a.username,l.minecraft_uuid FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id LEFT JOIN site_clan_members m ON m.user_id=a.id WHERE m.user_id IS NULL AND a.password_hash NOT LIKE '!%' ORDER BY a.id");
const {house,institutions}=chooseClanRosters(eligible),plan=[house,...institutions];console.log(JSON.stringify(names.map((name,i)=>({name,members:plan[i].map((p,j)=>({username:p.username,role:i===0?(j===0?'officer':'member'):(j===0?'owner':j===1?'officer':'member')}))})),null,2));if(!apply)return;
const images=await Promise.all(['house-veyr-v1.png','veiled-concord-v1.png','vaerkring-v1.png'].map(image));
await db.query("SELECT GET_LOCK('alpha1009-clan-bootstrap',10)");await db.beginTransaction();
const [repeat]=await db.query("SELECT id FROM account_audit WHERE action='clan-bootstrap' AND details LIKE ? FOR UPDATE",['%'+seed+'%']);if(repeat.length)throw Error('Bootstrap already completed.');
const [actor]=await db.query("SELECT id FROM site_accounts WHERE LOWER(username)='unimatrix999' LIMIT 1");if(actor.length!==1)throw Error('Authorising operator identity unavailable');
const now=Date.now(),manifest=[];
for(let i=0;i<3;i++){
for(const p of plan[i]){const [rows]=await db.query('SELECT a.id FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id LEFT JOIN site_clan_members m ON m.user_id=a.id WHERE a.id=? AND l.minecraft_uuid=? AND m.user_id IS NULL AND a.password_hash NOT LIKE ? FOR UPDATE',[p.id,p.minecraft_uuid,'!%']);if(rows.length!==1)throw Error('Selected player membership or account changed.');}
const username=['house_veyr_steward','veiled_concord_steward','vaerkring_steward'][i],custodian=randomUUID(),clanId=randomUUID();
const [reserved]=await db.query('SELECT id FROM site_accounts WHERE username=? FOR UPDATE',[username]);if(reserved.length)throw Error('Steward identity already exists; no accounts overwritten');
await db.query("INSERT INTO site_accounts(id,username,display_name,password_salt,password_hash,role,created_at) VALUES(?,?,?,?,?,'player',?)",[custodian,username,names[i]+' Steward','0'.repeat(32),'!system-clan-custodian',now]);
const owner=i===0?custodian:plan[i][0].id,descriptions=[
'House Veyr — an original minor House of caravan surveyors and keepers of safe routes. Motto: The route endures. Clearly designated test House for clan information, emblems and future patronage testing. No patronage agreement is active.',
'Veiled Concord — the veiled institution of discipline, memory and counsel. Protected institutional clan; five-player maximum. Its founding roster is prepared for the future franchise system. No elected office or game-faction change is granted by this setup.',
'Vaerkring — the Routekeepers of the interworld compact. Protected institutional clan; five-player maximum. Its founding roster is prepared for the future franchise system. No elected office or game-faction change is granted by this setup.'
];
await db.query('INSERT INTO site_clans(id,name,name_key,tag,description,home_world,owner_id,active,version,created_at,updated_at) VALUES(?,?,?,?,?,?,?,1,1,?,?)',[clanId,names[i],names[i].toLowerCase(),['VEYR','VEIL','VAER'][i],descriptions[i],i===0?'kaladam':null,owner,now,now]);
if(i===0)await db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,NULL,?,'owner',?)",[custodian,clanId,now]);
for(let j=0;j<plan[i].length;j++){const p=plan[i][j],role=i===0?(j===0?'officer':'member'):(j===0?'owner':j===1?'officer':'member');await db.query('INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,?,?)',[p.id,p.minecraft_uuid,clanId,role,now]);await db.query("UPDATE site_clan_requests SET status='withdrawn',updated_at=? WHERE user_id=? AND status='pending'",[now,p.id]);}
if(i>0)await db.query('INSERT INTO site_clan_institutions(clan_id,institution_key,member_limit,franchise_terms,recruitment_open,custodian_user_id) VALUES(?,?,5,5,0,?)',[clanId,i===1?'bene':'guild',custodian]);
await db.query('INSERT INTO site_clan_emblems(clan_id,image_blob,version,updated_by,updated_at) VALUES(?,?,1,?,?)',[clanId,images[i],actor[0].id,now]);
await db.query('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor[0].id,'clan-bootstrap',JSON.stringify({seed,clanId,name:names[i],members:plan[i].map(p=>p.username),institution:i>0,gameFactionsUnchanged:true,companiesUnchanged:true}),now]);manifest.push({id:clanId,name:names[i],members:plan[i]});
}
const dir='/mnt/HC_Volume_107481500/dunegit/migration-backups';await mkdir(dir,{recursive:true,mode:0o700});await writeFile(dir+'/clan-bootstrap-'+now+'.json',JSON.stringify(manifest),{flag:'wx',mode:0o600});await db.commit();console.log('Created three clans and emblems. No companies, factions, bank accounts or elected offices changed.');
}catch(error){await db.rollback();throw error;}finally{await db.end();}
}
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href)void main(process.argv.includes('--apply')).catch(error=>{console.error('Clan setup stopped and rolled back.',error.code||error.message);process.exitCode=1;});