feat: 新增多插件 UI 支持及运行日志集中回传功能

本次提交包含多项功能更新:
1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持
2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储
3. 新增插件分类字段支持,用于场景库分组管理
4. 优化 xq0034/0037/0048 等插件的功能及描述
5. 修复控制面响应兼容问题,支持新旧版本数据格式
6. 新增 xq0033 插件的状态存储模块,用于历史记录管理
7. 优化 CRM 登录窗口模式,支持全屏置顶
This commit is contained in:
2026-10-26 15:42:50 +08:00
parent 8bf33b65cd
commit c73c113721
453 changed files with 243002 additions and 4493 deletions
@@ -2,7 +2,9 @@ import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Get, Headers, Inject, Post, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as md5 from 'md5';
import { AccountEntity } from '../../entity/account';
import { BaseSysUserEntity } from '../../../base/entity/sys/user';
import { PluginEntity, AccountPluginEntity, AccountPlatformEntity } from '../../entity/plugin';
import { CenterAuthService, ApiError } from '../../service/auth';
import { hashPassword } from '../../service/crypto';
@@ -39,7 +41,7 @@ export class AdminAccountController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:account:list', xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
@@ -88,7 +90,7 @@ export class AdminAccountController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:account:list', xAdminToken, xApiToken);
const account = (a?.account || '').trim();
if (!account || !a?.password) throw new ApiError(400, 'account 与 password 必填');
if (String(a.password).length < 8) throw new ApiError(400, '密码至少 8 位');
@@ -103,6 +105,8 @@ export class AdminAccountController extends BaseController {
dept: (a?.dept || '').trim(),
nickname: (a?.nickname || '').trim(),
});
// 同步控制台登录身份源(客户端账号密码登录校验 base_sys_user)
await this.syncLoginUser(account, String(a.password), (a?.nickname || '').trim());
await this.centerAuthService.audit(login, 'account-create', account,
`is_admin=${Number(!!a.is_admin)}, dept=${(a?.dept || '').trim()}`);
return { ok: true, account, dept: (a?.dept || '').trim(), nickname: (a?.nickname || '').trim(), is_admin: !!a.is_admin };
@@ -115,7 +119,7 @@ export class AdminAccountController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:account:list', xAdminToken, xApiToken);
const account = (a?.account || '').trim();
if (!account) throw new ApiError(400, 'account 必填');
const exists = await this.accountRepo.findOneBy({ account });
@@ -149,7 +153,7 @@ export class AdminAccountController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:account:list', xAdminToken, xApiToken);
const account = (r?.account || '').trim();
if (!account || !r?.new_password) throw new ApiError(400, 'account 与新密码必填');
if (String(r.new_password).length < 8) throw new ApiError(400, '新密码至少 8 位');
@@ -160,10 +164,41 @@ export class AdminAccountController extends BaseController {
'UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 1 WHERE account = ?',
[hash, salt, account]
);
// 登录身份源在 base_sys_user(客户端账号密码登录校验此表,md5),重置必须双写,否则客户端登录不了
await this.syncLoginUser(account, String(r.new_password), exists.nickname || '');
// 清登录失败计数,避免重置后仍被防爆破临时锁定
await this.centerAuthService.authReset(account);
await this.centerAuthService.audit(login, 'account-reset-pwd', account);
return { ok: true, account };
}
/**
* 同步控制台登录身份源 base_sys_user(客户端账号密码登录校验此表,md5)。
* accounts 是执行机业务账号(hash+salt,仅登记用,无登录消费方),两表算法不同、必须双写。
*/
private async syncLoginUser(account: string, plainPwd: string, nickname: string): Promise<void> {
const userRepo = this.accountRepo.manager.getRepository(BaseSysUserEntity);
const exist = await userRepo.findOneBy({ username: account });
const now = new Date();
if (exist) {
await userRepo.update(
{ id: exist.id },
{ password: md5(plainPwd), passwordV: Number(exist.passwordV || 0) + 1, updateTime: now } as any
);
} else {
await userRepo.insert({
username: account,
password: md5(plainPwd),
nickName: nickname || account,
status: 1,
passwordV: 1,
remark: '由账号管理同步',
createTime: now,
updateTime: now,
} as any);
}
}
/** POST /api/admin/account/delete */
@Post('/account/delete')
async accountDelete(
@@ -171,7 +206,7 @@ export class AdminAccountController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:account:list', xAdminToken, xApiToken);
const account = (d?.account || '').trim();
if (!account) throw new ApiError(400, 'account 必填');
if (account === login) throw new ApiError(400, '不能删除当前登录的账号');
@@ -190,7 +225,8 @@ export class AdminAccountController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms(
['center:account:list', 'center:grant:list'], xAdminToken, xApiToken);
const account = (g?.account || '').trim();
const pluginId = (g?.plugin_id || '').trim();
if (!account || !pluginId) throw new ApiError(400, 'account 与 plugin_id 不能为空');
@@ -221,7 +257,8 @@ export class AdminAccountController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms(
['center:account:list', 'center:grant:list'], xAdminToken, xApiToken);
const account = (g?.account || '').trim();
const platformId = (g?.platform_id || '').trim();
if (!account || !platformId) throw new ApiError(400, 'account 与 platform_id 不能为空');
@@ -2,15 +2,18 @@ import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Get, Headers, Inject, Post, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as md5 from 'md5';
import { AccountEntity } from '../../entity/account';
import { CenterAuthService, ApiError } from '../../service/auth';
import { hashPassword, verifyPassword, signAdminToken } from '../../service/crypto';
import { CenterRbacService } from '../../service/rbac';
import { signAdminToken } from '../../service/crypto';
/**
* 管理面登录/身份(对齐旧 FastAPI apis/auth.py + 壳子 server.js 代理)
* 管理面登录/身份(RBAC 版)
* 身份源:base_sys_user(cool RBAC),不再查 accounts(accounts 仅执行机业务账号)。
* - POST /api/admin/auth:账号密码登录(公开入口)→ 签发 X-Admin-Token + 云令牌
* - GET /api/admin/me:当前账号信息
* - POST /api/admin/password:自助改密(旧密码校验)
* - POST /api/admin/password:自助改密(原密码校验,base_sys_user passwordV+1)
* - POST /api/admin/logout:退出(壳子代理调用,简单返回 ok)
* - GET /api/admin/platforms:可授权平台列表(管理员)
*/
@@ -25,36 +28,52 @@ export class AdminAuthController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@Inject()
centerRbacService: CenterRbacService;
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
/** POST /api/admin/auth — 统一账户登录 */
/** POST /api/admin/auth — 统一账户登录(base_sys_user + md5) */
@Post('/auth')
async auth(
@Body() a: any,
@Headers('X-API-Token') xApiToken: string = ''
) {
async auth(@Body() a: any) {
const account = (a?.account || '').trim();
if (!account) throw new ApiError(400, 'account 不能为空');
await this.centerAuthService.authGate(account);
const row = await this.accountRepo.findOneBy({ account });
if (!row || !verifyPassword(a?.password || '', row.salt, row.passwordHash)) {
const user = await this.centerRbacService.getUserByUsername(account);
if (!user) {
// 业务工号(accounts 已建号)尚未同步控制台登录凭据时,给出可行动的提示
const acct = await this.accountRepo.findOneBy({ account });
await this.centerAuthService.authFail(account);
throw new ApiError(401, acct ? '该账号尚未开通控制台登录密码,请联系管理员重置密码' : '账号或密码错误');
}
if (String(user.password || '') !== md5(String(a?.password || ''))) {
await this.centerAuthService.authFail(account);
throw new ApiError(401, '账号或密码错误');
}
if (!Number(row.status)) throw new ApiError(403, '账号已停用,请联系管理员');
if (!Number(user.status)) throw new ApiError(403, '账号已停用,请联系管理员');
await this.centerAuthService.authReset(account);
const nickname = row.nickname || '';
const ctx = await this.centerRbacService.context(account);
const isAdmin = !!ctx?.isAdmin;
const nickname = user.nickName || user.name || user.username;
const dept = await this.centerRbacService.deptName(user.departmentId);
// 云令牌只对 accounts(执行机业务账号)有意义:cloudAccount() 会 innerJoin accounts
const acctRow = await this.accountRepo.findOneBy({ account });
const cloudToken = acctRow
? await this.centerAuthService.issueCloudToken(account, nickname)
: '';
return {
ok: true,
account,
is_admin: !!Number(row.isAdmin),
dept: row.dept || '',
is_admin: isAdmin,
dept,
nickname,
avatar: row.avatar || '',
must_change_pwd: !!Number(row.mustChangePwd),
avatar: user.headImg || '',
must_change_pwd: false,
token: signAdminToken(account),
cloud_token: await this.centerAuthService.issueCloudToken(account, nickname),
cloud_token: cloudToken,
};
}
@@ -74,19 +93,22 @@ export class AdminAuthController extends BaseController {
}
// 无效身份 → 401(触发前端自动登出回登录页,避免 200-空被误判为已登录)
if (!account) throw new ApiError(401, '登录态无效或已过期,请重新登录');
const row = await this.accountRepo.findOneBy({ account });
if (!row || !Number(row.status)) throw new ApiError(401, '登录态无效或已过期,请重新登录');
const ctx = await this.centerRbacService.context(account);
if (!ctx || !Number(ctx.user.status)) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
const user = ctx.user;
return {
account,
is_admin: !!Number(row.isAdmin),
dept: row.dept || '',
nickname: row.nickname || '',
avatar: row.avatar || '',
must_change_pwd: !!Number(row.mustChangePwd),
account: user.username,
is_admin: !!ctx.isAdmin,
dept: await this.centerRbacService.deptName(user.departmentId),
nickname: user.nickName || user.name || user.username,
avatar: user.headImg || '',
must_change_pwd: false,
};
}
/** POST /api/admin/password — 自助改密 */
/** POST /api/admin/password — 自助改密(base_sys_user) */
@Post('/password')
async password(
@Body() p: any,
@@ -106,15 +128,18 @@ export class AdminAuthController extends BaseController {
}
if (String(p.new_password).length < 8) throw new ApiError(400, '新密码至少 8 位');
if (p.account !== login) throw new ApiError(403, '只能修改自己的密码');
const row = await this.accountRepo.findOneBy({ account: login });
const row = await this.centerRbacService.getUserByUsername(login);
if (!row) throw new ApiError(401, '账号不存在');
if (!row.salt || !verifyPassword(p.old_password || '', row.salt, row.passwordHash)) {
if (String(row.password || '') !== md5(String(p.old_password || ''))) {
throw new ApiError(401, '原密码错误');
}
const { hash, salt } = hashPassword(p.new_password);
await this.accountRepo.manager.query(
'UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 0 WHERE account = ?',
[hash, salt, login]
await this.centerRbacService.userRepo.update(
{ id: row.id },
{
password: md5(String(p.new_password)),
passwordV: Number(row.passwordV || 0) + 1,
updateTime: new Date(),
} as any
);
return { ok: true, account: login };
}
@@ -131,7 +156,7 @@ export class AdminAuthController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requireLogin(xAdminToken, xApiToken);
return { platforms: CONTROLPLANE_PLATFORMS };
}
}
@@ -0,0 +1,176 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Del, Get, Headers, Inject, Param, Post, Provide, Put } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { DictItemEntity } from '../../entity/dict';
import { CenterAuthService, ApiError } from '../../service/auth';
/** 字典标识仅允许小写字母/数字/下划线 */
const DICT_KEY_RE = /^[a-z][a-z0-9_]{0,63}$/;
/** 场景分类默认项:字典为空时一次性初始化(现网已有分类一并自动收录) */
const DEFAULT_PLUGIN_CATEGORIES = ['人事考勤', '考勤', '人事', '人事绩效', '社保', '报表', '财务'];
const SEED_DICT_KEY = 'plugin_category';
/**
* 控制台字典(可维护枚举,如场景分类)
* - GET /api/admin/dict/:key/items 列表(sort,id 升序)
* - POST /api/admin/dict/:key/items 新增 { label }
* - PUT /api/admin/dict/:key/items/:id 改名 { label } / 上移下移 { move: 'up'|'down' }
* - DEL /api/admin/dict/:key/items/:id 删除
* 权限跟随插件管理(center:plugin:list):字典项当前即场景分类,供插件页内维护。
*/
@Provide()
@CoolController('/api/admin')
export class AdminDictController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(DictItemEntity)
dictRepo: Repository<DictItemEntity>;
/** GET /api/admin/dict/:key/items */
@Get('/dict/:key/items')
async items(
@Param('key') key: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
const k = this.normKey(key);
await this.ensureSeeded(k);
const rows = await this.dictRepo
.createQueryBuilder('d')
.where('d.dictKey = :k', { k })
.orderBy('d.sort', 'ASC')
.addOrderBy('d.id', 'ASC')
.getMany();
return { items: rows.map(r => ({ id: Number(r.id), label: r.label, sort: r.sort })) };
}
/** POST /api/admin/dict/:key/items — 新增字典项 */
@Post('/dict/:key/items')
async addItem(
@Param('key') key: string = '',
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
const k = this.normKey(key);
const label = String(b?.label || '').trim();
this.checkLabel(label);
await this.ensureSeeded(k);
const dup = await this.dictRepo.findOneBy({ dictKey: k, label });
if (dup) throw new ApiError(400, `字典项「${label}」已存在`);
const max: any = await this.dictRepo
.createQueryBuilder('d')
.select('COALESCE(MAX(d.sort), -1)', 'max')
.where('d.dictKey = :k', { k })
.getRawOne();
const sort = Number(max?.max ?? -1) + 1;
const r = await this.dictRepo.insert({ dictKey: k, label, sort });
await this.centerAuthService.audit(login, 'dict-add', `${k}:${label}`);
return { ok: true, id: Number(r.identifiers?.[0]?.id || 0), label, sort };
}
/** PUT /api/admin/dict/:key/items/:id — 改名 / 排序 */
@Put('/dict/:key/items/:id')
async updateItem(
@Param('key') key: string = '',
@Param('id') id: any,
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
const k = this.normKey(key);
const itemId = Number(id || 0);
const row = await this.dictRepo.findOneBy({ dictKey: k, id: itemId });
if (!row) throw new ApiError(404, '字典项不存在');
if (b?.move === 'up' || b?.move === 'down') {
const rows = await this.dictRepo
.createQueryBuilder('d')
.where('d.dictKey = :k', { k })
.orderBy('d.sort', 'ASC')
.addOrderBy('d.id', 'ASC')
.getMany();
const idx = rows.findIndex(r => Number(r.id) === itemId);
const j = b.move === 'up' ? idx - 1 : idx + 1;
if (idx >= 0 && j >= 0 && j < rows.length) {
const a = rows[idx];
const c = rows[j];
await this.dictRepo.update({ id: a.id }, { sort: c.sort });
await this.dictRepo.update({ id: c.id }, { sort: a.sort });
}
await this.centerAuthService.audit(login, 'dict-move', `${k}:${row.label} ${b.move}`);
return { ok: true };
}
if (b?.label !== undefined) {
const label = String(b.label || '').trim();
this.checkLabel(label);
if (label !== row.label) {
const dup = await this.dictRepo.findOneBy({ dictKey: k, label });
if (dup) throw new ApiError(400, `字典项「${label}」已存在`);
await this.dictRepo.update({ id: itemId }, { label });
await this.centerAuthService.audit(login, 'dict-rename', `${k}:${row.label} → ${label}`);
}
return { ok: true };
}
return { ok: true };
}
/** DEL /api/admin/dict/:key/items/:id — 删除字典项(不影响已引用该值的插件) */
@Del('/dict/:key/items/:id')
async delItem(
@Param('key') key: string = '',
@Param('id') id: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
const k = this.normKey(key);
const itemId = Number(id || 0);
const row = await this.dictRepo.findOneBy({ dictKey: k, id: itemId });
if (!row) throw new ApiError(404, '字典项不存在');
await this.dictRepo.delete({ id: itemId });
await this.centerAuthService.audit(login, 'dict-delete', `${k}:${row.label}`);
return { ok: true };
}
private normKey(key: string): string {
const k = String(key || '').trim();
if (!DICT_KEY_RE.test(k)) throw new ApiError(400, '字典标识仅允许小写字母/数字/下划线');
return k;
}
private checkLabel(label: string): void {
if (!label) throw new ApiError(400, '字典项名称不能为空');
if (label.length > 64) throw new ApiError(400, '字典项名称过长(≤64 字符)');
}
/** 场景分类字典空表时一次性初始化:默认项 + 现网 plugins.category 自动收录(幂等) */
private async ensureSeeded(k: string): Promise<void> {
if (k !== SEED_DICT_KEY) return;
const cnt = await this.dictRepo.createQueryBuilder('d').where('d.dictKey = :k', { k }).getCount();
if (cnt > 0) return;
const m = this.dictRepo.manager;
for (let i = 0; i < DEFAULT_PLUGIN_CATEGORIES.length; i++) {
await m.query(
`INSERT IGNORE INTO dict_items(dict_key, label, sort) VALUES (?, ?, ?)`,
[k, DEFAULT_PLUGIN_CATEGORIES[i], i]
);
}
const rows: any[] = await m.query(
`SELECT DISTINCT category FROM plugins WHERE category IS NOT NULL AND category <> '' ORDER BY category`
);
let sort = 100;
for (const r of rows) {
const label = String(r.category || '').trim();
if (!label) continue;
await m.query(`INSERT IGNORE INTO dict_items(dict_key, label, sort) VALUES (?, ?, ?)`, [k, label, sort++]);
}
}
}
@@ -1,114 +1,22 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Get, Headers, Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { AccountEntity } from '../../entity/account';
import { CenterAuthService, ApiError } from '../../service/auth';
import { CenterRbacService } from '../../service/rbac';
/**
* 控制台业务菜单(RBAC 驱动)。
* - GET /api/admin/me/menus:返回当前操作者的业务菜单树 + 权限标识集合。
* 管理员(is_admin=1)返回全量;非管理员按 cool-admin 角色权限过滤(预留,2F 用户体系落地后生效)。
* - GET /api/admin/me/menus:按当前账号角色从 base_sys_menu 过滤组树,返回业务菜单树 + 权限标识集合。
* 超管(admin 用户 / label='admin' 角色)返回全部;普通账号仅返回其角色勾选的菜单(含祖先自动补全)。
* - 前端据此驱动动态路由与按钮权限("菜单要权限"落点)。
*/
interface MenuNode {
path: string;
name: string;
component: string;
meta: {
title: string;
icon: string;
perms: string[];
roles?: string[];
/** 侧栏隐藏(如个人中心,仅从用户菜单进入) */
isHide?: boolean;
};
children?: MenuNode[];
}
/** 控制台菜单目录(path/component 与前端视图一一对应;perms 为按钮/页面权限标识) */
const CONSOLE_MENUS: MenuNode[] = [
{
path: '/overview', name: 'Overview', component: '/overview/index',
meta: { title: '概览', icon: 'ri:pie-chart-line', perms: ['center:overview:view'] },
},
{
path: '/stats', name: 'Stats', component: '/stats/index',
meta: { title: '数据看板', icon: 'ri:bar-chart-2-line', perms: ['center:stats:view'] },
},
{
path: '/plugins', name: 'Plugins', component: '/plugins/index',
meta: { title: '插件管理', icon: 'ri:box-3-line', perms: ['center:plugin:list'] },
},
{
path: '/accounts', name: 'Accounts', component: '/accounts/index',
meta: { title: '账号管理', icon: 'ri:user-3-line', perms: ['center:account:list'] },
},
{
path: '/grants', name: 'Grants', component: '/grants/index',
meta: { title: '权限授权', icon: 'ri:key-2-line', perms: ['center:grant:list'] },
},
{
path: '/audit', name: 'Audit', component: '/audit/index',
meta: { title: '审计报表', icon: 'ri:file-list-3-line', perms: ['center:audit:list'] },
},
{
path: '/reports', name: 'Reports', component: '/reports/index',
meta: { title: '运行记录', icon: 'ri:terminal-box-line', perms: ['center:report:list'] },
},
{
path: '/devices', name: 'Devices', component: '/devices/index',
meta: { title: '执行机设备', icon: 'ri:computer-line', perms: ['center:device:list'] },
},
{
path: '/upgrade', name: 'Upgrade', component: '/upgrade/index',
meta: { title: '升级进度', icon: 'ri:rocket-2-line', perms: ['center:device:summary'] },
},
{
path: '/notify', name: 'Notify', component: '/notify/index',
meta: { title: '通知推送', icon: 'ri:notification-3-line', perms: ['center:notify:list'] },
},
{
path: '/creds', name: 'Creds', component: '/creds/index',
meta: { title: '敏感凭证', icon: 'ri:shield-keyhole-line', perms: ['center:creds:list'] },
},
{
path: '/file-sources', name: 'FileSources', component: '/file-sources/index',
meta: { title: '大文件源', icon: 'ri:database-2-line', perms: ['center:fileSource:list'] },
},
{
// 嵌套菜单的父级 component 必须是布局容器(RoutesAlias.Layout='/index/index'),
// 否则一级带 children 的路由不会包 Layout,子页面渲染不出(空白页)
path: '/system', name: 'System', component: '/index/index',
meta: { title: '系统管理', icon: 'ri:settings-3-line', perms: [] },
children: [
{ path: 'user', name: 'SysUser', component: '/system/user', meta: { title: '用户管理', icon: '', perms: ['center:sys:user'] } },
{ path: 'role', name: 'SysRole', component: '/system/role', meta: { title: '角色管理', icon: '', perms: ['center:sys:role'] } },
{ path: 'menu', name: 'SysMenu', component: '/system/menu', meta: { title: '菜单管理', icon: '', perms: ['center:sys:menu'] } },
{ path: 'department', name: 'SysDept', component: '/system/department', meta: { title: '部门管理', icon: '', perms: ['center:sys:dept'] } },
// 个人中心:从头像下拉进入,不在侧栏显示(自助改密 + 头像)
{ path: 'user-center', name: 'UserCenter', component: '/system/user-center', meta: { title: '个人中心', icon: '', perms: [], isHide: true } },
],
},
];
/** 全部权限标识集合(供按钮级 v-permission 使用) */
function allPerms(nodes: MenuNode[]): string[] {
const out: string[] = [];
const walk = (ns: MenuNode[]) => ns.forEach(n => { out.push(...n.meta.perms); if (n.children) walk(n.children); });
walk(nodes);
return out;
}
@Provide()
@CoolController('/api/admin')
export class AdminMenuController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
@Inject()
centerRbacService: CenterRbacService;
/** GET /api/admin/me/menus */
@Get('/me/menus')
@@ -126,13 +34,6 @@ export class AdminMenuController extends BaseController {
}
// 无效身份 → 401(触发前端自动登出,避免 200-空菜单被误判后跳 500)
if (!account) throw new ApiError(401, '登录态无效或已过期,请重新登录');
const row = await this.accountRepo.findOneBy({ account });
if (!row || !Number(row.status)) throw new ApiError(401, '登录态无效或已过期,请重新登录');
const isAdmin = !!Number(row.isAdmin);
// 非管理员:按 cool-admin 角色权限过滤(2F 用户体系落地后生效;当前业务控制台仍以 is_admin 为准)
if (isAdmin) {
return { account, menus: CONSOLE_MENUS, perms: allPerms(CONSOLE_MENUS), is_admin: true };
}
return { account, menus: [], perms: [], is_admin: false };
return this.centerRbacService.menusForUser(account);
}
}
@@ -14,8 +14,9 @@ import { FileSourceEntity, FileserverStatusEntity } from '../../entity/resource'
import { ClientCredEntity } from '../../entity/account';
import { CenterAuthService, ApiError } from '../../service/auth';
import { rsaEncrypt } from '../../service/crypto';
import { CenterLogService } from '../../service/logstore';
import { PKG_DIR, SHELL_DIR, AVATAR_DIR } from '../../comm/conf';
import { pageBounds } from '../../comm/util';
import { pageBounds, readUploadFile } from '../../comm/util';
const ALLOWED_CREDS_KEYS = ['DINGTALK_APPKEY', 'DINGTALK_APPSECRET', 'DINGTALK_AGENT_ID', 'DINGTALK_CORP_ID'];
const SAFE_NAME_RE = /^[A-Za-z0-9._-]+$/;
@@ -35,6 +36,9 @@ export class AdminOpsController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@Inject()
centerLogService: CenterLogService;
@InjectEntityModel(PluginEntity) pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(PluginVersionEntity) pluginVersionRepo: Repository<PluginVersionEntity>;
@InjectEntityModel(AccountPluginEntity) accountPluginRepo: Repository<AccountPluginEntity>;
@@ -53,7 +57,7 @@ export class AdminOpsController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:overview:view', xAdminToken, xApiToken);
const plugins = await this.pluginRepo.find();
const accounts = await this.accountRepo.find();
const admins = (await this.accountRepo
@@ -86,7 +90,7 @@ export class AdminOpsController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:stats:view', xAdminToken, xApiToken);
const m = this.runtimeRepo.manager;
const users: any = (await m.query(
`SELECT (SELECT COUNT(*) FROM accounts) AS total,
@@ -152,7 +156,7 @@ export class AdminOpsController extends BaseController {
@Query('action') action: string = '', @Query('q') q: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:audit:list', xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
@@ -180,7 +184,7 @@ export class AdminOpsController extends BaseController {
@Query('status') status: string = '', @Query('q') q: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:report:list', xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
@@ -216,7 +220,7 @@ export class AdminOpsController extends BaseController {
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:device:list', xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const m = this.deviceRepo.manager;
const total: any = (await m.query('SELECT COUNT(*) AS c FROM devices'))[0];
@@ -232,7 +236,7 @@ export class AdminOpsController extends BaseController {
async devicesSummary(
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:device:list', xAdminToken, xApiToken);
const m = this.deviceRepo.manager;
const total: any = (await m.query('SELECT COUNT(*) AS c FROM devices'))[0];
const byVersion: any[] = await m.query(
@@ -305,11 +309,11 @@ export class AdminOpsController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:device:summary', xAdminToken, xApiToken);
version = (version || '').trim();
if (!version) throw new ApiError(400, 'version 不能为空');
if (!SAFE_NAME_RE.test(version)) throw new ApiError(400, 'version 仅允许字母数字及 . _ -');
const content: Buffer = file?.data || (file?.filepath ? fs.readFileSync(file.filepath) : null);
const content: Buffer = readUploadFile(file);
if (!content || !content.length) throw new ApiError(400, '上传内容为空');
if (content.length > 1024 * 1024 * 1024) throw new ApiError(413, '壳子安装包超过大小上限(1GB)');
const filename = `setup-37du-host-${version}.exe`;
@@ -330,7 +334,7 @@ export class AdminOpsController extends BaseController {
@Query('page_size') pageSize: number = 20,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:fileSource:list', xAdminToken, xApiToken);
const qb = this.fileSourceRepo.createQueryBuilder('f');
if ((category || '').trim()) qb.where('f.category = :c', { c: category.trim() });
const rows = await qb.orderBy('f.id', 'DESC').getMany();
@@ -348,7 +352,7 @@ export class AdminOpsController extends BaseController {
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:fileSource:list', xAdminToken, xApiToken);
const category = (b?.category || '').trim();
const version = (b?.version || '').trim();
const url = (b?.url || '').trim();
@@ -375,7 +379,7 @@ export class AdminOpsController extends BaseController {
@Body() b: any, @Param('fid') fid: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:fileSource:list', xAdminToken, xApiToken);
const id = Number(fid || 0);
if (b?.enabled === undefined && b?.enabled === null && b?.notes === undefined) {
throw new ApiError(400, '无更新字段');
@@ -398,7 +402,7 @@ export class AdminOpsController extends BaseController {
@Param('fid') fid: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:fileSource:list', xAdminToken, xApiToken);
const id = Number(fid || 0);
const m = this.fileSourceRepo.manager;
const r: any = await m.query('DELETE FROM file_sources WHERE id = ?', [id]);
@@ -413,7 +417,7 @@ export class AdminOpsController extends BaseController {
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:creds:list', xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const m = this.clientCredRepo.manager;
const total: any = (await m.query('SELECT COUNT(*) AS c FROM client_creds'))[0];
@@ -436,7 +440,7 @@ export class AdminOpsController extends BaseController {
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:creds:list', xAdminToken, xApiToken);
const account = (b?.account || '').trim();
if (!account) throw new ApiError(400, 'account 不能为空');
const allowed: Record<string, string> = {};
@@ -461,7 +465,7 @@ export class AdminOpsController extends BaseController {
@Query('limit') limit: number = 15,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requireLogin(xAdminToken, xApiToken);
const n = Math.max(1, Math.min(50, Number(limit) || 15));
const rows: any[] = await this.notificationRepo.manager.query(
`SELECT id, title, content, level, target, account, created_at, expires_at
@@ -482,7 +486,7 @@ export class AdminOpsController extends BaseController {
@Query('q') q: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:notify:list', xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
@@ -507,7 +511,7 @@ export class AdminOpsController extends BaseController {
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:notify:list', xAdminToken, xApiToken);
const title = (b?.title || '').trim();
if (!title) throw new ApiError(400, '标题不能为空');
if (!NOTIF_LEVELS.has(b?.level)) throw new ApiError(400, 'level 仅允许 info/warning/important');
@@ -525,7 +529,7 @@ export class AdminOpsController extends BaseController {
@Param('nid') nid: any, @Query('active') active: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:notify:list', xAdminToken, xApiToken);
const id = Number(nid || 0);
await this.notificationRepo.manager.query('UPDATE notifications SET active = ? WHERE id = ?', [Number(active === 'true'), id]);
await this.centerAuthService.audit(login, 'notify-toggle', `通知 #${id} active=${active}`);
@@ -537,7 +541,7 @@ export class AdminOpsController extends BaseController {
@Param('nid') nid: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:notify:list', xAdminToken, xApiToken);
const id = Number(nid || 0);
await this.notificationRepo.manager.query('DELETE FROM notifications WHERE id = ?', [id]);
await this.centerAuthService.audit(login, 'notify-delete', `通知 #${id}`);
@@ -549,7 +553,7 @@ export class AdminOpsController extends BaseController {
async fileserverStatus(
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:fileSource:list', xAdminToken, xApiToken);
const rows = await this.fileserverRepo.find({ order: { lastSeen: 'DESC' } as any });
return {
// 契约对齐旧 FastAPI:键名 fileservers;status/offline_notified 布尔;total_size 数值
@@ -582,11 +586,11 @@ export class AdminOpsController extends BaseController {
account = (account || '').trim();
if (!account) throw new ApiError(400, 'account 不能为空');
if (!SAFE_NAME_RE.test(account)) throw new ApiError(400, 'account 含非法字符(仅允许字母数字及 . _ -)');
if (account !== login) await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
if (account !== login) await this.centerAuthService.requirePerms('center:sys:user', xAdminToken, xApiToken);
const filename = (file?.filename || '').toLowerCase();
const ext = path.extname(filename);
if (!AVATAR_EXT.includes(ext)) throw new ApiError(400, '仅支持图片格式(jpg/png/gif/webp)');
const content: Buffer = file?.data || (file?.filepath ? fs.readFileSync(file.filepath) : null);
const content: Buffer = readUploadFile(file);
if (!content || !content.length || content.length > 2 * 1024 * 1024) throw new ApiError(400, '头像文件为空或超过 2MB');
const acc = await this.accountRepo.findOneBy({ account });
if (!acc) throw new ApiError(400, `账号 ${account} 不存在`);
@@ -599,6 +603,94 @@ export class AdminOpsController extends BaseController {
await this.accountRepo.update({ account }, { avatar: fname });
return { ok: true, account, avatar: fname };
}
// ==================== 集中日志(运行日志 / 客户端壳日志) ====================
/** GET /api/admin/run-logs — 运行日志列表(分页 + 账号/设备/插件/状态/关键字/近N天筛选) */
@Get('/run-logs')
async runLogs(
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
@Query('account') account: string = '', @Query('device') device: string = '',
@Query('plugin') plugin: string = '', @Query('status') status: string = '',
@Query('q') q: string = '', @Query('days') days: number = 0,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
const r = await this.centerLogService.queryRunLogs({ page, pageSize, account, device, plugin, status, q, days });
// 关联账号昵称(对齐旧接口)
const nick: Record<string, string> = {};
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
return {
items: r.items.map((x: any) => ({ ...x, nickname: nick[x.account] || '' })),
total: r.total,
};
}
/** GET /api/admin/run-logs/:runId — 单次运行日志详情(含日志正文) */
@Get('/run-logs/:runId')
async runLogDetail(
@Param('runId') runId: string,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
const row = await this.centerLogService.getRunLog(runId);
if (!row) throw new ApiError(404, '未找到该运行日志');
return row;
}
/** GET /api/admin/device-logs — 已回传壳日志的设备列表 */
@Get('/device-logs')
async deviceLogs(
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
@Query('account') account: string = '', @Query('q') q: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
const r = await this.centerLogService.queryDeviceLogs({ page, pageSize, account, q });
const nick: Record<string, string> = {};
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
return {
items: r.items.map((x: any) => ({ ...x, nickname: nick[x.account] || '' })),
total: r.total,
};
}
/** GET /api/admin/device-logs/:deviceId — 设备壳日志尾部内容(最多尾部 512KB) */
@Get('/device-logs/:deviceId')
async deviceLogDetail(
@Param('deviceId') deviceId: string,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
const row = await this.centerLogService.getDeviceLog(deviceId);
if (!row) throw new ApiError(404, '未找到该设备的壳日志');
return row;
}
/** GET /api/admin/device-logs/:deviceId/download — 设备壳日志全文下载 */
@Get('/device-logs/:deviceId/download')
async deviceLogDownload(
@Param('deviceId') deviceId: string,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
const file = this.centerLogService.deviceLogFilePath(deviceId);
if (!file) throw new ApiError(404, '未找到该设备的壳日志文件');
this.ctx.attachment(`shell-${deviceId}.log`);
this.ctx.type = 'text/plain; charset=utf-8';
this.ctx.body = fs.createReadStream(file);
}
/** POST /api/admin/logs/cleanup — 手动触发一次保留期清理 */
@Post('/logs/cleanup')
async logsCleanup(
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
const result = await this.centerLogService.cleanupExpired();
await this.centerAuthService.audit(login, 'logs-cleanup', 'run-logs',
`deleted_run_logs=${result.deleted_run_logs}, deleted_device_logs=${result.deleted_device_logs}`);
return { ok: true, ...result };
}
}
function versionKey(v: string): number {
@@ -9,7 +9,7 @@ import * as AdmZip from 'adm-zip';
import { PluginEntity, PluginVersionEntity, AccountPluginEntity } from '../../entity/plugin';
import { CenterAuthService, ApiError } from '../../service/auth';
import { PKG_DIR } from '../../comm/conf';
import { pageBounds } from '../../comm/util';
import { pageBounds, readUploadFile } from '../../comm/util';
const SAFE_NAME_RE = /^[A-Za-z0-9._-]+$/;
@@ -49,7 +49,7 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
@@ -104,7 +104,7 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
pluginId = (pluginId || '').trim();
version = (version || '').trim();
name = (name || '').trim() || pluginId;
@@ -112,7 +112,7 @@ export class AdminPluginController extends BaseController {
if (!SAFE_NAME_RE.test(pluginId) || !SAFE_NAME_RE.test(version)) {
throw new ApiError(400, 'plugin_id/version 仅允许字母数字及 . _ -');
}
const content: Buffer = file?.data || (file?.filepath ? fs.readFileSync(file.filepath) : null);
const content: Buffer = readUploadFile(file);
if (!content || !content.length) throw new ApiError(400, '上传内容为空');
if (content.length > 200 * 1024 * 1024) throw new ApiError(413, '插件包超过大小上限(200MB)');
// 校验 zip + 提取 manifest(plugin.json 内 id 与路径 plugin_id 需一致)
@@ -138,16 +138,24 @@ export class AdminPluginController extends BaseController {
fs.writeFileSync(target, content);
const sha256 = crypto.createHash('sha256').update(content).digest('hex');
const manifestJson = JSON.stringify(manifest, null, 0) || '{}';
// 插件主记录 upsert
// 插件主记录 upsert(分类只在首次登记时取 plugin.json,之后以后台手动维护为准,不被新版本覆盖)
await this.pluginRepo.manager.query(
`INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE name = VALUES(name), manifest = VALUES(manifest)
${manifest.description !== undefined ? ', description = VALUES(description)' : ''}
${manifest.category !== undefined ? ', category = VALUES(category)' : ''}
${manifest.icon !== undefined ? ', icon = VALUES(icon)' : ''}`,
[pluginId, name, version, manifest.description || '', manifest.category || '', manifest.icon || '', manifestJson]
);
// plugin.json 自带分类不在字典时自动收录进场景分类字典(幂等,重复项跳过)
const cat = String(manifest.category || '').trim();
if (cat) {
await this.pluginRepo.manager.query(
`INSERT IGNORE INTO dict_items(dict_key, label, sort)
SELECT 'plugin_category', ?, COALESCE((SELECT MAX(sort) FROM dict_items WHERE dict_key = 'plugin_category'), -1) + 1`,
[cat]
);
}
await this.pluginVersionRepo.manager.query(
`INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256, size_bytes)
VALUES (?, ?, ?, NOW(), ?, ?)
@@ -181,7 +189,7 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
const pid = (d?.plugin_id || '').trim();
if (!pid) throw new ApiError(400, 'plugin_id 必填');
const pl = await this.pluginRepo.findOneBy({ id: pid });
@@ -207,13 +215,13 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
const pid = (pluginId || '').trim();
if (!pid) throw new ApiError(400, 'plugin_id 必填');
const set: Record<string, any> = {};
if (d?.name && String(d.name).trim()) set.name = String(d.name).trim();
if (d?.description) set.description = String(d.description).trim();
if (d?.category) set.category = String(d.category).trim();
if (d?.category !== undefined) set.category = String(d.category ?? '').trim();
if (d?.icon) set.icon = String(d.icon).trim();
if (['published', 'disabled', 'revoked'].includes(d?.status)) set.status = d.status;
if (d?.force_min_version && d?.force_deadline) {
@@ -238,7 +246,8 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms(
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
const plugins = await this.pluginRepo
.createQueryBuilder('p').select(['p.id', 'p.name', 'p.status']).orderBy('p.id', 'ASC').getMany();
const accounts = await this.pluginRepo.manager.query(
@@ -253,7 +262,8 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms(
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
account = (account || '').trim();
const grants = await this.accountPluginRepo.findBy({ account });
const platforms = await this.pluginRepo.manager.query(
@@ -273,7 +283,8 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms(
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
pluginId = (pluginId || '').trim();
if (!pluginId) throw new ApiError(400, 'plugin_id 不能为空');
const pl = await this.pluginRepo.findOneBy({ id: pluginId });
@@ -305,7 +316,8 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms(
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
const pluginId = String(b?.plugin_id || '').trim();
const items: any[] = Array.isArray(b?.items) ? b.items : [];
if (!pluginId) throw new ApiError(400, 'plugin_id 不能为空');
@@ -349,7 +361,8 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const login = await this.centerAuthService.requirePerms(
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
const pluginId = String(b?.plugin_id || '').trim();
const accounts: string[] = Array.isArray(b?.accounts) ? b.accounts.map((a: any) => String(a || '').trim()).filter(Boolean) : [];
if (!pluginId) throw new ApiError(400, 'plugin_id 不能为空');
@@ -370,7 +383,8 @@ export class AdminPluginController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
await this.centerAuthService.requirePerms(
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
const m = this.accountPluginRepo.manager;
const plugins: any[] = await m.query(`SELECT id, name, status, latest_version FROM plugins ORDER BY id`);
const accounts: any[] = await m.query(
@@ -18,8 +18,8 @@ import { BaseSysDepartmentEntity } from '../../../base/entity/sys/department';
/**
* 系统管理(37du 控制台侧自建 RBAC 管理)。
*
* 身份体系:控制台登录 = accounts + HMAC 管理员票据(requireAdmin),与 cool-admin 的
* base_sys_user + JWT 不同体系,故由本层统一出口管理 cool-admin 的 RBAC 表(base_sys_*)。
* 身份体系:控制台登录 = base_sys_user + HMAC 管理员票据,接口按角色 perms 拦截。
* 本层统一出口管理 cool-admin 的 RBAC 表(base_sys_*)。
* 写操作全部委托 base 原生 service(md5 密码 / passwordV 失效旧 token / 授权缓存刷新
* 与原生登录链路完全一致),并对内置超管(admin 用户 / admin 角色)加保护。
*
@@ -68,8 +68,8 @@ export class AdminSysController extends BaseController {
@InjectEntityModel(BaseSysDepartmentEntity)
baseSysDeptRepo: Repository<BaseSysDepartmentEntity>;
private async admin(xAdminToken: string, xApiToken: string): Promise<string> {
return this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
private async admin(perms: string | string[], xAdminToken: string, xApiToken: string): Promise<string> {
return this.centerAuthService.requirePerms(perms, xAdminToken, xApiToken);
}
/**
@@ -99,7 +99,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
await this.admin('center:sys:user', xAdminToken, xApiToken);
const rows: any[] = await this.baseSysUserRepo.manager.query(
`SELECT a.id, a.username, a.name, a.nickName, a.departmentId, b.name AS departmentName,
a.status, a.createTime
@@ -128,7 +128,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
await this.admin('center:sys:role', xAdminToken, xApiToken);
const rows: any[] = await this.baseSysUserRepo.manager.query(
`SELECT id, name, label, remark, relevance FROM base_sys_role ORDER BY id`
);
@@ -143,9 +143,9 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
await this.admin(['center:sys:menu', 'center:sys:role'], xAdminToken, xApiToken);
const rows: any[] = await this.baseSysUserRepo.manager.query(
`SELECT id, parentId, name, router, perms, icon, type, orderNum FROM base_sys_menu ORDER BY orderNum, id`
`SELECT id, parentId, name, router, perms, icon, type, orderNum, viewPath, keepAlive, isShow FROM base_sys_menu ORDER BY orderNum, id`
);
return { items: buildTree(rows) };
}
@@ -156,7 +156,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
await this.admin(['center:sys:dept', 'center:sys:user', 'center:sys:role'], xAdminToken, xApiToken);
const rows: any[] = await this.baseSysUserRepo.manager.query(
`SELECT id, parentId, name, orderNum, createTime FROM base_sys_department ORDER BY orderNum, id`
);
@@ -172,7 +172,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
await this.admin('center:sys:user', xAdminToken, xApiToken);
if (!id) throw err(400, 'id 不能为空');
this.prepareDelegation();
return this.baseSysUserService.info(id);
@@ -185,7 +185,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:user', xAdminToken, xApiToken);
const username = String(b?.username || '').trim();
if (!username) throw err(400, 'username 不能为空');
if (!b?.password) throw err(400, 'password 不能为空');
@@ -209,7 +209,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:user', xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysUserRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '用户不存在');
@@ -231,7 +231,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:user', xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysUserRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '用户不存在');
@@ -255,7 +255,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
await this.admin('center:sys:role', xAdminToken, xApiToken);
if (!id) throw err(400, 'id 不能为空');
this.prepareDelegation();
return this.baseSysRoleService.info(id);
@@ -268,7 +268,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:role', xAdminToken, xApiToken);
const name = String(b?.name || '').trim();
if (!name) throw err(400, 'name 不能为空');
if (String(b?.label || '').trim().toLowerCase() === 'admin') throw err(400, 'label admin 为内置超管标识,不可使用');
@@ -301,7 +301,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:role', xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysRoleRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '角色不存在');
@@ -344,7 +344,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:role', xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysRoleRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '角色不存在');
@@ -370,7 +370,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:menu', xAdminToken, xApiToken);
const name = String(b?.name || '').trim();
if (!name) throw err(400, 'name 不能为空');
const type = Number(b?.type ?? 0);
@@ -389,6 +389,11 @@ export class AdminSysController extends BaseController {
icon: String(b?.icon || '').trim(),
type,
orderNum: Number(b?.orderNum || 0) || 0,
viewPath: String(b?.viewPath || '').trim(),
keepAlive: b?.keepAlive === undefined ? true : !!b.keepAlive,
isShow: b?.isShow === undefined ? true : !!b.isShow,
createTime: new Date(),
updateTime: new Date(),
} as any);
const id = Number((res as any).identifiers?.[0]?.id || 0);
await this.audit(login, 'sys-menu-add', name, { id });
@@ -402,7 +407,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:menu', xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysMenuRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '菜单不存在');
@@ -424,7 +429,11 @@ export class AdminSysController extends BaseController {
patch.type = type;
}
if (b?.orderNum !== undefined) patch.orderNum = Number(b.orderNum) || 0;
if (b?.viewPath !== undefined) patch.viewPath = String(b.viewPath).trim();
if (b?.keepAlive !== undefined) patch.keepAlive = !!b.keepAlive;
if (b?.isShow !== undefined) patch.isShow = !!b.isShow;
if (Object.keys(patch).length) {
patch.updateTime = new Date();
await this.baseSysMenuRepo.update({ id: Number(b.id) }, patch);
}
await this.audit(login, 'sys-menu-edit', row.name, { id: Number(b.id) });
@@ -438,7 +447,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:menu', xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const id = Number(b.id);
const row = await this.baseSysMenuRepo.findOneBy({ id });
@@ -460,7 +469,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:dept', xAdminToken, xApiToken);
const name = String(b?.name || '').trim();
if (!name) throw err(400, 'name 不能为空');
if (b?.parentId) {
@@ -484,7 +493,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:dept', xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysDeptRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '部门不存在');
@@ -511,7 +520,7 @@ export class AdminSysController extends BaseController {
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const login = await this.admin('center:sys:dept', xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const id = Number(b.id);
const row = await this.baseSysDeptRepo.findOneBy({ id });
@@ -0,0 +1,84 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Headers, Inject, Post, Provide, Query } from '@midwayjs/core';
import { CenterAuthService, ApiError } from '../../service/auth';
import { CenterLogService } from '../../service/logstore';
import { SHELL_LOG_CHUNK_MAX } from '../../comm/conf';
/**
* 客户端日志回传(对齐旧 FastAPI apis/plugins.py /api/runtime/logs、/api/runtime/shell-log):
* - 运行日志:每次运行结束整次回传,按 run_id 幂等 upsert(离线补报安全)
* - 壳日志:shell.log 增量字节(O_APPEND 追加落盘 logs/shell/<device_id>.log;reset=1 先截断)
*/
@Provide()
@CoolController('/api')
export class ApiLogController extends BaseController {
@Inject()
ctx: any;
@Inject()
centerAuthService: CenterAuthService;
@Inject()
centerLogService: CenterLogService;
/** POST /api/runtime/logs */
@Post('/runtime/logs')
async runtimeLogs(@Body() b: any, @Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
if (!b?.run_id) throw new ApiError(400, 'run_id 不能为空');
await this.centerLogService.storeRunLog(b);
return { ok: true, run_id: b.run_id };
}
/** POST /api/runtime/shell-log — 原始字节体增量回传 */
@Post('/runtime/shell-log')
async shellLog(
@Query('device_id') deviceId: string = '',
@Query('account') account: string = '',
@Query('hostname') hostname: string = '',
@Query('client_version') clientVersion: string = '',
@Query('reset') reset: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
deviceId = (deviceId || '').trim();
if (!deviceId) throw new ApiError(400, 'device_id 不能为空');
const buf = await this.readRawBody();
if (buf.length > SHELL_LOG_CHUNK_MAX) {
throw new ApiError(413, `单次回传超过大小上限(${Math.floor(SHELL_LOG_CHUNK_MAX / 1024 / 1024)}MB)`);
}
try {
const result = await this.centerLogService.appendShellLog(
deviceId, buf,
{ account: account || '', hostname: hostname || '', clientVersion: clientVersion || '' },
reset === '1' || reset === 'true'
);
return { ok: true, device_id: result.device_id, size_bytes: result.size_bytes };
} catch (e) {
if (e instanceof Error) throw new ApiError(400, e.message);
throw e;
}
}
/** 读取原始请求体(无 Content-Type 或 octet-stream 的字节流;koa-bodyparser 不会消费未匹配类型的流) */
private async readRawBody(): Promise<Buffer> {
const parsed: any = (this.ctx.request as any).body;
if (Buffer.isBuffer(parsed)) return parsed;
const req = this.ctx.req;
// 流已被中间件消费完:回退空(异常路径,不挂起)
if (req.readableEnded || req.complete) return Buffer.alloc(0);
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let settled = false;
const done = (err?: Error) => {
if (settled) return;
settled = true;
if (err) reject(err);
else resolve(Buffer.concat(chunks));
};
req.on('data', (c: Buffer) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
req.on('end', () => done());
req.on('error', done);
});
}
}
@@ -53,13 +53,23 @@ export class ApiPluginsController extends BaseController {
const rows = await this.accountPluginRepo
.createQueryBuilder('ap')
.innerJoin(PluginEntity, 'p', 'p.id = ap.pluginId')
.select(['p.id AS id', 'p.name AS name', 'p.latestVersion AS version'])
.select([
'p.id AS id',
'p.name AS name',
'p.latestVersion AS version',
'p.category AS category',
])
.where('ap.account = :account', { account: acct })
.orderBy('p.id', 'ASC')
.getRawMany();
return {
account: acct,
plugins: rows.map(r => ({ id: r.id, name: r.name, version: r.version })),
plugins: rows.map(r => ({
id: r.id,
name: r.name,
version: r.version,
category: r.category || '',
})),
};
}