forked from unimatrix/web
Route native account tools through CP and Imperial Post while retaining Dev access
This commit is contained in:
parent
2779b84990
commit
c145d26e4b
8 changed files with 169 additions and 2 deletions
36
website/integrations/mybb/central-account-controls.php
Normal file
36
website/integrations/mybb/central-account-controls.php
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
<?php
|
||||
// DuneRealms adapter only: native forum content and preferences stay in MyBB.
|
||||
function dune_central_account_identity($identity){return is_array($identity)&&($identity['nativePermissionManagement']??null)===false;}
|
||||
function dune_central_account_target($identity,$script,$action=''){
|
||||
if(!dune_central_account_identity($identity))return null;
|
||||
$script=basename($script);$action=strtolower($action);
|
||||
if($script==='private.php')return 'https://cp.dunerealms.com/#post/mail-inbox';
|
||||
if($script==='usercp.php'){
|
||||
if(in_array($action,['profile','do_profile','changename','do_changename','avatar','do_avatar','editsig','do_editsig'],true))return 'https://cp.dunerealms.com/#realm/site-profile';
|
||||
if(in_array($action,['email','do_email','password','do_password'],true))return 'https://cp.dunerealms.com/#realm/security';
|
||||
}
|
||||
if($script==='member.php'){
|
||||
if(in_array($action,['lostpw','do_lostpw','resetpassword','do_resetpassword'],true))return 'https://cp.dunerealms.com/#realm/security';
|
||||
if(in_array($action,['emailuser','do_emailuser'],true))return 'https://cp.dunerealms.com/#post/mail-inbox';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function dune_central_account_permissions(){
|
||||
if(empty($GLOBALS['dune_central_account_user']))return;
|
||||
global $mybb;
|
||||
foreach(['canusepms','cansendpms','cantrackpms','canchangename','canuploadavatars','caneditprofiles','cansendemail'] as $permission)$mybb->usergroup[$permission]=0;
|
||||
}
|
||||
function dune_central_account_menu(){
|
||||
if(empty($GLOBALS['dune_central_account_user']))return;
|
||||
global $templates;
|
||||
$templates->cache['usercp_nav_profile']='<tbody><tr><td class="tcat"><strong>DuneRealms account</strong></td></tr></tbody><tbody><tr><td class="trow1"><a href="https://cp.dunerealms.com/#realm/site-profile">Manage profile & identity</a></td></tr><tr><td class="trow1"><a href="https://cp.dunerealms.com/#realm/security">Account security</a></td></tr><tr><td class="trow1"><a href="https://cp.dunerealms.com/#post/mail-inbox">Imperial Post</a></td></tr></tbody>';
|
||||
}
|
||||
function dune_central_account_output($html){
|
||||
if(empty($GLOBALS['dune_central_account_user']))return $html;
|
||||
return preg_replace_callback('~<a\b([^>]*?)href=(["\x27])([^"\x27]+)\2([^>]*)>([\s\S]*?)</a>~i',static function($m){
|
||||
$url=parse_url(html_entity_decode($m[3],ENT_QUOTES|ENT_HTML5,'UTF-8'));if(!$url||isset($url['host'])&&strtolower($url['host'])!=='forums.dunerealms.com')return $m[0];
|
||||
$query=[];parse_str($url['query']??'',$query);$script=basename($url['path']??'');$target=dune_central_account_target(['nativePermissionManagement'=>false],$script,is_string($query['action']??null)?$query['action']:'');if(!$target)return $m[0];
|
||||
$label=$script==='private.php'?'Imperial Post':(str_contains($target,'security')?'Account security':'Manage account');
|
||||
return '<a'.$m[1].'href="'.htmlspecialchars($target,ENT_QUOTES,'UTF-8').'"'.$m[4].'>'.$label.'</a>';
|
||||
},$html);
|
||||
}
|
||||
62
website/integrations/mybb/inc/plugins/dune_accounts.php
Normal file
62
website/integrations/mybb/inc/plugins/dune_accounts.php
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
<?php
|
||||
if (!defined('IN_MYBB')) die('Direct access denied');
|
||||
require_once MYBB_ROOT.'forum-access.php';
|
||||
require_once MYBB_ROOT.'central-account-controls.php';
|
||||
$plugins->add_hook('global_intermediate','dune_central_account_permissions');
|
||||
$plugins->add_hook('usercp_menu','dune_central_account_menu',1);
|
||||
if(is_file(MYBB_ROOT.'forum-awards.php')){require_once MYBB_ROOT.'forum-awards.php';$plugins->add_hook('postbit','dune_forum_post_awards');$plugins->add_hook('postbit_prev','dune_forum_post_awards');$plugins->add_hook('postbit_announcement','dune_forum_post_awards');$plugins->add_hook('member_profile_end','dune_forum_profile_awards');}
|
||||
if(is_file(MYBB_ROOT.'public-profile.php')){require_once MYBB_ROOT.'public-profile.php';$plugins->add_hook('postbit','dune_forum_author_profile');$plugins->add_hook('postbit_prev','dune_forum_author_profile');$plugins->add_hook('postbit_announcement','dune_forum_author_profile');$plugins->add_hook('member_profile_end','dune_forum_member_public_profile');}
|
||||
if(is_file(MYBB_ROOT.'staff-seal-signatures.php')){require_once MYBB_ROOT.'staff-seal-signatures.php';$plugins->add_hook('postbit','dune_forum_staff_signature');$plugins->add_hook('postbit_prev','dune_forum_staff_signature');$plugins->add_hook('postbit_announcement','dune_forum_staff_signature');$plugins->add_hook('usercp_start','dune_mybb_signature_settings');$plugins->add_hook('datahandler_user_update','dune_mybb_lock_signature_data');}
|
||||
$plugins->add_hook('global_start','dune_accounts_guard');
|
||||
$plugins->add_hook('global_start','dune_forum_age_guard',1);
|
||||
$plugins->add_hook('pre_output_page','dune_accounts_theme');
|
||||
$plugins->add_hook('admin_load','dune_accounts_admin');
|
||||
$plugins->add_hook('admin_login','dune_accounts_admin_login');
|
||||
$plugins->add_hook('admin_page_show_login_start','dune_accounts_admin_login');
|
||||
$plugins->add_hook('admin_page_output_header','dune_accounts_admin_theme');
|
||||
$plugins->add_hook('member_login','dune_accounts_login');
|
||||
$plugins->add_hook('member_do_login_start','dune_accounts_login');
|
||||
$plugins->add_hook('member_register_start','dune_accounts_login');
|
||||
$plugins->add_hook('member_do_register_start','dune_accounts_login');
|
||||
function dune_accounts_info(){return ['name'=>'DuneRealms accounts','description'=>'Central CP sign-in; no password copying.','website'=>'https://www.dunerealms.com','author'=>'DuneRealms','version'=>'1.0.0','compatibility'=>'18*'];}
|
||||
function dune_accounts_login(){header('Location: /dune-sso.php');exit;}
|
||||
function dune_accounts_theme($html){require_once '/home/dunerealms/apps/integrations/shared-header.php';return dune_shared_header(str_replace('</head>','<link rel="stylesheet" href="/dune-theme.css"><style>.signature img[src*="/assets/seals/"]{width:calc(71px * var(--dune-seal-scale,1))!important;height:calc(71px * var(--dune-seal-scale,1))!important;object-fit:contain;margin:6px!important;vertical-align:middle}</style></head>',dune_central_account_output($html)));}
|
||||
function dune_accounts_admin_login(){header('Location: /dune-sso.php?admin=1');exit;}
|
||||
function dune_accounts_admin(){
|
||||
require_once '/home/dunerealms/apps/integrations/shared-header.php';ob_start('dune_shared_header');
|
||||
if(session_status()!==PHP_SESSION_ACTIVE)session_start(['cookie_secure'=>true,'cookie_httponly'=>true,'cookie_samesite'=>'Lax']);
|
||||
require_once '/home/dunerealms/apps/integrations/bridge.php';
|
||||
$identity=dune_bridge('identity',['sessionRef'=>$_SESSION['dune_session_ref']??'']);
|
||||
global $mybb,$db;
|
||||
$mapping=$db->fetch_array($db->simple_select('dune_accounts','website_id','uid='.(int)$mybb->user['uid']));
|
||||
if(!$identity||!$mapping||$mapping['website_id']!==$identity['id']||!dune_forum_can_admin($identity)){http_response_code(403);exit('Forum administration permission required.');}
|
||||
}
|
||||
function dune_accounts_guard(){
|
||||
global $mybb,$db;
|
||||
if (session_status()!==PHP_SESSION_ACTIVE) session_start(['cookie_secure'=>true,'cookie_httponly'=>true,'cookie_samesite'=>'Lax']);
|
||||
if (basename($_SERVER['SCRIPT_NAME']??'')==='dune-sso.php') return;
|
||||
if (empty($mybb->user['uid'])) return;
|
||||
require_once '/home/dunerealms/apps/integrations/bridge.php';
|
||||
$identity=dune_bridge('identity',['sessionRef'=>$_SESSION['dune_session_ref']??'']);
|
||||
$mapping=$db->fetch_array($db->simple_select('dune_accounts','website_id','uid='.(int)$mybb->user['uid']));
|
||||
if (!$identity || !$mapping || $mapping['website_id']!==$identity['id']) {my_unsetcookie('mybbuser');header('Location: /dune-sso.php');exit;}
|
||||
$GLOBALS['dune_central_account_user']=dune_central_account_identity($identity);
|
||||
$target=dune_central_account_target($identity,$_SERVER['SCRIPT_NAME']??'',(string)$mybb->get_input('action'));
|
||||
if($target){header('Location: '.$target,true,303);exit;}
|
||||
require_once MYBB_ROOT.'political-groups.php';dune_apply_political_groups((int)$mybb->user['uid'],$identity['id']);
|
||||
require_once MYBB_ROOT.'staff-seal-signatures.php';dune_apply_staff_seal((int)$mybb->user['uid'],$identity['id']);
|
||||
$group=dune_forum_group_for($identity);
|
||||
if ((int)$mybb->user['usergroup']!==$group){$db->update_query('users',['usergroup'=>$group],'uid='.(int)$mybb->user['uid']);header('Location: /');exit;}
|
||||
if (!$identity['linked']&&empty($identity['gameLinkExempt']) && $_SERVER['REQUEST_METHOD']==='POST' && in_array(basename($_SERVER['SCRIPT_NAME']),['newthread.php','newreply.php','editpost.php'],true)) {header('Location: https://cp.dunerealms.com/account-required.html?context=forum');exit;}
|
||||
}
|
||||
|
||||
function dune_accounts_admin_theme($args){$args['this']->extra_header.='<link rel="stylesheet" href="/dune-theme.css">';}
|
||||
|
||||
function dune_forum_age_guard(){
|
||||
if(basename($_SERVER['SCRIPT_NAME']??'')==='dune-sso.php')return;
|
||||
if(session_status()!==PHP_SESSION_ACTIVE)session_start(['cookie_secure'=>true,'cookie_httponly'=>true,'cookie_samesite'=>'Lax']);
|
||||
require_once '/home/dunerealms/apps/integrations/bridge.php';
|
||||
$identity=dune_bridge('identity',['sessionRef'=>$_SESSION['dune_session_ref']??'']);
|
||||
if(!$identity){header('Location: /dune-sso.php');exit;}
|
||||
if(($identity['forumAllowed']??true)===false){header('Location: https://cp.dunerealms.com/error.html?reason=age-restricted');exit;}
|
||||
}
|
||||
17
website/integrations/mybb/test-central-account-controls.php
Normal file
17
website/integrations/mybb/test-central-account-controls.php
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
if(PHP_SAPI!=='cli')exit(1);
|
||||
require __DIR__.'/central-account-controls.php';
|
||||
$checks=0;$check=static function($ok)use(&$checks){if(!$ok)throw new RuntimeException('Central account policy check failed');$checks++;};
|
||||
$human=['nativePermissionManagement'=>false];$dev=['username'=>'dev','permissions'=>['web.forum.admin']];
|
||||
$check(dune_central_account_target($human,'/private.php','send')==='https://cp.dunerealms.com/#post/mail-inbox');
|
||||
foreach(['profile','do_profile','changename','do_changename','avatar','do_avatar','editsig','do_editsig']as$action)$check(dune_central_account_target($human,'usercp.php',$action)==='https://cp.dunerealms.com/#realm/site-profile');
|
||||
foreach(['email','do_email','password','do_password']as$action)$check(dune_central_account_target($human,'usercp.php',$action)==='https://cp.dunerealms.com/#realm/security');
|
||||
foreach(['options','do_options','subscriptions','attachments']as$action)$check(dune_central_account_target($human,'usercp.php',$action)===null);
|
||||
$check(dune_central_account_target($dev,'private.php')===null);$check(dune_central_account_target($dev,'usercp.php','do_password')===null);
|
||||
$GLOBALS['dune_central_account_user']=true;$mybb=(object)['usergroup'=>['canusepms'=>1,'cansendpms'=>1,'canusercp'=>1,'canusesig'=>1]];dune_central_account_permissions();
|
||||
$check($mybb->usergroup['canusepms']===0&&$mybb->usergroup['cansendpms']===0);$check($mybb->usergroup['canusercp']===1&&$mybb->usergroup['canusesig']===1);
|
||||
$templates=(object)['cache'=>[]];dune_central_account_menu();$check(str_contains($templates->cache['usercp_nav_profile'],'Manage profile & identity'));
|
||||
$html='<a href="private.php">Private Messages (Unread 0, Total 0)</a><a href="usercp.php?action=options">Forum preferences</a><a href="https://other.invalid/private.php">External</a>';
|
||||
$result=dune_central_account_output($html);$check(!str_contains($result,'Private Messages'));$check(str_contains($result,'#post/mail-inbox'));$check(str_contains($result,'usercp.php?action=options'));$check(str_contains($result,'https://other.invalid/private.php'));
|
||||
$GLOBALS['dune_central_account_user']=false;$check(dune_central_account_output($html)===$html);
|
||||
echo json_encode(['passed'=>$checks,'devNativeToolsPreserved'=>true,'forumPreferencesPreserved'=>true]).PHP_EOL;
|
||||
|
|
@ -4,7 +4,7 @@ import {createSkinResolver,minecraftSkins} from './minecraft-skins.mjs';
|
|||
const uuid=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
||||
export async function avatarForAccount(db,userId){
|
||||
try{const profile=await db.prepare('SELECT avatar_key FROM site_profiles WHERE user_id=?').bind(userId).first();if(profile?.avatar_key)return{url:'/api/avatars/site/'+profile.avatar_key,mode:'image'};}catch{}
|
||||
try{const linked=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(userId).first();if(uuid.test(linked?.minecraft_uuid||''))return{url:'/api/avatars/minecraft/'+linked.minecraft_uuid,mode:'skin'};}catch{}
|
||||
try{const linked=await db.prepare('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?').bind(userId).first();if(uuid.test(linked?.minecraft_uuid||''))return{url:'/api/avatars/face/'+linked.minecraft_uuid,mode:'image'};}catch{}
|
||||
return{url:'/api/avatars/fallback',mode:'image'};
|
||||
}
|
||||
const fallback='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" shape-rendering="crispEdges"><path fill="#976e50" d="M0 0h8v8H0z"/><path fill="#493225" d="M0 0h8v3H0zM0 3h1v2H0zM7 3h1v2H7z"/><path fill="#bc916a" d="M1 3h6v3H1z"/><path fill="#eee8d8" d="M1 4h2v1H1zM5 4h2v1H5z"/><path fill="#5c77b7" d="M2 4h1v1H2zM5 4h1v1H5z"/><path fill="#79513c" d="M3 5h2v1H3zM2 7h4v1H2z"/><path fill="#432c25" d="M2 6h1v1H2zM5 6h1v1H5zM3 7h2v1H3z"/></svg>';
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {protectedStaffRanks,managedRoleSeals,currentStaffRanks} from './game-staff-seals.mjs';
|
||||
import {OFFICIAL_ACCOUNT} from './official-account.mjs';
|
||||
import{staffClosureStats,statsForAccount,departmentAwardEarned}from './staff-closure-stats.mjs';
|
||||
import{spawn}from 'node:child_process';
|
||||
import{existsSync,readFileSync}from 'node:fs';
|
||||
|
|
@ -6,6 +7,7 @@ import{accessFor}from './permissions.mjs';
|
|||
import{badgesFor,BADGES,communityBadgeVisible}from './community-badges.mjs';
|
||||
export function visibleCommunityBadges(keys,ranks){return keys.filter(key=>BADGES.includes(key)&&ranks.length>0&&communityBadgeVisible(key,ranks));}
|
||||
export function staffSealFor(account,manifest){
|
||||
if(account.id===OFFICIAL_ACCOUNT.id)return null; // Official showcase identity never uses a personal seal.
|
||||
const ranks=Array.isArray(account.ranks)?account.ranks:[account.role];
|
||||
const role=(ranks.includes('owners')||ranks.includes('org_owner_ceo'))?'OWNER':ranks.includes('web_net_admin')?'MAINNETWORKADMIN':ranks.includes('corestaff')?'CORESTAFF':(ranks.includes('network_admin')||ranks.includes('network_admin'))?'NETWORKSTAFF':'';
|
||||
const named=kind=>Object.values(manifest).find(asset=>asset.role===kind&&asset.label?.toLowerCase()===account.username.toLowerCase())?.footer150||null;
|
||||
|
|
|
|||
39
website/scripts/install-native-account-controls.py
Normal file
39
website/scripts/install-native-account-controls.py
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Install the existing MyBB account adapter and disable duplicate human account tools."""
|
||||
import hashlib,json,os,subprocess
|
||||
from pathlib import Path
|
||||
import pymysql
|
||||
|
||||
def main():
|
||||
if os.geteuid()!=0:raise RuntimeError('Run as the authorised deployment operator')
|
||||
source=Path(__file__).resolve().parents[1]/'integrations'/'mybb'
|
||||
target=Path('/home/dunerealms/apps/integrations/mybb')
|
||||
files=['central-account-controls.php','inc/plugins/dune_accounts.php']
|
||||
for name in files:
|
||||
subprocess.run(['php','-l',str(source/name)],check=True,capture_output=True)
|
||||
if not (target/'inc/plugins/dune_accounts.php').is_file():raise RuntimeError('Expected existing account adapter is missing')
|
||||
installed=[]
|
||||
for name in files:
|
||||
destination=target/name
|
||||
metadata=destination.stat() if destination.exists() else (target/'inc/plugins/dune_accounts.php').stat()
|
||||
temporary=destination.with_name('.'+destination.name+'.central-next')
|
||||
if temporary.exists():raise RuntimeError('Stale integration staging file')
|
||||
temporary.write_bytes((source/name).read_bytes());os.chown(temporary,metadata.st_uid,metadata.st_gid);os.chmod(temporary,metadata.st_mode&0o777);temporary.replace(destination)
|
||||
installed.append({'file':name,'sha256':hashlib.sha256(destination.read_bytes()).hexdigest()})
|
||||
config=json.loads(Path('/home/dunerealms/.config/integrations.json').read_text())
|
||||
db=pymysql.connect(host=config['host'],user=config['username'],password=config['password'],database=config['database'])
|
||||
permissions=['canusepms','cansendpms','cantrackpms','canchangename','canuploadavatars','caneditprofiles','cansendemail']
|
||||
try:
|
||||
with db.cursor() as cursor:
|
||||
# Native administrator group is reserved for the exempt Dev service.
|
||||
cursor.execute('UPDATE drforum_usergroups SET '+','.join(name+'=0' for name in permissions)+' WHERE gid<>4')
|
||||
changed=cursor.rowcount
|
||||
db.commit()
|
||||
except BaseException:
|
||||
db.rollback();raise
|
||||
finally:db.close()
|
||||
php="define('IN_MYBB',1);$_SERVER['SCRIPT_NAME']='/index.php';require './inc/init.php';$cache->update_usergroups();echo 'Native group cache refreshed';"
|
||||
subprocess.run(['php','-r',php],cwd=target,check=True,capture_output=True)
|
||||
print(json.dumps({'installed':installed,'humanGroupsUpdated':changed,'nativeDevAdministratorPreserved':True,'privateMessagesDeleted':False,'forumCoreChanged':False}))
|
||||
|
||||
if __name__=='__main__':main()
|
||||
|
|
@ -1,7 +1,11 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {createAvatars} from '../node/avatar.mjs';
|
||||
import {createAvatars,avatarForAccount} from '../node/avatar.mjs';
|
||||
const uuid='49d2fe76-7977-4d49-bd39-e48fc8c648b8';
|
||||
const request=path=>new Request('https://cp.dunerealms.com/api/avatars/'+path);
|
||||
test('Shared account avatar uses the face route so native profile sync never receives the skin atlas',async()=>{
|
||||
const db={prepare:sql=>({bind(){return this;},first:async()=>sql.includes('avatar_key')?null:{minecraft_uuid:uuid}})};
|
||||
assert.deepEqual(await avatarForAccount(db,'account'),{url:'/api/avatars/face/'+uuid,mode:'image'});
|
||||
});
|
||||
function fixture({skin={bytes:Buffer.from('trusted-resolver-png'),height:64},uploaded=false,linked=uuid,exists=true}={}){
|
||||
const db={prepare(sql){return{bind(){return this;},async first(){if(sql.includes('SELECT avatar_key'))return uploaded?{avatar_key:uuid}:null;if(sql.includes('SELECT avatar_mime'))return null;return exists?{id:uuid,minecraft_uuid:linked}:null;}};}};
|
||||
return createAvatars(db,{}, {resolver:{resolve:async value=>value===uuid?skin:null}});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,13 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {OFFICIAL_ACCOUNT,organisationSubject} from '../node/official-account.mjs';
|
||||
import {organisationRuntimeAccess} from '../node/organisation-runtime.mjs';import {DEFAULT_RANKS,NODES} from '../node/permissions.mjs';
|
||||
import {staffSealFor} from '../node/native-seals.mjs';
|
||||
|
||||
test('Official alt has no personal signature seal while the human Owner keeps their own',()=>{
|
||||
const manifest={official:{role:'OWNER',label:'dunerealms',footer150:'/assets/seals/owner-dunerealms-150.png'},owner:{role:'OWNER',label:'unimatrix999',footer150:'/assets/seals/owner-unimatrix999-150.png'}};
|
||||
assert.equal(staffSealFor({id:OFFICIAL_ACCOUNT.id,username:'dunerealms',ranks:['org_owner_ceo']},manifest),null);
|
||||
assert.equal(staffSealFor({id:OFFICIAL_ACCOUNT.ownerId,username:'unimatrix999',ranks:['org_owner_ceo']},manifest),'/assets/seals/owner-unimatrix999-150.png');
|
||||
});
|
||||
test('Owner alias is pinned, requires current verified database link, and falls back after revocation',async()=>{
|
||||
const queries=[];let enabled=true;const reader={query:async(sql,args)=>{queries.push({sql,args});return enabled?[{user_id:OFFICIAL_ACCOUNT.id}]:[];}};
|
||||
assert.deepEqual(await organisationSubject(reader,'other-account'),{userId:'other-account',alias:false});assert.equal(queries.length,0);
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff