Prepare audited clan bootstrap and protected institution rosters
This commit is contained in:
parent
4ca8ac1fcd
commit
f74828225b
7 changed files with 100 additions and 3 deletions
12
website/control-panel/clan-institutions.mjs
Normal file
12
website/control-panel/clan-institutions.mjs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
export const CLAN_INSTITUTION_SCHEMA=`CREATE TABLE IF NOT EXISTS site_clan_institutions (
|
||||
clan_id CHAR(36) PRIMARY KEY,institution_key VARCHAR(24) NOT NULL UNIQUE,
|
||||
member_limit INTEGER NOT NULL DEFAULT 5,franchise_terms INTEGER NOT NULL DEFAULT 5,
|
||||
recruitment_open INTEGER NOT NULL DEFAULT 0,custodian_user_id CHAR(36) NOT NULL,
|
||||
FOREIGN KEY(clan_id) REFERENCES site_clans(id),FOREIGN KEY(custodian_user_id) REFERENCES site_accounts(id))`;
|
||||
export function institutionalClanDenial(institution,action,body={}){
|
||||
if(!institution)return null;
|
||||
if(['archive','transfer','edit'].includes(action))return 'This institution has a permanent identity. Its franchise cannot be sold, transferred or conquered through ordinary clan management.';
|
||||
if(action==='request'||action==='review'&&body.decision==='accept')return 'Institution membership is reserved for its authorised franchise roster. Recruitment is not open.';
|
||||
if(action==='role'||action==='remove')return 'The institution roster is managed through its franchise.';
|
||||
return null;
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import {CLAN_INSTITUTION_SCHEMA,institutionalClanDenial} from './clan-institutions.mjs';
|
||||
import {clanEmblemUrl,CLAN_EMBLEM_SCHEMA} from './clan-emblems.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {identity} from '../node/auth.mjs';
|
||||
|
|
@ -13,12 +14,13 @@ export const CLAN_SCHEMA=[
|
|||
`CREATE TABLE IF NOT EXISTS site_clan_members (user_id CHAR(36) PRIMARY KEY,minecraft_uuid CHAR(36) NULL UNIQUE,clan_id CHAR(36) NOT NULL,clan_role VARCHAR(12) NOT NULL,joined_at BIGINT NOT NULL,FOREIGN KEY(user_id) REFERENCES site_accounts(id),FOREIGN KEY(clan_id) REFERENCES site_clans(id))`,
|
||||
`CREATE TABLE IF NOT EXISTS site_clan_requests (clan_id CHAR(36) NOT NULL,user_id CHAR(36) NOT NULL,status VARCHAR(12) NOT NULL,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL,decided_by CHAR(36) DEFAULT NULL,PRIMARY KEY(clan_id,user_id),FOREIGN KEY(clan_id) REFERENCES site_clans(id),FOREIGN KEY(user_id) REFERENCES site_accounts(id))`
|
||||
];
|
||||
CLAN_SCHEMA.push(CLAN_EMBLEM_SCHEMA);
|
||||
CLAN_SCHEMA.push(CLAN_EMBLEM_SCHEMA,CLAN_INSTITUTION_SCHEMA);
|
||||
export async function initializeClans(db,{mysql=true}={}){for(const sql of CLAN_SCHEMA)await db.prepare(sql+(mysql?' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4':'')).run();if(mysql){const column=await db.prepare("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='site_clans' AND COLUMN_NAME='home_world'").first();if(!column)try{await db.prepare('ALTER TABLE site_clans ADD COLUMN home_world VARCHAR(32) NULL').run();}catch(e){if(e.errno!==1060&&e.code!=='ER_DUP_FIELDNAME')throw e;}}}
|
||||
|
||||
/** Website clan membership only; never grants a website staff rank or claims game synchronization. */
|
||||
export function createClans(db,{origin='https://cp.dunerealms.com',authenticate=request=>identity(request,db),access=user=>accessFor(db,user),onClanCreated=async()=>{},onClanDeleted=async()=>{}}={}){
|
||||
const membership=id=>db.prepare('SELECT clan_id,clan_role FROM site_clan_members WHERE user_id=?').bind(id).first();
|
||||
const institution=id=>db.prepare('SELECT institution_key,member_limit,franchise_terms,recruitment_open,custodian_user_id FROM site_clan_institutions WHERE clan_id=?').bind(id).first();
|
||||
const clan=id=>db.prepare('SELECT id,name,tag,description,home_world,owner_id,version,created_at,updated_at FROM site_clans WHERE id=? AND active=1').bind(id).first();
|
||||
const publicClan=row=>{const {owner_id,...safe}=row;return {...safe,homeworldName:CLAN_HOMEWORLDS.find(w=>w.key===row.home_world)?.name||null,realm:CLAN_HOMEWORLDS.find(w=>w.key===row.home_world)?.realm||null,emblem:clanEmblemUrl(row.id,row.emblemVersion||0)};};
|
||||
return async request=>{
|
||||
|
|
@ -36,11 +38,12 @@ export function createClans(db,{origin='https://cp.dunerealms.com',authenticate=
|
|||
return json({homeworlds:CLAN_HOMEWORLDS,clans:results.map(row=>({...row,realm:CLAN_HOMEWORLDS.find(w=>w.key===row.home_world)?.realm||null,emblem:clanEmblemUrl(row.id)})),membership:own,applications,linked,username:user.username});
|
||||
}
|
||||
const record=await clan(match[1]);if(!record)return json({message:'Clan not found.'},404);
|
||||
const charter=await institution(record.id);record.institution=charter?{key:charter.institution_key,memberLimit:Number(charter.member_limit),franchiseTerms:Number(charter.franchise_terms),protected:true,recruitmentOpen:false}:null;
|
||||
const emblem=await db.prepare('SELECT version,image_blob IS NOT NULL AS has_image FROM site_clan_emblems WHERE clan_id=?').bind(record.id).first();record.emblemVersion=Number(emblem?.version||0);record.hasEmblem=!!emblem?.has_image;record.emblem=clanEmblemUrl(record.id,record.emblemVersion);
|
||||
const {results:members}=await db.prepare("SELECT a.username,m.clan_role,m.joined_at FROM site_clan_members m JOIN site_accounts a ON a.id=m.user_id WHERE m.clan_id=? ORDER BY CASE m.clan_role WHEN 'owner' THEN 0 WHEN 'officer' THEN 1 ELSE 2 END,a.username").bind(record.id).all();
|
||||
const role=own?.clan_id===record.id?own.clan_role:null,canReview=linked&&['owner','officer'].includes(role);
|
||||
const role=own?.clan_id===record.id?own.clan_role:null,canReview=linked&&!record.institution&&['owner','officer'].includes(role);
|
||||
const requests=canReview?(await db.prepare("SELECT a.username,r.created_at FROM site_clan_requests r JOIN site_accounts a ON a.id=r.user_id WHERE r.clan_id=? AND r.status='pending' ORDER BY r.created_at,a.username").bind(record.id).all()).results:[];
|
||||
return json({clan:publicClan(record),members,requests,role,canReview,canManage:linked&&role==='owner',linked});
|
||||
return json({clan:publicClan(record),members,requests,role,canReview,canManage:linked&&role==='owner'&&!record.institution,linked});
|
||||
}
|
||||
if(request.headers.get('origin')!==origin)return json({message:'Request origin rejected.'},403);
|
||||
let body;try{body=await request.json();}catch{return json({message:'Invalid request.'},400);}
|
||||
|
|
|
|||
57
website/scripts/create-alpha1009-clans.mjs
Normal file
57
website/scripts/create-alpha1009-clans.mjs
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
// 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;});
|
||||
25
website/tests/clan-institutions.test.mjs
Normal file
25
website/tests/clan-institutions.test.mjs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {institutionalClanDenial} from '../control-panel/clan-institutions.mjs';
|
||||
import {chooseClanRosters} from '../scripts/create-alpha1009-clans.mjs';
|
||||
import {LocalD1} from './d1-adapter.mjs';
|
||||
import {initializeClans,createClans} from '../control-panel/clans.mjs';
|
||||
test('protected institutions reject ordinary ownership and roster mutations without restricting normal clans',()=>{
|
||||
const charter={institution_key:'bene',member_limit:5};
|
||||
for(const action of ['archive','transfer','edit','request','role','remove']){assert.ok(institutionalClanDenial(charter,action));assert.equal(institutionalClanDenial(null,action),null);}
|
||||
assert.ok(institutionalClanDenial(charter,'review',{decision:'accept'}));assert.equal(institutionalClanDenial(charter,'review',{decision:'decline'}),null);assert.equal(institutionalClanDenial(charter,'withdraw'),null);
|
||||
});
|
||||
test('bootstrap reserves named House Veyr members, never duplicates a player and respects institution caps',()=>{
|
||||
const players=['halobeau143','racoonvibz','yooshi',...Array.from({length:8},(_,i)=>'player'+i)].map((username,i)=>({id:String(i),username,minecraft_uuid:String(i)}));
|
||||
const result=chooseClanRosters(players);assert.equal(result.house.length,4);assert.equal(result.house[0].username,'halobeau143');assert.equal(new Set([...result.house,...result.institutions.flat()].map(p=>p.id)).size,11);assert.deepEqual(result.institutions.map(r=>r.length),[4,3]);assert.throws(()=>chooseClanRosters(players.slice(1)),/requested player/);
|
||||
});
|
||||
test('actual clan API keeps protected identities and franchise rosters unchanged',async()=>{
|
||||
const db=new LocalD1('CREATE TABLE site_accounts(id TEXT PRIMARY KEY,username TEXT,role TEXT);CREATE TABLE site_game_links(user_id TEXT,minecraft_uuid TEXT);CREATE TABLE account_audit(id TEXT,actor_id TEXT,action TEXT,details TEXT,created_at INTEGER);');
|
||||
try{
|
||||
await initializeClans(db,{mysql:false});db.sqlite.exec("INSERT INTO site_accounts VALUES('owner','Leader','player'),('other','Other','player'),('steward','Steward','player');INSERT INTO site_game_links VALUES('owner','owner-mc'),('other','other-mc');");
|
||||
const id='11111111-1111-4111-8111-111111111111';db.sqlite.prepare("INSERT INTO site_clans(id,name,name_key,tag,description,owner_id,created_at,updated_at) VALUES(?,'Veiled Concord','veiled concord','VEIL','','owner',1,1)").run(id);db.sqlite.prepare("INSERT INTO site_clan_members VALUES('owner','owner-mc',?,'owner',1)").run(id);db.sqlite.prepare("INSERT INTO site_clan_institutions VALUES(?,'bene',5,5,0,'steward')").run(id);
|
||||
const app=actor=>createClans(db,{authenticate:async()=>({id:actor,username:actor}),access:async()=>({nodes:['web.menu.game']})});
|
||||
const post=(actor,action)=>app(actor)(new Request('https://cp.dunerealms.com/api/clans',{method:'POST',headers:{origin:'https://cp.dunerealms.com','Content-Type':'application/json'},body:JSON.stringify({action,clanId:id,version:1,target:'Other',decision:'accept',confirmTag:'VEIL'})}));
|
||||
for(const action of ['edit','archive','transfer','role','remove','review'])assert.equal((await post('owner',action)).status,403,action);
|
||||
assert.equal((await post('other','request')).status,403);const detail=await(await app('owner')(new Request('https://cp.dunerealms.com/api/clans/'+id))).json();assert.equal(detail.canManage,false);assert.equal(detail.canReview,false);assert.equal(detail.clan.institution.memberLimit,5);assert.equal(detail.members.length,1);assert.equal(db.sqlite.prepare('SELECT COUNT(*) n FROM account_audit').get().n,0);
|
||||
}finally{db.close();}
|
||||
});
|
||||
BIN
website/web/assets/clans/house-veyr-v1.png
Normal file
BIN
website/web/assets/clans/house-veyr-v1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.8 MiB |
BIN
website/web/assets/clans/vaerkring-v1.png
Normal file
BIN
website/web/assets/clans/vaerkring-v1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2 MiB |
BIN
website/web/assets/clans/veiled-concord-v1.png
Normal file
BIN
website/web/assets/clans/veiled-concord-v1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.1 MiB |
Loading…
Reference in a new issue

Staff