forked from unimatrix/web
Project central game rights and reuse native support department adapters
This commit is contained in:
parent
5291938c1a
commit
04532cb7ec
10 changed files with 103 additions and 8 deletions
|
|
@ -100,3 +100,5 @@ Effective-access preview: GET /api/admin/organisation/effective?userId=UUID requ
|
|||
Default policies now enumerate 22 function mappings (nine branches with Officer/Lead, two Department Heads, Owner/Executive). Native permission editors are excluded for humans; official bank management remains departmental/executive, payroll requires pinned control identity. bootstrap-organisation-policies.mjs defaults to a plan; explicit --apply --actor=UUID requires an active control principal, retains existing policies, versions each scope and audits inserts atomically. It stores preparation data only, with no legacy rank replacement, user appointments or native group projection.
|
||||
|
||||
Runtime integration: ORGANISATION_ACCESS_ENABLED=true opts the central database adapter into fresh, read-snapshot organisation access. The default remains disabled. Enabled accessFor replaces legacy staff/owner bypass with new explicit policies, preserves ordinary/VIP/Order membership, and keeps only the pinned exempt Dev service on its existing access path. Invalid policy data fails closed, never falls back to old admin grants. This switch must not be enabled before control baseline, assignments, policy coverage and native projections are reconciled. This source batch does not enable it in production. Public session exports the account's own active functions.
|
||||
|
||||
Native bridge integration: activated game sync sends stable permission-set groups through the existing revision-confirmed /permissions/teams bridge. Explicit canonical game nodes plus retained citizen gameplay perks are combined; wildcard/OP/LuckPerms editor grants and service identities are excluded. Duplicate verified UUIDs abort the projection. Unactivated game sync stays on its existing path. Native agent sync reuses the installed osTicket adapter and maps ticket department tags; active human payloads omit native administration flags while retaining business department access. Dev service payload is unchanged. No game server or native application code is rewritten or deployed by this source batch.
|
||||
|
|
|
|||
|
|
@ -1,11 +1,22 @@
|
|||
import {projectOrganisationGameUsers} from './organisation-game-projection.mjs';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {accessFor,rankFor} from './permissions.mjs';
|
||||
import {gameNodesForRank} from './game-ranks.mjs';
|
||||
import {accessFor,rankFor,NODES} from './permissions.mjs';
|
||||
import {gameNodesForRank,GAME_NODE_SET,BANK_MAP} from './game-ranks.mjs';
|
||||
export async function syncGamePermissions(db,{settings=process.env,fetcher=fetch,access=user=>accessFor(db,user)}={}){
|
||||
if((settings.SERVER_CONTROL_TOKEN||'').length<64)throw Error('Game permission bridge unavailable');
|
||||
if(db.organisationAccessEnabled){
|
||||
const {results:accounts}=await db.prepare("SELECT a.id,a.username,a.role,l.minecraft_uuid FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND a.role<>'memorial' AND NOT EXISTS (SELECT 1 FROM site_account_policies p WHERE p.user_id=a.id AND p.game_link_exempt=1) ORDER BY a.id").all();
|
||||
const projection=await projectOrganisationGameUsers(accounts,{access,gameNodes:new Set([...GAME_NODE_SET,...Object.keys(NODES).filter(n=>/^(?:dune|duneess|duneprotect|dunelobby)\./.test(n))]),bankMap:BANK_MAP,citizenGameNodes:async keys=>{
|
||||
const nodes=[];for(const key of keys.filter(k=>!k.startsWith('org_'))){const rank=await rankFor(db,key);for(const node of(await gameNodesForRank(db,rank)).nodes)nodes.push(node);}return nodes;
|
||||
}});
|
||||
return deliverGamePermissions(projection,{settings,fetcher});
|
||||
}
|
||||
const {results:stored}=await db.prepare("SELECT rank_key FROM cp_ranks WHERE kind='access' AND rank_level>0 ORDER BY rank_key").all();const ranks=[];
|
||||
for(const row of stored){if(!/^[a-z][a-z0-9_]{2,29}$/.test(row.rank_key))throw Error('Rank cannot be projected to game');const rank=await rankFor(db,row.rank_key),game=await gameNodesForRank(db,rank);ranks.push({id:rank.key,permissions:Object.fromEntries(game.nodes.map(n=>[n,true]))});}
|
||||
const {results:accounts}=await db.prepare("SELECT a.id,a.username,a.role,l.minecraft_uuid FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE a.password_hash NOT LIKE '!%' AND a.role<>'memorial' ORDER BY a.id").all();const users=[];
|
||||
for(const user of accounts){if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(user.minecraft_uuid))throw Error('Invalid verified identity');const rights=await access(user);users.push({uuid:user.minecraft_uuid.toLowerCase(),ranks:rights.ranks});}
|
||||
return deliverGamePermissions({ranks,users},{settings,fetcher});
|
||||
}
|
||||
async function deliverGamePermissions({ranks,users},{settings,fetcher}){
|
||||
const revision=randomUUID(),r=await fetcher('http://127.0.0.1:15433/permissions/teams',{method:'POST',headers:{Authorization:'Bearer '+settings.SERVER_CONTROL_TOKEN,'Content-Type':'application/json'},body:JSON.stringify({revision,actor:'website-sync',ranks,users}),signal:AbortSignal.timeout(20000)});if(!r.ok)throw Error('Game permission synchronization unavailable');const d=await r.json();if(d.ok!==true||d.revision!==revision)throw Error('Game permission synchronization unconfirmed');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {nativeAgentIdentity} from './organisation-native-projection.mjs';
|
||||
import {syncGamePermissions} from './game-permission-sync.mjs';
|
||||
import {spawn} from 'node:child_process';
|
||||
import {existsSync} from 'node:fs';
|
||||
|
|
@ -7,7 +8,7 @@ const native='/home/dunerealms/apps/integrations/osticket/sync-agents.php';
|
|||
export async function syncNativeAgents(db){
|
||||
if(!existsSync(native))return;
|
||||
const {results}=await db.prepare('SELECT id,username,role FROM site_accounts').all();
|
||||
const accounts=[];for(const user of results){const access=await accessFor(db,user);accounts.push({...user,role:access.rank,ranks:access.ranks,permissions:access.nodes});}
|
||||
const accounts=[];for(const user of results){const access=await accessFor(db,user);accounts.push(nativeAgentIdentity(user,access));}
|
||||
await new Promise((resolve,reject)=>{const child=spawn('/usr/bin/php',[native],{stdio:['pipe','ignore','pipe']});let error='';child.stderr.on('data',chunk=>{error+=chunk.toString().slice(0,1000)});const timer=setTimeout(()=>{child.kill();reject(Error('Native staff sync timed out'));},20000);child.once('error',reject);child.once('exit',code=>{clearTimeout(timer);code===0?resolve():reject(Error('Native staff sync failed'));});child.stdin.on('error',()=>{});child.stdin.end(JSON.stringify(accounts));});
|
||||
await syncNativeSeals(db);
|
||||
await syncGamePermissions(db);
|
||||
|
|
|
|||
|
|
@ -3,15 +3,15 @@ import {ORGANISATION} from './organisation-model.mjs';
|
|||
import {validatePolicyNodes} from './organisation-management.mjs';
|
||||
const staff=['web.menu.staffmanual','web.mail.internal.view'];
|
||||
const branchNodes={
|
||||
customer_support:['web.menu.tickets','web.tickets.staff','web.accounts.view','dune.tickets.staff','dune.staff.open','dune.staff.history'],
|
||||
sales_accounts:['web.menu.tickets','web.tickets.staff','web.shop.support','web.accounts.view','web.bank.staff.view'],
|
||||
customer_support:['web.tickets.support','web.tickets.staff','web.menu.tickets','web.accounts.view','dune.tickets.staff','dune.staff.open','dune.staff.history'],
|
||||
sales_accounts:['web.tickets.sales','web.tickets.staff','web.menu.tickets','web.shop.support','web.accounts.view','web.bank.staff.view'],
|
||||
content_creative:['web.menu.items','web.items.manage','web.menu.inventory','web.quests.view','web.quests.manage','dune.items.give','dune.quests.view','dune.quests.admin','dune.atelier.view','dune.atelier.redeem'],
|
||||
news_media:['web.menu.posts','web.posts.view','web.posts.edit'],
|
||||
trust_safety:['web.menu.bans','web.bans.view','web.bans.manage','web.bans.evidence','web.bans.tickets','web.tickets.appeals','web.menu.forum','web.forum.moderate','web.menu.tickets','web.tickets.staff','dune.staff.open','dune.staff.history','dune.staff.kick','dune.staff.warn','dune.staff.mute','dune.staff.ban.local','dune.ban.local','dune.unban.local','dune.moderation.ban','dune.moderation.unban','duneprotect.inspect','duneprotect.lookup'],
|
||||
it_operations:['web.menu.servers','web.servers.view','web.servers.logs','web.servers.power','web.servers.console','duneprotect.inspect','duneprotect.lookup','duneprotect.regions'],
|
||||
engineering:['web.menu.items','web.items.manage','web.menu.servers','web.servers.view','web.servers.logs','web.luckperms.view','web.quests.view'],
|
||||
it_operations:['web.tickets.network','web.tickets.staff','web.menu.tickets','web.menu.servers','web.servers.view','web.servers.logs','web.servers.power','web.servers.console','duneprotect.inspect','duneprotect.lookup','duneprotect.regions'],
|
||||
engineering:['web.tickets.dev','web.tickets.staff','web.menu.tickets','web.menu.items','web.items.manage','web.menu.servers','web.servers.view','web.servers.logs','web.luckperms.view','web.quests.view'],
|
||||
people_operations:['web.accounts.view','web.menu.staffmanual','web.menu.tickets','web.tickets.staff'],
|
||||
legal_compliance:['web.accounts.view','web.menu.tickets','web.tickets.staff','web.tickets.appeals','web.bans.view']
|
||||
legal_compliance:['web.tickets.legal','web.tickets.staff','web.menu.tickets','web.accounts.view','web.tickets.appeals','web.bans.view']
|
||||
};
|
||||
const leadNodes={
|
||||
customer_support:['web.tickets.admin'],sales_accounts:['web.bank.projects.approve'],
|
||||
|
|
|
|||
22
website/node/organisation-game-projection.mjs
Normal file
22
website/node/organisation-game-projection.mjs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import {createHash} from 'node:crypto';
|
||||
const serviceId='f7b88778-f0bc-41cc-9227-d8ef2f52264d';
|
||||
const blocked=node=>node.includes('*')||/(^|\.)op($|\.)/.test(node)||node.startsWith('luckperms.')||node.startsWith('minecraft.command.op');
|
||||
export async function projectOrganisationGameUsers(accounts,{access,citizenGameNodes,gameNodes,bankMap}){
|
||||
const groups=new Map(),users=[],seen=new Set();
|
||||
for(const account of accounts){
|
||||
if(account.id===serviceId||account.game_link_exempt)continue;
|
||||
const uuid=account.minecraft_uuid?.toLowerCase();
|
||||
if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(uuid||'')||seen.has(uuid))throw Error('Game projection requires unique verified player identities.');
|
||||
seen.add(uuid);
|
||||
const rights=await access(account);
|
||||
if(rights.organisation?.mode!=='active')throw Error('Central game projection requires active organisation authority.');
|
||||
const nodes=new Set(rights.nodes.filter(n=>gameNodes.has(n)&&!blocked(n)));
|
||||
for(const n of await citizenGameNodes(rights.ranks))if(gameNodes.has(n)&&!blocked(n)&&!Object.hasOwn(bankMap,n))nodes.add(n);
|
||||
for(const [game,web]of Object.entries(bankMap))if(rights.nodes.includes(web)&&gameNodes.has(game)&&!blocked(game))nodes.add(game);
|
||||
const permissions=Object.fromEntries([...nodes].sort().map(n=>[n,true]));
|
||||
const id='org_'+createHash('sha256').update(JSON.stringify(permissions)).digest('hex').slice(0,20);
|
||||
if(!groups.has(id))groups.set(id,{id,permissions});
|
||||
users.push({uuid,ranks:[id]});
|
||||
}
|
||||
return {ranks:[...groups.values()].sort((a,b)=>a.id.localeCompare(b.id)),users};
|
||||
}
|
||||
7
website/node/organisation-native-projection.mjs
Normal file
7
website/node/organisation-native-projection.mjs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
const localPrivilegeEditors=new Set(['web.tickets.admin','web.luckperms.edit','cp.luckperms.edit']);
|
||||
export function nativeAgentIdentity(user,access){
|
||||
const centralHuman=access.organisation?.mode==='active';
|
||||
return {...user,role:access.rank,ranks:access.ranks,
|
||||
permissions:centralHuman?access.nodes.filter(n=>!localPrivilegeEditors.has(n)):access.nodes,
|
||||
...(centralHuman?{organisation:access.organisation,nativePermissionManagement:false}:{} )};
|
||||
}
|
||||
|
|
@ -1,5 +1,10 @@
|
|||
import {organisationRuntimeAccess} from './organisation-runtime.mjs';
|
||||
export const NODES={
|
||||
'web.tickets.support':'Work Customer Support tickets',
|
||||
'web.tickets.sales':'Work Sales and Account Services tickets',
|
||||
'web.tickets.network':'Work IT Operations tickets',
|
||||
'web.tickets.dev':'Work Engineering tickets',
|
||||
'web.tickets.legal':'Work Legal and Compliance tickets',
|
||||
'web.payroll.manage':'Manage P&O payroll (Big Four only)',
|
||||
'web.bank.projects.approve':'Approve Support requests for temporary project bank accounts',
|
||||
'cp.menu.staffmanual':'Read the staff manual',
|
||||
|
|
|
|||
17
website/tests/organisation-game-projection.test.mjs
Normal file
17
website/tests/organisation-game-projection.test.mjs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {projectOrganisationGameUsers} from '../node/organisation-game-projection.mjs';
|
||||
const account=(id='11111111-1111-4111-8111-111111111111')=>({id,minecraft_uuid:id});
|
||||
const rights={organisation:{mode:'active'},ranks:['user','org_officer'],nodes:['dune.staff.warn','web.bank.personal.view','worldedit.*','luckperms.editor','minecraft.command.op']};
|
||||
const options={access:async()=>rights,citizenGameNodes:async()=>['duneess.basics','dunebank.staff.manage'],gameNodes:new Set(['dune.staff.warn','duneess.basics','dunebank.use','dunebank.staff.manage','worldedit.*','luckperms.editor','minecraft.command.op']),bankMap:{'dunebank.use':'web.bank.personal.view','dunebank.staff.manage':'web.bank.staff.manage'}};
|
||||
test('Game groups contain explicit effective rights, no stale staff labels or privileged citizen banking',async()=>{
|
||||
const result=await projectOrganisationGameUsers([account()],options);assert.deepEqual(result.ranks[0].permissions,{'dune.staff.warn':true,'dunebank.use':true,'duneess.basics':true});assert.match(result.ranks[0].id,/^org_[a-f0-9]{20}$/);assert.deepEqual(result.users[0].ranks,[result.ranks[0].id]);
|
||||
});
|
||||
test('Identical effective rights reuse one stable group independent of node order',async()=>{
|
||||
const accounts=[account(),account('22222222-2222-4222-8222-222222222222')];const first=await projectOrganisationGameUsers(accounts,options);assert.equal(first.ranks.length,1);
|
||||
const second=await projectOrganisationGameUsers(accounts,{...options,access:async()=>({...rights,nodes:[...rights.nodes].reverse()})});assert.deepEqual(first,second);
|
||||
});
|
||||
test('Dev service never receives a player group; duplicate player UUIDs and legacy fallback abort',async()=>{
|
||||
assert.deepEqual(await projectOrganisationGameUsers([account('f7b88778-f0bc-41cc-9227-d8ef2f52264d')],options),{ranks:[],users:[]});
|
||||
await assert.rejects(projectOrganisationGameUsers([account(),account()],options),/unique verified/);
|
||||
await assert.rejects(projectOrganisationGameUsers([account()],{...options,access:async()=>({...rights,organisation:undefined})}),/active organisation/);
|
||||
});
|
||||
15
website/tests/organisation-game-sync.test.mjs
Normal file
15
website/tests/organisation-game-sync.test.mjs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {syncGamePermissions} from '../node/game-permission-sync.mjs';
|
||||
test('Activated game sync sends central effective groups through the existing revision-confirmed bridge',async()=>{
|
||||
const player={id:'11111111-1111-4111-8111-111111111111',role:'owners',username:'test',minecraft_uuid:'22222222-2222-4222-8222-222222222222'};
|
||||
const db={organisationAccessEnabled:true,prepare(sql){assert(sql.includes('game_link_exempt'));return {all:async()=>({results:[player]})};}};
|
||||
let posted;
|
||||
await syncGamePermissions(db,{settings:{SERVER_CONTROL_TOKEN:'test'.repeat(16)},access:async()=>({organisation:{mode:'active'},ranks:[],nodes:['dune.staff.warn','web.bank.personal.view']}),fetcher:async(url,options)=>{
|
||||
assert.equal(url,'http://127.0.0.1:15433/permissions/teams');posted=JSON.parse(options.body);return Response.json({ok:true,revision:posted.revision});
|
||||
}});
|
||||
assert.deepEqual(posted.ranks[0].permissions,{'dune.staff.warn':true,'dunebank.use':true});assert(!posted.users[0].ranks.includes('owners'));assert.equal(posted.users[0].uuid,player.minecraft_uuid);
|
||||
});
|
||||
test('A game bridge response with the wrong revision is never treated as successful',async()=>{
|
||||
const db={organisationAccessEnabled:true,prepare(){return {all:async()=>({results:[]})};}};
|
||||
await assert.rejects(syncGamePermissions(db,{settings:{SERVER_CONTROL_TOKEN:'test'.repeat(16)},fetcher:async()=>Response.json({ok:true,revision:'wrong'})}),/unconfirmed/);
|
||||
});
|
||||
15
website/tests/organisation-native-projection.test.mjs
Normal file
15
website/tests/organisation-native-projection.test.mjs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {nativeAgentIdentity} from '../node/organisation-native-projection.mjs';
|
||||
import {defaultOrganisationPolicies} from '../node/organisation-default-policies.mjs';
|
||||
const user={id:'account',username:'staff'};
|
||||
test('Central staff retains ticket department access but not native user/permission administration',()=>{
|
||||
const access={rank:'org_executive',ranks:['user','org_executive'],nodes:['web.tickets.admin','web.tickets.staff','web.tickets.support','web.tickets.sales','web.luckperms.edit'],organisation:{mode:'active',assignments:[]}};
|
||||
const result=nativeAgentIdentity(user,access);assert.deepEqual(result.permissions,['web.tickets.staff','web.tickets.support','web.tickets.sales']);assert.equal(result.nativePermissionManagement,false);assert.equal(access.nodes.length,5);
|
||||
});
|
||||
test('Existing legacy access and verified Dev service payload remain unchanged',()=>{
|
||||
const access={rank:'network_admin',ranks:['network_admin'],nodes:['web.tickets.admin','web.luckperms.edit']};assert.deepEqual(nativeAgentIdentity(user,access).permissions,access.nodes);assert.equal(nativeAgentIdentity(user,access).nativePermissionManagement,undefined);
|
||||
});
|
||||
test('Native ticket tags are present for existing support, sales, technical and legal adapters',()=>{
|
||||
const policies=defaultOrganisationPolicies(),officer=key=>policies.find(p=>p.scopeKey===key&&p.role==='officer').nodes;
|
||||
for(const [key,node]of [['customer_support','web.tickets.support'],['sales_accounts','web.tickets.sales'],['it_operations','web.tickets.network'],['engineering','web.tickets.dev'],['legal_compliance','web.tickets.legal']])assert(officer(key).includes(node));
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff