feat(permissions,clients,ai,system,server,web,client,shared)!: 权限组 + 客户端设备远控与自动更新 + 大模型助手 + 系统诊断(1.3.0)
功能级准入改为「权限键」,`requireRole` 退成默认模板。 权限组 - 权限目录(39 键:键 / 中文名 / 分类 / 默认角色)收口到 shared,路由挂 requirePermission / requireAnyPermission - 有效权限每请求实时算,改完分组立刻生效:ADMIN 全集且 permission:manage、system:manage 不可剥夺; CLASS_DEVICE 空集(不受分组影响);有分组 = 并集(因此也能用来**收回**权限);无分组 = 角色默认模板 - 新增「权限组」页:组增删改、成员分配、生效权限预览 - 班级维度的科目规则(assertCanManageSubjectContent)故意不可被权限组覆盖 客户端设备(ClassHelper 桌面端) - 设备身份是 deviceKey(首次启动生成的 UUID,saveConfig 拒绝改写、退出登录也保留) - 心跳走「DB 记状态 + 客户端定时拉」,不引入新的长连接:30 秒一次,在线窗口 90 秒 - 远控命令 shutdown / restart / logoff / lock:服务端有效期 10 分钟,客户端弹默认选中「取消」的对话框、 60 秒未确认按取消处理,执行后必须回执(重复回执幂等),同一台机器同一条命令只弹一次 - 新增「客户端设备」页:版本一览、一键推送更新、下发远控 客户端安装包由服务端下载并缓存(教室机常常没有外网,浏览器也受 CSP 限制) - POST /api/update/client/fetch 由服务端下载到 data/client-releases/<版本>/ 并登记 sha256 + size - 自动安装三条护栏:没有 sha256 就拒收、必须等到非上课且主窗口隐藏满 5 分钟、冒烟模式永不安装 大模型助手:只解析、不落库 - POST /api/ai/interpret 返回**待确认**的结构化动作(建作业 / 发通知 / 叫人), 真正落库仍调既有端点 —— 权限断言、上课时段紧急通知保护、ClassIsland 推送全部自动复用 - 模型给的 params 用与手动入口**同一份** zod 再校验(模型输出不可信) - API Key 走 AES-256-GCM(密钥由 JWT_SECRET 经 scrypt 派生)加密存 AppSetting,只进不出 - provider=mock 是离线确定性解析,自动化验收一律用它;每次解析写一条 AiAudit(不含密钥) 系统与运维 - 开发者模式(服务端内存缓存开关,热路径不查库;开启后 500 才附 error.stack)、运行诊断(绝不回传密钥) - 开机自启动运行期可改:Windows 改 HKCU\...\Run、Linux systemctl enable/disable, **非安装形态一律返回 supported:false**,不往开发机的注册表里写自启项 - 服务端侧栏折叠只用 CSS 收拢(不重建 DOM),关怀模式只放大字号与控件、不动任何几何令牌 客户端 - 崩溃自愈:渲染进程挂掉 / 超 10 秒无响应先静默重建主窗口(10 分钟最多 3 次), 未捕获异常只在「没在上课、没人看着」时才重启进程;冒烟模式绝不重启(会杀掉验证实例) - 上线补弹离线期间收到的消息只做一次:起点只在「可达 → 不可达」的边界写,恢复时取最近 5 条按时间升序推 发布内容批量 - POST /notifications/bulk、POST /homeworks/bulk:**单班失败不影响整批**,逐班返回结果 - 作业的科目名跨班**按名匹配**已有课程,找不到就整班记失败,绝不自动建课 (自动建课会把创建者写成任课老师,等于越权改任教关系) - 通知与作业同口径按「所属日期」归档,新增 /notifications/days 与 /notifications/creators BREAKING CHANGE: 能不能做某件事不再看角色名,而是看权限键(GET /api/permissions/me)。 未分组的账号按角色默认模板生效,行为与 1.2.0 一致;分组之后生效集合只由组的并集决定。 服务端首次启动会自动应用 1 个数据库迁移(权限组 3 表 / AppSetting / 客户端设备·命令·安装包 / AiAudit / Notification.assignDate / User.careMode,历史通知按本地日期回填),升级前请先备份。
This commit is contained in:
1 parent
e51879667a
commit
817af02357
131 files changed
+12995
-538
No files matched your search
@@ -0,0 +1,153 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
CLIENT_ONLINE_WINDOW_MS,
|
||||
type AutostartStatusDto,
|
||||
type SystemDiagnosticsDto,
|
||||
type SystemSettingsDto,
|
||||
} from '@classhelper/shared';
|
||||
import { env } from '../../config/env.js';
|
||||
import { prisma } from '../../lib/db.js';
|
||||
import { ApiError } from '../../lib/http.js';
|
||||
import type { TokenPayload } from '../../lib/jwt.js';
|
||||
import { logger } from '../../lib/logger.js';
|
||||
import { SETTING_KEYS, getBooleanSetting, setBooleanSetting } from '../../lib/settings.js';
|
||||
import { APP_VERSION } from '../../lib/version.js';
|
||||
import type { UpdateAutostartInput, UpdateSystemSettingsInput } from './system.schemas.js';
|
||||
|
||||
/**
|
||||
* 服务端系统设置:开发者模式、开机自启、运行诊断。
|
||||
*
|
||||
* 为什么"开机自启"要做成接口而不是只在安装器里勾一下:教室服务器换机器、改过安装目录、
|
||||
* 或者管理员当时没勾,事后都得能补 —— 安装器只负责**默认值**,运行期由这里改。
|
||||
* 它改的是**操作系统**的东西(注册表 Run 项 / systemd 单元),所以:
|
||||
* 1. 只在"装好的形态"里放行(开发机、免安装包、容器里返回 `supported:false`);
|
||||
* 2. 失败原因是运维性质的(权限不足、单元文件不存在),一律带原文回给管理员,不吞成 500。
|
||||
*/
|
||||
const RUN_KEY_PATH = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
|
||||
const RUN_KEY_NAME = 'ClassHelperServer';
|
||||
const SYSTEMD_UNIT = 'classhelper';
|
||||
|
||||
function runCommand(file: string, args: string[]): { ok: boolean; output: string } {
|
||||
const result = spawnSync(file, args, { encoding: 'utf8', windowsHide: true });
|
||||
const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim();
|
||||
return { ok: result.status === 0, output: output || (result.error ? result.error.message : '') };
|
||||
}
|
||||
|
||||
/** 安装器写在安装目录里的启动脚本:它存在才算"装好的形态" */
|
||||
function startCmdPath(): string {
|
||||
return path.join(path.dirname(process.execPath), 'start.cmd');
|
||||
}
|
||||
|
||||
export async function getSystemSettings(): Promise<SystemSettingsDto> {
|
||||
return { developerMode: await getBooleanSetting(SETTING_KEYS.developerMode, false) };
|
||||
}
|
||||
|
||||
export async function updateSystemSettings(
|
||||
user: TokenPayload,
|
||||
input: UpdateSystemSettingsInput,
|
||||
): Promise<SystemSettingsDto> {
|
||||
if (input.developerMode !== undefined) {
|
||||
await setBooleanSetting(SETTING_KEYS.developerMode, input.developerMode);
|
||||
logger.info(`开发者模式已${input.developerMode ? '开启' : '关闭'}(操作人=${user.username})`);
|
||||
}
|
||||
return getSystemSettings();
|
||||
}
|
||||
|
||||
export async function getAutostartStatus(): Promise<AutostartStatusDto> {
|
||||
if (process.platform === 'win32') {
|
||||
const cmd = startCmdPath();
|
||||
if (!fs.existsSync(cmd)) {
|
||||
return {
|
||||
supported: false,
|
||||
enabled: false,
|
||||
mechanism: 'unsupported',
|
||||
detail: '未检测到安装形态(缺少 start.cmd):开发环境或免安装目录不提供开机自启切换',
|
||||
};
|
||||
}
|
||||
const query = runCommand('reg.exe', ['query', RUN_KEY_PATH, '/v', RUN_KEY_NAME]);
|
||||
return {
|
||||
supported: true,
|
||||
enabled: query.ok,
|
||||
mechanism: 'run-key',
|
||||
detail: `注册表 HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\${RUN_KEY_NAME} → "${cmd}"`,
|
||||
};
|
||||
}
|
||||
|
||||
if (process.platform === 'linux') {
|
||||
const unit = `/etc/systemd/system/${SYSTEMD_UNIT}.service`;
|
||||
if (!fs.existsSync(unit)) {
|
||||
return {
|
||||
supported: false,
|
||||
enabled: false,
|
||||
mechanism: 'unsupported',
|
||||
detail: `未找到 ${unit}(不是 systemd 安装形态)`,
|
||||
};
|
||||
}
|
||||
const query = runCommand('systemctl', ['is-enabled', SYSTEMD_UNIT]);
|
||||
return {
|
||||
supported: true,
|
||||
enabled: query.ok,
|
||||
mechanism: 'systemd',
|
||||
detail: `systemctl is-enabled ${SYSTEMD_UNIT}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
supported: false,
|
||||
enabled: false,
|
||||
mechanism: 'unsupported',
|
||||
detail: `当前平台(${process.platform})不支持切换开机自启`,
|
||||
};
|
||||
}
|
||||
|
||||
export async function updateAutostart(input: UpdateAutostartInput): Promise<AutostartStatusDto> {
|
||||
const current = await getAutostartStatus();
|
||||
if (!current.supported) throw ApiError.badRequest(current.detail);
|
||||
|
||||
if (current.mechanism === 'run-key') {
|
||||
const cmd = startCmdPath();
|
||||
const result = input.enabled
|
||||
? runCommand('reg.exe', ['add', RUN_KEY_PATH, '/v', RUN_KEY_NAME, '/t', 'REG_SZ', '/d', `"${cmd}"`, '/f'])
|
||||
: runCommand('reg.exe', ['delete', RUN_KEY_PATH, '/v', RUN_KEY_NAME, '/f']);
|
||||
if (!result.ok) throw ApiError.internal(`写入开机自启项失败:${result.output}`);
|
||||
} else {
|
||||
const result = runCommand('systemctl', [input.enabled ? 'enable' : 'disable', SYSTEMD_UNIT]);
|
||||
if (!result.ok) {
|
||||
throw ApiError.badRequest(
|
||||
`systemctl ${input.enabled ? 'enable' : 'disable'} ${SYSTEMD_UNIT} 失败:${result.output}(服务是否以特权用户运行?)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`服务端开机自启已${input.enabled ? '开启' : '关闭'}(机制=${current.mechanism})`);
|
||||
return getAutostartStatus();
|
||||
}
|
||||
|
||||
export async function getDiagnostics(): Promise<SystemDiagnosticsDto> {
|
||||
const now = Date.now();
|
||||
// 延迟 import:registry 会 import 本模块,顶层互相引用在 ESM 下会拿到未初始化的绑定
|
||||
const { apiModules } = await import('../registry.js');
|
||||
const [clientReleaseCount, onlineClientCount, settings] = await Promise.all([
|
||||
prisma.clientRelease.count(),
|
||||
prisma.clientDevice.count({
|
||||
where: { lastHeartbeatAt: { gt: new Date(now - CLIENT_ONLINE_WINDOW_MS) } },
|
||||
}),
|
||||
getSystemSettings(),
|
||||
]);
|
||||
|
||||
return {
|
||||
version: APP_VERSION,
|
||||
nodeVersion: process.versions.node,
|
||||
platform: `${process.platform}-${process.arch}`,
|
||||
uptimeSeconds: Math.round(process.uptime()),
|
||||
databaseProvider: env.databaseProvider,
|
||||
serverRoot: env.serverRoot,
|
||||
dataDir: path.resolve(env.serverRoot, '..', 'data'),
|
||||
clientReleaseCount,
|
||||
onlineClientCount,
|
||||
moduleCount: apiModules.length,
|
||||
developerMode: settings.developerMode,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user