fix(boards): provision missing private forums from verified clan identity

This commit is contained in:
unimatrix 2026-11-17 12:57:45 +00:00
commit e32d46fe79
10 changed files with 476 additions and 246 deletions

View file

@ -1,62 +1,92 @@
# System Boards
# System Boards
Implementation batch: central access projection, native provisioning, scoped child forum management and shared CP embeds. Written and checked; not live yet.
## Agreed structure
System Boards is one bottom-of-index category, collapsed by default. Clan
Boards, Company Boards and Election Board live beneath it. Clan and company
CPs embed their own organisation board. The menu structure is shared.
Use MyBB's native forum permissions, moderator records and inheritance.
Membership is authoritative in the central organisation records, never in
browser parameters. Revoke stale managed forum groups before content is
served, retaining unrelated political and staff groups. Existing staff retain
global moderation. The Big 4.1 retain inspection rights; inspection itself
does not grant moderation. Clan owners moderate only their own subtree and
can create unlimited nested forums/categories there. No global ACP access.
`website/node/system-board-access.mjs` is the shared server-side projection.
Clan owners must have both current ownership and the owner membership role.
Company access reuses the current founder/CEO registry; scoped management
belongs to the current CEO. Additional company-member roles must use the
actual membership service when it is implemented, rather than fabricated
memberships. Every identity refresh must reload the projection, so leaving,
removal and changes of ownership invalidate old grants.
Public feeds, search, attachments, direct links and main-index counts must
respect private forum permissions. The existing website's public forum-feed
adapter also needs explicit exclusion of private System Boards descendants.
Election topics are discussions of already confirmed candidatures. MyBB does
not create candidatures, cast votes or decide election results. Publish topics
idempotently by application ID; never expose private application records.
## Publication order
1. CI must pass for the exact commit. Keep PR #337 open.
2. Stage the matching native PHP helpers and run lint plus test-system-board-policy.php. No native helper is installed in production yet.
3. Run website/ops/system-board-snapshot.mjs with the existing application environment; pipe its organisation snapshot to provision-system-boards.php as the native application owner. No credentials or private account records are emitted.
4. Run test-system-board-native.php against actual MyBB. It checks guest/nonmember denial, every organisation pair and existing staff using native permission merging, without modifying users.
5. Activate the matching central release with SYSTEM_BOARDS_ENABLED=1, install the helpers and reviewed plugin hook together. Preserve newer unrelated plugin changes; apply the small hook diff rather than overwriting an unverified live plugin.
6. Forum frame-ancestors must include every ancestor: CP, clans, corp and the politics shell (currently www). The present policy lacks clans/corp and needs a scoped update before nested embeds will work.
7. Publish the matching Clan/Company outer shells, then verify real membership revocation, post/reply forms, attachments, search, subtree creation and mobile layout before calling this live.
## Remaining work
- Execute publication and authenticated live verification.
- Add idempotent confirmed-candidature topic publication and lifecycle synchronization. Election Board navigation is provided; automatic candidature topics are not implemented. Applications and ballots remain authoritative in the existing election service.
Ordinary SSH as unimatrix works; sudo -n currently requires interactive authentication. Native publication therefore needs restored privileged access or the server administrator. Uploading approved sources into /tmp is not publication.
## Deleted organisations
On clan deletion, current central membership grants disappear. Preserve forum history and let native MyBB autoprune handle eventual post cleanup. No custom clan/forum deletion or cleanup worker is required (user decision, 16 November 2026).
## Compact internal view
The first board batch is live from main 39bb5486 (PR #351, CI #354); the four existing active clans have private forums. Native MyBB permission merging passed 52 checks. The user has posted a test thread successfully. The following styling batch gives embedded CP pages a separate green/gold dev presentation and shared palace background, small author rows, no public-profile decoration or signatures, and a full-forum link. Category defaults use MyBB’s native collapse cookie once, then respect the user preference. No custom deletion/pruning worker is needed.
## Management page and normal-index control
The management page uses a pure shared PHP view (system-board-manage-view.php) with the compact board stylesheet, illustrated heading, field cards, native field names and CSRF token, and a read-only structure guide. POST validation and inherited membership/moderation remain unchanged. The existing dune_sections.php index renderer replaces MyBB category markup; it now restores the native expander image and cat_<fid>_e container for the System Boards root, respecting native collapse cookies. Other categories keep their previous presentation. The CLI publisher disables front-end plugins during initialization, avoiding duplicate helper loading after installation.
Implementation batch: central access projection, native provisioning, scoped child forum management and shared CP embeds. Written and checked; not live yet.
## Automatic registration/first-open repair
## Agreed structure
The CLI publisher and authenticated MyBB entry point share
`system-board-provision.php`. Central SSO includes current organisation names
alongside the existing membership grants. On first authenticated access, any
missing board for a verified read/post grant is provisioned idempotently before
native group synchronization and redirect. Registration therefore does not
block on a remote MyBB request, and members no longer require a manual forum
publication after creating a clan. The initial rollout publisher also
reconciles every current active clan/company from the central snapshot.
System Boards is one bottom-of-index category, collapsed by default. Clan
Boards, Company Boards and Election Board live beneath it. Clan and company
CPs embed their own organisation board. The menu structure is shared.
Browser-supplied ids/names cannot create boards. The existing MySQL publication
lock, private permission matrix, leader moderation and global staff moderation
are unchanged. Archived clan cleanup remains a separate native forum concern.
Use MyBB's native forum permissions, moderator records and inheritance.
Membership is authoritative in the central organisation records, never in
browser parameters. Revoke stale managed forum groups before content is
served, retaining unrelated political and staff groups. Existing staff retain
global moderation. The Big 4.1 retain inspection rights; inspection itself
does not grant moderation. Clan owners moderate only their own subtree and
can create unlimited nested forums/categories there. No global ACP access.
After CI and application promotion, run from the active release:
`website/node/system-board-access.mjs` is the shared server-side projection.
Clan owners must have both current ownership and the owner membership role.
Company access reuses the current founder/CEO registry; scoped management
belongs to the current CEO. Additional company-member roles must use the
actual membership service when it is implemented, rather than fabricated
memberships. Every identity refresh must reload the projection, so leaving,
removal and changes of ownership invalidate old grants.
```sh
sudo python3 /home/dunerealms/apps/dunerealms/current/ops/publish-system-board-repair.py
sudo python3 /home/dunerealms/apps/dunerealms/current/ops/publish-system-board-repair.py --apply
```
Public feeds, search, attachments, direct links and main-index counts must
respect private forum permissions. The existing website's public forum-feed
adapter also needs explicit exclusion of private System Boards descendants.
Election topics are discussions of already confirmed candidatures. MyBB does
not create candidatures, cast votes or decide election results. Publish topics
idempotently by application ID; never expose private application records.
## Publication order
1. CI must pass for the exact commit. Keep PR #337 open.
2. Stage the matching native PHP helpers and run lint plus test-system-board-policy.php. No native helper is installed in production yet.
3. Run website/ops/system-board-snapshot.mjs with the existing application environment; pipe its organisation snapshot to provision-system-boards.php as the native application owner. No credentials or private account records are emitted.
4. Run test-system-board-native.php against actual MyBB. It checks guest/nonmember denial, every organisation pair and existing staff using native permission merging, without modifying users.
5. Activate the matching central release with SYSTEM_BOARDS_ENABLED=1, install the helpers and reviewed plugin hook together. Preserve newer unrelated plugin changes; apply the small hook diff rather than overwriting an unverified live plugin.
6. Forum frame-ancestors must include every ancestor: CP, clans, corp and the politics shell (currently www). The present policy lacks clans/corp and needs a scoped update before nested embeds will work.
7. Publish the matching Clan/Company outer shells, then verify real membership revocation, post/reply forms, attachments, search, subtree creation and mobile layout before calling this live.
## Remaining work
- Execute publication and authenticated live verification.
- Add idempotent confirmed-candidature topic publication and lifecycle synchronization. Election Board navigation is provided; automatic candidature topics are not implemented. Applications and ballots remain authoritative in the existing election service.
Ordinary SSH as unimatrix works; sudo -n currently requires interactive authentication. Native publication therefore needs restored privileged access or the server administrator. Uploading approved sources into /tmp is not publication.
## Deleted organisations
On clan deletion, current central membership grants disappear. Preserve forum history and let native MyBB autoprune handle eventual post cleanup. No custom clan/forum deletion or cleanup worker is required (user decision, 16 November 2026).
## Compact internal view
The first board batch is live from main 39bb5486 (PR #351, CI #354); the four existing active clans have private forums. Native MyBB permission merging passed 52 checks. The user has posted a test thread successfully. The following styling batch gives embedded CP pages a separate green/gold dev presentation and shared palace background, small author rows, no public-profile decoration or signatures, and a full-forum link. Category defaults use MyBB’s native collapse cookie once, then respect the user preference. No custom deletion/pruning worker is needed.
## Management page and normal-index control
The management page uses a pure shared PHP view (system-board-manage-view.php) with the compact board stylesheet, illustrated heading, field cards, native field names and CSRF token, and a read-only structure guide. POST validation and inherited membership/moderation remain unchanged. The existing dune_sections.php index renderer replaces MyBB category markup; it now restores the native expander image and cat_<fid>_e container for the System Boards root, respecting native collapse cookies. Other categories keep their previous presentation. The CLI publisher disables front-end plugins during initialization, avoiding duplicate helper loading after installation.
The publisher checks active release identity, lints PHP, runs policy tests,
refuses unreviewed native helper changes, backs up only the small overwritten
helpers, installs the shared helper before its callers, reconciles current
boards, and runs native permission tests. It does not overwrite MyBB plugins,
forum content or staff permissions. Native installation requires the existing
server publication privilege; an application CI merge alone does not copy
these files into MyBB.

View file

@ -1,112 +1,10 @@
<?php
// Install from a CI-approved release. CLI input is an explicit organisation
// snapshot from the central service, never a browser's claimed membership.
// CLI publication and authenticated first-open repair share the same provisioner.
if (PHP_SAPI !== 'cli') { http_response_code(404); exit; }
$input = json_decode(stream_get_contents(STDIN), true, 512, JSON_THROW_ON_ERROR);
if (!is_array($input) || !isset($input['organisations']) || !is_array($input['organisations'])) throw new RuntimeException('Organisation snapshot required');
foreach ($input['organisations'] as $org) {
if (!in_array($org['kind'] ?? '', ['clan','company'], true) || !preg_match('/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i', $org['id'] ?? '') || !is_string($org['name'] ?? null) || trim($org['name']) === '' || strlen($org['name']) > 120) throw new RuntimeException('Invalid organisation');
}
define('IN_MYBB', 1);
$input=json_decode(stream_get_contents(STDIN),true,512,JSON_THROW_ON_ERROR);
define('IN_MYBB',1);
if(!defined('NO_PLUGINS'))define('NO_PLUGINS',1);
define('MYBB_ROOT', '/home/dunerealms/apps/integrations/mybb/');
define('MYBB_ROOT','/home/dunerealms/apps/integrations/mybb/');
require MYBB_ROOT.'inc/init.php';
require __DIR__.'/system-board-policy.php';
$lock = $db->fetch_array($db->write_query("SELECT GET_LOCK('dune_system_boards_provision',10) acquired"));
if ((int)($lock['acquired'] ?? 0) !== 1) throw new RuntimeException('System Boards publication is busy');
try {
$db->write_query('CREATE TABLE IF NOT EXISTS '.TABLE_PREFIX.'dune_system_boards (kind VARCHAR(12) NOT NULL, organisation_id VARCHAR(36) NOT NULL, fid INT NOT NULL, member_gid INT NOT NULL DEFAULT 0, leader_gid INT NOT NULL DEFAULT 0, PRIMARY KEY(kind,organisation_id), UNIQUE KEY forum_id(fid)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
$db->write_query('START TRANSACTION');
$groups = []; $query = $db->simple_select('usergroups');
while ($row = $db->fetch_array($query)) $groups[(int)$row['gid']] = $row;
if (!isset($groups[2])) throw new RuntimeException('Registered group unavailable');
$template = $db->fetch_array($db->simple_select('forums', '*', "type='f'", ['limit'=>1]));
if (!$template) throw new RuntimeException('Native forum template unavailable');
$permissionColumns = ['canview','canviewthreads','canonlyviewownthreads','candlattachments','canpostthreads','canpostreplys','canonlyreplyownthreads','canpostattachments','canratethreads','caneditposts','candeleteposts','candeletethreads','caneditattachments','canviewdeletionnotice','modposts','modthreads','mod_edit_posts','modattachments','canpostpolls','canvotepolls','cansearch'];
function board_row($kind, $id) {
global $db;
return $db->fetch_array($db->simple_select('dune_system_boards', '*', "kind='".$db->escape_string($kind)."' AND organisation_id='".$db->escape_string($id)."'"));
}
function make_board($kind, $id, $name, $parent, $type = 'c') {
global $db, $template;
if ($existing = board_row($kind, $id)) return $existing;
$row = $template; unset($row['fid']);
foreach (['threads','posts','lastpost','lastposteruid','unapprovedthreads','unapprovedposts','deletedthreads','deletedposts'] as $key) if (array_key_exists($key, $row)) $row[$key] = 0;
foreach (['lastposter','lastpostsubject','linkto','password','rules','rulestitle'] as $key) if (array_key_exists($key, $row)) $row[$key] = '';
$row = array_merge($row, ['name'=>htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), 'description'=>'', 'type'=>$type, 'pid'=>$parent, 'parentlist'=>'', 'disporder'=>1000, 'active'=>0, 'open'=>1, 'allowhtml'=>0, 'allowmycode'=>1, 'allowsmilies'=>1, 'allowimgcode'=>1, 'showinjump'=>1]);
foreach ($row as $key=>$value) if (is_string($value)) $row[$key]=$db->escape_string($value);
$fid = (int)$db->insert_query('forums', $row);
$parentRow = $parent ? $db->fetch_array($db->simple_select('forums','parentlist','fid='.$parent)) : null;
$parentlist = ($parentRow ? $parentRow['parentlist'].',' : '').$fid;
$db->update_query('forums', ['parentlist'=>$db->escape_string($parentlist)], 'fid='.$fid);
$db->insert_query('dune_system_boards', ['kind'=>$db->escape_string($kind), 'organisation_id'=>$db->escape_string($id), 'fid'=>$fid]);
return board_row($kind, $id);
}
$root = make_board('system','root','System Boards',0);
$clans = make_board('system','clans','Clan Boards',(int)$root['fid']);
$companies = make_board('system','companies','Company Boards',(int)$root['fid']);
make_board('system','elections','Election Board',(int)$root['fid'],'f');
foreach ($input['organisations'] as $org) {
$board = make_board($org['kind'], $org['id'], $org['name'], (int)($org['kind']==='clan' ? $clans['fid'] : $companies['fid']), 'f');
foreach (['member_gid','leader_gid'] as $field) {
$role=$field==='leader_gid'?'leaders':'members';
$title=my_substr(($org['kind']==='clan'?'Clan':'Company').' '.$role.' · '.$org['name'],0,45);
if ((int)$board[$field] > 0) {
$db->update_query('usergroups',['title'=>$db->escape_string($title)],'gid='.(int)$board[$field]);
continue;
}
$group = $groups[2]; unset($group['gid']);
$group['title'] = $title;
$group['cancp'] = 0; $group['issupermod'] = 0; $group['canmodcp'] = $field==='leader_gid' ? 1 : 0;
foreach ($group as $key=>$value) if (is_string($value)) $group[$key]=$db->escape_string($value);
$gid = (int)$db->insert_query('usergroups', $group);
$board[$field] = $gid; $groups[$gid] = $group;
$db->update_query('dune_system_boards', [$field=>$gid], 'fid='.(int)$board['fid']);
}
// Every known group gets an explicit policy: additional political
// groups cannot accidentally make an unrelated organisation visible.
foreach ($groups as $gid=>$group) {
$member = in_array($gid, [(int)$board['member_gid'],(int)$board['leader_gid'],3,4,6], true);
$permissions = dune_board_private_permissions($permissionColumns, $member);
save_board_permissions((int)$board['fid'], (int)$gid, $permissions);
}
$moderator = ['fid'=>(int)$board['fid'], 'id'=>(int)$board['leader_gid'], 'isgroup'=>1,
'caneditposts'=>1,'cansoftdeleteposts'=>1,'canrestoreposts'=>1,'cansoftdeletethreads'=>1,'canrestorethreads'=>1,
'canopenclosethreads'=>1,'canstickunstickthreads'=>1,'canapproveunapprovethreads'=>1,'canapproveunapproveposts'=>1,
'canapproveunapproveattachs'=>1,'canmanagethreads'=>1,'canmanagepolls'=>1,'canpostclosedthreads'=>1,'canmanagereportedposts'=>1,'canviewmodlog'=>1];
$db->delete_query('moderators', 'fid='.(int)$board['fid'].' AND id='.(int)$board['leader_gid'].' AND isgroup=1');
$db->insert_query('moderators', $moderator);
// Existing native Moderators retain moderation on every new board;
// Super Moderators and Administrators already have native global power.
$moderator['id']=6;
$db->delete_query('moderators', 'fid='.(int)$board['fid'].' AND id=6 AND isgroup=1');
$db->insert_query('moderators', $moderator);
}
// Refresh earlier boards too, since later provisioning adds managed groups.
// These groups must also be denied access to every other private board.
$query = $db->simple_select('dune_system_boards', '*', "kind IN ('clan','company')");
while ($board = $db->fetch_array($query)) foreach ($groups as $gid=>$group) {
$member = in_array($gid, [(int)$board['member_gid'],(int)$board['leader_gid'],3,4,6], true);
save_board_permissions((int)$board['fid'], (int)$gid, dune_board_private_permissions($permissionColumns, $member));
}
// No guest feed may publish System Boards topics.
save_board_permissions((int)$root['fid'], 1, dune_board_private_permissions($permissionColumns, false));
$query = $db->simple_select('dune_system_boards', 'fid');
while ($row = $db->fetch_array($query)) $db->update_query('forums', ['active'=>1], 'fid='.(int)$row['fid']);
$db->write_query('COMMIT');
foreach (['usergroups','forums','forumpermissions','moderators'] as $key) { $method='update_'.$key; $cache->$method(); }
echo json_encode(['status'=>'provisioned', 'organisations'=>count($input['organisations']), 'rootForum'=>(int)$root['fid']], JSON_THROW_ON_ERROR)."\n";
} catch (Throwable $error) {
$db->write_query('ROLLBACK');
throw $error;
} finally {
$db->write_query("SELECT RELEASE_LOCK('dune_system_boards_provision')");
}
function save_board_permissions(int $fid, int $gid, array $permissions): void {
global $db;
$where = 'fid='.$fid.' AND gid='.$gid;
$existing = $db->fetch_array($db->simple_select('forumpermissions', 'pid', $where));
if ($existing) $db->update_query('forumpermissions', $permissions, $where);
else $db->insert_query('forumpermissions', array_merge($permissions, ['fid'=>$fid,'gid'=>$gid]));
}
require __DIR__.'/system-board-provision.php';
echo json_encode(dune_provision_system_boards($input),JSON_THROW_ON_ERROR)."\n";

View file

@ -1,44 +1,49 @@
<?php
if (!defined('IN_MYBB')) die('Direct access denied');
<?php
if (!defined('IN_MYBB')) die('Direct access denied');
require_once __DIR__.'/system-board-policy.php';
function dune_system_board_registry(): array {
global $db;
if (!$db->table_exists('dune_system_boards')) throw new RuntimeException('System Boards are not provisioned');
$query = $db->simple_select('dune_system_boards', '*', "kind IN ('clan','company')");
$rows = [];
while ($row = $db->fetch_array($query)) $rows[$row['kind'].':'.$row['organisation_id']] = $row;
return $rows;
}
function dune_apply_system_board_membership(array $identity): void {
global $mybb, $db;
if (empty($mybb->user['uid'])) return;
$boards = dune_system_board_registry();
$gids = array_values(array_unique(array_filter(array_merge([(int)$mybb->user['usergroup']], array_map('intval', explode(',', (string)($mybb->user['additionalgroups'] ?? '')))), fn($gid) => $gid > 0)));
if ($boards) {
$fids = array_map(fn($board) => (int)$board['fid'], array_values($boards));
$checks = $db->simple_select('forumpermissions', 'fid,COUNT(DISTINCT gid) AS policy_count', 'fid IN ('.implode(',', $fids).') AND gid IN ('.implode(',', $gids).')', ['group_by'=>'fid']);
$covered = [];
while ($row = $db->fetch_array($checks)) if ((int)$row['policy_count'] === count($gids)) $covered[(int)$row['fid']] = true;
foreach ($fids as $fid) if (empty($covered[$fid])) throw new RuntimeException('Forum group policies require refresh');
}
require_once __DIR__.'/system-board-provision.php';
function dune_system_board_registry(): array {
global $db;
if (!$db->table_exists('dune_system_boards')) return [];
$query = $db->simple_select('dune_system_boards', '*', "kind IN ('clan','company')");
$rows = [];
while ($row = $db->fetch_array($query)) $rows[$row['kind'].':'.$row['organisation_id']] = $row;
return $rows;
}
function dune_apply_system_board_membership(array $identity): void {
global $mybb, $db;
if (empty($mybb->user['uid'])) return;
$projection = $identity['systemBoards'] ?? null;
if (!is_array($projection)) throw new RuntimeException('Forum membership projection unavailable');
$GLOBALS['dune_system_board_identity'] = $identity;
$managed = [];
foreach ($boards as $board) { $managed[] = (int)$board['member_gid']; $managed[] = (int)$board['leader_gid']; }
$allowed = dune_board_managed_groups($projection, $boards);
$groups = dune_board_additional_groups((string)($mybb->user['additionalgroups'] ?? ''), $managed, $allowed);
$old = array_filter(array_map('intval', explode(',', (string)($mybb->user['additionalgroups'] ?? ''))));
sort($old, SORT_NUMERIC);
if (implode(',', $old) === $groups) return;
$db->update_query('users', ['additionalgroups'=>$groups], 'uid='.(int)$mybb->user['uid']);
// MyBB has already resolved this request's usergroup. Discard it and start
// a fresh GET before permission caches, posting or attachment handlers run.
$path = $_SERVER['REQUEST_URI'] ?? '/';
if (!str_starts_with($path, '/') || str_starts_with($path, '//') || preg_match('/[\r\n]/', $path)) $path = '/';
header('Cache-Control: private, no-store');
header('Location: '.$path, true, 303);
exit;
}
if (!is_array($projection) || ($projection['version'] ?? null) !== 1) throw new RuntimeException('Forum membership projection unavailable');
$boards = dune_system_board_registry();
$missing=dune_missing_system_boards($projection,$boards);
if ($missing) { dune_provision_system_boards(['organisations'=>$missing]); $boards=dune_system_board_registry(); }
$gids = array_values(array_unique(array_filter(array_merge([(int)$mybb->user['usergroup']], array_map('intval', explode(',', (string)($mybb->user['additionalgroups'] ?? '')))), fn($gid) => $gid > 0)));
if ($boards) {
$fids = array_map(fn($board) => (int)$board['fid'], array_values($boards));
$checks = $db->simple_select('forumpermissions', 'fid,COUNT(DISTINCT gid) AS policy_count', 'fid IN ('.implode(',', $fids).') AND gid IN ('.implode(',', $gids).')', ['group_by'=>'fid']);
$covered = [];
while ($row = $db->fetch_array($checks)) if ((int)$row['policy_count'] === count($gids)) $covered[(int)$row['fid']] = true;
foreach ($fids as $fid) if (empty($covered[$fid])) throw new RuntimeException('Forum group policies require refresh');
}
$projection = $identity['systemBoards'] ?? null;
if (!is_array($projection)) throw new RuntimeException('Forum membership projection unavailable');
$GLOBALS['dune_system_board_identity'] = $identity;
$managed = [];
foreach ($boards as $board) { $managed[] = (int)$board['member_gid']; $managed[] = (int)$board['leader_gid']; }
$allowed = dune_board_managed_groups($projection, $boards);
$groups = dune_board_additional_groups((string)($mybb->user['additionalgroups'] ?? ''), $managed, $allowed);
$old = array_filter(array_map('intval', explode(',', (string)($mybb->user['additionalgroups'] ?? ''))));
sort($old, SORT_NUMERIC);
if (implode(',', $old) === $groups) return;
$db->update_query('users', ['additionalgroups'=>$groups], 'uid='.(int)$mybb->user['uid']);
// MyBB has already resolved this request's usergroup. Discard it and start
// a fresh GET before permission caches, posting or attachment handlers run.
$path = $_SERVER['REQUEST_URI'] ?? '/';
if (!str_starts_with($path, '/') || str_starts_with($path, '//') || preg_match('/[\r\n]/', $path)) $path = '/';
header('Cache-Control: private, no-store');
header('Location: '.$path, true, 303);
exit;
}

View file

@ -0,0 +1,128 @@
<?php
if (!defined('IN_MYBB')) die('Direct access denied');
require_once __DIR__.'/system-board-policy.php';
// Input comes only from the authenticated central SSO identity, never GET/POST.
function dune_missing_system_boards(array $projection, array $boards): array {
if (($projection['version'] ?? null) !== 1) throw new RuntimeException('Forum membership projection unavailable');
$missing=[];
foreach ($projection['organisations'] ?? [] as $grant) {
if (!in_array($grant['kind'] ?? '', ['clan','company'],true) || ($grant['read'] ?? false) !== true || ($grant['post'] ?? false) !== true) continue;
if (!preg_match('/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i',$grant['id'] ?? '')) throw new RuntimeException('Invalid verified organisation');
$key=$grant['kind'].':'.$grant['id'];
if (isset($boards[$key]) || isset($missing[$key])) continue;
if (!is_string($grant['name'] ?? null) || trim($grant['name']) === '' || strlen($grant['name'])>120) throw new RuntimeException('Verified organisation name unavailable');
$missing[$key]=['kind'=>$grant['kind'],'id'=>$grant['id'],'name'=>$grant['name']];
}
return array_values($missing);
}
function dune_provision_system_boards(array $input): array {
global $db,$cache,$dune_board_template;
if (!is_array($input) || !isset($input['organisations']) || !is_array($input['organisations'])) throw new RuntimeException('Organisation snapshot required');
foreach ($input['organisations'] as $org) {
if (!in_array($org['kind'] ?? '', ['clan','company'], true) || !preg_match('/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i', $org['id'] ?? '') || !is_string($org['name'] ?? null) || trim($org['name']) === '' || strlen($org['name']) > 120) throw new RuntimeException('Invalid organisation');
}
$lock = $db->fetch_array($db->write_query("SELECT GET_LOCK('dune_system_boards_provision',10) acquired"));
if ((int)($lock['acquired'] ?? 0) !== 1) throw new RuntimeException('System Boards publication is busy');
try {
$db->write_query('CREATE TABLE IF NOT EXISTS '.TABLE_PREFIX.'dune_system_boards (kind VARCHAR(12) NOT NULL, organisation_id VARCHAR(36) NOT NULL, fid INT NOT NULL, member_gid INT NOT NULL DEFAULT 0, leader_gid INT NOT NULL DEFAULT 0, PRIMARY KEY(kind,organisation_id), UNIQUE KEY forum_id(fid)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
$db->write_query('START TRANSACTION');
$groups = []; $query = $db->simple_select('usergroups');
while ($row = $db->fetch_array($query)) $groups[(int)$row['gid']] = $row;
if (!isset($groups[2])) throw new RuntimeException('Registered group unavailable');
$dune_board_template = $db->fetch_array($db->simple_select('forums', '*', "type='f'", ['limit'=>1]));
if (!$dune_board_template) throw new RuntimeException('Native forum template unavailable');
$permissionColumns = ['canview','canviewthreads','canonlyviewownthreads','candlattachments','canpostthreads','canpostreplys','canonlyreplyownthreads','canpostattachments','canratethreads','caneditposts','candeleteposts','candeletethreads','caneditattachments','canviewdeletionnotice','modposts','modthreads','mod_edit_posts','modattachments','canpostpolls','canvotepolls','cansearch'];
$root = dune_provision_make_board('system','root','System Boards',0);
$clans = dune_provision_make_board('system','clans','Clan Boards',(int)$root['fid']);
$companies = dune_provision_make_board('system','companies','Company Boards',(int)$root['fid']);
dune_provision_make_board('system','elections','Election Board',(int)$root['fid'],'f');
foreach ($input['organisations'] as $org) {
$board = dune_provision_make_board($org['kind'], $org['id'], $org['name'], (int)($org['kind']==='clan' ? $clans['fid'] : $companies['fid']), 'f');
foreach (['member_gid','leader_gid'] as $field) {
$role=$field==='leader_gid'?'leaders':'members';
$title=my_substr(($org['kind']==='clan'?'Clan':'Company').' '.$role.' · '.$org['name'],0,45);
if ((int)$board[$field] > 0) {
$db->update_query('usergroups',['title'=>$db->escape_string($title)],'gid='.(int)$board[$field]);
continue;
}
$group = $groups[2]; unset($group['gid']);
$group['title'] = $title;
$group['cancp'] = 0; $group['issupermod'] = 0; $group['canmodcp'] = $field==='leader_gid' ? 1 : 0;
foreach ($group as $key=>$value) if (is_string($value)) $group[$key]=$db->escape_string($value);
$gid = (int)$db->insert_query('usergroups', $group);
$board[$field] = $gid; $groups[$gid] = $group;
$db->update_query('dune_system_boards', [$field=>$gid], 'fid='.(int)$board['fid']);
}
// Every known group gets an explicit policy: additional political
// groups cannot accidentally make an unrelated organisation visible.
foreach ($groups as $gid=>$group) {
$member = in_array($gid, [(int)$board['member_gid'],(int)$board['leader_gid'],3,4,6], true);
$permissions = dune_board_private_permissions($permissionColumns, $member);
dune_provision_save_permissions((int)$board['fid'], (int)$gid, $permissions);
}
$moderator = ['fid'=>(int)$board['fid'], 'id'=>(int)$board['leader_gid'], 'isgroup'=>1,
'caneditposts'=>1,'cansoftdeleteposts'=>1,'canrestoreposts'=>1,'cansoftdeletethreads'=>1,'canrestorethreads'=>1,
'canopenclosethreads'=>1,'canstickunstickthreads'=>1,'canapproveunapprovethreads'=>1,'canapproveunapproveposts'=>1,
'canapproveunapproveattachs'=>1,'canmanagethreads'=>1,'canmanagepolls'=>1,'canpostclosedthreads'=>1,'canmanagereportedposts'=>1,'canviewmodlog'=>1];
$db->delete_query('moderators', 'fid='.(int)$board['fid'].' AND id='.(int)$board['leader_gid'].' AND isgroup=1');
$db->insert_query('moderators', $moderator);
// Existing native Moderators retain moderation on every new board;
// Super Moderators and Administrators already have native global power.
$moderator['id']=6;
$db->delete_query('moderators', 'fid='.(int)$board['fid'].' AND id=6 AND isgroup=1');
$db->insert_query('moderators', $moderator);
}
// Refresh earlier boards too, since later provisioning adds managed groups.
// These groups must also be denied access to every other private board.
$query = $db->simple_select('dune_system_boards', '*', "kind IN ('clan','company')");
while ($board = $db->fetch_array($query)) foreach ($groups as $gid=>$group) {
$member = in_array($gid, [(int)$board['member_gid'],(int)$board['leader_gid'],3,4,6], true);
dune_provision_save_permissions((int)$board['fid'], (int)$gid, dune_board_private_permissions($permissionColumns, $member));
}
// No guest feed may publish System Boards topics.
dune_provision_save_permissions((int)$root['fid'], 1, dune_board_private_permissions($permissionColumns, false));
$query = $db->simple_select('dune_system_boards', 'fid');
while ($row = $db->fetch_array($query)) $db->update_query('forums', ['active'=>1], 'fid='.(int)$row['fid']);
$db->write_query('COMMIT');
foreach (['usergroups','forums','forumpermissions','moderators'] as $key) { $method='update_'.$key; $cache->$method(); }
return ['status'=>'provisioned', 'organisations'=>count($input['organisations']), 'rootForum'=>(int)$root['fid']];
} catch (Throwable $error) {
$db->write_query('ROLLBACK');
throw $error;
} finally {
$db->write_query("SELECT RELEASE_LOCK('dune_system_boards_provision')");
}
}
function dune_provision_board_row($kind, $id) {
global $db;
return $db->fetch_array($db->simple_select('dune_system_boards', '*', "kind='".$db->escape_string($kind)."' AND organisation_id='".$db->escape_string($id)."'"));
}
function dune_provision_make_board($kind, $id, $name, $parent, $type = 'c') {
global $db, $dune_board_template;
if ($existing = dune_provision_board_row($kind, $id)) return $existing;
$row = $dune_board_template; unset($row['fid']);
foreach (['threads','posts','lastpost','lastposteruid','unapprovedthreads','unapprovedposts','deletedthreads','deletedposts'] as $key) if (array_key_exists($key, $row)) $row[$key] = 0;
foreach (['lastposter','lastpostsubject','linkto','password','rules','rulestitle'] as $key) if (array_key_exists($key, $row)) $row[$key] = '';
$row = array_merge($row, ['name'=>htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), 'description'=>'', 'type'=>$type, 'pid'=>$parent, 'parentlist'=>'', 'disporder'=>1000, 'active'=>0, 'open'=>1, 'allowhtml'=>0, 'allowmycode'=>1, 'allowsmilies'=>1, 'allowimgcode'=>1, 'showinjump'=>1]);
foreach ($row as $key=>$value) if (is_string($value)) $row[$key]=$db->escape_string($value);
$fid = (int)$db->insert_query('forums', $row);
$parentRow = $parent ? $db->fetch_array($db->simple_select('forums','parentlist','fid='.$parent)) : null;
$parentlist = ($parentRow ? $parentRow['parentlist'].',' : '').$fid;
$db->update_query('forums', ['parentlist'=>$db->escape_string($parentlist)], 'fid='.$fid);
$db->insert_query('dune_system_boards', ['kind'=>$db->escape_string($kind), 'organisation_id'=>$db->escape_string($id), 'fid'=>$fid]);
return dune_provision_board_row($kind, $id);
}
function dune_provision_save_permissions(int $fid, int $gid, array $permissions): void {
global $db;
$where = 'fid='.$fid.' AND gid='.$gid;
$existing = $db->fetch_array($db->simple_select('forumpermissions', 'pid', $where));
if ($existing) $db->update_query('forumpermissions', $permissions, $where);
else $db->insert_query('forumpermissions', array_merge($permissions, ['fid'=>$fid,'gid'=>$gid]));
}

View file

@ -0,0 +1,13 @@
<?php
define('IN_MYBB',1);
require __DIR__.'/system-board-provision.php';
$grant=['kind'=>'clan','id'=>'11111111-1111-4111-8111-111111111111','name'=>'Fixture Clan','read'=>true,'post'=>true];
$projection=['version'=>1,'organisations'=>[$grant,$grant,array_merge($grant,['kind'=>'unknown']),array_merge($grant,['read'=>false])]];
$missing=dune_missing_system_boards($projection,[]);
if(count($missing)!==1 || $missing[0]['name']!=='Fixture Clan')throw new RuntimeException('Missing verified clan must be deduplicated and provisioned');
if(dune_missing_system_boards($projection,['clan:'.$grant['id']=>['fid'=>10]])!==[])throw new RuntimeException('Existing board must not be recreated');
foreach([array_merge($grant,['id'=>'injected']),array_merge($grant,['name'=>''])] as $invalid){
$rejected=false;try{dune_missing_system_boards(['version'=>1,'organisations'=>[$invalid]],[]);}catch(RuntimeException $e){$rejected=true;}
if(!$rejected)throw new RuntimeException('Invalid verified identity must fail closed');
}
echo "Automatic System Boards provisioning policy checks passed\n";

View file

@ -6,13 +6,13 @@ export function projectSystemBoardAccess({clans=[],companies=[],userId,inspectAl
if(typeof userId!=='string'||!userId)return {version:1,inspectAll:false,moderateAll:false,organisations:[]};
for(const clan of clans){
if(Number(clan.active)!==1||clan.user_id!==userId||!['owner','officer','member'].includes(clan.clan_role))continue;
grants.set('clan:'+clan.id,{kind:'clan',id:clan.id,read:true,post:true,manage:clan.owner_id===userId&&clan.clan_role==='owner'});
grants.set('clan:'+clan.id,{kind:'clan',id:clan.id,...(typeof clan.name==='string'?{name:clan.name}:{}),read:true,post:true,manage:clan.owner_id===userId&&clan.clan_role==='owner'});
}
for(const company of companies){
if(company.status!=='active'||company.founded_by!==userId&&company.ceo_account_id!==userId)continue;
// Founder access follows the existing Company CP. Current management,
// including scoped moderation, belongs to the appointed CEO.
grants.set('company:'+company.id,{kind:'company',id:company.id,read:true,post:true,manage:company.ceo_account_id===userId});
grants.set('company:'+company.id,{kind:'company',id:company.id,...(typeof company.name==='string'?{name:company.name}:{}),read:true,post:true,manage:company.ceo_account_id===userId});
}
return {version:1,inspectAll:inspectAll===true,moderateAll:moderateAll===true,organisations:[...grants.values()].sort((a,b)=>(a.kind+':'+a.id).localeCompare(b.kind+':'+b.id))};
}
@ -20,8 +20,8 @@ export function projectSystemBoardAccess({clans=[],companies=[],userId,inspectAl
export async function loadSystemBoardAccess(db,user,{inspectAll=false,moderateAll=false}={}){
if(!user?.id)return projectSystemBoardAccess();
const [{results:clans=[]},{results:companies=[]}]=await Promise.all([
db.prepare('SELECT c.id,c.active,c.owner_id,m.user_id,m.clan_role FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id WHERE m.user_id=? AND c.active=1').bind(user.id).all(),
db.prepare('SELECT id,status,founded_by,ceo_account_id FROM corrino_companies WHERE founded_by=? OR ceo_account_id=?').bind(user.id,user.id).all()
db.prepare('SELECT c.id,c.name,c.active,c.owner_id,m.user_id,m.clan_role FROM site_clans c JOIN site_clan_members m ON m.clan_id=c.id WHERE m.user_id=? AND c.active=1').bind(user.id).all(),
db.prepare('SELECT id,name,status,founded_by,ceo_account_id FROM corrino_companies WHERE founded_by=? OR ceo_account_id=?').bind(user.id,user.id).all()
]);
const projected=projectSystemBoardAccess({clans,companies,userId:user.id,inspectAll,moderateAll}),operators=await clanDeedOperators(db);for(const [id,users]of operators)if(users.includes(user.id)){const existing=projected.organisations.find(o=>o.kind==='clan'&&o.id===id);if(existing)existing.manage=true;else projected.organisations.push({kind:'clan',id,read:true,post:true,manage:true});}return projected;
const projected=projectSystemBoardAccess({clans,companies,userId:user.id,inspectAll,moderateAll}),operators=await clanDeedOperators(db);for(const [id,users]of operators)if(users.includes(user.id)){const existing=projected.organisations.find(o=>o.kind==='clan'&&o.id===id);if(existing)existing.manage=true;else projected.organisations.push({kind:'clan',id,read:true,post:true,manage:true});}for(const org of projected.organisations)if(org.kind==='clan'&&!org.name){const record=await db.prepare('SELECT name FROM site_clans WHERE id=? AND active=1').bind(org.id).first();if(record)org.name=record.name;}return projected;
}

View file

@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Publish only the owned board helpers from the active, CI-promoted release."""
import argparse
import datetime
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
EXPECTED = {
'provision-system-boards.php': 'b866ac27a8caf56d89307d386a9eac4a977f524646f4b2251e750d24e2fe6b5c',
'system-board-membership.php': '8d9fc7126a229b2ca0f6033ec0647946e418558981af75eb731ef5526f63a15f',
}
FILES = ['system-board-provision.php', 'provision-system-boards.php', 'system-board-membership.php']
def digest(data):
return hashlib.sha256(data).hexdigest()
def publication_changes(source, target):
changes = []
for name in FILES:
destination = target / name
content = (source / name).read_bytes()
if destination.is_symlink():
raise RuntimeError('Refusing a symlink destination: ' + name)
old = destination.read_bytes() if destination.exists() else None
if old == content:
continue
if old is not None and digest(old) != EXPECTED.get(name):
raise RuntimeError('Native helper has unreviewed changes: ' + name)
if old is None and name in EXPECTED:
raise RuntimeError('Expected existing helper missing: ' + name)
changes.append((name, content, old))
return changes
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
release = Path(__file__).resolve().parents[1]
app = Path('/home/dunerealms/apps/dunerealms')
if (app / 'current').resolve(strict=True) != release or not re.fullmatch(r'ci-[0-9a-f]{40}', release.name):
raise RuntimeError('Use this publisher from the active CI-promoted release')
if Path('/var/lib/dunerealms-ci-promote/deployed').read_text().strip() != release.name[3:]:
raise RuntimeError('Publication state does not match the active release')
source = release / 'integrations/mybb'
target = Path('/home/dunerealms/apps/integrations/mybb').resolve(strict=True)
if not (target / 'global.php').is_file():
raise RuntimeError('Native MyBB installation missing')
changes = publication_changes(source, target)
for name in FILES:
subprocess.run(['php', '-l', str(source / name)], check=True, capture_output=True)
for name in ['test-system-board-policy.php', 'test-system-board-provision.php']:
subprocess.run(['php', str(source / name)], check=True, capture_output=True)
if not args.apply:
print(json.dumps({'applied': False, 'files': [name for name, _, _ in changes]}))
return
backup = Path('/var/backups/dunerealms-system-boards') / datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
if changes:
backup.mkdir(parents=True, mode=0o700, exist_ok=False)
reference = (target / 'system-board-membership.php').stat()
for name, content, old in changes:
destination = target / name
current = destination.read_bytes() if destination.exists() else None
if current != old:
raise RuntimeError('Native helper changed during publication: ' + name)
if old is not None:
shutil.copy2(destination, backup / name)
fd, temporary = tempfile.mkstemp(prefix='.dune-board-', dir=target)
try:
with os.fdopen(fd, 'wb') as output:
output.write(content)
os.chmod(temporary, reference.st_mode & 0o777)
os.chown(temporary, reference.st_uid, reference.st_gid)
os.replace(temporary, destination)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
node = '/home/dunerealms/.nvm/versions/node/v22.23.3/bin/node'
snapshot = subprocess.run(['runuser', '-u', 'dunerealms', '--', node,
'--env-file=/home/dunerealms/.config/dunerealms.env',
str(release / 'ops/system-board-snapshot.mjs')],
check=True, capture_output=True, text=True)
result = subprocess.run(['php', str(target / 'provision-system-boards.php')],
input=snapshot.stdout, check=True, capture_output=True, text=True)
# Existing native permission tests inspect real MyBB without editing users.
subprocess.run(['php', str(source / 'test-system-board-native.php')], check=True, capture_output=True)
print(json.dumps({'applied': True, 'files': [name for name, _, _ in changes],
'provisioning': json.loads(result.stdout)}))
if __name__ == '__main__':
main()

View file

@ -0,0 +1,42 @@
import importlib.util
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('board_publisher', Path(__file__).with_name('publish-system-board-repair.py'))
publisher = importlib.util.module_from_spec(spec)
spec.loader.exec_module(publisher)
class BoardPublicationGuardTest(unittest.TestCase):
def test_changed_native_helpers_are_refused_without_overwriting_them(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source, target = root / 'source', root / 'target'
source.mkdir()
target.mkdir()
for name in publisher.FILES:
(source / name).write_text('reviewed new helper')
for name in publisher.EXPECTED:
(target / name).write_text('unexpected native customization')
with self.assertRaisesRegex(RuntimeError, 'unreviewed changes'):
publisher.publication_changes(source, target)
for name in publisher.EXPECTED:
self.assertEqual((target / name).read_text(), 'unexpected native customization')
self.assertFalse((target / publisher.FILES[0]).exists())
def test_repeated_completed_publication_needs_no_writes(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source, target = root / 'source', root / 'target'
source.mkdir()
target.mkdir()
for name in publisher.FILES:
(source / name).write_text('same approved helper')
(target / name).write_text('same approved helper')
self.assertEqual(publisher.publication_changes(source, target), [])
if __name__ == '__main__':
unittest.main()

View file

@ -1,29 +1,32 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {projectSystemBoardAccess} from '../node/system-board-access.mjs';
const clan={id:'ours',active:1,user_id:'member',owner_id:'leader',clan_role:'member'};
test('private board membership excludes other users, inactive clans and departed users',()=>{
const access=projectSystemBoardAccess({userId:'member',clans:[clan,{...clan,id:'other',user_id:'other'},{...clan,id:'closed',active:0}]});
assert.deepEqual(access.organisations,[{kind:'clan',id:'ours',read:true,post:true,manage:false}]);
assert.equal(projectSystemBoardAccess({userId:'member',clans:[]}).organisations.length,0);
});
test('only verified current clan ownership grants subtree management',()=>{
for(const role of ['member','officer','owner']){
const result=projectSystemBoardAccess({userId:'member',clans:[{...clan,clan_role:role}]}).organisations[0];
assert.equal(result.manage,false);
}
assert.equal(projectSystemBoardAccess({userId:'member',clans:[{...clan,owner_id:'member',clan_role:'owner'}]}).organisations[0].manage,true);
});
test('company founder and CEO access remain distinct; unrelated and inactive companies are excluded',()=>{
const company={id:'company',status:'active',founded_by:'founder',ceo_account_id:'ceo'};
const view=userId=>projectSystemBoardAccess({userId,companies:[company]}).organisations;
assert.equal(view('founder')[0].manage,false);assert.equal(view('ceo')[0].manage,true);assert.deepEqual(view('stranger'),[]);
assert.deepEqual(projectSystemBoardAccess({userId:'ceo',companies:[{...company,status:'closed'}]}).organisations,[]);
});
test('inspection is not moderation, and neither can be enabled with truthy strings or an anonymous identity',()=>{
assert.deepEqual(projectSystemBoardAccess({inspectAll:true,moderateAll:true}),{version:1,inspectAll:false,moderateAll:false,organisations:[]});
assert.equal(projectSystemBoardAccess({userId:'owner',inspectAll:true}).moderateAll,false);
assert.equal(projectSystemBoardAccess({userId:'member',inspectAll:'true',moderateAll:1}).inspectAll,false);
assert.equal(projectSystemBoardAccess({userId:'mod',moderateAll:true}).moderateAll,true);
});
import test from 'node:test';
import assert from 'node:assert/strict';
import {projectSystemBoardAccess} from '../node/system-board-access.mjs';
const clan={id:'ours',active:1,user_id:'member',owner_id:'leader',clan_role:'member'};
test('verified organisation names accompany board grants for automatic provisioning',()=>{
assert.equal(projectSystemBoardAccess({userId:'member',clans:[{...clan,name:'Current clan'}]}).organisations[0].name,'Current clan');
});
test('private board membership excludes other users, inactive clans and departed users',()=>{
const access=projectSystemBoardAccess({userId:'member',clans:[clan,{...clan,id:'other',user_id:'other'},{...clan,id:'closed',active:0}]});
assert.deepEqual(access.organisations,[{kind:'clan',id:'ours',read:true,post:true,manage:false}]);
assert.equal(projectSystemBoardAccess({userId:'member',clans:[]}).organisations.length,0);
});
test('only verified current clan ownership grants subtree management',()=>{
for(const role of ['member','officer','owner']){
const result=projectSystemBoardAccess({userId:'member',clans:[{...clan,clan_role:role}]}).organisations[0];
assert.equal(result.manage,false);
}
assert.equal(projectSystemBoardAccess({userId:'member',clans:[{...clan,owner_id:'member',clan_role:'owner'}]}).organisations[0].manage,true);
});
test('company founder and CEO access remain distinct; unrelated and inactive companies are excluded',()=>{
const company={id:'company',status:'active',founded_by:'founder',ceo_account_id:'ceo'};
const view=userId=>projectSystemBoardAccess({userId,companies:[company]}).organisations;
assert.equal(view('founder')[0].manage,false);assert.equal(view('ceo')[0].manage,true);assert.deepEqual(view('stranger'),[]);
assert.deepEqual(projectSystemBoardAccess({userId:'ceo',companies:[{...company,status:'closed'}]}).organisations,[]);
});
test('inspection is not moderation, and neither can be enabled with truthy strings or an anonymous identity',()=>{
assert.deepEqual(projectSystemBoardAccess({inspectAll:true,moderateAll:true}),{version:1,inspectAll:false,moderateAll:false,organisations:[]});
assert.equal(projectSystemBoardAccess({userId:'owner',inspectAll:true}).moderateAll,false);
assert.equal(projectSystemBoardAccess({userId:'member',inspectAll:'true',moderateAll:1}).inspectAll,false);
assert.equal(projectSystemBoardAccess({userId:'mod',moderateAll:true}).moderateAll,true);
});

View file

@ -0,0 +1,11 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {spawnSync} from 'node:child_process';
import {fileURLToPath} from 'node:url';
const available=spawnSync('php',['-v'],{encoding:'utf8'}).status===0;
test('native automatic board provisioner syntax and verified membership policy',{skip:!available},()=>{
for(const name of ['system-board-provision.php','system-board-membership.php','provision-system-boards.php']){
const result=spawnSync('php',['-l',fileURLToPath(new URL('../integrations/mybb/'+name,import.meta.url))],{encoding:'utf8'});assert.equal(result.status,0,result.stderr||result.stdout);
}
const result=spawnSync('php',[fileURLToPath(new URL('../integrations/mybb/test-system-board-provision.php',import.meta.url))],{encoding:'utf8'});assert.equal(result.status,0,result.stderr||result.stdout);
});