build(desktop): 升级 electron-shell 版本至 1.6.3 并调整插件执行超时配置
- 插件执行超时默认延长至 6 小时,支持插件单独配置超时时间 - 新增插件根目录迁移逻辑,解决旧版权限问题 - 新增多个服务端实体、DTO、配置模块等基础代码 - 新增插件 UI 模板及相关静态资源
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user