173 lines
13 KiB
PHP
173 lines
13 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
/** Independent source SQL -> visible-cell digests. Never loads app/session code. */
|
|
function uiTrim(mixed $value): string
|
|
{
|
|
// Match JavaScript String.trim(), including Unicode spaces, without changing cell internals.
|
|
$space = '[\x{0009}-\x{000D}\x{0020}\x{00A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}\x{FEFF}]';
|
|
return preg_replace('/^' . $space . '+|' . $space . '+$/u', '', (string) ($value ?? '')) ?? '';
|
|
}
|
|
|
|
function uiRow(int $id, array $cells): array
|
|
{
|
|
$normalized = array_map('uiTrim', $cells);
|
|
$json = json_encode($normalized, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
|
|
| JSON_UNESCAPED_LINE_TERMINATORS | JSON_THROW_ON_ERROR);
|
|
return ['id' => $id, 'hash' => hash('sha256', $json)];
|
|
}
|
|
|
|
function readNumericLabels(string $file): array
|
|
{
|
|
$source = file_get_contents($file);
|
|
if ($source === false || !preg_match('/const scopeLabels: Record<number, string> = \{([^}]+)\}/', $source, $match)) {
|
|
throw new RuntimeException('Scope schema unavailable');
|
|
}
|
|
preg_match_all("/(\d+): '([^']*)'/", $match[1], $matches, PREG_SET_ORDER);
|
|
$result = [];
|
|
foreach ($matches as $label) { $result[(int) $label[1]] = $label[2]; }
|
|
if (count($result) !== 4) { throw new RuntimeException('Scope schema changed'); }
|
|
return $result;
|
|
}
|
|
|
|
try {
|
|
$root = dirname(__DIR__, 2);
|
|
$views = $root . '/identity-admin/web/src/views/';
|
|
$scopeLabels = readNumericLabels($views . 'Roles.vue');
|
|
$menuSource = file_get_contents($views . 'Menus.vue');
|
|
if (!is_string($menuSource) || !preg_match("/const typeLabels:[^=]+ = \{ M: '([^']*)', C: '([^']*)', A: '([^']*)' \}/", $menuSource, $labelMatch)) {
|
|
throw new RuntimeException('Menu schema changed');
|
|
}
|
|
$typeLabels = ['M' => $labelMatch[1], 'C' => $labelMatch[2], 'A' => $labelMatch[3]];
|
|
$departmentSource = file_get_contents($views . 'Departments.vue');
|
|
if (!is_string($departmentSource)) { throw new RuntimeException('Department schema unavailable'); }
|
|
$departmentHasCount = (bool) preg_match('/<el-table-column[^>]+(?:label="[^"]*人数|prop="admin_count)/', $departmentSource);
|
|
if ($departmentHasCount) { throw new RuntimeException('Department visible-count schema changed'); }
|
|
|
|
$environment = @parse_ini_file($root . '/server/.env', true, INI_SCANNER_RAW);
|
|
if (!is_array($environment)) { throw new RuntimeException('Source configuration unavailable'); }
|
|
$database = array_change_key_case($environment['database'] ?? [], CASE_LOWER);
|
|
$prefix = (string) ($database['prefix'] ?? '');
|
|
if (!preg_match('/^[a-zA-Z0-9_]*$/D', $prefix)) { throw new RuntimeException('Invalid prefix'); }
|
|
$pdo = new PDO('mysql:host=' . $database['hostname'] . ';port=' . ($database['hostport'] ?? '3306')
|
|
. ';dbname=' . $database['database'] . ';charset=utf8mb4', $database['username'], $database['password'],
|
|
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 5, PDO::ATTR_EMULATE_PREPARES => false]);
|
|
unset($environment, $database);
|
|
$table = static fn (string $name): string => '`' . $prefix . $name . '`';
|
|
$pdo->exec('START TRANSACTION READ ONLY');
|
|
$generatedAt = gmdate('c');
|
|
$users = $pdo->query('SELECT id,root,name,account,disable FROM ' . $table('admin') . ' WHERE delete_time IS NULL ORDER BY id ASC')->fetchAll(PDO::FETCH_ASSOC);
|
|
$roles = $pdo->query('SELECT id,name,`desc`,sort,data_scope FROM ' . $table('system_role') . ' WHERE delete_time IS NULL ORDER BY id ASC')->fetchAll(PDO::FETCH_ASSOC);
|
|
$depts = $pdo->query('SELECT id,name,sort,status FROM ' . $table('dept') . ' WHERE delete_time IS NULL ORDER BY id ASC')->fetchAll(PDO::FETCH_ASSOC);
|
|
$menus = $pdo->query('SELECT id,name,type,paths,perms,sort,is_show,is_disable FROM ' . $table('system_menu') . ' ORDER BY id ASC')->fetchAll(PDO::FETCH_ASSOC);
|
|
$roleNames = $deptNames = [];
|
|
foreach ($roles as $role) { $roleNames[(int) $role['id']] = (string) $role['name']; }
|
|
foreach ($depts as $dept) { $deptNames[(int) $dept['id']] = (string) $dept['name']; }
|
|
// Preserve original accessor query semantics: it has no ORDER BY clause.
|
|
$roleAccessor = $pdo->prepare('SELECT role_id FROM ' . $table('admin_role') . ' WHERE admin_id = ?');
|
|
$deptAccessor = $pdo->prepare('SELECT dept_id FROM ' . $table('admin_dept') . ' WHERE admin_id = ?');
|
|
$roleGrantIds = $pdo->prepare('SELECT menu_id FROM ' . $table('system_role_menu') . ' WHERE role_id = ?');
|
|
$digests = ['users' => [], 'roles' => [], 'menus' => [], 'departments' => []];
|
|
foreach ($users as $user) {
|
|
$roleDisplay = '';
|
|
if ((int) $user['root'] === 1) { $roleDisplay = '系统管理员'; }
|
|
else {
|
|
$roleAccessor->execute([(int) $user['id']]);
|
|
foreach ($roleAccessor->fetchAll(PDO::FETCH_COLUMN) as $roleId) { $roleDisplay .= ($roleNames[(int) $roleId] ?? '') . '/'; }
|
|
$roleDisplay = trim($roleDisplay, '/');
|
|
}
|
|
$deptAccessor->execute([(int) $user['id']]);
|
|
$deptDisplay = '';
|
|
foreach ($deptAccessor->fetchAll(PDO::FETCH_COLUMN) as $deptId) { $deptDisplay .= ($deptNames[(int) $deptId] ?? '') . '/'; }
|
|
$deptDisplay = trim($deptDisplay, '/');
|
|
$digests['users'][] = uiRow((int) $user['id'], [$user['name'], $user['account'],
|
|
$roleDisplay === '' ? '未分配' : $roleDisplay, $deptDisplay === '' ? '未分配' : $deptDisplay,
|
|
(int) $user['disable'] ? '停用' : '启用']);
|
|
}
|
|
foreach ($roles as $role) {
|
|
$roleGrantIds->execute([(int) $role['id']]);
|
|
$menuIds = array_map('intval', $roleGrantIds->fetchAll(PDO::FETCH_COLUMN));
|
|
$roleDigest = uiRow((int) $role['id'], [$role['name'], $role['desc'],
|
|
count($menuIds) . ' 项', (string) (int) $role['sort'], $scopeLabels[(int) $role['data_scope']] ?? '—']);
|
|
$menuIds = array_values(array_unique($menuIds));
|
|
sort($menuIds, SORT_NUMERIC);
|
|
$roleDigest['menuIds'] = $menuIds;
|
|
$digests['roles'][] = $roleDigest;
|
|
}
|
|
foreach ($menus as $menu) {
|
|
$type = (string) $menu['type'];
|
|
$paths = (string) ($menu['paths'] ?? '');
|
|
$perms = (string) ($menu['perms'] ?? '');
|
|
// The actual Vue A branch is row.perms without a fallback; its label is 按钮.
|
|
$firstLine = $type === 'A' ? $perms : ($paths === '' ? '—' : $paths);
|
|
$secondLine = $type === 'C' ? ($perms === '' ? '未配置权限标识' : $perms) : '';
|
|
$digests['menus'][] = uiRow((int) $menu['id'], [$menu['name'], $typeLabels[$type] ?? '', $firstLine,
|
|
$secondLine, (string) (int) $menu['sort'], $type === 'A' ? '—' : ((int) $menu['is_show'] ? '显示' : '隐藏'),
|
|
(int) $menu['is_disable'] ? '停用' : '启用']);
|
|
}
|
|
foreach ($depts as $dept) {
|
|
$digests['departments'][] = uiRow((int) $dept['id'], [$dept['name'], (string) (int) $dept['sort'], (int) $dept['status'] === 1 ? '启用' : '停用']);
|
|
}
|
|
$invalidRoles = $pdo->query('SELECT ar.admin_id,ar.role_id,a.id AS admin_exists,r.id AS role_exists FROM '
|
|
. $table('admin_role') . ' ar LEFT JOIN ' . $table('admin') . ' a ON a.id=ar.admin_id LEFT JOIN '
|
|
. $table('system_role') . ' r ON r.id=ar.role_id WHERE a.id IS NULL OR r.id IS NULL ORDER BY ar.admin_id ASC,ar.role_id ASC')->fetchAll(PDO::FETCH_ASSOC);
|
|
$pdo->rollBack();
|
|
$pdo = null;
|
|
// Drop all source strings before serializing/writing any artifact.
|
|
unset($users, $roles, $menus, $depts, $roleNames, $deptNames, $user, $role, $menu, $dept, $roleDisplay, $deptDisplay, $paths, $perms, $firstLine, $secondLine);
|
|
foreach ($digests as &$rows) {
|
|
usort($rows, static fn (array $a, array $b): int => strcmp($a['hash'], $b['hash']) ?: $a['id'] <=> $b['id']);
|
|
}
|
|
unset($rows);
|
|
$counts = array_map('count', $digests);
|
|
$output = ['schema' => ['version' => 1, 'generated_at_utc' => $generatedAt, 'source' => 'independent read-only SQL over original tables',
|
|
'canonicalization' => 'SHA256(UTF8(JSON.stringify(cells.map(value => String(value ?? "").trim()))))); each row is a JSON array of strings',
|
|
'php_json_flags' => ['JSON_UNESCAPED_UNICODE', 'JSON_UNESCAPED_SLASHES', 'JSON_UNESCAPED_LINE_TERMINATORS'],
|
|
'row_order' => 'hash ascending, then id; compare as multisets, preserving duplicate hashes',
|
|
'role_menuIds' => 'Each roles row additionally includes menuIds as a numerically ascending unique list of original menu IDs',
|
|
'fields' => ['users' => ['name', 'account', 'roleDisplay', 'deptDisplay', 'status'],
|
|
'roles' => ['name', 'desc', 'grantCount + " 项"', 'sort string', 'scope label'],
|
|
'menus' => ['name', 'type label', 'stacked first line', 'stacked second line', 'sort string', 'navigation label', 'status'],
|
|
'departments' => ['name', 'sort string', 'status']],
|
|
'scope_labels' => $scopeLabels, 'menu_type_labels' => $typeLabels, 'department_has_count_column' => false,
|
|
'menu_rules' => ['A_first_line' => 'perms (empty remains empty, per actual Menus.vue)', 'other_first_line' => 'paths || em dash',
|
|
'C_second_line' => 'perms || 未配置权限标识', 'other_second_line' => 'empty string', 'navigation_A' => 'em dash'],
|
|
'excluded_columns' => ['user avatar initial', 'user root/current-account badge', 'user create_time', 'operations'],
|
|
'privacy' => 'Only IDs, hashes, schema and counts are saved; no original name/account/phone, credentials, sessions or tokens'],
|
|
'counts' => $counts] + $digests;
|
|
$expectedPath = __DIR__ . '/ui-expected-hashes.json';
|
|
$encoded = json_encode($output, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
|
|
if (file_put_contents($expectedPath, $encoded . PHP_EOL) === false) { throw new RuntimeException('Digest output failed'); }
|
|
|
|
$section = [PHP_EOL . '## UI 可见字段摘要与无效关联细化', '', '采集时间(UTC):' . $generatedAt, '',
|
|
'只读脚本 `identity-admin/.test-runtime/consistency-ui-baseline.php` 独立查询原表,按四个实际 Vue 页面可见字段生成 `ui-expected-hashes.json`;不调用 SourceMapper,不读取会话或密码,不登录、不写业务数据。实际字符串仅驻留进程内,输出只有记录ID、SHA-256、schema与数量。', '',
|
|
'摘要数量:用户 ' . $counts['users'] . ';角色 ' . $counts['roles'] . ';菜单 ' . $counts['menus'] . ';部门 ' . $counts['departments'] . '。这些是数据库期望摘要,尚需与真实登录后的 DOM 比较。', '',
|
|
'已核实:Departments.vue 无人数列;Menus.vue 的 A 类型实际标签为「按钮」,A 的路径/权限第一行直接显示 perms,空值不补「—」。期望摘要遵循实际 Vue。角色 scopeLabels 直接从 Roles.vue 读取。用户关系名称按原模型访问器无 ORDER BY 的关联查询顺序拼接,保留原 AdminLists 的斜线拼接和 trim 规则。', '',
|
|
'以下只列非个人信息的关联 ID。物理缺失判断覆盖原实体全表(包含软删记录),因此可与单纯软删区别。', '',
|
|
'| admin_id(组合主键之一) | role_id(组合主键之二) | 缺失端点 |', '|---:|---:|---|'];
|
|
$missingAdmin = $missingRole = $missingBoth = 0;
|
|
foreach ($invalidRoles as $invalid) {
|
|
$adminAbsent = $invalid['admin_exists'] === null;
|
|
$roleAbsent = $invalid['role_exists'] === null;
|
|
$missingAdmin += (int) $adminAbsent;
|
|
$missingRole += (int) $roleAbsent;
|
|
$missingBoth += (int) ($adminAbsent && $roleAbsent);
|
|
$missing = $adminAbsent && $roleAbsent ? 'admin 与 system_role' : ($adminAbsent ? 'admin' : 'system_role');
|
|
$section[] = '| ' . (int) $invalid['admin_id'] . ' | ' . (int) $invalid['role_id'] . ' | ' . $missing . ' |';
|
|
}
|
|
array_push($section, '', '物理缺失关联总行数:' . count($invalidRoles) . ';缺 admin 端:' . $missingAdmin . ';缺 system_role 端:' . $missingRole . ';两端都缺:' . $missingBoth . '。未修改或清理这些历史记录。', '');
|
|
$reportPath = $root . '/artifacts/iam-extraction/data-consistency-baseline.md';
|
|
$existing = file_get_contents($reportPath);
|
|
if (!is_string($existing)) { throw new RuntimeException('Baseline report unavailable'); }
|
|
$marker = strpos($existing, '## UI 可见字段摘要与无效关联细化');
|
|
if ($marker !== false) { $existing = rtrim(substr($existing, 0, $marker)) . PHP_EOL; }
|
|
if (file_put_contents($reportPath, $existing . implode(PHP_EOL, $section)) === false) { throw new RuntimeException('Report update failed'); }
|
|
echo json_encode(['ok' => true, 'counts' => $counts, 'invalid_admin_role_rows' => count($invalidRoles),
|
|
'missing_admin_endpoint' => $missingAdmin, 'missing_role_endpoint' => $missingRole,
|
|
'department_has_count_column' => false, 'menu_A_label' => $typeLabels['A']], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;
|
|
} catch (Throwable $error) {
|
|
if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) { $pdo->rollBack(); }
|
|
echo json_encode(['ok' => false, 'error_code' => (string) $error->getCode(), 'message' => 'UI digest baseline failed; source strings and credentials were not printed.']) . PHP_EOL;
|
|
exit(1);
|
|
}
|