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