Enable ordinary player voice chat permissions #642

Merged
unimatrix merged 1 commit from dev/MC:feat/user-voice-permissions-20261130 into main 2026-11-30 18:46:53 +01:00
6 changed files with 108 additions and 1 deletions

View file

@ -330,6 +330,24 @@
"label": "Visit lobby",
"source": "DuneRealms central registered permission catalogue",
"highRisk": false
},
{
"node": "voicechat.listen",
"label": "Listen to nearby voice chat",
"source": "Simple Voice Chat 2.6.25 plugin.yml",
"highRisk": false
},
{
"node": "voicechat.speak",
"label": "Speak in voice chat",
"source": "Simple Voice Chat 2.6.25 plugin.yml",
"highRisk": false
},
{
"node": "voicechat.groups",
"label": "Use voice chat groups",
"source": "Simple Voice Chat 2.6.25 plugin.yml",
"highRisk": false
}
],
"networkAdministratorRoles": [
@ -350,7 +368,10 @@
"duneess.chat.faction": true,
"duneess.chat.nearby": true,
"duneess.chat.network": true,
"duneess.chat.team": true
"duneess.chat.team": true,
"voicechat.listen": true,
"voicechat.speak": true,
"voicechat.groups": true
},
"scope": "network-global; local-only moderation requires a separate server-context design, not this global snapshot"
},

View file

@ -0,0 +1,5 @@
export const USER_VOICE_NODES=Object.freeze(['voicechat.listen','voicechat.speak','voicechat.groups']);
export function voicePermissions(existing){
if(!Array.isArray(existing)||existing.some(n=>typeof n!=='string'))throw Error('Invalid stored User permissions');
return [...new Set([...existing,...USER_VOICE_NODES])];
}

View file

@ -0,0 +1,32 @@
import {readFile} from 'node:fs/promises';
import {fileURLToPath} from 'node:url';
import {realpath} from 'node:fs/promises';
import mysql from 'mysql2/promise';
import {randomUUID} from 'node:crypto';
import {OFFICIAL_ACCOUNT} from '../node/official-account.mjs';
import {accessFor} from '../node/permissions.mjs';
import {syncGamePermissions} from '../node/game-permission-sync.mjs';
import {voicePermissions} from '../node/user-voice-permissions.mjs';
async function main(){
const [source,apply]=process.argv.slice(2);
if(!/^[a-f0-9]{40}$/.test(source||'')||apply&&apply!=='--apply')throw Error('Exact reviewed release required');
if(!(await realpath(fileURLToPath(new URL('..',import.meta.url)))).endsWith('/releases/ci-'+source))throw Error('Run the immutable built release');
process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');const e=process.env;
const c=await mysql.createConnection({host:e.DB_HOST||'127.0.0.1',port:Number(e.DB_PORT||3306),user:e.DB_USER,password:e.DB_PASSWORD,database:e.DB_NAME,multipleStatements:false});
const db={organisationAccessEnabled:e.ORGANISATION_ACCESS_ENABLED==='true',prepare(sql){let v=[];return {bind(...values){v=values;return this;},async first(){return (await c.execute(sql,v))[0][0]||null;},async all(){return {results:(await c.execute(sql,v))[0]};}};},async readSnapshot(fn){await c.query('START TRANSACTION READ ONLY');try{const r=await fn(db);await c.commit();return r;}catch(err){await c.rollback();throw err;}}};
try{
const actor=(await c.execute("SELECT id,username,role FROM site_accounts WHERE id=? AND username='unimatrix999' AND password_hash NOT LIKE '!%'",[OFFICIAL_ACCOUNT.ownerId]))[0][0];
if(!actor||!(await accessFor(db,actor)).nodes.includes('web.ranks.manage'))throw Error('Existing Owner rank authority required');
await c.beginTransaction();
try{
const row=(await c.execute("SELECT permissions_json,version FROM cp_rank_game_permissions WHERE rank_key='user' FOR UPDATE"))[0][0];if(!row)throw Error('Existing User rank required');
const before=JSON.parse(row.permissions_json),after=voicePermissions(before),changed=JSON.stringify(before)!==JSON.stringify(after);
if(!apply){await c.rollback();console.log(JSON.stringify({applied:false,rank:'user',added:after.filter(n=>!before.includes(n)),source}));return;}
if(changed){await c.execute("UPDATE cp_rank_game_permissions SET permissions_json=?,version=version+1 WHERE rank_key='user' AND version=?",[JSON.stringify(after),row.version]);await c.execute('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),actor.id,'game-rank-permissions',JSON.stringify({rank:'user',version:row.version,added:after.filter(n=>!before.includes(n)),source}),Date.now()]);}
await c.commit();console.log(JSON.stringify({applied:true,changed,rank:'user',source}));
}catch(err){await c.rollback();throw err;}
await syncGamePermissions(db);console.log(JSON.stringify({nativeSyncConfirmed:true,source}));
}finally{await c.end();}
}
main().catch(()=>{console.error('User voice permission update or synchronization could not be confirmed.');process.exitCode=1;});

View file

@ -0,0 +1,34 @@
"""Add only the three reviewed player voice nodes to the native permission bridge."""
import argparse,hashlib,json,os,shutil,subprocess,tempfile
from pathlib import Path
TARGET=Path('/opt/dunerealms/server-control/managed-game-permissions.json')
NODES=('voicechat.listen','voicechat.speak','voicechat.groups')
BASE='bcb6f06da0e0a29a600ca577225ac4c4f94910fd086f5ca7b3be3c59ba71646b'
def extend(old,catalogue):
before=json.loads(old);source=json.loads(catalogue);by_name={n['node']:n for n in source['nodes']};have={n['node']:n for n in before['nodes']}
for name in NODES:
item=by_name[name]
if item.get('highRisk') is not False:raise ValueError('Invalid player voice node')
if name in have and have[name]!=item:raise ValueError('Existing voice node differs')
if name not in have:before['nodes'].append(item)
return (json.dumps(before,indent=2)+'\n').encode()
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--catalogue',required=True);p.add_argument('--apply',action='store_true');a=p.parse_args()
old=TARGET.read_bytes();new=extend(old,Path(a.catalogue).read_bytes());digest=lambda b:hashlib.sha256(b).hexdigest()
if digest(old)!=BASE and json.loads(old)!=json.loads(new):raise ValueError('Native bridge baseline changed')
print(json.dumps({'before':digest(old),'after':digest(new),'nodes':NODES,'changed':json.loads(old)!=json.loads(new)}))
if not a.apply or json.loads(old)==json.loads(new):return
if os.getuid()!=0:raise ValueError('Root required')
backup=Path('/var/lib/dunerealms-operations/user-voice-catalogue-before.json');backup.parent.mkdir(mode=0o700,parents=True,exist_ok=True)
if backup.exists() and backup.read_bytes()!=old:raise ValueError('Prior recovery record differs')
backup.write_bytes(old);backup.chmod(0o600);st=TARGET.stat();temp=TARGET.with_name(TARGET.name+'.voice-new')
try:
temp.write_bytes(new);os.chmod(temp,st.st_mode&0o777);os.chown(temp,st.st_uid,st.st_gid)
if TARGET.read_bytes()!=old:raise ValueError('Native bridge catalogue changed before write')
os.replace(temp,TARGET)
try:subprocess.run(['systemctl','restart','dunerealms-server-control.service'],check=True);subprocess.run(['systemctl','is-active','--quiet','dunerealms-server-control.service'],check=True)
except Exception:
TARGET.write_bytes(old);subprocess.run(['systemctl','restart','dunerealms-server-control.service'],check=False);raise
finally:temp.unlink(missing_ok=True)
print(json.dumps({'applied':True,'voiceAdminGranted':False}))
if __name__=='__main__':main()

View file

@ -0,0 +1,9 @@
import importlib.util,json,unittest
from pathlib import Path
spec=importlib.util.spec_from_file_location('voice',Path(__file__).with_name('install-user-voice-catalogue.py'));v=importlib.util.module_from_spec(spec);spec.loader.exec_module(v)
class VoiceCatalogue(unittest.TestCase):
def test_only_new_player_nodes_are_added_and_existing_roles_retained(self):
old={'version':1,'nodes':[{'node':'existing','highRisk':True}],'suggestedRoles':[{'id':'user','permissions':{'existing':True}}]};catalogue={'nodes':[{'node':n,'highRisk':False} for n in v.NODES]+[{'node':'voicechat.admin','highRisk':True}]};new=json.loads(v.extend(json.dumps(old),json.dumps(catalogue)));self.assertEqual(new['suggestedRoles'],old['suggestedRoles']);self.assertEqual(new['nodes'][0],old['nodes'][0]);self.assertEqual(len(new['nodes']),4);self.assertNotIn('voicechat.admin',[n['node'] for n in new['nodes']]);self.assertEqual(json.loads(v.extend(json.dumps(new),json.dumps(catalogue))),new)
def test_existing_conflicting_node_is_refused(self):
with self.assertRaises(ValueError):v.extend(json.dumps({'nodes':[{'node':'voicechat.listen','highRisk':True}]}),json.dumps({'nodes':[{'node':n,'highRisk':False} for n in v.NODES]}))
if __name__=='__main__':unittest.main()

View file

@ -0,0 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {USER_VOICE_NODES,voicePermissions} from '../node/user-voice-permissions.mjs';
import {GAME_CATALOG,validateGameNodes} from '../node/game-ranks.mjs';
test('voice addition preserves existing permissions and is replay safe',()=>{const existing=['duneess.basics','dune.quests.view'];const result=voicePermissions(existing);assert.deepEqual(result,[...existing,...USER_VOICE_NODES]);assert.deepEqual(voicePermissions(result),result);assert.deepEqual(existing,['duneess.basics','dune.quests.view']);});
test('only three non-administrative nodes are registered for ordinary users',()=>{assert.deepEqual(GAME_CATALOG.nodes.filter(n=>n.node.startsWith('voicechat.')).map(n=>n.node),USER_VOICE_NODES);assert.ok(validateGameNodes(USER_VOICE_NODES,'user'));assert.equal(validateGameNodes(['voicechat.admin'],'user'),false);assert.equal(validateGameNodes(['voicechat.*'],'user'),false);for(const node of USER_VOICE_NODES)assert.equal(GAME_CATALOG.suggestedRoles.find(r=>r.id==='user').permissions[node],true);});