build(desktop): 升级 electron-shell 版本至 1.6.3 并调整插件执行超时配置

- 插件执行超时默认延长至 6 小时,支持插件单独配置超时时间
- 新增插件根目录迁移逻辑,解决旧版权限问题
- 新增多个服务端实体、DTO、配置模块等基础代码
- 新增插件 UI 模板及相关静态资源
This commit is contained in:
2026-10-15 11:38:45 +08:00
parent 872d3dc5c8
commit f0a94bf523
717 changed files with 88647 additions and 17543 deletions
@@ -0,0 +1,58 @@
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';
import { loadEnvFile } from './env';
// 进程启动即加载本模块 .env(server/.env,不覆盖已有环境变量)
loadEnvFile();
/**
* 中心机业务配置(与旧 FastAPI controlplane/config.py 对齐)
* - CENTER_DATA_DIR 可经环境变量指向现网真实目录(packages/shell/avatars 与旧后端共用)
*/
export const CENTER_DATA_DIR =
process.env.CENTER_DATA_DIR || path.join(os.homedir(), '.cool-admin', '37du-center');
export const PKG_DIR = path.join(CENTER_DATA_DIR, 'packages');
export const SHELL_DIR = path.join(CENTER_DATA_DIR, 'shell');
export const AVATAR_DIR = path.join(CENTER_DATA_DIR, 'avatars');
/** 离线授权票据有效期(天):执行机最多离线该天数 */
export const LICENSE_TTL_DAYS = 7;
/**
* 钉钉扫码自动建号的初始密码(对齐 config._dingtalk_default_password):
* 优先 DINGTALK_DEFAULT_PASSWORD 环境变量;未配置时首次生成随机密码并持久化到
* CENTER_DATA_DIR/.dingtalk_default_pwd(重启复用,保证未改密用户拿到的初始密码稳定)。
*/
export function dingtalkDefaultPassword(): string {
const env = (process.env.DINGTALK_DEFAULT_PASSWORD || '').trim();
if (env) return env;
const f = path.join(CENTER_DATA_DIR, '.dingtalk_default_pwd');
try {
if (fs.existsSync(f)) {
const saved = fs.readFileSync(f, 'utf8').trim();
if (saved) return saved;
}
} catch (e) {
/* fallthrough */
}
const pwd = require('crypto').randomBytes(9).toString('base64url'); // 约 12 位,无易混淆字符
try {
fs.mkdirSync(CENTER_DATA_DIR, { recursive: true });
fs.writeFileSync(f, pwd, 'utf8');
} catch (e) {
/* 持久化失败不阻断 */
}
return pwd;
}
/** 内网文件服务器离线监控参数(对齐 config.py:超时 180s / 扫描间隔 30s) */
export const FILESERVER_HEARTBEAT_TIMEOUT = Number(process.env.FILESERVER_HEARTBEAT_TIMEOUT || 180) || 180;
export const FILESERVER_MONITOR_INTERVAL = Number(process.env.FILESERVER_MONITOR_INTERVAL || 30) || 30;
/** 格式化时间 'YYYY-MM-DD HH:mm:ss'(对齐 Python strftime("%Y-%m-%d %H:%M:%S")) */
export function fmtNow(d: Date = new Date()): string {
const p = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
@@ -0,0 +1,40 @@
import * as fs from 'fs';
import * as path from 'path';
/**
* 轻量 .env 加载器(对齐老 controlplane/.env 语义,不引入 dotenv 依赖):
* - 只读取本模块目录(server/)下的 .env,禁止读取/改写其它模块的 .env;
* - 已存在的进程环境变量优先(不覆盖),便于部署平台直接注入;
* - 支持 KEY=VALUE、#注释、单双引号包裹、行内注释(带空格的 #)。
*/
export function loadEnvFile(filePath?: string): void {
const f = filePath || path.join(process.cwd(), '.env');
let text = '';
try {
text = fs.readFileSync(f, 'utf8');
} catch (e) {
return; // 无 .env 静默跳过
}
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const eq = line.indexOf('=');
if (eq <= 0) continue;
const key = line.slice(0, eq).trim();
let value = line.slice(eq + 1).trim();
// 行内注释:仅当值未加引号时截断 " #"
const quoted =
(value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
(value.startsWith("'") && value.endsWith("'") && value.length >= 2);
if (!quoted) {
const hash = value.indexOf(' #');
if (hash >= 0) value = value.slice(0, hash).trim();
} else {
value = value.slice(1, -1);
}
if (!key) continue;
if (process.env[key] === undefined || process.env[key] === '') {
process.env[key] = value;
}
}
}
@@ -0,0 +1,10 @@
/**
* 统一分页边界(对齐 core/paging.py page_bounds 的换算;返回 [limit, offset])。
* 注意:调用方均按 `LIMIT ? OFFSET ?` / `slice(offset, offset + limit)` 消费,
* 因此首元素必须是每页条数(limit),次元素是起始偏移(offset)。
*/
export function pageBounds(page: number, pageSize: number): [number, number] {
const p = Math.max(1, Math.floor(page || 1));
const s = Math.max(1, Math.min(1000, Math.floor(pageSize || 20)));
return [s, (p - 1) * s];
}
@@ -0,0 +1,20 @@
import { ModuleConfig } from '@cool-midway/core';
import { ApiErrorMiddleware } from './middleware/api-error';
/**
* 37du 中心机业务模块配置
*/
export default () => {
return {
// 模块名称
name: '中心机业务',
// 模块描述
description: '插件管理、账号、授权、上报、审计、下载票据等业务(映射现网 37du 库)',
// 中间件,只对本模块有效
middlewares: [],
// 全局有效中间件:契约错误渲染(/api/* 输出 {detail})
globalMiddlewares: [ApiErrorMiddleware],
// 模块加载顺序
order: 0,
} as ModuleConfig;
};
@@ -0,0 +1,253 @@
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 { AccountEntity } from '../../entity/account';
import { PluginEntity, AccountPluginEntity, AccountPlatformEntity } from '../../entity/plugin';
import { CenterAuthService, ApiError } from '../../service/auth';
import { hashPassword } from '../../service/crypto';
import { pageBounds } from '../../comm/util';
/**
* 账号管理与授权(对齐旧 FastAPI apis/admin.py 账号 CRUD + 授权接口)
* 鉴权:requireAdmin(管理员票据;X-Admin-Token 或 X-API-Token 体系保持)
*/
@Provide()
@CoolController('/api/admin')
export class AdminAccountController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
@InjectEntityModel(PluginEntity)
pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(AccountPluginEntity)
accountPluginRepo: Repository<AccountPluginEntity>;
@InjectEntityModel(AccountPlatformEntity)
accountPlatformRepo: Repository<AccountPlatformEntity>;
/** GET /api/admin/accounts — 账号列表(分页 + 搜索 q) */
@Get('/accounts')
async accounts(
@Query('page') page: number = 1,
@Query('page_size') pageSize: number = 20,
@Query('q') q: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
if ((q || '').trim()) {
cond.push('(account LIKE ? OR nickname LIKE ? OR dept LIKE ?)');
args.push(`%${q.trim()}%`, `%${q.trim()}%`, `%${q.trim()}%`);
}
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
const m = this.accountRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM accounts${where}`, args))[0];
const rows: any[] = await m.query(
`SELECT id, account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd,
avatar, status, created_at
FROM accounts${where} ORDER BY id LIMIT ? OFFSET ?`,
[...args, limit, offset]
);
const items = [];
for (const r of rows) {
const grants: any[] = await m.query(
'SELECT plugin_id, can_download, can_run FROM account_plugins WHERE account = ?', [r.account]);
const platforms: any[] = await m.query(
'SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id', [r.account]);
items.push({
id: r.id,
account: r.account,
is_admin: !!Number(r.is_admin),
dept: r.dept || '',
nickname: r.nickname || '',
dingtalk_uid: r.dingtalk_uid || '',
must_change_pwd: !!Number(r.must_change_pwd),
avatar: r.avatar || '',
status: Number(r.status),
created_at: fmtStr(r.created_at),
plugins: grants.map((g: any) => g.plugin_id),
grants: grants.map((g: any) => ({ plugin_id: g.plugin_id, can_download: !!Number(g.can_download), can_run: !!Number(g.can_run) })),
platforms: platforms.map((p: any) => p.platform_id),
});
}
return { items, total: Number(total.c || 0) };
}
/** POST /api/admin/account — 新建账号 */
@Post('/account')
async accountCreate(
@Body() a: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(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 位');
const exists = await this.accountRepo.findOneBy({ account });
if (exists) throw new ApiError(400, `账号 ${account} 已存在`);
const { hash, salt } = hashPassword(a.password);
await this.accountRepo.insert({
account,
passwordHash: hash,
salt,
isAdmin: Number(!!a.is_admin),
dept: (a?.dept || '').trim(),
nickname: (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 };
}
/** POST /api/admin/account/update */
@Post('/account/update')
async accountUpdate(
@Body() a: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const account = (a?.account || '').trim();
if (!account) throw new ApiError(400, 'account 必填');
const exists = await this.accountRepo.findOneBy({ account });
if (!exists) throw new ApiError(400, `账号 ${account} 不存在`);
const set: Record<string, any> = {};
if (a?.dept !== undefined && a?.dept !== null) set.dept = String(a.dept || '').trim();
if (a?.nickname !== undefined && a?.nickname !== null) set.nickname = String(a.nickname || '').trim();
if (a?.is_admin !== undefined && a?.is_admin !== null) {
if (a.is_admin) set.isAdmin = 1;
else await this.accountRepo.manager.query('UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?', [account, login]);
}
if (a?.status !== undefined && a?.status !== null) {
if (!a.status && account === login) throw new ApiError(400, '不能停用当前登录的账号');
set.status = Number(!!a.status);
}
if (Object.keys(set).length) {
await this.accountRepo.update({ account }, set);
}
if (a?.status !== undefined && a?.status !== null && !a.status) {
await this.centerAuthService.revokeAccountTokens(account);
}
await this.centerAuthService.audit(login, 'account-update', account,
`dept=${a?.dept !== undefined}, nickname=${a?.nickname !== undefined}, is_admin=${a?.is_admin !== undefined}, status=${a?.status !== undefined}`);
return { ok: true, account };
}
/** POST /api/admin/account/reset_pwd */
@Post('/account/reset_pwd')
async accountResetPwd(
@Body() r: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(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 位');
const exists = await this.accountRepo.findOneBy({ account });
if (!exists) throw new ApiError(400, `账号 ${account} 不存在`);
const { hash, salt } = hashPassword(r.new_password);
await this.accountRepo.manager.query(
'UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 1 WHERE account = ?',
[hash, salt, account]
);
await this.centerAuthService.audit(login, 'account-reset-pwd', account);
return { ok: true, account };
}
/** POST /api/admin/account/delete */
@Post('/account/delete')
async accountDelete(
@Body() d: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const account = (d?.account || '').trim();
if (!account) throw new ApiError(400, 'account 必填');
if (account === login) throw new ApiError(400, '不能删除当前登录的账号');
const exists = await this.accountRepo.findOneBy({ account });
if (!exists) throw new ApiError(400, `账号 ${account} 不存在`);
await this.accountRepo.manager.query('DELETE FROM accounts WHERE account = ?', [account]);
await this.centerAuthService.revokeAccountTokens(account);
await this.centerAuthService.audit(login, 'account-delete', account);
return { ok: true, account };
}
/** POST /api/admin/account_plugins — 授权/撤销插件 */
@Post('/account_plugins')
async grant(
@Body() g: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const account = (g?.account || '').trim();
const pluginId = (g?.plugin_id || '').trim();
if (!account || !pluginId) throw new ApiError(400, 'account 与 plugin_id 不能为空');
if (g.granted) {
const acc = await this.accountRepo.findOneBy({ account });
if (!acc) throw new ApiError(400, `账号 ${account} 不存在,请先建号`);
const pl = await this.pluginRepo.findOneBy({ id: pluginId });
if (!pl) throw new ApiError(400, `插件 ${pluginId} 不存在,请先上传发布`);
await this.accountPluginRepo.manager.query(
`INSERT INTO account_plugins(account, plugin_id, can_download, can_run) VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE can_download = VALUES(can_download), can_run = VALUES(can_run)`,
[account, pluginId, Number(!!g.can_download), Number(!!g.can_run)]
);
} else {
await this.accountPluginRepo.manager.query(
'DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?', [account, pluginId]
);
}
await this.centerAuthService.audit(login, g.granted ? 'grant' : 'revoke-grant', pluginId,
`account=${account},can_download=${!!g.can_download},can_run=${!!g.can_run}`);
return { ok: true, account, plugin_id: pluginId, granted: !!g.granted };
}
/** POST /api/admin/account_platforms — 授权/撤销平台 */
@Post('/account_platforms')
async platformGrant(
@Body() g: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const account = (g?.account || '').trim();
const platformId = (g?.platform_id || '').trim();
if (!account || !platformId) throw new ApiError(400, 'account 与 platform_id 不能为空');
if (g.granted) {
const acc = await this.accountRepo.findOneBy({ account });
if (!acc) throw new ApiError(400, `账号 ${account} 不存在,请先建号`);
await this.accountPlatformRepo.manager.query(
'INSERT IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)', [account, platformId]
);
} else {
await this.accountPlatformRepo.manager.query(
'DELETE FROM account_platforms WHERE account = ? AND platform_id = ?', [account, platformId]
);
}
await this.centerAuthService.audit(login, g.granted ? 'grant-platform' : 'revoke-platform', platformId, account);
return { ok: true, account, platform_id: platformId, granted: !!g.granted };
}
}
function fmt(d: Date | null): string {
if (!d) return '';
const p = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
function fmtStr(d: any): string {
if (!d) return '';
if (d instanceof Date) return fmt(d);
return String(d).replace('T', ' ').slice(0, 19);
}
@@ -0,0 +1,137 @@
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 { AccountEntity } from '../../entity/account';
import { CenterAuthService, ApiError } from '../../service/auth';
import { hashPassword, verifyPassword, signAdminToken } from '../../service/crypto';
/**
* 管理面登录/身份(对齐旧 FastAPI apis/auth.py + 壳子 server.js 代理)
* - POST /api/admin/auth:账号密码登录(公开入口)→ 签发 X-Admin-Token + 云令牌
* - GET /api/admin/me:当前账号信息
* - POST /api/admin/password:自助改密(旧密码校验)
* - POST /api/admin/logout:退出(壳子代理调用,简单返回 ok)
* - GET /api/admin/platforms:可授权平台列表(管理员)
*/
const CONTROLPLANE_PLATFORMS = [
{ id: 'hr', label: 'HR 系统' },
{ id: 'oa', label: 'OA 系统' },
];
@Provide()
@CoolController('/api/admin')
export class AdminAuthController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
/** POST /api/admin/auth — 统一账户登录 */
@Post('/auth')
async auth(
@Body() a: any,
@Headers('X-API-Token') xApiToken: string = ''
) {
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)) {
await this.centerAuthService.authFail(account);
throw new ApiError(401, '账号或密码错误');
}
if (!Number(row.status)) throw new ApiError(403, '账号已停用,请联系管理员');
await this.centerAuthService.authReset(account);
const nickname = row.nickname || '';
return {
ok: true,
account,
is_admin: !!Number(row.isAdmin),
dept: row.dept || '',
nickname,
avatar: row.avatar || '',
must_change_pwd: !!Number(row.mustChangePwd),
token: signAdminToken(account),
cloud_token: await this.centerAuthService.issueCloudToken(account, nickname),
};
}
/** GET /api/admin/me */
@Get('/me')
async me(
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
let account = '';
try {
account = await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
account = '';
}
// 无效身份 → 401(触发前端自动登出回登录页,避免 200-空被误判为已登录)
if (!account) throw new ApiError(401, '登录态无效或已过期,请重新登录');
const row = await this.accountRepo.findOneBy({ account });
if (!row || !Number(row.status)) throw new ApiError(401, '登录态无效或已过期,请重新登录');
return {
account,
is_admin: !!Number(row.isAdmin),
dept: row.dept || '',
nickname: row.nickname || '',
avatar: row.avatar || '',
must_change_pwd: !!Number(row.mustChangePwd),
};
}
/** POST /api/admin/password — 自助改密 */
@Post('/password')
async password(
@Body() p: any,
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
let login = '';
try {
login = await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
if (!(p?.account || '').trim() || !p?.new_password) {
throw new ApiError(400, 'account 与新密码不能为空');
}
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 });
if (!row) throw new ApiError(401, '账号不存在');
if (!row.salt || !verifyPassword(p.old_password || '', row.salt, row.passwordHash)) {
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]
);
return { ok: true, account: login };
}
/** POST /api/admin/logout */
@Post('/logout')
async logout() {
return { ok: true };
}
/** GET /api/admin/platforms — 可授权平台列表 */
@Get('/platforms')
async platforms(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
return { platforms: CONTROLPLANE_PLATFORMS };
}
}
@@ -0,0 +1,132 @@
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';
/**
* 控制台业务菜单(RBAC 驱动)。
* - GET /api/admin/me/menus:返回当前操作者的业务菜单树 + 权限标识集合。
* 管理员(is_admin=1)返回全量;非管理员按 cool-admin 角色权限过滤(预留,2F 用户体系落地后生效)。
* - 前端据此驱动动态路由与按钮权限("菜单要权限"落点)。
*/
interface MenuNode {
path: string;
name: string;
component: string;
meta: {
title: string;
icon: string;
perms: string[];
roles?: string[];
};
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'] },
},
{
path: '/system', name: 'System', component: '/system/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'] } },
],
},
];
/** 全部权限标识集合(供按钮级 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>;
/** GET /api/admin/me/menus */
@Get('/me/menus')
async meMenus(
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
let account = '';
try {
account = await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
account = '';
}
// 无效身份 → 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 };
}
}
@@ -0,0 +1,547 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Del, File, Get, Headers, Inject, Param, Post, Provide, Put, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import {
PluginEntity, PluginVersionEntity, AccountPluginEntity,
} from '../../entity/plugin';
import { AccountEntity } from '../../entity/account';
import { AuditLogEntity, RuntimeReportEntity, DeviceEntity, NotificationEntity } from '../../entity/runtime';
import { FileSourceEntity, FileserverStatusEntity } from '../../entity/resource';
import { ClientCredEntity } from '../../entity/account';
import { CenterAuthService, ApiError } from '../../service/auth';
import { rsaEncrypt } from '../../service/crypto';
import { PKG_DIR, SHELL_DIR, AVATAR_DIR } from '../../comm/conf';
import { pageBounds } 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._-]+$/;
const AVATAR_EXT = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
const NOTIF_LEVELS = new Set(['info', 'warning', 'important']);
const NOTIF_TARGETS = new Set(['all', 'account']);
/**
* 管理面运维/看板/文件源/凭证/通知(对齐旧 FastAPI apis/admin.py + file_sources.py + config_push.py 管理侧)
*/
@Provide()
@CoolController('/api/admin')
export class AdminOpsController extends BaseController {
@Inject()
ctx: any;
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(PluginEntity) pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(PluginVersionEntity) pluginVersionRepo: Repository<PluginVersionEntity>;
@InjectEntityModel(AccountPluginEntity) accountPluginRepo: Repository<AccountPluginEntity>;
@InjectEntityModel(AccountEntity) accountRepo: Repository<AccountEntity>;
@InjectEntityModel(AuditLogEntity) auditRepo: Repository<AuditLogEntity>;
@InjectEntityModel(RuntimeReportEntity) runtimeRepo: Repository<RuntimeReportEntity>;
@InjectEntityModel(DeviceEntity) deviceRepo: Repository<DeviceEntity>;
@InjectEntityModel(NotificationEntity) notificationRepo: Repository<NotificationEntity>;
@InjectEntityModel(FileSourceEntity) fileSourceRepo: Repository<FileSourceEntity>;
@InjectEntityModel(FileserverStatusEntity) fileserverRepo: Repository<FileserverStatusEntity>;
@InjectEntityModel(ClientCredEntity) clientCredRepo: Repository<ClientCredEntity>;
/** GET /api/admin/overview */
@Get('/overview')
async overview(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const plugins = await this.pluginRepo.find();
const accounts = await this.accountRepo.find();
const admins = (await this.accountRepo
.createQueryBuilder('a').select('a.account').where('a.isAdmin = 1').orderBy('a.account', 'ASC').getRawMany())
.map((r: any) => r.account);
const pluginOut = [];
for (const p of plugins) {
let m: any = {};
try { m = p.manifest ? JSON.parse(p.manifest) : {}; } catch (e) { /* ignore */ }
const versions = await this.pluginVersionRepo.findBy({ pluginId: p.id });
pluginOut.push({
id: p.id, name: p.name, description: p.description || '', category: p.category || '',
icon: p.icon || '', status: p.status, latest_version: p.latestVersion,
force_min_version: p.forceMinVersion, force_deadline: p.forceDeadline,
manifest: m, capabilities: m.capabilities || [], permissions: m.permissions || {},
field_count: Object.keys((m.fields || {}).properties || {}).length,
versions: versions.map(v => ({ version: v.version, filename: v.filename, sha256: v.sha256, uploaded_at: fmt(v.uploadedAt) })),
});
}
const accountOut = accounts.map(a => ({
id: a.id, account: a.account, is_admin: !!Number(a.isAdmin), dept: a.dept || '',
nickname: a.nickname || '', avatar: a.avatar || '', status: Number(a.status), created_at: fmt(a.createdAt),
}));
return { plugins: pluginOut, accounts: accountOut, admins };
}
/** GET /api/admin/stats — 数据看板 */
@Get('/stats')
async stats(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const m = this.runtimeRepo.manager;
const users: any = (await m.query(
`SELECT (SELECT COUNT(*) FROM accounts) AS total,
(SELECT COUNT(*) FROM accounts WHERE is_admin = 1) AS admins,
(SELECT COUNT(DISTINCT account) FROM account_plugins) AS authorized`))[0];
const plugins: any = (await m.query(
`SELECT (SELECT COUNT(*) FROM plugins) AS total,
(SELECT COUNT(*) FROM plugins WHERE status='published') AS published,
(SELECT COUNT(*) FROM plugins WHERE status='disabled') AS disabled,
(SELECT COUNT(*) FROM plugins WHERE status='revoked') AS revoked`))[0];
const runs: any = (await m.query(
`SELECT (SELECT COUNT(*) FROM runtime_reports WHERE status='start') AS started,
(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('done','success')) AS success,
(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('error','failed')) AS failed,
(SELECT COALESCE(SUM(duration_sec),0) FROM runtime_reports) AS duration_sec,
(SELECT COUNT(DISTINCT account) FROM runtime_reports WHERE account <> '') AS active_users,
(SELECT COUNT(DISTINCT plugin_id) FROM runtime_reports WHERE plugin_id <> '') AS active_plugins`))[0];
const trendRows: any[] = await m.query(
`SELECT LEFT(at,10) AS day,
SUM(CASE WHEN status='start' THEN 1 ELSE 0 END) AS runs,
SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success,
SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed
FROM runtime_reports WHERE at >= CURDATE() - INTERVAL 13 DAY GROUP BY day ORDER BY day`);
const trendMap: Record<string, any> = {};
for (const r of trendRows) trendMap[r.day] = r;
const trend = [];
const d = new Date();
for (let i = 13; i >= 0; i--) {
const day = new Date(d.getTime() - i * 86400000);
const key = `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`;
const r = trendMap[key];
trend.push({ day: key.slice(5), runs: Number(r?.runs || 0), success: Number(r?.success || 0), failed: Number(r?.failed || 0) });
}
const topPlugins: any[] = await m.query(
`SELECT plugin_id AS pluginId, COUNT(*) AS runs,
SUM(CASE WHEN status='start' THEN 1 ELSE 0 END) AS triggered,
SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success,
SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed,
COALESCE(SUM(duration_sec),0) AS durationSec
FROM runtime_reports GROUP BY plugin_id ORDER BY triggered DESC LIMIT 8`);
const pnames: Record<string, string> = {};
for (const p of await this.pluginRepo.find()) pnames[p.id] = p.name;
const topUsers: any[] = await m.query(
`SELECT account, COUNT(*) AS runs FROM runtime_reports
WHERE status='start' AND account <> '' GROUP BY account ORDER BY runs DESC LIMIT 8`);
const nick: Record<string, string> = {};
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
return {
users: { total: Number(users.total || 0), admins: Number(users.admins || 0), authorized: Number(users.authorized || 0) },
plugins: { total: Number(plugins.total || 0), published: Number(plugins.published || 0), disabled: Number(plugins.disabled || 0), revoked: Number(plugins.revoked || 0) },
runs: { total: Number(runs.started || 0), success: Number(runs.success || 0), failed: Number(runs.failed || 0), durationSec: Number(runs.duration_sec || 0), activeUsers: Number(runs.active_users || 0), activePlugins: Number(runs.active_plugins || 0) },
trend,
topPlugins: topPlugins.map((tp: any) => ({ ...tp, name: pnames[tp.pluginId] || tp.pluginId, runs: Number(tp.triggered || 0) })),
topUsers: topUsers.map((tu: any) => ({ account: tu.account, runs: Number(tu.runs || 0), nickname: nick[tu.account] || '' })),
today: d.toISOString().slice(0, 10),
};
}
/** GET /api/admin/audit */
@Get('/audit')
async audit(
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
@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);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
if ((action || '').trim()) { cond.push('action = ?'); args.push(action.trim()); }
if ((q || '').trim()) { cond.push('(account LIKE ? OR target LIKE ? OR detail LIKE ?)'); args.push(`%${q.trim()}%`, `%${q.trim()}%`, `%${q.trim()}%`); }
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
const m = this.auditRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM audit_logs${where}`, args))[0];
const today: any = (await m.query(`SELECT COUNT(*) AS c FROM audit_logs WHERE at >= CURDATE()`))[0];
const rows: any[] = await m.query(
`SELECT id, account, action, target, detail, at FROM audit_logs${where} ORDER BY id DESC LIMIT ? OFFSET ?`,
[...args, limit, offset]);
const nick: Record<string, string> = {};
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
return {
items: rows.map((r: any) => ({ ...r, nickname: nick[r.account] || '', at: fmtStr(r.at) })),
total: Number(total.c || 0), today: Number(today.c || 0),
};
}
/** GET /api/admin/reports */
@Get('/reports')
async reports(
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
@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);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
if ((status || '').trim()) {
const vals = status.split(',').map((s: string) => s.trim()).filter(Boolean);
if (vals.length === 1) { cond.push('status = ?'); args.push(vals[0]); }
else if (vals.length > 1) { cond.push(`status IN (${vals.map(() => '?').join(',')})`); args.push(...vals); }
}
if ((q || '').trim()) {
cond.push('(account LIKE ? OR device_id LIKE ? OR plugin_id LIKE ? OR msg LIKE ?)');
args.push(`%${q.trim()}%`, `%${q.trim()}%`, `%${q.trim()}%`, `%${q.trim()}%`);
}
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
const m = this.runtimeRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM runtime_reports${where}`, args))[0];
const today: any = (await m.query('SELECT COUNT(*) AS c FROM runtime_reports WHERE at >= CURDATE()'))[0];
const failed: any = (await m.query(`SELECT COUNT(*) AS c FROM runtime_reports WHERE status IN ('error','failed')`))[0];
const rows: any[] = await m.query(
`SELECT id, account, device_id AS deviceId, plugin_id AS pluginId, version, status, msg,
duration_sec AS durationSec, at
FROM runtime_reports${where} ORDER BY id DESC LIMIT ? OFFSET ?`, [...args, limit, offset]);
const nick: Record<string, string> = {};
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
return {
items: rows.map((r: any) => ({ ...r, nickname: nick[r.account] || '', at: fmtStr(r.at) })),
total: Number(total.c || 0), today: Number(today.c || 0), failed: Number(failed.c || 0),
};
}
/** GET /api/admin/devices */
@Get('/devices')
async devices(
@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);
const [limit, offset] = pageBounds(page, pageSize);
const m = this.deviceRepo.manager;
const total: any = (await m.query('SELECT COUNT(*) AS c FROM devices'))[0];
const rows: any[] = await m.query(
`SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, chrome_ok,
last_seen, status, created_at, updated_at
FROM devices ORDER BY last_seen DESC LIMIT ? OFFSET ?`, [limit, offset]);
return { items: rows.map((r: any) => ({ ...r, last_seen: fmtStr(r.last_seen), created_at: fmtStr(r.created_at), updated_at: fmtStr(r.updated_at) })), total: Number(total.c || 0) };
}
/** GET /api/admin/devices/summary */
@Get('/devices/summary')
async devicesSummary(
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const m = this.deviceRepo.manager;
const total: any = (await m.query('SELECT COUNT(*) AS c FROM devices'))[0];
const byAccount: any[] = await m.query(
'SELECT account, COUNT(*) AS device_count, MAX(last_seen) AS last_seen FROM devices GROUP BY account ORDER BY account');
const nick: Record<string, [string, string]> = {};
for (const a of await this.accountRepo.find()) nick[a.account] = [a.nickname || '', a.dept || ''];
return {
total: Number(total.c || 0),
by_version: [],
by_account: byAccount.map((r: any) => ({ ...r, nickname: nick[r.account]?.[0] || '', dept: nick[r.account]?.[1] || '' })),
};
}
/** POST /api/admin/shell-release — 发布壳子新版 */
@Post('/shell-release')
async shellRelease(
@File() file: any,
@Query('version') version: string = '',
@Query('notes') notes: string = '',
@Query('sha256') sha256: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(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);
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`;
fs.mkdirSync(SHELL_DIR, { recursive: true });
fs.writeFileSync(path.join(SHELL_DIR, filename), content);
const sha = sha256 || crypto.createHash('sha256').update(content).digest('hex');
fs.writeFileSync(path.join(SHELL_DIR, 'version.json'), JSON.stringify({
version, filename, sha256: sha, notes: notes || '',
}, null, 2), 'utf8');
await this.centerAuthService.audit(login, 'shell-release', filename);
return { ok: true, version, filename, sha256: sha };
}
/** file-sources 管理端 CRUD */
@Get('/file-sources')
async fileSourcesList(
@Query('category') category: string = '', @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);
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();
const [limit, offset] = pageBounds(page, pageSize);
const sliced = rows.sort((a, b) => (versionKey(b.version) - versionKey(a.version)) || (b.id - a.id)).slice(offset, offset + limit);
return {
category: category || '',
items: sliced.map(r => ({ id: r.id, category: r.category, version: r.version, filename: r.filename, url: r.url, sha256: r.sha256, notes: r.notes, enabled: !!Number(r.enabled), updated_at: fmt(r.updatedAt) })),
total: rows.length,
};
}
@Post('/file-sources')
async fileSourcesUpsert(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const category = (b?.category || '').trim();
const version = (b?.version || '').trim();
const url = (b?.url || '').trim();
if (!category) throw new ApiError(400, 'category 不能为空');
if (!url) throw new ApiError(400, 'url 不能为空');
const m = this.fileSourceRepo.manager;
const row: any = (await m.query('SELECT id FROM file_sources WHERE category = ? AND version = ?', [category, version]))[0];
let fid: number;
if (row) {
await m.query('UPDATE file_sources SET filename=?, url=?, sha256=?, notes=?, enabled=?, updated_at=NOW() WHERE id=?',
[(b?.filename || '').trim(), url, (b?.sha256 || '').trim(), (b?.notes || '').trim(), Number(!!b?.enabled), row.id]);
fid = row.id;
} else {
const r: any = await m.query('INSERT INTO file_sources(category, version, filename, url, sha256, notes, enabled, updated_at) VALUES (?,?,?,?,?,?,?,NOW())',
[category, version, (b?.filename || '').trim(), url, (b?.sha256 || '').trim(), (b?.notes || '').trim(), Number(!!b?.enabled)]);
fid = r.insertId;
}
await this.centerAuthService.audit(login, 'file-source-upsert', `${category}@${version}`, url);
return { ok: true, id: fid, category, version };
}
@Put('/file-sources/:fid')
async fileSourcesPatch(
@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 id = Number(fid || 0);
if (b?.enabled === undefined && b?.enabled === null && b?.notes === undefined) {
throw new ApiError(400, '无更新字段');
}
const m = this.fileSourceRepo.manager;
if (b?.enabled !== undefined && b?.enabled !== null) {
await m.query('UPDATE file_sources SET enabled = ?, updated_at = NOW() WHERE id = ?', [Number(!!b.enabled), id]);
}
if (b?.notes !== undefined && b?.notes !== null) {
await m.query('UPDATE file_sources SET notes = ?, updated_at = NOW() WHERE id = ?', [String(b.notes).trim(), id]);
}
const chk: any = (await m.query('SELECT id FROM file_sources WHERE id = ?', [id]))[0];
if (!chk) throw new ApiError(404, '记录不存在');
await this.centerAuthService.audit(login, 'file-source-patch', String(id));
return { ok: true, id };
}
@Del('/file-sources/:fid')
async fileSourcesDelete(
@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 id = Number(fid || 0);
const m = this.fileSourceRepo.manager;
const r: any = await m.query('DELETE FROM file_sources WHERE id = ?', [id]);
if (!r.affectedRows) throw new ApiError(404, '记录不存在');
await this.centerAuthService.audit(login, 'file-source-delete', String(id));
return { ok: true, id };
}
/** creds 管理(manage 列表 / seed 明文源) */
@Get('/creds/manage')
async credsManage(
@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);
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];
const rows: any[] = await m.query(
'SELECT c.account, c.pubkey_pem, c.creds, c.updated_at, a.nickname FROM client_creds c LEFT JOIN accounts a ON a.account = c.account ORDER BY c.account LIMIT ? OFFSET ?',
[limit, offset]);
return {
items: rows.map((r: any) => {
let creds: any = {};
try { creds = JSON.parse(r.creds || '{}'); } catch (e) { /* ignore */ }
return { account: r.account, nickname: r.nickname || '', has_pubkey: !!r.pubkey_pem, creds, updated_at: fmtStr(r.updated_at) };
}),
total: Number(total.c || 0),
allowed_keys: ALLOWED_CREDS_KEYS,
};
}
@Post('/creds/seed')
async credsSeed(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const account = (b?.account || '').trim();
if (!account) throw new ApiError(400, 'account 不能为空');
const allowed: Record<string, string> = {};
for (const [k, v] of Object.entries(b?.values || {})) {
if (ALLOWED_CREDS_KEYS.includes(k)) allowed[k] = String(v);
}
const m = this.clientCredRepo.manager;
const row: any = (await m.query('SELECT pubkey_pem FROM client_creds WHERE account = ?', [account]))[0];
if (row) {
await m.query('UPDATE client_creds SET creds = ?, updated_at = NOW() WHERE account = ?', [JSON.stringify(allowed), account]);
} else {
await m.query('INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (?, ?, ?, NOW())',
[account, '', JSON.stringify(allowed)]);
}
await this.centerAuthService.audit(login, 'creds-seed', account, `keys=${Object.keys(allowed).sort()}`);
return { ok: true, account, seeded_keys: Object.keys(allowed).sort() };
}
/** 通知管理 CRUD */
@Get('/notifications')
async notifList(
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
@Query('q') q: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
if ((q || '').trim()) {
cond.push('(title LIKE ? OR content LIKE ? OR account LIKE ?)');
args.push(`%${q.trim()}%`, `%${q.trim()}%`, `%${q.trim()}%`);
}
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
const m = this.notificationRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM notifications${where}`, args))[0];
const rows: any[] = await m.query(
`SELECT id, title, content, level, target, account, created_at, expires_at, active
FROM notifications${where} ORDER BY id DESC LIMIT ? OFFSET ?`, [...args, limit, offset]);
return {
items: rows.map((r: any) => ({ id: r.id, title: r.title, content: r.content, level: r.level, target: r.target, account: r.account, created_at: fmtStr(r.created_at), expires_at: r.expires_at ? fmtStr(r.expires_at) : null, active: Number(r.active) })),
total: Number(total.c || 0),
};
}
@Post('/notifications')
async notifCreate(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(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');
if (!NOTIF_TARGETS.has(b?.target)) throw new ApiError(400, 'target 仅允许 all/account');
if (b?.target === 'account' && !(b?.account || '').trim()) throw new ApiError(400, 'target=account 时必须指定 account');
const r: any = await this.notificationRepo.manager.query(
'INSERT INTO notifications(title, content, level, target, account, expires_at) VALUES (?,?,?,?,?,?)',
[title, (b?.content || '').trim(), b?.level, b?.target, (b?.account || '').trim(), b?.expires_at ? String(b.expires_at).replace('T', ' ').slice(0, 19) : null]);
await this.centerAuthService.audit(login, 'notify-create', `通知 #${r.insertId} ${title} → ${b?.target}`);
return { ok: true, id: r.insertId, title, target: b?.target, pushed: 0 };
}
@Put('/notifications/:nid')
async notifToggle(
@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 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}`);
return { ok: true, id, active: active === 'true' };
}
@Del('/notifications/:nid')
async notifDelete(
@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 id = Number(nid || 0);
await this.notificationRepo.manager.query('DELETE FROM notifications WHERE id = ?', [id]);
await this.centerAuthService.audit(login, 'notify-delete', `通知 #${id}`);
return { ok: true, id };
}
/** GET /api/admin/fileserver/status */
@Get('/fileserver/status')
async fileserverStatus(
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const rows = await this.fileserverRepo.find({ order: { lastSeen: 'DESC' } as any });
return {
// 契约对齐旧 FastAPI:键名 fileservers;status/offline_notified 布尔;total_size 数值
fileservers: rows.map(r => ({
id: r.id, host: r.host, base_url: r.baseUrl, hostname: r.hostname, ip: r.ip,
port: r.port, file_count: r.fileCount, total_size: Number(r.totalSize),
version: r.version, uptime_sec: r.uptimeSec, last_seen: fmt(r.lastSeen),
status: !!Number(r.status), last_status_change: fmt(r.lastStatusChange),
offline_notified: !!Number(r.offlineNotified), created_at: fmt(r.createdAt),
})),
};
}
/** POST /api/admin/avatar — 上传头像 */
@Post('/avatar')
async avatarUpload(
@File() file: any,
@Query('account') account: string = '',
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
let login = '';
try {
login = await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
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);
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);
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} 不存在`);
fs.mkdirSync(AVATAR_DIR, { recursive: true });
const fname = `${account}${ext}`;
fs.writeFileSync(path.join(AVATAR_DIR, fname), content);
if (acc.avatar && acc.avatar !== fname) {
try { fs.unlinkSync(path.join(AVATAR_DIR, acc.avatar)); } catch (e) { /* ignore */ }
}
await this.accountRepo.update({ account }, { avatar: fname });
return { ok: true, account, avatar: fname };
}
}
function versionKey(v: string): number {
return Number(String(v || '').split('.').map(s => s.padStart(4, '0')).join('')) || 0;
}
function fmt(d: Date | null): string {
if (!d) return '';
const p = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
function fmtStr(d: any): string {
if (!d) return '';
if (d instanceof Date) return fmt(d);
return String(d).replace('T', ' ').slice(0, 19);
}
@@ -0,0 +1,277 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, File, Get, Headers, Inject, Post, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
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';
const SAFE_NAME_RE = /^[A-Za-z0-9._-]+$/;
/** 版本号数值键("1.10" > "1.9") */
function versionKey(v: string): number[] {
return String(v || '').split('.').map(s => parseInt(s, 10) || 0);
}
/**
* 插件管理(对齐旧 FastAPI apis/admin.py 插件部分)
* - GET /api/admin/plugins:插件列表(分页 + 搜索 + 版本历史 + 授权账号)
* - POST /api/admin/pkg:上传发布插件包(校验 zip + manifest + sha256 + 保留最近 3 版)
* - POST /api/admin/plugin/delete、/api/admin/plugin/patch
* - GET /api/admin/grant_data、/api/admin/account_grants
*/
@Provide()
@CoolController('/api/admin')
export class AdminPluginController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(PluginEntity)
pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(PluginVersionEntity)
pluginVersionRepo: Repository<PluginVersionEntity>;
@InjectEntityModel(AccountPluginEntity)
accountPluginRepo: Repository<AccountPluginEntity>;
/** GET /api/admin/plugins */
@Get('/plugins')
async plugins(
@Query('page') page: number = 1,
@Query('page_size') pageSize: number = 20,
@Query('q') q: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
if ((q || '').trim()) {
cond.push('(id LIKE ? OR name LIKE ?)');
args.push(`%${q.trim()}%`, `%${q.trim()}%`);
}
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
const m = this.pluginRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM plugins${where}`, args))[0];
const rows: any[] = await m.query(
`SELECT id, name, description, category, icon, status, latest_version,
force_min_version, force_deadline, manifest
FROM plugins${where} ORDER BY id LIMIT ? OFFSET ?`,
[...args, limit, offset]
);
const items = [];
for (const p of rows) {
let manifest: any = {};
try { manifest = p.manifest ? JSON.parse(p.manifest) : {}; } catch (e) { /* ignore */ }
const versions: any[] = await m.query(
'SELECT version, filename, sha256, uploaded_at FROM plugin_versions WHERE plugin_id = ? ORDER BY version', [p.id]);
const accounts: any[] = await m.query(
'SELECT ap.account, a.nickname FROM account_plugins ap LEFT JOIN accounts a ON a.account = ap.account WHERE ap.plugin_id = ? ORDER BY ap.account', [p.id]);
items.push({
id: p.id,
name: p.name,
description: p.description || '',
category: p.category || '',
icon: p.icon || '',
status: p.status,
latest_version: p.latest_version,
force_min_version: p.force_min_version,
force_deadline: p.force_deadline,
manifest,
capabilities: manifest.capabilities || [],
field_count: Object.keys((manifest.fields || {}).properties || {}).length,
versions: versions.map((v: any) => ({ version: v.version, filename: v.filename, sha256: v.sha256, uploaded_at: fmtStr(v.uploaded_at) })),
accounts: accounts.map((r: any) => ({ account: r.account, nickname: r.nickname || '' })),
});
}
return { items, total: Number(total.c || 0) };
}
/** POST /api/admin/pkg — 上传发布插件包 */
@Post('/pkg')
async pkg(
@File() file: any,
@Query('plugin_id') pluginId: string = '',
@Query('name') name: string = '',
@Query('version') version: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
pluginId = (pluginId || '').trim();
version = (version || '').trim();
name = (name || '').trim() || pluginId;
if (!pluginId || !version) throw new ApiError(400, 'plugin_id 与 version 不能为空');
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);
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 需一致)
let manifest: any = {};
try {
const zip = new AdmZip(content);
const entry = zip.getEntry('plugin.json');
if (entry) {
manifest = JSON.parse(entry.getData().toString('utf8').replace(/^\uFEFF/, ''));
const mid = String(manifest.id || '').trim();
if (mid && mid !== pluginId) {
throw new ApiError(400, `plugin.json 内 id「${mid}」与路径 plugin_id「${pluginId}」不一致`);
}
name = String(manifest.name || name).trim() || pluginId;
}
} catch (e: any) {
if (e instanceof ApiError) throw e;
throw new ApiError(400, `插件包校验失败: ${e.message || e}`);
}
const filename = `${pluginId}_v${version}.zip`;
const target = path.join(PKG_DIR, filename);
fs.mkdirSync(PKG_DIR, { recursive: true });
fs.writeFileSync(target, content);
const sha256 = crypto.createHash('sha256').update(content).digest('hex');
const manifestJson = JSON.stringify(manifest, null, 0) || '{}';
// 插件主记录 upsert
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]
);
await this.pluginVersionRepo.manager.query(
`INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256, size_bytes)
VALUES (?, ?, ?, NOW(), ?, ?)
ON DUPLICATE KEY UPDATE filename = VALUES(filename), uploaded_at = VALUES(uploaded_at), sha256 = VALUES(sha256)`,
[pluginId, version, filename, sha256, content.length]
);
// 更新 latest_version(若更高)
const cur = await this.pluginRepo.findOneBy({ id: pluginId });
if (cur && versionKey(cur.latestVersion) < versionKey(version)) {
await this.pluginRepo.update({ id: pluginId }, { latestVersion: version });
}
// 仅保留最近 3 个版本(DB + 磁盘)
const versions = await this.pluginVersionRepo
.createQueryBuilder('v')
.where('v.pluginId = :id', { id: pluginId })
.orderBy('v.id', 'DESC')
.getMany();
const stale = versions.slice(3);
for (const s of stale) {
await this.pluginVersionRepo.delete({ id: s.id });
try { fs.unlinkSync(path.join(PKG_DIR, s.filename)); } catch (e) { /* ignore */ }
}
await this.centerAuthService.audit(login, 'plugin-publish', pluginId, `version=${version}, filename=${filename}`);
return { ok: true, plugin_id: pluginId, version, filename };
}
/** POST /api/admin/plugin/delete */
@Post('/plugin/delete')
async pluginDelete(
@Body() d: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const pid = (d?.plugin_id || '').trim();
if (!pid) throw new ApiError(400, 'plugin_id 必填');
const pl = await this.pluginRepo.findOneBy({ id: pid });
if (!pl) throw new ApiError(400, `插件 ${pid} 不存在`);
const files = await this.pluginVersionRepo.findBy({ pluginId: pid });
await this.pluginVersionRepo.manager.query(
'DELETE FROM account_plugins WHERE plugin_id = ?', [pid]);
await this.pluginVersionRepo.manager.query(
'DELETE FROM plugin_versions WHERE plugin_id = ?', [pid]);
await this.pluginRepo.delete({ id: pid });
for (const f of files) {
try { fs.unlinkSync(path.join(PKG_DIR, f.filename)); } catch (e) { /* ignore */ }
}
await this.centerAuthService.audit(login, 'plugin-delete', pid, `files=${files.length}`);
return { ok: true, plugin_id: pid };
}
/** POST /api/admin/plugin/patch — 更新元信息/状态/强制更新 */
@Post('/plugin/patch')
async pluginPatch(
@Body() d: any,
@Query('plugin_id') pluginId: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(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?.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) {
set.force_min_version = String(d.force_min_version).trim();
set.force_deadline = String(d.force_deadline).trim();
} else if ((d?.force_min_version || d?.force_deadline) && !d?.clear_force) {
throw new ApiError(400, '强制更新需同时提供 force_min_version 与 force_deadline');
} else if (d?.clear_force) {
set.force_min_version = null;
set.force_deadline = null;
}
if (!Object.keys(set).length) return { ok: true };
const pl = await this.pluginRepo.findOneBy({ id: pid });
if (!pl) throw new ApiError(400, `插件 ${pid} 不存在`);
await this.pluginRepo.update({ id: pid }, set);
return { ok: true, plugin_id: pid };
}
/** GET /api/admin/grant_data */
@Get('/grant_data')
async grantData(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(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(
'SELECT account, nickname, dept, status FROM accounts WHERE status = 1 ORDER BY account');
return { plugins, accounts };
}
/** GET /api/admin/account_grants?account= */
@Get('/account_grants')
async accountGrants(
@Query('account') account: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
account = (account || '').trim();
const grants = await this.accountPluginRepo.findBy({ account });
const platforms = await this.pluginRepo.manager.query(
'SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id', [account]);
return {
plugins: grants.map(g => ({ plugin_id: g.pluginId, canRun: !!Number(g.canRun), canDownload: !!Number(g.canDownload) })),
platforms: platforms.map((r: any) => r.platform_id),
};
}
}
function fmt(d: Date | null): string {
if (!d) return '';
const p = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
function fmtStr(d: any): string {
if (!d) return '';
if (d instanceof Date) return fmt(d);
return String(d).replace('T', ' ').slice(0, 19);
}
@@ -0,0 +1,568 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Get, Headers, Inject, InjectClient, Post, Provide, Query } from '@midwayjs/core';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
import { CenterAuthService } from '../../service/auth';
import { BaseSysUserService } from '../../../base/service/sys/user';
import { BaseSysRoleService } from '../../../base/service/sys/role';
import { BaseSysPermsService } from '../../../base/service/sys/perms';
import { BaseSysUserEntity } from '../../../base/entity/sys/user';
import { BaseSysUserRoleEntity } from '../../../base/entity/sys/user_role';
import { BaseSysRoleEntity } from '../../../base/entity/sys/role';
import { BaseSysRoleMenuEntity } from '../../../base/entity/sys/role_menu';
import { BaseSysRoleDepartmentEntity } from '../../../base/entity/sys/role_department';
import { BaseSysMenuEntity } from '../../../base/entity/sys/menu';
import { BaseSysDepartmentEntity } from '../../../base/entity/sys/department';
/**
* 系统管理(37du 控制台侧自建 RBAC 管理)。
*
* 身份体系:控制台登录 = accounts + HMAC 管理员票据(requireAdmin),与 cool-admin 的
* base_sys_user + JWT 不同体系,故由本层统一出口管理 cool-admin 的 RBAC 表(base_sys_*)。
* 写操作全部委托 base 原生 service(md5 密码 / passwordV 失效旧 token / 授权缓存刷新
* 与原生登录链路完全一致),并对内置超管(admin 用户 / admin 角色)加保护。
*
* 只读:GET /api/admin/sys/{users,roles,menus,departments}
* 用户:POST /api/admin/sys/user/{add,edit,del} + GET /user/info
* 角色:POST /api/admin/sys/role/{add,edit,del} + GET /role/info(含 menuIdList/departmentIdList)
* 菜单:POST /api/admin/sys/menu/{add,edit,del}
* 部门:POST /api/admin/sys/dept/{add,edit,del}
*/
@Provide()
@CoolController('/api/admin/sys')
export class AdminSysController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@Inject()
baseSysUserService: BaseSysUserService;
@Inject()
baseSysRoleService: BaseSysRoleService;
@Inject()
baseSysPermsService: BaseSysPermsService;
@InjectClient(CachingFactory, 'default')
midwayCache: MidwayCache;
@InjectEntityModel(BaseSysUserEntity)
baseSysUserRepo: Repository<BaseSysUserEntity>;
@InjectEntityModel(BaseSysUserRoleEntity)
baseSysUserRoleRepo: Repository<BaseSysUserRoleEntity>;
@InjectEntityModel(BaseSysRoleEntity)
baseSysRoleRepo: Repository<BaseSysRoleEntity>;
@InjectEntityModel(BaseSysRoleMenuEntity)
baseSysRoleMenuRepo: Repository<BaseSysRoleMenuEntity>;
@InjectEntityModel(BaseSysRoleDepartmentEntity)
baseSysRoleDeptRepo: Repository<BaseSysRoleDepartmentEntity>;
@InjectEntityModel(BaseSysMenuEntity)
baseSysMenuRepo: Repository<BaseSysMenuEntity>;
@InjectEntityModel(BaseSysDepartmentEntity)
baseSysDeptRepo: Repository<BaseSysDepartmentEntity>;
private async admin(xAdminToken: string, xApiToken: string): Promise<string> {
return this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
}
/**
* cool BaseService 的实体由原生 CRUD 控制器经 setEntity(repo) 注入;
* 本控制器直接委托 base service,需先注入对应 Repository(否则报"未设置操作实体")。
*/
private prepareDelegation(): void {
this.baseSysUserService.setEntity(this.baseSysUserRepo);
this.baseSysRoleService.setEntity(this.baseSysRoleRepo);
}
private async audit(account: string, action: string, target: string, detail: any) {
let json = '';
try {
json = detail === undefined ? '' : JSON.stringify(detail);
} catch (e) {
json = '';
}
await this.centerAuthService.audit(account, action, target, json);
}
// ==================== 只读列表 ====================
/** GET /api/admin/sys/users — 控制台用户(含部门名/角色,不含密码) */
@Get('/users')
async users(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(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
FROM base_sys_user a LEFT JOIN base_sys_department b ON a.departmentId = b.id
ORDER BY a.id`
);
const userRoles: any[] = await this.baseSysUserRepo.manager.query(
`SELECT a.userId, a.roleId, r.name AS roleName FROM base_sys_user_role a
LEFT JOIN base_sys_role r ON r.id = a.roleId`
);
const items = rows.map(r => {
const roles = userRoles.filter(u => Number(u.userId) === Number(r.id));
return {
...r,
roleIds: roles.map(u => Number(u.roleId)),
roleName: roles.map(u => u.roleName || '').filter(Boolean).join(','),
usernameProtected: r.username === 'admin',
};
});
return { items };
}
/** GET /api/admin/sys/roles — 角色 */
@Get('/roles')
async roles(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
const rows: any[] = await this.baseSysUserRepo.manager.query(
`SELECT id, name, label, remark, relevance FROM base_sys_role ORDER BY id`
);
return {
items: rows.map(r => ({ ...r, relevance: !!Number(r.relevance), protected: Number(r.id) === 1 })),
};
}
/** GET /api/admin/sys/menus — 菜单(树) */
@Get('/menus')
async menus(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(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`
);
return { items: buildTree(rows) };
}
/** GET /api/admin/sys/departments — 部门(树) */
@Get('/departments')
async departments(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
const rows: any[] = await this.baseSysUserRepo.manager.query(
`SELECT id, parentId, name, orderNum, createTime FROM base_sys_department ORDER BY orderNum, id`
);
return { items: buildTree(rows) };
}
// ==================== 用户管理 ====================
/** GET /api/admin/sys/user/info?id= — 用户详情(含 roleIdList,不含密码) */
@Get('/user/info')
async userInfo(
@Query('id') id: number,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
if (!id) throw err(400, 'id 不能为空');
this.prepareDelegation();
return this.baseSysUserService.info(id);
}
/** POST /api/admin/sys/user/add — 新增用户(md5 密码 + 角色分配 + 缓存刷新) */
@Post('/user/add')
async userAdd(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const username = String(b?.username || '').trim();
if (!username) throw err(400, 'username 不能为空');
if (!b?.password) throw err(400, 'password 不能为空');
if (String(b.username).toLowerCase() === 'admin') throw err(400, '不能创建内置用户名 admin');
this.prepareDelegation();
const param = {
...b,
username,
roleIdList: Array.isArray(b?.roleIdList) ? b.roleIdList.map(Number) : [],
};
const raw = await this.baseSysUserService.add(param as any);
const id = Number((raw as any)?.id ?? raw ?? 0);
await this.audit(login, 'sys-user-add', username, { id });
return { ok: true, id };
}
/** POST /api/admin/sys/user/edit — 编辑用户(改密自动 passwordV+1 使旧 token 失效;不支持改 username) */
@Post('/user/edit')
async userEdit(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysUserRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '用户不存在');
if (row.username === 'admin') throw err(403, '内置管理员不允许编辑');
this.prepareDelegation();
const param: any = { ...b, id: Number(b.id) };
delete param.username; // 用户名不可改
if (Array.isArray(b?.roleIdList)) param.roleIdList = b.roleIdList.map(Number);
else delete param.roleIdList;
await this.baseSysUserService.update(param);
await this.audit(login, 'sys-user-edit', row.username, { id: param.id });
return { ok: true };
}
/** POST /api/admin/sys/user/del — 删除用户(内置 admin 保护) */
@Post('/user/del')
async userDel(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysUserRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '用户不存在');
if (row.username === 'admin' || Number(b.id) === 1) throw err(403, '内置管理员不允许删除');
await this.baseSysUserRoleRepo.delete({ userId: Number(b.id) });
await this.baseSysUserRepo.delete({ id: Number(b.id) });
await this.midwayCache.del(`admin:token:${b.id}`);
await this.midwayCache.del(`admin:perms:${b.id}`);
await this.midwayCache.del(`admin:department:${b.id}`);
await this.midwayCache.del(`admin:passwordVersion:${b.id}`);
await this.audit(login, 'sys-user-del', row.username, { id: Number(b.id) });
return { ok: true };
}
// ==================== 角色管理 ====================
/** GET /api/admin/sys/role/info?id= — 角色详情(含 menuIdList/departmentIdList) */
@Get('/role/info')
async roleInfo(
@Query('id') id: number,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
if (!id) throw err(400, 'id 不能为空');
this.prepareDelegation();
return this.baseSysRoleService.info(id);
}
/** POST /api/admin/sys/role/add — 新增角色(可带 menuIdList/departmentIdList,原生链路刷新授权) */
@Post('/role/add')
async roleAdd(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(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 为内置超管标识,不可使用');
this.prepareDelegation();
const menuIdList = Array.isArray(b?.menuIdList) ? b.menuIdList.map(Number) : [];
const departmentIdList = Array.isArray(b?.departmentIdList) ? b.departmentIdList.map(Number) : [];
const res = await this.baseSysRoleRepo.insert({
userId: String(b?.userId ?? 0),
name,
label: String(b?.label || '').trim(),
remark: String(b?.remark || ''),
// base_sys_role.userId 为非空"创建者ID"列(原生流程由 JWT 上下文注入);
// 控制台身份是 accounts 体系,无法映射 base_sys_user 时记 0(控制台创建)
relevance: !!b?.relevance,
// JSON 冗余列与关系表同源写入(原生 info/授权读取走关系表)
menuIdList,
departmentIdList,
} as any);
const id = Number((res as any).identifiers?.[0]?.id || 0);
// 显式 await 授权关系写入(不依赖原生 modifyAfter 的 fire-and-forget,避免竞态/重复行)
await this.baseSysRoleService.updatePerms(id, menuIdList, departmentIdList);
await this.audit(login, 'sys-role-add', name, { id });
return { ok: true, id };
}
/** POST /api/admin/sys/role/edit — 编辑角色(含授权,自动刷新相关用户权限缓存) */
@Post('/role/edit')
async roleEdit(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysRoleRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '角色不存在');
if (Number(b.id) === 1 || row.label === 'admin') throw err(403, '内置超管角色不允许编辑');
if (b?.label && String(b.label).trim().toLowerCase() === 'admin') throw err(400, 'label admin 为内置超管标识,不可使用');
const patch: any = {};
if (b?.name !== undefined) patch.name = String(b.name).trim();
if (b?.label !== undefined) patch.label = String(b.label).trim();
if (b?.remark !== undefined) patch.remark = String(b.remark);
if (b?.relevance !== undefined) patch.relevance = !!b.relevance;
let menuIdList: number[] | null = null;
let departmentIdList: number[] | null = null;
if (Array.isArray(b?.menuIdList)) {
menuIdList = b.menuIdList.map(Number);
patch.menuIdList = menuIdList;
}
if (Array.isArray(b?.departmentIdList)) {
departmentIdList = b.departmentIdList.map(Number);
patch.departmentIdList = departmentIdList;
}
if (Object.keys(patch).length) {
await this.baseSysRoleRepo.update({ id: Number(b.id) }, patch);
}
// 授权关系显式一次写入(不依赖原生 modifyAfter 的 fire-and-forget,避免竞态/重复行)
if (menuIdList !== null || departmentIdList !== null) {
await this.baseSysRoleService.updatePerms(
Number(b.id),
menuIdList ?? [],
departmentIdList ?? []
);
}
await this.audit(login, 'sys-role-edit', row.name, { id: Number(b.id) });
return { ok: true };
}
/** POST /api/admin/sys/role/del — 删除角色(内置超管保护,级联清理授权关系) */
@Post('/role/del')
async roleDel(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysRoleRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '角色不存在');
if (Number(b.id) === 1 || row.label === 'admin') throw err(403, '内置超管角色不允许删除');
const userRoles = await this.baseSysUserRoleRepo.findBy({ roleId: Number(b.id) });
await this.baseSysUserRoleRepo.delete({ roleId: Number(b.id) });
await this.baseSysRoleMenuRepo.delete({ roleId: Number(b.id) });
await this.baseSysRoleDeptRepo.delete({ roleId: Number(b.id) });
await this.baseSysRoleRepo.delete({ id: Number(b.id) });
for (const ur of userRoles) {
await this.baseSysPermsService.refreshPerms(ur.userId);
}
await this.audit(login, 'sys-role-del', row.name, { id: Number(b.id) });
return { ok: true };
}
// ==================== 菜单管理 ====================
/** POST /api/admin/sys/menu/add — 新增菜单(type: 0目录 1菜单 2按钮) */
@Post('/menu/add')
async menuAdd(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const name = String(b?.name || '').trim();
if (!name) throw err(400, 'name 不能为空');
const type = Number(b?.type ?? 0);
if (![0, 1, 2].includes(type)) throw err(400, 'type 仅允许 0/1/2');
if (type !== 2 && !String(b?.router || '').trim()) throw err(400, '该类型必须填写路由地址');
if (b?.parentId) {
const parent = await this.baseSysMenuRepo.findOneBy({ id: Number(b.parentId) });
if (!parent) throw err(404, '上级菜单不存在');
if (Number(parent.type) === 2) throw err(400, '按钮下不能再挂子级');
}
const res = await this.baseSysMenuRepo.insert({
parentId: b?.parentId ? Number(b.parentId) : null,
name,
router: String(b?.router || '').trim(),
perms: String(b?.perms || '').trim(),
icon: String(b?.icon || '').trim(),
type,
orderNum: Number(b?.orderNum || 0) || 0,
} as any);
const id = Number((res as any).identifiers?.[0]?.id || 0);
await this.audit(login, 'sys-menu-add', name, { id });
return { ok: true, id };
}
/** POST /api/admin/sys/menu/edit — 编辑菜单 */
@Post('/menu/edit')
async menuEdit(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysMenuRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '菜单不存在');
if (Number(b.id) === Number(b?.parentId)) throw err(400, '上级菜单不能是自己');
if (b?.parentId) {
// 防环:parentId 不能落在本菜单子树内
const all = await this.baseSysMenuRepo.find();
if (isDescendant(all, Number(b.id), Number(b.parentId))) throw err(400, '上级菜单不能是自己的子级');
}
const patch: any = {};
if (b?.parentId !== undefined) patch.parentId = b.parentId ? Number(b.parentId) : null;
if (b?.name !== undefined) patch.name = String(b.name).trim();
if (b?.router !== undefined) patch.router = String(b.router).trim();
if (b?.perms !== undefined) patch.perms = String(b.perms).trim();
if (b?.icon !== undefined) patch.icon = String(b.icon).trim();
if (b?.type !== undefined) {
const type = Number(b.type);
if (![0, 1, 2].includes(type)) throw err(400, 'type 仅允许 0/1/2');
patch.type = type;
}
if (b?.orderNum !== undefined) patch.orderNum = Number(b.orderNum) || 0;
if (Object.keys(patch).length) {
await this.baseSysMenuRepo.update({ id: Number(b.id) }, patch);
}
await this.audit(login, 'sys-menu-edit', row.name, { id: Number(b.id) });
return { ok: true };
}
/** POST /api/admin/sys/menu/del — 删除菜单(有子级时拒绝;级联清理角色授权) */
@Post('/menu/del')
async menuDel(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const id = Number(b.id);
const row = await this.baseSysMenuRepo.findOneBy({ id });
if (!row) throw err(404, '菜单不存在');
const children = await this.baseSysMenuRepo.count({ where: { parentId: id } as any });
if (children > 0) throw err(400, '存在子级菜单,请先删除子级');
await this.baseSysRoleMenuRepo.delete({ menuId: id });
await this.baseSysMenuRepo.delete({ id });
await this.audit(login, 'sys-menu-del', row.name, { id });
return { ok: true };
}
// ==================== 部门管理 ====================
/** POST /api/admin/sys/dept/add — 新增部门 */
@Post('/dept/add')
async deptAdd(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const name = String(b?.name || '').trim();
if (!name) throw err(400, 'name 不能为空');
if (b?.parentId) {
const parent = await this.baseSysDeptRepo.findOneBy({ id: Number(b.parentId) });
if (!parent) throw err(404, '上级部门不存在');
}
const res = await this.baseSysDeptRepo.insert({
parentId: b?.parentId ? Number(b.parentId) : null,
name,
orderNum: Number(b?.orderNum || 0) || 0,
} as any);
const id = Number((res as any).identifiers?.[0]?.id || 0);
await this.audit(login, 'sys-dept-add', name, { id });
return { ok: true, id };
}
/** POST /api/admin/sys/dept/edit — 编辑部门 */
@Post('/dept/edit')
async deptEdit(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysDeptRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '部门不存在');
if (Number(b.id) === Number(b?.parentId)) throw err(400, '上级部门不能是自己');
if (b?.parentId) {
const all = await this.baseSysDeptRepo.find();
if (isDescendant(all, Number(b.id), Number(b.parentId))) throw err(400, '上级部门不能是自己的子级');
}
const patch: any = {};
if (b?.parentId !== undefined) patch.parentId = b.parentId ? Number(b.parentId) : null;
if (b?.name !== undefined) patch.name = String(b.name).trim();
if (b?.orderNum !== undefined) patch.orderNum = Number(b.orderNum) || 0;
if (Object.keys(patch).length) {
await this.baseSysDeptRepo.update({ id: Number(b.id) }, patch);
}
await this.audit(login, 'sys-dept-edit', row.name, { id: Number(b.id) });
return { ok: true };
}
/** POST /api/admin/sys/dept/del — 删除部门(有子级或在用用户时拒绝) */
@Post('/dept/del')
async deptDel(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const id = Number(b.id);
const row = await this.baseSysDeptRepo.findOneBy({ id });
if (!row) throw err(404, '部门不存在');
const children = await this.baseSysDeptRepo.count({ where: { parentId: id } as any });
if (children > 0) throw err(400, '存在子部门,请先删除子部门');
const userCount = await this.baseSysUserRepo.count({ where: { departmentId: id } as any });
if (userCount > 0) throw err(400, `该部门仍有 ${userCount} 个用户,请先转移用户`);
await this.baseSysRoleDeptRepo.delete({ departmentId: id });
await this.baseSysDeptRepo.delete({ id });
await this.audit(login, 'sys-dept-del', row.name, { id });
return { ok: true };
}
}
/** 业务错误(ApiError 语义:携带 HTTP 状态码) */
function err(status: number, message: string): Error & { status: number } {
const e: any = new Error(message);
e.status = status;
return e;
}
/** 以 parentId 构建树(通用) */
function buildTree(rows: any[]): any[] {
const map = new Map<number, any>();
rows.forEach((r) => map.set(Number(r.id), { ...r, children: [] }));
const roots: any[] = [];
map.forEach((node) => {
const pid = node.parentId ? Number(node.parentId) : 0;
if (map.has(pid)) map.get(pid).children.push(node);
else roots.push(node);
});
return roots;
}
/** 判断 targetId 是否在 rootId 的子树内(防环) */
function isDescendant(all: any[], rootId: number, targetId: number): boolean {
const childrenMap = new Map<number, number[]>();
for (const r of all) {
const pid = r.parentId ? Number(r.parentId) : 0;
if (!childrenMap.has(pid)) childrenMap.set(pid, []);
childrenMap.get(pid)!.push(Number(r.id));
}
const queue = [...(childrenMap.get(rootId) || [])];
const seen = new Set<number>();
while (queue.length) {
const id = queue.shift()!;
if (id === targetId) return true;
if (seen.has(id)) continue;
seen.add(id);
queue.push(...(childrenMap.get(id) || []));
}
return false;
}
@@ -0,0 +1,100 @@
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 { ClientCredEntity } from '../../entity/account';
import { AccountEntity } from '../../entity/account';
import { CenterAuthService, ApiError } from '../../service/auth';
import { rsaEncrypt } from '../../service/crypto';
/**
* 执行机敏感凭证(对齐旧 FastAPI apis/config_push.py):
* - POST /api/admin/creds/register:登记/更新 RSA 公钥(管理员任意账号 / 云令牌本人)
* - GET /api/admin/creds:仅管理员可拉,服务端用账号公钥 OAEP 加密每个明文值下发
*/
@Provide()
@CoolController('/api/admin')
export class ApiCredsController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(ClientCredEntity)
clientCredRepo: Repository<ClientCredEntity>;
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
/** POST /api/admin/creds/register */
@Post('/creds/register')
async credsRegister(
@Body() b: any,
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
// 鉴权双轨:管理员可为任意账号登记;云令牌账号只能登记本人
let adminOk = false;
try {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
adminOk = true;
} catch (e) {
adminOk = false;
}
if (!adminOk) {
const self = await this.centerAuthService.cloudAccount(authorization);
if (!self || self !== (b?.account || '').trim()) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
}
const account = (b?.account || '').trim();
const pem = (b?.pubkey_pem || '').trim();
if (!account || !pem) throw new ApiError(400, 'account 与 pubkey_pem 不能为空');
const existing = await this.clientCredRepo.findOneBy({ account });
const creds = existing?.creds || '{}';
await this.clientCredRepo.manager.query(
`INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE pubkey_pem = VALUES(pubkey_pem), creds = VALUES(creds), updated_at = VALUES(updated_at)`,
[account, pem, creds]
);
return { ok: true, account };
}
/** GET /api/admin/creds — 下发敏感凭证(仅管理员) */
@Get('/creds')
async credsFetch(
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
let account = '';
try {
account = await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
account = '';
}
if (!account) throw new ApiError(401, '登录态无效或已过期,请重新登录');
const admin = await this.accountRepo
.createQueryBuilder('a')
.select('a.isAdmin', 'isAdmin')
.where('a.account = :account', { account })
.getRawOne();
if (!admin || !Number(admin.isAdmin)) throw new ApiError(403, '仅管理员可拉取敏感凭证');
const row = await this.clientCredRepo.findOneBy({ account });
if (!row || !row.pubkeyPem) return { account, creds: {} };
let encrypted: Record<string, string> = {};
try {
const source = JSON.parse(row.creds || '{}');
for (const [k, v] of Object.entries(source)) {
if (v !== null && v !== undefined) encrypted[k] = rsaEncrypt(row.pubkeyPem, String(v));
}
} catch (e: any) {
throw new ApiError(500, `凭证加密失败: ${e.message || e}`);
}
await this.clientCredRepo.manager.query(
'UPDATE client_creds SET updated_at = NOW() WHERE account = ?',
[account]
);
return { account, creds: encrypted };
}
}
@@ -0,0 +1,69 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Headers, Inject, Post, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { RuntimeReportEntity, DeviceEntity } from '../../entity/runtime';
import { CenterAuthService, ApiError } from '../../service/auth';
/**
* 运行上报 + 设备上报(对齐旧 FastAPI apis/plugins.py /api/runtime/report、/api/device/report)
* 注意:现网 devices 表无 client_version 列(以现网 schema 为准),上报仅 upsert 现有列
*/
@Provide()
@CoolController('/api')
export class ApiDeviceController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(RuntimeReportEntity)
runtimeRepo: Repository<RuntimeReportEntity>;
@InjectEntityModel(DeviceEntity)
deviceRepo: Repository<DeviceEntity>;
/** POST /api/runtime/report */
@Post('/runtime/report')
async runtimeReport(@Body() b: any, @Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
await this.runtimeRepo.insert({
account: b?.account || '',
deviceId: b?.device_id || '',
pluginId: b?.plugin_id || '',
version: b?.version || '',
status: b?.status || '',
msg: b?.msg || '',
durationSec: Number(b?.duration_sec || 0),
at: new Date(),
});
return { ok: true };
}
/** POST /api/device/report — 执行机心跳/环境上报(按 device_id 幂等 upsert) */
@Post('/device/report')
async deviceReport(@Body() b: any, @Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
const deviceId = (b?.device_id || '').trim();
if (!deviceId) throw new ApiError(400, 'device_id 不能为空');
await this.deviceRepo.manager.query(
`INSERT INTO devices(device_id, account, hostname, os, ip, chrome_installed, chrome_version, chrome_ok, last_seen, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)
ON DUPLICATE KEY UPDATE
account = VALUES(account), hostname = VALUES(hostname), os = VALUES(os),
ip = VALUES(ip), chrome_installed = VALUES(chrome_installed),
chrome_version = VALUES(chrome_version), chrome_ok = VALUES(chrome_ok),
last_seen = VALUES(last_seen), status = VALUES(status)`,
[
deviceId,
(b?.account || '').trim(),
(b?.hostname || '').trim(),
(b?.os || '').trim(),
(b?.ip || '').trim(),
Number(!!b?.chrome_installed),
(b?.chrome_version || '').trim(),
Number(!!b?.chrome_ok),
Number(!!b?.status),
]
);
return { ok: true, device_id: deviceId };
}
}
@@ -0,0 +1,95 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Inject, Post, 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 { hashPassword } from '../../service/crypto';
import { dingtalkUserinfo } from '../../service/dingtalk';
import { CenterNotifyService } from '../../service/notify';
import { dingtalkDefaultPassword } from '../../comm/conf';
// 壳子直连入口:错误渲染走 api-error 中间件({"detail"} 契约)
/**
* 员工端扫码登录 /auth/exchange(对齐旧 FastAPI apis/auth.py v3 最简方案,壳本机直连 code):
* 壳把浏览器带回的钉钉 code POST 到此,用 AppSecret 换身份 → 找建账号
* (不存在则自动建号:空壳+默认密码+强制改密,并推送钉钉通知)→ 签发云端会话 token
* (供壳调 /api/plugins 鉴权)。注意:路径不在 /api/ 下,属壳子直连的公开入口。
*/
@Provide()
@CoolController('/auth')
export class AuthExchangeController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@Inject()
centerNotifyService: CenterNotifyService;
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
/** POST /auth/exchange — 壳 → 云端:钉钉授权码换员工工号 + 云端会话 token(找建账号) */
@Post('/exchange')
async exchange(@Body() d: any) {
const code = String(d?.code || '').trim();
if (!code) throw new ApiError(400, '缺少 code');
const appKey = (process.env.DINGTALK_APP_KEY || '').trim();
const appSecret = (process.env.DINGTALK_APP_SECRET || '').trim();
if (!appKey || !appSecret) {
throw new ApiError(503, '未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)');
}
let info: { account: string; nickname: string; unionid: string };
try {
info = await dingtalkUserinfo(code);
} catch (e: any) {
// 已带状态码的(401/503)原样透出;网络类错误包装为 502
if (e?.status) throw new ApiError(e.status, e.message || '钉钉接口访问失败');
throw new ApiError(502, e?.message || '钉钉接口访问失败');
}
const account = (info.account || '').trim();
if (!account) throw new ApiError(401, '扫码未解析到有效账号,请重新扫码');
const nickname = (info.nickname || '').trim();
const unionid = (info.unionid || '').trim();
// 找建账号(与 /api/admin/dingtalk/auth 同语义):已存在则同步昵称;不存在则自动建号并通知
let created = false;
let mustChange = false;
let isAdmin = false;
const existing = await this.accountRepo.findOneBy({ account });
if (existing) {
if (!Number(existing.status)) throw new ApiError(403, '账号已停用,请联系管理员');
if (nickname && nickname !== (existing.nickname || '')) {
await this.accountRepo.update({ account }, { nickname });
}
mustChange = !!Number(existing.mustChangePwd);
isAdmin = !!Number(existing.isAdmin);
} else {
// 自动建号(空壳):初始密码取默认值,强制首次改密
const pwd = dingtalkDefaultPassword();
const { hash, salt } = hashPassword(pwd);
await this.accountRepo.insert({
account,
passwordHash: hash,
salt,
isAdmin: 0,
dept: '',
nickname,
dingtalkUid: unionid,
mustChangePwd: 1,
} as any);
created = true;
mustChange = true;
isAdmin = false;
this.centerNotifyService.notifyAccountCreated(account, nickname, pwd, unionid, '钉钉扫码');
}
const token = await this.centerAuthService.issueCloudToken(account, nickname);
return {
token,
account,
nickname,
exists: !created,
created,
must_change_pwd: mustChange,
is_admin: isAdmin,
};
}
}
@@ -0,0 +1,80 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Headers, Inject, Post, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { FileserverStatusEntity } from '../../entity/resource';
import { CenterAuthService, ApiError } from '../../service/auth';
import { fmtNow } from '../../comm/conf';
// 心跳 upsert 语义:恢复上线翻转 status=1 并清除 offline_notified(对齐 fileserver_status.py)
/**
* 内网文件服务器状态 API(对齐旧 FastAPI apis/fileserver_status.py):
* - POST /api/fileserver/heartbeat:文件服务器(8802)周期心跳上报,upsert 状态快照;
* 离线中收到心跳则恢复在线并清除告警标记(恢复时不再推送)。
* 心跳上报仅需 X-API-Token(底座凭证)。
*/
@Provide()
@CoolController('/api/fileserver')
export class ApiFileserverController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(FileserverStatusEntity)
fileserverRepo: Repository<FileserverStatusEntity>;
/** POST /api/fileserver/heartbeat — 接收文件服务器心跳 */
@Post('/heartbeat')
async heartbeat(
@Body() b: any,
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
const host = String(b?.host || '').trim();
if (!host) throw new ApiError(400, 'host 不能为空');
const now = new Date();
const nowStr = fmtNow(now);
const payload = {
baseUrl: String(b?.base_url || '').trim(),
hostname: String(b?.hostname || '').trim(),
ip: String(b?.ip || '').trim(),
port: Number(b?.port || 0) || 0,
fileCount: Number(b?.file_count || 0) || 0,
totalSize: Number(b?.total_size || 0) || 0,
version: String(b?.version || '').trim(),
uptimeSec: Number(b?.uptime_sec || 0) || 0,
};
const m = this.fileserverRepo.manager;
const row: any = (
await m.query('SELECT status, offline_notified FROM fileserver_status WHERE host = ?', [host])
)[0];
if (row) {
// 离线期间恢复上线:标记在线、清除离线告警标记(恢复时不再推送)
const wasOffline = !Number(row.status) || !!Number(row.offline_notified);
if (wasOffline) {
await m.query(
'UPDATE fileserver_status SET base_url=?, hostname=?, ip=?, port=?, file_count=?, ' +
'total_size=?, version=?, uptime_sec=?, last_seen=?, status=1, offline_notified=0, ' +
'last_status_change=? WHERE host=?',
[payload.baseUrl, payload.hostname, payload.ip, payload.port, payload.fileCount,
payload.totalSize, payload.version, payload.uptimeSec, nowStr, nowStr, host]
);
} else {
await m.query(
'UPDATE fileserver_status SET base_url=?, hostname=?, ip=?, port=?, file_count=?, ' +
'total_size=?, version=?, uptime_sec=?, last_seen=?, status=1, offline_notified=0 WHERE host=?',
[payload.baseUrl, payload.hostname, payload.ip, payload.port, payload.fileCount,
payload.totalSize, payload.version, payload.uptimeSec, nowStr, host]
);
}
} else {
await m.query(
'INSERT INTO fileserver_status(host, base_url, hostname, ip, port, file_count, ' +
'total_size, version, uptime_sec, last_seen, status, offline_notified, created_at, last_status_change) ' +
'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, ?, ?)',
[host, payload.baseUrl, payload.hostname, payload.ip, payload.port, payload.fileCount,
payload.totalSize, payload.version, payload.uptimeSec, nowStr, nowStr, nowStr]
);
}
return { ok: true, host, last_seen: nowStr };
}
}
@@ -0,0 +1,107 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Get, Headers, Inject, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { PluginEntity, AccountPluginEntity } from '../../entity/plugin';
import { CenterAuthService, ApiError } from '../../service/auth';
import { pubkeyPem, signBlob } from '../../service/crypto';
import { LICENSE_TTL_DAYS, fmtNow } from '../../comm/conf';
/**
* 客户端票据接口(对齐旧 FastAPI apis/plugins.py /api/me/*)
* - /api/me/pubkey:下发中心机公钥(Ed25519 PEM)
* - /api/me/license:签发离线授权票据(插件授权快照,Ed25519 签名)
* - /api/me/control-list:签发管控清单(revoked/disabled/forcedUpdates,Ed25519 签名)
*/
@Provide()
@CoolController('/api')
export class ApiMeController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(PluginEntity)
pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(AccountPluginEntity)
accountPluginRepo: Repository<AccountPluginEntity>;
private expiresAtEpoch(): number {
return Math.floor(Date.now() / 1000) + LICENSE_TTL_DAYS * 24 * 3600;
}
/** GET /api/me/pubkey */
@Get('/me/pubkey')
async pubkey() {
return { pub: pubkeyPem(), algo: 'ed25519' };
}
/** GET /api/me/license?account=&device= */
@Get('/me/license')
async license(
@Query('account') account: string = '',
@Query('device') device: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
if (!(account || '').trim()) throw new ApiError(400, 'account 不能为空');
if (await this.centerAuthService.accountDisabled(account.trim())) {
throw new ApiError(403, '账号已停用,无法获取授权');
}
const rows = await this.accountPluginRepo
.createQueryBuilder('g')
.innerJoin(PluginEntity, 'p', 'p.id = g.pluginId')
.select([
'g.pluginId AS pluginId',
'g.canDownload AS canDownload',
'g.canRun AS canRun',
'p.name AS name',
'p.status AS status',
'p.latestVersion AS latestVersion',
])
.where('g.account = :account', { account: account.trim() })
.getRawMany();
const plugins = rows.map(r => ({
pluginId: r.pluginId,
name: r.name,
canDownload: !!Number(r.canDownload),
canRun: !!Number(r.canRun),
status: r.status,
latestVersion: r.latestVersion,
}));
const issuedAt = fmtNow();
const expiresAt = this.expiresAtEpoch();
const blob = signBlob({
userId: account.trim(),
deviceId: device || '',
issuedAt,
expiresAt,
plugins,
});
return { ticket: blob, plugins, issuedAt, expiresAt };
}
/** GET /api/me/control-list */
@Get('/me/control-list')
async controlList(@Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
const revoked: string[] = [];
const disabled: string[] = [];
const forced: any[] = [];
const rows = await this.pluginRepo.find();
for (const r of rows) {
if (r.status === 'revoked') revoked.push(r.id);
else if (r.status === 'disabled') disabled.push(r.id);
if (r.forceMinVersion && r.forceDeadline) {
forced.push({ pluginId: r.id, minVersion: r.forceMinVersion, deadline: r.forceDeadline });
}
}
const payload = {
revokedPlugins: revoked,
disabledPlugins: disabled,
forcedUpdates: forced,
updatedAt: fmtNow(),
expiresAt: this.expiresAtEpoch(),
};
return { ticket: signBlob(payload), control: payload };
}
}
@@ -0,0 +1,231 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Get, Headers, Inject, Param, Post, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as fs from 'fs';
import * as path from 'path';
import { FileSourceEntity } from '../../entity/resource';
import { NotificationEntity } from '../../entity/runtime';
import { ScheduleBackupEntity } from '../../entity/resource';
import { CenterAuthService, ApiError } from '../../service/auth';
import { AVATAR_DIR } from '../../comm/conf';
/**
* 客户端杂项接口(对齐旧 FastAPI):
* - GET /api/file-sources/{category}:内网大文件源最新启用直链
* - GET /api/notifications:通知拉取(HTTP 兜底)
* - GET/POST /api/schedules/backup:壳子定时任务配置备份(自助,身份=账号)
* - GET /api/dingtalk/login-url:钉钉扫码授权 URL(执行机代理调用)
*/
@Provide()
@CoolController('/api')
export class ApiMiscController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@Inject()
ctx: any;
@InjectEntityModel(FileSourceEntity)
fileSourceRepo: Repository<FileSourceEntity>;
@InjectEntityModel(NotificationEntity)
notificationRepo: Repository<NotificationEntity>;
@InjectEntityModel(ScheduleBackupEntity)
scheduleBackupRepo: Repository<ScheduleBackupEntity>;
/** GET /api/file-sources/{category} — 客户端取某分类最新启用的一条 */
@Get('/file-sources/:category')
async fileSourceLatest(
@Param('category') category: string,
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
const rows = await this.fileSourceRepo
.createQueryBuilder('f')
.select(['f.id', 'f.category', 'f.version', 'f.filename', 'f.url', 'f.sha256', 'f.notes'])
.where('f.category = :c', { c: (category || '').trim() })
.andWhere('f.enabled = 1')
.getMany();
if (!rows.length) return { available: false, category: (category || '').trim() };
// 版本号按数值语义取最新("1.10" > "1.9")
const r = rows.reduce((a, b) => (versionKey(b.version) > versionKey(a.version) ? b : a));
return {
available: true,
category: r.category,
version: r.version,
filename: r.filename,
url: r.url,
sha256: r.sha256,
notes: r.notes || '',
};
}
/** GET /api/notifications — 客户端拉取通知(云令牌优先,兜底 account+X-API-Token) */
@Get('/notifications')
async notifications(
@Query('account') account: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('Authorization') authorization: string = ''
) {
let acct = await this.centerAuthService.cloudAccount(authorization);
if (!acct) {
this.centerAuthService.checkApiToken(xApiToken);
acct = (account || '').trim();
}
if (!acct) throw new ApiError(400, '缺少有效会话或 account');
const rows = await this.notificationRepo
.createQueryBuilder('n')
.select(['n.id', 'n.title', 'n.content', 'n.level', 'n.target', 'n.account', 'n.createdAt', 'n.expiresAt'])
.where('n.active = 1')
.andWhere('(n.target = :all OR (n.target = :acct AND n.account = :acct))', { all: 'all', acct })
.andWhere('(n.expiresAt IS NULL OR n.expiresAt > NOW())')
.orderBy('n.createdAt', 'DESC')
.limit(50)
.getMany();
return {
notifications: rows.map(r => ({
id: r.id,
title: r.title,
content: r.content,
level: r.level,
target: r.target,
account: r.account,
created_at: fmtDt(r.createdAt),
expires_at: r.expiresAt ? fmtDt(r.expiresAt) : null,
})),
};
}
/** POST /api/schedules/backup — 覆盖保存某账号定时任务配置 */
@Post('/schedules/backup')
async schedBackupSave(
@Body() b: any,
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
const account = await this.requireIdentity(authorization, xAdminToken, xApiToken, xAdminUser);
const payload = b?.data && typeof b.data === 'object' ? b.data : {};
if (!Array.isArray(payload.schedules)) throw new ApiError(400, 'data.schedules 必须为数组');
await this.scheduleBackupRepo.manager.query(
`INSERT INTO schedule_backups(account, data, updated_at) VALUES (?, ?, NOW())
ON DUPLICATE KEY UPDATE data = VALUES(data), updated_at = VALUES(updated_at)`,
[account, JSON.stringify(payload)]
);
return { ok: true, account };
}
/** GET /api/schedules/backup — 读取某账号定时任务备份 */
@Get('/schedules/backup')
async schedBackupLoad(
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
const account = await this.requireIdentity(authorization, xAdminToken, xApiToken, xAdminUser);
const row = await this.scheduleBackupRepo.findOneBy({ account });
if (!row) return { data: { schedules: [] } };
try {
const data = JSON.parse(row.data);
if (data && typeof data === 'object' && Array.isArray(data.schedules)) return { data };
} catch (e) {
/* fallthrough */
}
return { data: { schedules: [] } };
}
/** GET /api/avatar/{account} — 读取账号头像(前端 img 直接引用) */
@Get('/avatar/:account')
async avatar(@Param('account') account: string) {
const row: any = await this.fileSourceRepo.manager.query(
'SELECT avatar FROM accounts WHERE account = ?', [account]);
if (!row.length || !row[0].avatar) throw new ApiError(404, '未设置头像');
const f = path.join(AVATAR_DIR, row[0].avatar);
if (!fs.existsSync(f)) throw new ApiError(404, '头像文件缺失');
this.ctx.type = path.extname(f);
this.ctx.body = fs.createReadStream(f);
}
/** GET /api/dingtalk/login-url — 构造钉钉扫码授权 URL */
@Get('/dingtalk/login-url')
async dingtalkLoginUrl(
@Query('back') back: string,
@Query('state') state: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
const appKey = process.env.DINGTALK_APP_KEY || '';
const appSecret = process.env.DINGTALK_APP_SECRET || '';
if (!appKey || !appSecret) {
throw new ApiError(503, '控制面未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)');
}
if (!safeBackUrl(back)) throw new ApiError(400, '回跳地址非法(仅允许回环/内网/控制面域名)');
const qs = new URLSearchParams({
redirect_uri: back,
response_type: 'code',
client_id: appKey,
scope: 'openid',
prompt: 'consent',
state: state || back,
});
return { url: `https://login.dingtalk.com/oauth2/challenge.htm?${qs.toString()}` };
}
/** 统一身份解析(core.auth._identity 语义),无效抛 401 */
private async requireIdentity(
authorization: string,
xAdminToken: string,
xApiToken: string,
xAdminUser: string
): Promise<string> {
try {
return await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
}
}
/** 版本号数值语义比较(对齐 pkgutil._version_key:"1.10" > "1.9") */
function versionKey(v: string): number[] {
return String(v || '')
.split('.')
.map(s => parseInt(s, 10) || 0);
}
/** 时间格式化为 'YYYY-MM-DD HH:mm:ss'(null 返回 null) */
function fmtDt(d: Date | null): string | null {
if (!d) return null;
const p = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
/** 回跳地址白名单(对齐 dingtalk.py _safe_back_url):http(s) + 回环/内网私有段/控制面域名 */
function safeBackUrl(url: string): boolean {
if (!url || !(url.startsWith('http://') || url.startsWith('https://'))) return false;
try {
const host = new URL(url).hostname.toLowerCase();
if (host === 'localhost' || host === '127.0.0.1' || host === '::1') return true;
const cb = (process.env.DINGTALK_CALLBACK || '');
if (cb) {
const cbHost = new URL(cb).hostname.toLowerCase();
if (host === cbHost) return true;
}
// IPv4 私有网段
const m = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (m) {
const a = Number(m[1]), b = Number(m[2]);
if (a === 10) return true;
if (a === 127) return true;
if (a === 172 && b >= 16 && b <= 31) return true;
if (a === 192 && b === 168) return true;
}
return false;
} catch (e) {
return false;
}
}
@@ -0,0 +1,29 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Get, Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { CenterAuthService, ApiError } from '../../service/auth';
/**
* 契约冒烟测试控制器(验证 /api/* 自定义路由 + ApiErrorMiddleware 的 {detail} 渲染)
*/
@Provide()
@CoolController('/api')
export class ApiPingController extends BaseController {
@Inject()
ctx: Context;
@Inject()
centerAuthService: CenterAuthService;
/** GET /api/ping */
@Get('/ping')
async ping() {
return { ok: true, time: Date.now() };
}
/** GET /api/ping/error → 验证错误渲染为 {"detail": "..."} + 状态码 */
@Get('/ping/error')
async error() {
throw new ApiError(401, '测试错误:登录态无效');
}
}
@@ -0,0 +1,85 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Get, Headers, Inject, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { PluginEntity, AccountPluginEntity, AccountPlatformEntity } from '../../entity/plugin';
import { CenterAuthService, ApiError } from '../../service/auth';
/**
* 客户端插件清单接口(对齐旧 FastAPI apis/plugins.py /api/plugins、/api/platforms/allowed)
* 身份:优先 Authorization: Bearer <cloud_token>,兜底 account + X-API-Token
*/
@Provide()
@CoolController('/api')
export class ApiPluginsController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(PluginEntity)
pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(AccountPluginEntity)
accountPluginRepo: Repository<AccountPluginEntity>;
@InjectEntityModel(AccountPlatformEntity)
accountPlatformRepo: Repository<AccountPlatformEntity>;
/** 解析账号身份;无有效身份抛 400 */
private async resolveAcct(
account: string,
xApiToken: string,
authorization: string
): Promise<string> {
let acct = await this.centerAuthService.cloudAccount(authorization);
if (!acct) {
this.centerAuthService.checkApiToken(xApiToken);
acct = (account || '').trim();
}
if (!acct) throw new ApiError(400, '缺少有效会话或 account');
return acct;
}
/** GET /api/plugins — 按账号返回可用插件清单(权限隔离) */
@Get('/plugins')
async plugins(
@Query('account') account: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('Authorization') authorization: string = ''
) {
const acct = await this.resolveAcct(account, xApiToken, authorization);
if (await this.centerAuthService.accountDisabled(acct)) {
return { account: acct, plugins: [] };
}
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'])
.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 })),
};
}
/** GET /api/platforms/allowed — 按账号返回可登录平台白名单 */
@Get('/platforms/allowed')
async platformsAllowed(
@Query('account') account: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('Authorization') authorization: string = ''
) {
const acct = await this.resolveAcct(account, xApiToken, authorization);
if (await this.centerAuthService.accountDisabled(acct)) {
return { account: acct, allowed: [] };
}
const rows = await this.accountPlatformRepo
.createQueryBuilder('ap')
.select('ap.platformId', 'platformId')
.where('ap.account = :account', { account: acct })
.orderBy('ap.platformId', 'ASC')
.getRawMany();
return { account: acct, allowed: rows.map(r => r.platformId) };
}
}
@@ -0,0 +1,104 @@
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 * as fs from 'fs';
import * as path from 'path';
import { FileSourceEntity } from '../../entity/resource';
import { CenterAuthService, ApiError } from '../../service/auth';
import { SHELL_DIR } from '../../comm/conf';
/**
* 壳子自动更新(对齐旧 FastAPI apis/plugins.py /api/shell/version、/api/shell/pkg)
* version.json 约定:{"version","filename","sha256","notes"}
*/
@Provide()
@CoolController('/api')
export class ApiShellController extends BaseController {
@Inject()
ctx: any;
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(FileSourceEntity)
fileSourceRepo: Repository<FileSourceEntity>;
/** 读 shell/version.json(utf-8-sig 兼容 BOM),缺失/非法返回 {} */
private shellMeta(): any {
const vf = path.join(SHELL_DIR, 'version.json');
if (!fs.existsSync(vf)) return {};
try {
const d = JSON.parse(fs.readFileSync(vf, 'utf-8').replace(/^\uFEFF/, ''));
return d && typeof d === 'object' ? d : {};
} catch (e) {
return {};
}
}
/** 优先取 file_sources category='shell' 的最新启用记录;无返回 {} */
private async shellSourceUrl(): Promise<any> {
try {
const rows = await this.fileSourceRepo
.createQueryBuilder('f')
.select(['f.version', 'f.filename', 'f.url', 'f.sha256', 'f.notes'])
.where('f.category = :c', { c: 'shell' })
.andWhere('f.enabled = 1')
.orderBy('f.id', 'DESC')
.getMany();
const row = rows[0];
if (!row || !row.url) return {};
return {
version: row.version || '',
filename: row.filename || '',
url: row.url,
sha256: row.sha256 || '',
notes: row.notes || '',
};
} catch (e) {
return {};
}
}
/** GET /api/shell/version */
@Get('/shell/version')
async shellVersion(@Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
const source = await this.shellSourceUrl();
const meta = this.shellMeta();
if (source.url) {
return {
available: true,
version: source.version || meta.version || '',
filename: source.filename || meta.filename || '',
url: source.url,
sha256: source.sha256 || meta.sha256 || '',
notes: source.notes || meta.notes || '',
};
}
if (!meta.version) return { available: false, version: '' };
return {
available: true,
version: String(meta.version),
filename: meta.filename || '',
sha256: meta.sha256 || '',
notes: meta.notes || '',
url: '',
};
}
/** GET /api/shell/pkg — 下载壳子安装包(setup.exe) */
@Get('/shell/pkg')
async shellPkg(@Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
const meta = this.shellMeta();
const fn = meta.filename || '';
const pkgPath = fn ? path.join(SHELL_DIR, fn) : '';
if (!pkgPath || !fs.existsSync(pkgPath)) {
throw new ApiError(404, '壳子安装包缺失,请联系管理员');
}
this.ctx.attachment(path.basename(pkgPath));
this.ctx.set('Content-Type', 'application/octet-stream');
this.ctx.body = fs.createReadStream(pkgPath);
}
}
@@ -0,0 +1,106 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Get, Headers, Inject, Param, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as fs from 'fs';
import * as path from 'path';
import { randomBytes } from 'node:crypto';
import { AccountPluginEntity } from '../../entity/plugin';
import { PluginVersionEntity } from '../../entity/plugin';
import { DownloadTicketEntity } from '../../entity/account';
import { AuditLogEntity } from '../../entity/runtime';
import { CenterAuthService, ApiError } from '../../service/auth';
import { PKG_DIR, fmtNow } from '../../comm/conf';
/**
* 一次性下载票据(对齐旧 FastAPI apis/plugins.py):
* - GET /api/plugins/{plugin_id}/versions/{version}/download-ticket:鉴权(can_download)后签发
* - GET /api/download/{ticket}:兑换即作废 + 写审计 + 流式返回包文件
*/
@Provide()
@CoolController('/api')
export class ApiTicketController extends BaseController {
@Inject()
ctx: any;
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(AccountPluginEntity)
accountPluginRepo: Repository<AccountPluginEntity>;
@InjectEntityModel(PluginVersionEntity)
pluginVersionRepo: Repository<PluginVersionEntity>;
@InjectEntityModel(DownloadTicketEntity)
downloadTicketRepo: Repository<DownloadTicketEntity>;
@InjectEntityModel(AuditLogEntity)
auditRepo: Repository<AuditLogEntity>;
/** GET /api/plugins/{plugin_id}/versions/{version}/download-ticket */
@Get('/plugins/:pluginId/versions/:version/download-ticket')
async downloadTicket(
@Param('pluginId') pluginId: string,
@Param('version') version: string,
@Query('account') account: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
if (!(account || '').trim()) throw new ApiError(400, 'account 不能为空');
const grant = await this.accountPluginRepo.findOneBy({
account: account.trim(),
pluginId,
});
const ver = await this.pluginVersionRepo.findOneBy({ pluginId, version });
if (!ver) throw new ApiError(404, `未找到插件包 ${pluginId}@${version}`);
if (!grant || !Number(grant.canDownload)) throw new ApiError(403, '无该插件的下载授权');
const pkgPath = path.join(PKG_DIR, ver.filename);
if (!fs.existsSync(pkgPath)) throw new ApiError(404, `包文件缺失:${ver.filename}`);
// 票据落库共享(多实例通用);顺手清理过期票据
const nonce = randomBytes(16).toString('hex');
await this.downloadTicketRepo.manager.query(
'DELETE FROM download_tickets WHERE created_at < DATE_SUB(NOW(), INTERVAL 3600 SECOND)'
);
await this.downloadTicketRepo.insert({
nonce,
filename: ver.filename,
sha256: ver.sha256 || '',
used: 0,
});
return {
ticket: nonce,
url: `/api/download/${nonce}`,
filename: ver.filename,
sha256: ver.sha256 || '',
expiresAt: fmtNow(),
};
}
/** GET /api/download/{ticket} — 兑换下载(一次性) */
@Get('/download/:ticket')
async download(@Param('ticket') ticket: string, @Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
// 原子占位:仅 used=0 能改成 1,命中行数=0 说明不存在或已用
const res = await this.downloadTicketRepo.manager.query(
'UPDATE download_tickets SET used = 1 WHERE nonce = ? AND used = 0',
[ticket]
);
const affected = Array.isArray(res) ? Number(res[0]?.affectedRows || 0) : Number(res?.affectedRows || 0);
const row = await this.downloadTicketRepo.findOneBy({ nonce: ticket });
if (!affected || !row) throw new ApiError(404, '下载票据无效或已使用');
const pkgPath = path.join(PKG_DIR, row.filename);
if (!fs.existsSync(pkgPath)) throw new ApiError(404, `包文件缺失:${row.filename}`);
// 审计
await this.auditRepo.insert({
account: '',
action: 'download-ticket',
target: row.filename,
detail: '',
at: new Date(),
});
this.ctx.attachment(row.filename);
this.ctx.set('Content-Type', 'application/octet-stream');
this.ctx.body = fs.createReadStream(pkgPath);
}
}
@@ -0,0 +1,128 @@
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
/**
* 统一账号(现网 accounts 表)
*/
@Entity('accounts')
export class AccountEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'int', unsigned: true, comment: '账号自增ID' })
id: number;
@Index({ unique: true })
@Column({ name: 'account', type: 'varchar', length: 64, comment: '登录账号(工号,唯一)' })
account: string;
@Column({ name: 'password_hash', type: 'varchar', length: 128, comment: '密码哈希(加盐)' })
passwordHash: string;
@Column({ name: 'salt', type: 'varchar', length: 64, comment: '密码盐值' })
salt: string;
@Column({ name: 'is_admin', type: 'tinyint', width: 1, default: 0, comment: '是否管理员' })
isAdmin: number;
@Index()
@Column({ name: 'dept', type: 'varchar', length: 64, default: '', comment: '所属部门' })
dept: string;
@Column({ name: 'nickname', type: 'varchar', length: 64, default: '', comment: '昵称/姓名' })
nickname: string;
@Column({ name: 'dingtalk_uid', type: 'varchar', length: 64, default: '', comment: '钉钉用户ID' })
dingtalkUid: string;
@Column({ name: 'must_change_pwd', type: 'tinyint', width: 1, default: 0, comment: '是否必须改密' })
mustChangePwd: number;
@Column({ name: 'avatar', type: 'varchar', length: 255, default: '', comment: '头像文件名' })
avatar: string;
@Column({ name: 'status', type: 'tinyint', width: 1, default: 1, comment: '1=启用 0=停用' })
status: number;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '创建时间' })
createdAt: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 云端会话令牌(现网 cloud_tokens 表,主键 token)
*/
@Entity('cloud_tokens')
export class CloudTokenEntity {
@PrimaryColumn({ name: 'token', type: 'varchar', length: 64, comment: '云端会话令牌' })
token: string;
@Column({ name: 'account', type: 'varchar', length: 64, comment: '所属账号(工号)' })
account: string;
@Column({ name: 'nickname', type: 'varchar', length: 64, default: '', comment: '昵称快照' })
nickname: string;
@Index()
@Column({ name: 'expires_at', type: 'datetime', comment: '过期时间' })
expiresAt: Date;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '签发时间' })
createdAt: Date;
}
/**
* 执行机敏感凭证(现网 client_creds 表,主键 account)
*/
@Entity('client_creds')
export class ClientCredEntity {
@PrimaryColumn({ name: 'account', type: 'varchar', length: 64, comment: '执行机账号(工号)' })
account: string;
@Column({ name: 'pubkey_pem', type: 'text', comment: 'RSA 公钥 PEM' })
pubkeyPem: string;
@Column({ name: 'creds', type: 'mediumtext', comment: '敏感凭证密文 JSON' })
creds: string;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 一次性下载票据(现网 download_tickets 表,主键 nonce)
*/
@Entity('download_tickets')
export class DownloadTicketEntity {
@PrimaryColumn({ name: 'nonce', type: 'varchar', length: 32, comment: '一次性下载票据' })
nonce: string;
@Column({ name: 'filename', type: 'varchar', length: 255, comment: '插件包文件名' })
filename: string;
@Column({ name: 'sha256', type: 'char', length: 64, default: '', comment: 'sha256 校验值' })
sha256: string;
@Column({ name: 'used', type: 'tinyint', width: 1, default: 0, comment: '是否已兑换' })
used: number;
@Index()
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '签发时间' })
createdAt: Date;
}
/**
* 登录防爆破计数(现网 auth_fail_counts 表,主键 account)
*/
@Entity('auth_fail_counts')
export class AuthFailCountEntity {
@PrimaryColumn({ name: 'account', type: 'varchar', length: 64, comment: '登录账号(工号)' })
account: string;
@Column({ name: 'fails', type: 'int', unsigned: true, default: 0, comment: '连续失败次数' })
fails: number;
@Column({ name: 'locked_until', type: 'datetime', nullable: true, comment: '锁定截止时间' })
lockedUntil: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
@@ -0,0 +1,110 @@
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
/**
* 插件元数据(现网 plugins 表)
*/
@Entity('plugins')
export class PluginEntity {
@PrimaryColumn({ name: 'id', type: 'varchar', length: 64, comment: '插件ID(唯一,如 seal_check)' })
id: string;
@Column({ name: 'name', type: 'varchar', length: 128, comment: '插件名称' })
name: string;
@Column({ name: 'latest_version', type: 'varchar', length: 32, comment: '最新版本号' })
latestVersion: string;
@Column({ name: 'description', type: 'varchar', length: 512, default: '', comment: '插件描述' })
description: string;
@Column({ name: 'category', type: 'varchar', length: 64, default: '', comment: '分类' })
category: string;
@Column({ name: 'icon', type: 'varchar', length: 255, default: '', comment: '图标标识' })
icon: string;
@Column({ name: 'status', type: 'varchar', length: 16, default: 'published', comment: 'published/disabled/revoked' })
status: string;
@Column({ name: 'force_min_version', type: 'varchar', length: 32, nullable: true, comment: '强制更新最低版本' })
forceMinVersion: string;
@Column({ name: 'force_deadline', type: 'varchar', length: 32, nullable: true, comment: '强制更新截止时间(ISO)' })
forceDeadline: string;
@Column({ name: 'manifest', type: 'text', nullable: true, comment: 'plugin.json 原文' })
manifest: string;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '创建时间' })
createdAt: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 插件版本(现网 plugin_versions 表)
*/
@Entity('plugin_versions')
export class PluginVersionEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'bigint', unsigned: true, comment: '版本记录自增ID' })
id: number;
@Index()
@Column({ name: 'plugin_id', type: 'varchar', length: 64, comment: '所属插件ID' })
pluginId: string;
@Column({ name: 'version', type: 'varchar', length: 32, comment: '版本号' })
version: string;
@Column({ name: 'filename', type: 'varchar', length: 255, comment: '包文件名' })
filename: string;
@Column({ name: 'sha256', type: 'char', length: 64, default: '', comment: 'sha256 校验值' })
sha256: string;
@Column({ name: 'size_bytes', type: 'bigint', unsigned: true, default: 0, comment: '包体积(字节)' })
sizeBytes: number;
@Column({ name: 'uploaded_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '上传时间' })
uploadedAt: Date;
}
/**
* 账号-插件授权(现网 account_plugins 表,复合主键)
*/
@Entity('account_plugins')
export class AccountPluginEntity {
@PrimaryColumn({ name: 'account', type: 'varchar', length: 64, comment: '账号(工号)' })
account: string;
@PrimaryColumn({ name: 'plugin_id', type: 'varchar', length: 64, comment: '插件ID' })
pluginId: string;
@Column({ name: 'can_download', type: 'tinyint', width: 1, default: 1, comment: '是否允许下载' })
canDownload: number;
@Column({ name: 'can_run', type: 'tinyint', width: 1, default: 1, comment: '是否允许运行' })
canRun: number;
@Column({ name: 'granted_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '授权时间' })
grantedAt: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 账号-平台白名单(现网 account_platforms 表,复合主键)
*/
@Entity('account_platforms')
export class AccountPlatformEntity {
@PrimaryColumn({ name: 'account', type: 'varchar', length: 64, comment: '账号(工号)' })
account: string;
@PrimaryColumn({ name: 'platform_id', type: 'varchar', length: 64, comment: '平台ID(hr/oa 等)' })
platformId: string;
@Column({ name: 'granted_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '授权时间' })
grantedAt: Date;
}
@@ -0,0 +1,152 @@
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
/**
* 大文件源(现网 file_sources 表)
*/
@Entity('file_sources')
export class FileSourceEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'int', unsigned: true, comment: '自增ID' })
id: number;
@Index()
@Column({ name: 'category', type: 'varchar', length: 32, default: '', comment: 'shell/chrome/browser 等' })
category: string;
@Column({ name: 'version', type: 'varchar', length: 32, default: '', comment: '版本号' })
version: string;
@Column({ name: 'filename', type: 'varchar', length: 255, default: '', comment: '原文件名' })
filename: string;
@Column({ name: 'url', type: 'text', comment: '内网文件服务器直链' })
url: string;
@Column({ name: 'sha256', type: 'char', length: 64, default: '', comment: 'sha256 校验值' })
sha256: string;
@Column({ name: 'notes', type: 'varchar', length: 512, default: '', comment: '说明' })
notes: string;
@Column({ name: 'enabled', type: 'tinyint', width: 1, default: 1, comment: '1=启用 0=停用' })
enabled: number;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* Chrome 安装包下载源(现网 chrome_releases 表)
*/
@Entity('chrome_releases')
export class ChromeReleaseEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'int', unsigned: true, comment: '配置自增ID' })
id: number;
@Column({ name: 'version', type: 'varchar', length: 32, default: '', comment: 'Chrome 版本号' })
version: string;
@Column({ name: 'url', type: 'text', comment: '安装包外链下载地址' })
url: string;
@Column({ name: 'filename', type: 'varchar', length: 255, default: '', comment: '落盘文件名' })
filename: string;
@Column({ name: 'sha256', type: 'char', length: 64, default: '', comment: 'sha256 校验值' })
sha256: string;
@Column({ name: 'notes', type: 'varchar', length: 512, default: '', comment: '说明' })
notes: string;
@Column({ name: 'enabled', type: 'tinyint', width: 1, default: 1, comment: '1=启用 0=停用' })
enabled: number;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 壳子定时任务备份(现网 schedule_backups 表,主键 account)
*/
@Entity('schedule_backups')
export class ScheduleBackupEntity {
@PrimaryColumn({ name: 'account', type: 'varchar', length: 64, comment: '执行机账号(工号)' })
account: string;
@Column({ name: 'data', type: 'mediumtext', comment: '定时任务全量配置 JSON' })
data: string;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 内网文件服务器状态(现网 fileserver_status 表)
*/
@Entity('fileserver_status')
export class FileserverStatusEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'int', unsigned: true, comment: '自增ID' })
id: number;
@Index({ unique: true })
@Column({ name: 'host', type: 'varchar', length: 255, comment: '文件服务器标识(唯一)' })
host: string;
@Column({ name: 'base_url', type: 'varchar', length: 255, default: '', comment: '对外下载根' })
baseUrl: string;
@Column({ name: 'hostname', type: 'varchar', length: 128, default: '', comment: '主机名' })
hostname: string;
@Column({ name: 'ip', type: 'varchar', length: 64, default: '', comment: 'IP 地址' })
ip: string;
@Column({ name: 'port', type: 'int', unsigned: true, default: 0, comment: '服务端口' })
port: number;
@Column({ name: 'file_count', type: 'int', unsigned: true, default: 0, comment: '文件数量' })
fileCount: number;
@Column({ name: 'total_size', type: 'bigint', unsigned: true, default: 0, comment: '文件总字节' })
totalSize: number;
@Column({ name: 'version', type: 'varchar', length: 64, default: '', comment: '服务版本' })
version: string;
@Column({ name: 'uptime_sec', type: 'int', unsigned: true, default: 0, comment: '进程运行秒数' })
uptimeSec: number;
@Index()
@Column({ name: 'last_seen', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '最后心跳时间' })
lastSeen: Date;
@Index()
@Column({ name: 'status', type: 'tinyint', width: 1, default: 1, comment: '1=在线 0=离线' })
status: number;
@Column({ name: 'last_status_change', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '最近在线/离线切换时间' })
lastStatusChange: Date;
@Column({ name: 'offline_notified', type: 'tinyint', width: 1, default: 0, comment: '离线已告警' })
offlineNotified: number;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '首次上报时间' })
createdAt: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 系统级键值配置(现网 system_settings 表,主键 key)
*/
@Entity('system_settings')
export class SystemSettingEntity {
@PrimaryColumn({ name: 'key', type: 'varchar', length: 64, comment: '配置键' })
key: string;
@Column({ name: 'value', type: 'text', comment: '配置值(JSON 文本)' })
value: string;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
@@ -0,0 +1,142 @@
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
/**
* 运行上报(现网 runtime_reports 表)
*/
@Entity('runtime_reports')
export class RuntimeReportEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'bigint', unsigned: true, comment: '记录自增ID' })
id: number;
@Index()
@Column({ name: 'account', type: 'varchar', length: 64, default: '', comment: '运行账号(工号)' })
account: string;
@Column({ name: 'device_id', type: 'varchar', length: 64, default: '', comment: '执行机设备ID' })
deviceId: string;
@Index()
@Column({ name: 'plugin_id', type: 'varchar', length: 64, default: '', comment: '插件ID' })
pluginId: string;
@Column({ name: 'version', type: 'varchar', length: 32, default: '', comment: '插件版本号' })
version: string;
@Index()
@Column({ name: 'status', type: 'varchar', length: 32, default: '', comment: 'start/done/success/error/failed' })
status: string;
@Column({ name: 'msg', type: 'text', comment: '结果/错误信息' })
msg: string;
@Column({ name: 'duration_sec', type: 'int', unsigned: true, default: 0, comment: '运行时长(秒)' })
durationSec: number;
@Index()
@Column({ name: 'at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '上报时间' })
at: Date;
}
/**
* 执行机设备(现网 devices 表,主键 device_id)
*/
@Entity('devices')
export class DeviceEntity {
@PrimaryColumn({ name: 'device_id', type: 'varchar', length: 64, comment: '执行机设备ID' })
deviceId: string;
@Index()
@Column({ name: 'account', type: 'varchar', length: 64, default: '', comment: '当前登录账号' })
account: string;
@Column({ name: 'hostname', type: 'varchar', length: 128, default: '', comment: '主机名' })
hostname: string;
@Column({ name: 'os', type: 'varchar', length: 64, default: '', comment: '操作系统' })
os: string;
@Column({ name: 'ip', type: 'varchar', length: 64, default: '', comment: 'IP 地址' })
ip: string;
@Column({ name: 'chrome_installed', type: 'tinyint', width: 1, default: 0, comment: '是否已安装 Chrome' })
chromeInstalled: number;
@Column({ name: 'chrome_version', type: 'varchar', length: 32, default: '', comment: 'Chrome 版本号' })
chromeVersion: string;
@Column({ name: 'chrome_ok', type: 'tinyint', width: 1, default: 0, comment: 'Chrome 是否就绪' })
chromeOk: number;
@Index()
@Column({ name: 'last_seen', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '最后在线时间' })
lastSeen: Date;
@Column({ name: 'status', type: 'tinyint', width: 1, default: 1, comment: '1=在线 0=离线' })
status: number;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '首次上报时间' })
createdAt: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 审计日志(现网 audit_logs 表)
*/
@Entity('audit_logs')
export class AuditLogEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'bigint', unsigned: true, comment: '日志自增ID' })
id: number;
@Index()
@Column({ name: 'account', type: 'varchar', length: 64, default: '', comment: '操作账号' })
account: string;
@Index()
@Column({ name: 'action', type: 'varchar', length: 64, comment: '动作' })
action: string;
@Column({ name: 'target', type: 'varchar', length: 128, default: '', comment: '操作对象' })
target: string;
@Column({ name: 'detail', type: 'text', comment: '操作详情(JSON)' })
detail: string;
@Index()
@Column({ name: 'at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '操作时间' })
at: Date;
}
/**
* 通知(现网 notifications 表)
*/
@Entity('notifications')
export class NotificationEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'int', unsigned: true, comment: '通知ID' })
id: number;
@Column({ name: 'title', type: 'varchar', length: 200, comment: '标题' })
title: string;
@Column({ name: 'content', type: 'text', comment: '内容' })
content: string;
@Column({ name: 'level', type: 'varchar', length: 16, default: 'info', comment: 'info/warning/important' })
level: string;
@Column({ name: 'target', type: 'varchar', length: 16, default: 'all', comment: 'all/account' })
target: string;
@Column({ name: 'account', type: 'varchar', length: 64, default: '', comment: 'target=account 时的目标账号' })
account: string;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '创建时间' })
createdAt: Date;
@Column({ name: 'expires_at', type: 'datetime', nullable: true, comment: '过期时间' })
expiresAt: Date;
@Column({ name: 'active', type: 'tinyint', width: 1, default: 1, comment: '1=启用 0=停用' })
active: number;
}
@@ -0,0 +1,39 @@
import { Middleware } from '@midwayjs/core';
import { Context, NextFunction } from '@midwayjs/koa';
import { IMiddleware } from '@midwayjs/core';
/**
* 全局错误兜底中间件(37du 定制):
* - /api/* 与 /auth/exchange:渲染 FastAPI 兼容的 `{"detail": "<消息>"}`(壳子/插件/agent_cli 依赖)
* - 其余路径(/admin/* 等):渲染 cool-admin 信封 `{"code": <状态码>, "message": "..."}`
*
* 关键职责:兜住一切未捕获异常(含框架对未匹配路由抛出的 404 NotFoundError),
* 不允许任何错误击穿中间件链导致进程崩溃(Node 24 下 unhandled rejection 会直接退出)。
*/
@Middleware()
export class ApiErrorMiddleware implements IMiddleware<Context, NextFunction> {
resolve() {
return async (ctx: Context, next: NextFunction) => {
try {
await next();
} catch (err: any) {
const url = (ctx.url || '').split('?')[0];
let status = Number(err?.status || err?.statusCode || 0);
// 框架 404 NotFoundError:err.code === '404'
if (!status && String(err?.code) === '404') status = 404;
const code = status >= 400 && status <= 599 ? status : 500;
const message = String(err?.message || err?.detail || '服务器内部错误');
const isDetailContract =
url.startsWith('/api/') || url === '/auth/exchange';
ctx.status = code;
if (isDetailContract) {
ctx.body = { detail: message };
} else {
ctx.body = { code: status || code, message };
}
ctx.set('Content-Type', 'application/json');
}
};
}
}
@@ -0,0 +1,199 @@
import { Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { randomBytes } from 'node:crypto';
import { AccountEntity, CloudTokenEntity, AuthFailCountEntity } from '../entity/account';
import { AuditLogEntity } from '../entity/runtime';
import { verifyAdminToken } from './crypto';
/**
* 业务鉴权(对齐旧 FastAPI core/auth.py):
* - X-API-Token:执行机底座→中心机的内部调用凭证
* - X-Admin-Token:管理员签名票据(HMAC,12h),管理操作唯一可信身份
* - Authorization: Bearer <cloud_token>:员工端扫码登录的云端会话(落库 7 天)
*/
/** 业务错误:携带 HTTP 状态码,由 api-error 中间件渲染为 {detail} */
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
@Provide()
export class CenterAuthService {
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
@InjectEntityModel(CloudTokenEntity)
cloudTokenRepo: Repository<CloudTokenEntity>;
@InjectEntityModel(AuthFailCountEntity)
authFailRepo: Repository<AuthFailCountEntity>;
// ==================== 内部凭证 ====================
checkApiToken(xApiToken: string = '') {
const token = process.env.CONTROLPLANE_TOKEN || '';
if (token && xApiToken !== token) {
throw new ApiError(401, '鉴权失败:无效或缺失 X-API-Token');
}
}
/** 账号是否已停用(停用后机器侧一律不给插件/授权) */
async accountDisabled(acct: string): Promise<boolean> {
const row = await this.accountRepo.findOneBy({ account: acct });
return !!row && !Number(row.status);
}
// ==================== 管理员票据 ====================
async requireAdmin(xAdminToken: string = '', xApiToken: string = ''): Promise<string> {
let account = '';
try {
account = verifyAdminToken(xAdminToken);
} catch (e) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
if (!account) throw new ApiError(401, '缺少有效登录态');
return this._adminGate(account);
}
private async _adminGate(account: string): Promise<string> {
const row = await this.accountRepo.findOneBy({ account });
if (!row || !Number(row.isAdmin)) throw new ApiError(403, `账号 ${account} 无管理权限`);
if (!Number(row.status)) throw new ApiError(403, '账号已停用,请联系管理员');
if (Number(row.mustChangePwd)) throw new ApiError(403, '请先修改初始密码后再执行管理操作');
return account;
}
// ==================== 云端会话 token ====================
async cloudAccount(bearer: string): Promise<string> {
let token = (bearer || '').trim();
if (token.toLowerCase().startsWith('bearer ')) token = token.slice(7).trim();
if (!token) return '';
try {
const row = await this.cloudTokenRepo
.createQueryBuilder('t')
.innerJoin(AccountEntity, 'a', 'a.account = t.account')
.select('t.account', 'account')
.where('t.token = :token', { token })
.andWhere('t.expiresAt > NOW()')
.andWhere('a.status = 1')
.getRawOne();
return row ? String(row.account) : '';
} catch (e) {
return '';
}
}
async issueCloudToken(account: string, nickname: string): Promise<string> {
const token = randomBytes(32).toString('base64url');
await this.cloudTokenRepo
.createQueryBuilder()
.delete()
.where('expiresAt < NOW()')
.execute();
await this.cloudTokenRepo.save(
this.cloudTokenRepo.create({
token,
account,
nickname: nickname || '',
expiresAt: new Date(Date.now() + 7 * 24 * 3600 * 1000),
})
);
return token;
}
async revokeAccountTokens(account: string) {
try {
await this.cloudTokenRepo.delete({ account });
} catch (e) {
/* 吊销失败不阻断 */
}
}
// ==================== 统一身份解析 ====================
async identity(
authorization: string = '',
xAdminToken: string = '',
xApiToken: string = '',
xAdminUser: string = ''
): Promise<string> {
const acct = await this.cloudAccount(authorization);
if (acct) return acct;
return this.resolveLogin(xAdminToken, xApiToken, xAdminUser);
}
resolveLogin(xAdminToken: string, xApiToken: string, xAdminUser: string): string {
try {
const account = verifyAdminToken(xAdminToken);
if (account) return account;
} catch (e) {
/* fallthrough */
}
if (
(xAdminUser || '').trim() &&
process.env.CONTROLPLANE_TOKEN &&
xApiToken === process.env.CONTROLPLANE_TOKEN
) {
return xAdminUser.trim();
}
throw new Error('no identity');
}
// ==================== 登录防爆破(auth_fail_counts) ====================
async authGate(account: string) {
try {
const row = await this.authFailRepo
.createQueryBuilder('f')
.select('1')
.where('f.account = :account', { account })
.andWhere('f.lockedUntil > NOW()')
.getRawOne();
if (row) throw new ApiError(429, '失败次数过多,账号已临时锁定,请 5 分钟后再试');
} catch (e) {
if (e instanceof ApiError) throw e;
/* 计数失败不阻断 */
}
}
async authFail(account: string) {
const LIMIT = 5;
try {
const conn = this.authFailRepo.manager;
await conn.query(
`INSERT INTO auth_fail_counts(account, fails, locked_until) VALUES (?, 1, NULL)
ON DUPLICATE KEY UPDATE
fails = IF(locked_until IS NOT NULL AND locked_until <= NOW(), 1, fails + 1),
locked_until = IF(fails + 1 >= ${LIMIT}, DATE_ADD(NOW(), INTERVAL 300 SECOND), NULL)`,
[account]
);
} catch (e) {
/* 计数失败不阻断 */
}
}
async authReset(account: string) {
try {
await this.authFailRepo.delete({ account });
} catch (e) {
/* 忽略 */
}
}
/** 写审计日志(audit_logs),失败不阻断 */
async audit(account: string, action: string, target: string = '', detail: string = '') {
try {
await this.authFailRepo.manager.insert(AuditLogEntity, {
account: account || '',
action,
target: target || '',
detail: detail || '',
at: new Date(),
});
} catch (e) {
/* 审计失败不阻断 */
}
}
}
@@ -0,0 +1,139 @@
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import { CENTER_DATA_DIR } from '../comm/conf';
/**
* 中心机密码学(与旧 FastAPI core/crypto.py 逐字对齐):
* - 口令哈希:pbkdf2_hmac(sha256, 120000 轮),盐随机 + 常数时间比较
* - Ed25519 签名:{base64url(json_canon)}.{base64url(sig64)},私钥持久化可导入现网密钥
* - RSA-OAEP(SHA256) 加密:执行机敏感凭证下发
*/
const PBKDF2_ITER = 120000;
const KEY_DIR = path.join(CENTER_DATA_DIR, 'keys');
/** 规范化 JSON(递归按 key 排序、紧凑分隔符),对齐 Python json.dumps(sort_keys=True, separators=(',',':')) */
export function canonicalJson(obj: any): string {
if (obj === null || typeof obj !== 'object') return JSON.stringify(obj);
if (Array.isArray(obj)) return '[' + obj.map(canonicalJson).join(',') + ']';
const keys = Object.keys(obj).sort();
return '{' + keys.map(k => JSON.stringify(k) + ':' + canonicalJson(obj[k])).join(',') + '}';
}
// ==================== 口令哈希 ====================
export function hashPassword(pwd: string, salt: string = ''): { hash: string; salt: string } {
const s = salt || crypto.randomBytes(8).toString('hex');
const dk = crypto.pbkdf2Sync(pwd, s, PBKDF2_ITER, 32, 'sha256');
return { hash: dk.toString('hex'), salt: s };
}
export function verifyPassword(pwd: string, salt: string, hexdigest: string): boolean {
const dk = crypto.pbkdf2Sync(pwd, salt, PBKDF2_ITER, 32, 'sha256');
const a = Buffer.from(dk.toString('hex'), 'utf8');
const b = Buffer.from(hexdigest || '', 'utf8');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
// ==================== Ed25519 密钥 + 签名票据 ====================
let _keys: { priv: crypto.KeyObject; pub: crypto.KeyObject } | null = null;
function loadOrCreateKeypair() {
if (_keys) return _keys;
fs.mkdirSync(KEY_DIR, { recursive: true });
const privPath = path.join(KEY_DIR, 'center_key.priv');
const pubPath = path.join(KEY_DIR, 'center_key.pub');
if (fs.existsSync(privPath) && fs.existsSync(pubPath)) {
_keys = {
priv: crypto.createPrivateKey(fs.readFileSync(privPath)),
pub: crypto.createPublicKey(fs.readFileSync(pubPath)),
};
} else {
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
fs.writeFileSync(privPath, privateKey.export({ type: 'pkcs8', format: 'pem' }));
fs.writeFileSync(pubPath, publicKey.export({ type: 'spki', format: 'pem' }));
_keys = { priv: privateKey, pub: publicKey };
}
return _keys;
}
/** 中心机公钥 PEM(/api/me/pubkey 下发,执行机缓存离线验签) */
export function pubkeyPem(): string {
return loadOrCreateKeypair().pub.export({ type: 'spki', format: 'pem' }).toString();
}
/** 签名打包:{base64url(json)}.{base64url(ed25519sig)} */
export function signBlob(payload: object): string {
const canon = Buffer.from(canonicalJson(payload), 'utf8');
const sig = crypto.sign(null, canon, loadOrCreateKeypair().priv);
return `${canon.toString('base64url')}.${sig.toString('base64url')}`;
}
/** 验签并返回 payload;签名非法抛 Error */
export function verifyBlob(blob: string, pub: crypto.KeyObject): any {
const idx = blob.lastIndexOf('.');
if (idx < 0) throw new Error('bad blob');
const canon = Buffer.from(blob.slice(0, idx), 'base64url');
const sig = Buffer.from(blob.slice(idx + 1), 'base64url');
if (sig.length !== 64) throw new Error('bad signature len');
const ok = crypto.verify(null, canon, pub, sig);
if (!ok) throw new Error('bad signature');
return JSON.parse(canon.toString('utf8'));
}
// ==================== RSA-OAEP 加密(凭证下发) ====================
export function rsaEncrypt(pubkeyPem: string, plaintext: string): string {
const pub = crypto.createPublicKey(pubkeyPem);
const ct = crypto.publicEncrypt(
{
key: pub,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha256',
},
Buffer.from(plaintext, 'utf8')
);
return ct.toString('base64');
}
// ==================== 管理员票据 HMAC 签名(对齐 core/auth.py) ====================
const ADMIN_TOKEN_TTL = 12 * 3600; // 12h
function loadAdminSecret(): string {
const env = (process.env.CONTROLPLANE_ADMIN_SECRET || '').trim();
if (env) return env;
const dir = CENTER_DATA_DIR;
fs.mkdirSync(dir, { recursive: true });
const f = path.join(dir, '.admin_secret');
if (fs.existsSync(f)) return fs.readFileSync(f, 'utf8').trim();
const secret = crypto.randomBytes(32).toString('hex');
fs.writeFileSync(f, secret, 'utf8');
return secret;
}
let _adminSecret: string | null = null;
export function adminSecret(): string {
if (!_adminSecret) _adminSecret = loadAdminSecret();
return _adminSecret;
}
export function signAdminToken(account: string): string {
const payload = Buffer.from(
JSON.stringify({ a: account, e: Math.floor(Date.now() / 1000) + ADMIN_TOKEN_TTL })
).toString('base64url');
const sig = crypto.createHmac('sha256', adminSecret()).update(payload).digest('hex');
return `${payload}.${sig}`;
}
export function verifyAdminToken(tok: string): string {
const idx = tok.lastIndexOf('.');
if (idx < 0) throw new Error('invalid token');
const payload = tok.slice(0, idx);
const sig = tok.slice(idx + 1);
const expect = crypto.createHmac('sha256', adminSecret()).update(payload).digest('hex');
const a = Buffer.from(expect, 'utf8');
const b = Buffer.from(sig, 'utf8');
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) throw new Error('bad signature');
const data = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
if (Number(data.e || 0) < Date.now() / 1000) throw new Error('expired');
return String(data.a || '');
}
@@ -0,0 +1,75 @@
import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseSysDepartmentEntity } from '../../base/entity/sys/department';
/**
* 部门数据范围("本部门及以下")补齐工具。
*
* cool-admin 原生:部门树(parentId) + 角色-部门授权(base_sys_role_department),
* 但 `role.relevance`(关联上下级)字段未被消费,"本部门及以下"的自动展开缺失。
* 本工具:
* 1. 解析操作者角色的授权部门集合(超管=全部)
* 2. 按 parentId 树递归向下展开后代部门("本部门及以下")
* 3. 业务列表查询据此拼 dept_id IN (...) 过滤
*/
@Provide()
export class CenterDeptScopeService {
@InjectEntityModel(BaseSysDepartmentEntity)
deptRepo: Repository<BaseSysDepartmentEntity>;
/**
* 某用户的部门数据范围
* @returns { admin: boolean, deptIds: number[] } — admin=true 表示全量;deptIds 为"本部门及以下"展开后的集合
*/
async userScope(userId: number, username: string): Promise<{ admin: boolean; deptIds: number[] }> {
if (username === 'admin') return { admin: true, deptIds: [] };
const m = this.deptRepo.manager;
// 用户 → 角色 → 授权部门
const rows: any[] = await m.query(
`SELECT DISTINCT rd.department_id AS departmentId
FROM base_sys_user_role ur
JOIN base_sys_role_department rd ON rd.role_id = ur.role_id
WHERE ur.user_id = ?`,
[userId]
);
const rootIds = rows.map((r: any) => Number(r.departmentId)).filter((n: number) => !isNaN(n) && n > 0);
if (!rootIds.length) return { admin: false, deptIds: [] };
return { admin: false, deptIds: await this.expandDescendants(rootIds) };
}
/**
* 按 parentId 树向下展开:返回 rootIds 及其所有后代部门 ID
*/
async expandDescendants(rootIds: number[]): Promise<number[]> {
const all = await this.deptRepo.find();
const children: Record<number, number[]> = {};
for (const d of all) {
const pid = d.parentId ? Number(d.parentId) : 0;
if (!children[pid]) children[pid] = [];
children[pid].push(Number(d.id));
}
const result = new Set<number>();
const queue = [...rootIds];
while (queue.length) {
const id = queue.shift()!;
if (result.has(id)) continue;
result.add(id);
for (const c of children[id] || []) queue.push(c);
}
return [...result];
}
/**
* 生成业务查询的 dept 过滤条件片段(含参数)。
* 返回 { sql: string, args: number[] };scope.admin=true 时返回 { sql: '', args: [] }(全量)。
*/
async deptFilter(userId: number, username: string, deptColumn = 'dept_id') {
const scope = await this.userScope(userId, username);
if (scope.admin || !scope.deptIds.length) return { sql: '', args: [] as number[] };
return {
sql: `${deptColumn} IN (${scope.deptIds.map(() => '?').join(',')})`,
args: scope.deptIds,
};
}
}
@@ -0,0 +1,115 @@
import axios from 'axios';
/**
* 中心机钉钉官方接口封装(对齐旧 FastAPI core/dingtalk.py):
* - dingtalkUserinfo(authCode):OAuth 扫码 authCode → unionid/昵称 →(可选)企业内部 token
* → getbyunionid 取 userid → v2/user/get 取工号;
* - 与执行机/老后端共用一套凭证语义:DINGTALK_APP_KEY/SECRET 即可完成全链路。
*/
const HTTP_TIMEOUT = 10000;
async function getJson(url: string, headers: Record<string, string> = {}): Promise<any> {
try {
const r = await axios.get(url, { timeout: HTTP_TIMEOUT, headers });
return r.data;
} catch (e: any) {
throw new Error(`钉钉接口访问失败:${e?.message || e}`);
}
}
async function postJson(url: string, payload: object, headers: Record<string, string> = {}): Promise<any> {
try {
const r = await axios.post(url, payload, {
timeout: HTTP_TIMEOUT,
headers: { 'Content-Type': 'application/json', ...headers },
});
return r.data;
} catch (e: any) {
throw new Error(`钉钉接口访问失败:${e?.message || e}`);
}
}
// 企业内部 token 缓存(gettoken 的 access_token 有 TTL,缓存到临近过期)
const topapiCache: { at: string; exp: number } = { at: '', exp: 0 };
/** 获取企业内部应用 access_token(取工号/发工作通知链路用)。失败返回空串不阻断。 */
export async function topapiToken(): Promise<string> {
const appKey = (process.env.DINGTALK_APP_KEY || '').trim();
const appSecret = (process.env.DINGTALK_APP_SECRET || '').trim();
if (!appKey || !appSecret) return '';
const now = Date.now() / 1000;
if (topapiCache.at && topapiCache.exp > now + 60) return topapiCache.at;
try {
const info = await getJson(
`https://oapi.dingtalk.com/gettoken?appkey=${encodeURIComponent(appKey)}&appsecret=${encodeURIComponent(appSecret)}`
);
const at = String(info?.access_token || '');
if (!at) return '';
topapiCache.at = at;
topapiCache.exp = now + Number(info?.expires_in || 7200);
return at;
} catch (e) {
return ''; // 取企业内部 token 失败不阻断扫码登录
}
}
/** 用钉钉扫码回调的 authCode 换取当前钉钉用户工号/姓名/unionid(对齐 _dingtalk_userinfo)。 */
export async function dingtalkUserinfo(authCode: string): Promise<{ account: string; nickname: string; unionid: string }> {
const appKey = (process.env.DINGTALK_APP_KEY || '').trim();
const appSecret = (process.env.DINGTALK_APP_SECRET || '').trim();
if (!appKey || !appSecret) {
const err: any = new Error('未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)');
err.status = 503;
throw err;
}
// Step1: authCode -> accessToken -> unionid + nick
let tok: any;
try {
tok = await postJson('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', {
clientId: appKey,
clientSecret: appSecret,
code: authCode,
grantType: 'authorization_code',
});
} catch (e) {
throw e; // 网络/接口错误原样上抛(502 语义由调用方包装)
}
const at = String(tok?.accessToken || '');
if (!at) {
const err: any = new Error('钉钉授权码无效或已过期,请重新扫码');
err.status = 401;
throw err;
}
const me = await getJson('https://api.dingtalk.com/v1.0/contact/users/me', {
'x-acs-dingtalk-access-token': at,
});
const unionid = String(me?.unionId || me?.unionid || '');
let nickname = String(me?.nick || '');
let account = String(me?.jobNumber || me?.userId || unionid);
// Step2/3: (可选)企业内部 token -> getbyunionid(userid) -> v2/user/get(job_number)
const topAt = await topapiToken();
if (topAt && unionid) {
try {
const byunion = await postJson(
`https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=${topAt}`,
{ unionid }
);
const ures = byunion?.result || {};
const userid = String(ures?.userid || ures?.userId || '');
if (userid) {
const ud = await postJson(
`https://oapi.dingtalk.com/topapi/v2/user/get?access_token=${topAt}`,
{ userid }
);
const res = ud?.result || {};
const job = String(res?.job_number || res?.jobNumber || '');
nickname = nickname || String(res?.name || '');
account = job || userid || account;
}
} catch (e) {
/* 取工号失败不阻断登录,回退已得字段 */
}
}
return { account, nickname, unionid };
}
@@ -0,0 +1,81 @@
import { Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { FileserverStatusEntity } from '../entity/resource';
import { CenterNotifyService } from './notify';
import { FILESERVER_HEARTBEAT_TIMEOUT, FILESERVER_MONITOR_INTERVAL } from '../comm/conf';
/**
* 内网文件服务器离线监控(对齐旧 FastAPI core/monitor.py):
* - 文件服务器周期主动上报心跳(/api/fileserver/heartbeat,默认 60s 一次,落库 last_seen);
* - 本服务按 FILESERVER_MONITOR_INTERVAL(默认 30s)扫描「在线且未告警」的记录,
* 对 last_seen 超过 FILESERVER_HEARTBEAT_TIMEOUT(默认 180s)的判定离线并推送钉钉;
* - 离线转换用「带条件的原子 UPDATE」认领(status=1 且 offline_notified=0 且 last_seen 超时),
* 多实例并发下仅一个实例认领成功,避免重复告警;
* - 恢复上线由心跳接口处理:收到心跳即翻转在线并清除告警标记。
*/
@Provide()
export class FileserverMonitorService {
@InjectEntityModel(FileserverStatusEntity)
fileserverRepo: Repository<FileserverStatusEntity>;
@Inject()
centerNotifyService: CenterNotifyService;
private timer: NodeJS.Timeout | null = null;
start(): void {
if (this.timer) return;
const interval = Math.max(5, FILESERVER_MONITOR_INTERVAL) * 1000;
this.timer = setInterval(() => {
this.scanOnce().catch(() => {
/* 监控异常不退出,下轮重试 */
});
}, interval);
// 不阻止进程退出
this.timer.unref?.();
}
stop(): void {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
/** 扫描一次:将心跳超时的在线文件服务器翻转为离线并告警(幂等 / 并发安全)。 */
async scanOnce(): Promise<void> {
const cutoff = new Date(Date.now() - FILESERVER_HEARTBEAT_TIMEOUT * 1000);
const rows = await this.fileserverRepo
.createQueryBuilder('f')
.select(['f.host', 'f.hostname', 'f.ip', 'f.lastSeen'])
.where('f.status = 1')
.andWhere('f.offlineNotified = 0')
.getMany();
for (const r of rows) {
let claimed = false;
try {
const res = await this.fileserverRepo
.createQueryBuilder()
.update(FileserverStatusEntity)
.set({ status: 0, offlineNotified: 1, lastStatusChange: new Date() })
.where('host = :host', { host: r.host })
.andWhere('status = 1')
.andWhere('offlineNotified = 0')
.andWhere('lastSeen < :cutoff', { cutoff })
.execute();
claimed = Number(res?.affected || 0) > 0;
} catch (e) {
continue; // 单条认领失败不影响其余扫描
}
if (!claimed) continue; // 已被其它实例认领,或刚恢复心跳
console.warn(`检测到文件服务器离线:${r.host}(最后心跳 ${r.lastSeen})`);
this.centerNotifyService.notifyFileserverDown(
r.host,
r.hostname || '',
r.ip || '',
String(r.lastSeen || '')
);
}
}
}
@@ -0,0 +1,204 @@
import axios from 'axios';
import * as crypto from 'crypto';
import { Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { AccountEntity } from '../entity/account';
import { topapiToken } from './dingtalk';
/**
* 钉钉通知(对齐旧 FastAPI core/notify.py):自建应用工作通知(个人推送)
* + 群机器人 webhook(备用渠道)。全部后台异步发送,失败仅记日志不阻断业务。
*
* 配置项(server/.env):
* - DINGTALK_AGENT_ID 自建应用 AgentId;留空则不发工作通知(KEY/SECRET 复用扫码那套)
* - DINGTALK_ADMIN_NAME 权限开通提醒管理员姓名(默认 夏一平)
* - DINGTALK_WEBHOOK_URL 群机器人 webhook(备用渠道)
* - DINGTALK_WEBHOOK_SECRET 群机器人加签密钥(可选)
*/
const HTTP_TIMEOUT = 10000;
const SIGN_NAME = '37du 自动化平台';
const STATUS_COLORS: Record<string, string> = {
info: '#0077ff',
success: '#00b300',
warning: '#ff9900',
error: '#ff0000',
};
function footer(): string {
const d = new Date();
const p = (n: number) => String(n).padStart(2, '0');
return `###### ${SIGN_NAME} | ${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
async function postJson(url: string, payload: object, headers: Record<string, string> = {}): Promise<any> {
const r = await axios.post(url, payload, {
timeout: HTTP_TIMEOUT,
headers: { 'Content-Type': 'application/json', ...headers },
});
return r.data;
}
@Provide()
export class CenterNotifyService {
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
// ==================== userid 解析(单次直查,不做通讯录遍历/缓存) ====================
private async useridByUnionid(at: string, unionid: string): Promise<string> {
try {
const body = await postJson(
`https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=${at}`,
{ unionid }
);
return String(body?.result?.userid || '');
} catch (e) {
return '';
}
}
private async useridByName(at: string, name: string): Promise<string> {
try {
const body = await postJson(
'https://api.dingtalk.com/v1.0/contact/users/search',
{ queryWord: name.trim(), offset: 0, size: 5, maxResults: 5 },
{ 'x-acs-dingtalk-access-token': at }
);
const list: any[] = body?.list || [];
return list.length ? String(list[0]) : '';
} catch (e) {
return '';
}
}
// ==================== 渠道一:自建应用工作通知 ====================
private async sendWorkTo(
at: string, agentId: string, userid: string, title: string, content: string,
status: string = 'info'
): Promise<boolean> {
const color = STATUS_COLORS[status] || STATUS_COLORS.info;
let text = `**<font color='${color}'>${title}</font>**\n\n`;
text += content.trim() + '\n';
text += `\n\n---\n\n${footer()}`;
try {
const body = await postJson(
`https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=${at}`,
{
agent_id: agentId,
userid_list: userid,
msg: { msgtype: 'markdown', markdown: { title, text } },
}
);
if (Number(body?.errcode) !== 0) return false;
return true;
} catch (e) {
return false; // 通知失败不阻断业务
}
}
// ==================== 渠道二:群机器人 webhook(+ 加签) ====================
private signedWebhookUrl(): string {
const url = (process.env.DINGTALK_WEBHOOK_URL || '').trim();
if (!url) return '';
const secret = (process.env.DINGTALK_WEBHOOK_SECRET || '').trim();
if (secret) {
const ts = String(Date.now());
const sign = crypto
.createHmac('sha256', secret)
.update(`${ts}\n${secret}`, 'utf8')
.digest('base64');
return `${url}${url.includes('?') ? '&' : '?'}timestamp=${ts}&sign=${encodeURIComponent(sign)}`;
}
return url;
}
private async sendRobot(title: string, text: string): Promise<void> {
const url = this.signedWebhookUrl();
if (!url) return;
try {
const body = await postJson(url, { msgtype: 'markdown', markdown: { title, text } });
if (Number(body?.errcode) !== 0) console.warn('钉钉群通知被拒:', JSON.stringify(body));
} catch (e: any) {
console.warn('钉钉群通知异常:', e?.message || e);
}
}
// ==================== 新账号创建通知(管理台/钉钉扫码共用) ====================
/** 新账号创建通知(新用户收账号+初始密码,管理员收权限开通提醒),异步发送。 */
notifyAccountCreated(account: string, nickname = '', password = '', unionid = '', source = '管理台'): void {
// 异步 fire-and-forget,不阻断业务主流程
this.workAccountCreated(account, nickname, password, unionid, source).catch(() => {});
}
private async workAccountCreated(
account: string, nickname: string, password: string, unionid: string, source: string
): Promise<void> {
const agentId = (process.env.DINGTALK_AGENT_ID || process.env.CREDS_DINGTALK_AGENT_ID || '').trim();
if (!agentId) return;
try {
const at = await topapiToken();
if (!at) return;
// 1) 新用户本人:unionid 精确解析 userid,兜底按昵称搜索直查
let uid = unionid ? await this.useridByUnionid(at, unionid) : '';
if (!uid && nickname) uid = await this.useridByName(at, nickname);
if (uid) {
await this.sendWorkTo(
at, agentId, uid, '账号开通通知',
`**🔹 ${nickname || account}‑账号开通**\n\n> 账号:${account}\n\n> 初始密码:${password}\n\n> 备注:首次登录须修改密码,请及时登录并妥善保管`,
'success'
);
}
// 2) 管理员:权限开通提醒(按姓名搜索直查)
const adminName = (process.env.DINGTALK_ADMIN_NAME || '夏一平').trim();
const adminUid = await this.useridByName(at, adminName);
if (adminUid) {
await this.sendWorkTo(
at, agentId, adminUid, '新账号待开通权限',
`> 账号:${account}\n\n> 姓名:${nickname || '—'}\n\n> 来源:${source}\n\n> 备注:请到管理台为该账号开通插件权限`,
'warning'
);
}
} catch (e) {
/* 通知失败不阻断业务 */
}
}
// ==================== 内网文件服务器离线告警 ====================
/** 管理员名单(nickname 优先,其次 account),用于离线告警收件人。 */
private async adminNames(): Promise<string[]> {
try {
const rows: any[] = await this.accountRepo.find({ where: { isAdmin: 1 } as any });
return rows
.sort((a, b) => a.id - b.id)
.map(r => (r.nickname || r.account || '').trim())
.filter(Boolean);
} catch (e) {
return [];
}
}
/** 文件服务器离线告警:优先工作通知推给全部管理员,无人送达回退群机器人 webhook。 */
notifyFileserverDown(host: string, hostname = '', ip = '', lastSeen = ''): void {
this.workFileserverDown(host, hostname, ip, lastSeen).catch(() => {});
}
private async workFileserverDown(host: string, hostname: string, ip: string, lastSeen: string): Promise<void> {
const title = '内网文件服务器下线告警';
const content =
`> 服务:${hostname || '—'}\n\n> 地址:${host}\n\n> IP:${ip || '—'}\n\n` +
`> 最后心跳:${lastSeen || '—'}\n\n` +
'> 提示:执行机将无法下载大文件(壳子/Chrome 安装包),请尽快排查进程或网络;服务恢复后将自动解除告警';
const agentId = (process.env.DINGTALK_AGENT_ID || process.env.CREDS_DINGTALK_AGENT_ID || '').trim();
const at = agentId ? await topapiToken() : '';
let sentAny = false;
if (at) {
for (const name of await this.adminNames()) {
if (!name) continue;
const uid = await this.useridByName(at, name);
if (uid && (await this.sendWorkTo(at, agentId, uid, title, content, 'error'))) sentAny = true;
}
}
if (!sentAny) await this.sendRobot(title, content);
}
}