fix: 加固备份数据覆盖率

This commit is contained in:
Nixevol
2026-07-05 01:09:22 +08:00
parent 5207af30f1
commit 7a51814307
2 changed files with 61 additions and 3 deletions
+1
View File
@@ -132,6 +132,7 @@
- 系统图标配置(2026-07-05):系统设置新增 `appIconUrl`,默认使用前端内置 `/app-icon.svg`。默认 SVG 图标为蓝绿渐变底、盾牌和金色艺术器形/印章元素,无底部横线;后台左上角导航图标、后台登录页图标、客户端首页图标、客户端溯源页顶部图标和浏览器 favicon 均从该设置读取。后台设置页可上传自定义图片/SVG 图标,上传接口已放行 `image/svg+xml` 并按 `.svg` 存储;清空图标设置会回退默认内置图标。
- 国际化覆盖修复(2026-07-05):后台清理设置页、备份恢复、出库导入、退出确认、表头筛选等用户可见硬编码中文,统一迁入 `apps/admin/src/locales/zh-CN.json` / `en-US.json`;`renderTableFilterTitle` 使用当前 i18n 的“全部/筛选”。全局 `message/dialog/loadingBar` 的 `createDiscreteApi` 现在跟随当前语言、日期语言和主题,避免页面切英文但离散弹窗仍中文。请求拦截器新增错误码翻译优先级:后台接口返回 `code` 时优先使用 `common.errorCode.*`,英文界面下若后端未知 message 含中文则回退英文通用错误,避免中文业务异常直接出现在英文 UI。上传组件失败提示改为语言包文案。客户端首页语言切换按钮从 `SUPPORTED_LOCALES` 读取标签,客户端语言包中的语言名统一为“简体中文 / English”;隐私说明同步移除已废弃的“地区”记录口径。
- 浏览器标题同步(2026-07-05):后台登录页 `document.title` 使用系统设置中的平台名称;后台主布局标题规则为“当前菜单 - 平台名称”,并通过 `artveris-settings-updated` 事件在保存系统设置后同步更新。客户端首页标题使用公开设置中的平台名称;客户端溯源详情页在查询到有效档案后把浏览器标题设置为当前 `artwork.archiveNo`,异常/加载失败时回退平台名称。
- 备份覆盖率加固(2026-07-05):备份数据库清单现在会在创建备份前对照 `Prisma.ModelName` 做覆盖校验,除 `BackupRecord`(备份包自身元数据,恢复旧路径会产生坏记录)外,所有业务模型必须在备份清单中,否则直接报错阻止生成不完整备份。`systemSetting` 备份不再只导出数据库已有行,而是导出 `SettingsService.getAll()` 的有效设置全集,确保平台名称、系统图标、备案信息、日志保留、备份策略、轮播间隔等默认但未保存过的设置也能随备份迁移。文件备份仍覆盖本地 `storage` 全目录,但会显式排除 `backupRoot`,避免 `BACKUP_DIR` 被配置到 storage 下时把旧备份包递归打进新备份;恢复清理 storage 时也保留 backupRoot。
## 当前代码基准与注意事项
+60 -3
View File
@@ -4,7 +4,8 @@ import { Response } from 'express';
import AdmZip from 'adm-zip';
import dayjs from 'dayjs';
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
import { dirname, join, relative, resolve } from 'path';
import { dirname, isAbsolute, join, relative, resolve } from 'path';
import { Prisma } from '@prisma/client';
import { BackupStatus, ErrorCode } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BusinessException } from '../common/exceptions/business.exception';
@@ -12,6 +13,7 @@ import { buildPage } from '../common/utils/pagination.util';
import { buildOrderBy } from '../common/utils/sort.util';
import { AuthUser } from '../common/decorators/current-user.decorator';
import { QueryBackupDto } from './dto/backup.dto';
import { SettingsService } from '../settings/settings.service';
const MODELS = [
'sysUser',
@@ -33,6 +35,25 @@ const MODELS = [
] as const;
const DELETE_ORDER = [...MODELS].reverse();
const EXCLUDED_PRISMA_MODELS = new Set(['BackupRecord']);
const PRISMA_MODEL_BY_DELEGATE: Record<(typeof MODELS)[number], string> = {
sysUser: 'SysUser',
template: 'Template',
templateField: 'TemplateField',
artwork: 'Artwork',
traceNode: 'TraceNode',
certificate: 'Certificate',
traceCodeGroup: 'TraceCodeGroup',
batch: 'Batch',
traceCode: 'TraceCode',
blockchainProof: 'BlockchainProof',
queryLog: 'QueryLog',
job: 'Job',
systemSetting: 'SystemSetting',
operationLog: 'OperationLog',
outboundImportSession: 'OutboundImportSession',
outboundImportRow: 'OutboundImportRow',
};
const DATE_KEYS = new Set([
'lastLoginAt',
'createdAt',
@@ -73,6 +94,11 @@ function isSafeZipPath(path: string): boolean {
return !path.includes('\\') && !path.includes('..') && !path.startsWith('/') && !/^[a-z]:/i.test(path);
}
function isSameOrChildPath(parent: string, child: string): boolean {
const rel = relative(resolve(parent), resolve(child));
return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
}
@Injectable()
export class BackupService {
private readonly storageRoot: string;
@@ -81,6 +107,7 @@ export class BackupService {
constructor(
private readonly prisma: PrismaService,
private readonly config: ConfigService,
private readonly settings: SettingsService,
) {
this.storageRoot = resolve(this.config.get<string>('storage.localDir') || './storage');
this.backupRoot = resolve(process.env.BACKUP_DIR || join(dirname(this.storageRoot), 'backups'));
@@ -100,6 +127,7 @@ export class BackupService {
}
async createBackup(user: AuthUser, mode = 'BACKUP') {
this.assertModelCoverage();
const stamp = dayjs().format('YYYYMMDDHHmmss');
const fileName = `artveris-${mode.toLowerCase()}-${stamp}.zip`;
const filePath = join(this.backupRoot, fileName);
@@ -206,11 +234,35 @@ export class BackupService {
private async dumpDatabase() {
const db: Record<string, unknown[]> = {};
for (const model of MODELS) {
db[model] = await (this.prisma as any)[model].findMany();
db[model] = model === 'systemSetting' ? await this.dumpEffectiveSettings() : await (this.prisma as any)[model].findMany();
}
return db;
}
private assertModelCoverage(): void {
const expected = new Set<string>(Object.values(Prisma.ModelName).filter((model) => !EXCLUDED_PRISMA_MODELS.has(model)));
const covered = new Set<string>(Object.values(PRISMA_MODEL_BY_DELEGATE));
const missing = [...expected].filter((model) => !covered.has(model));
const stale = [...covered].filter((model) => !expected.has(model));
if (missing.length || stale.length) {
throw new Error(`备份模型清单不完整:missing=${missing.join(',') || '-'}; stale=${stale.join(',') || '-'}`);
}
}
private async dumpEffectiveSettings() {
const rows = await this.prisma.systemSetting.findMany();
const byKey = new Map(rows.map((row) => [row.key, row]));
const all = await this.settings.getAll();
let nextId = rows.reduce((max, row) => Math.max(max, row.id), 0) + 1;
const now = new Date();
for (const [key, value] of Object.entries(all)) {
if (!byKey.has(key)) {
byKey.set(key, { id: nextId++, key, value: String(value), updatedAt: now });
}
}
return [...byKey.values()];
}
private addStorageFiles(zip: AdmZip) {
const files: string[] = [];
if (!existsSync(this.storageRoot)) return files;
@@ -218,6 +270,7 @@ export class BackupService {
for (const name of readdirSync(dir)) {
const full = join(dir, name);
const st = statSync(full);
if (isSameOrChildPath(this.backupRoot, full)) continue;
if (st.isDirectory()) {
walk(full);
} else {
@@ -248,8 +301,12 @@ export class BackupService {
}
private restoreStorage(zip: AdmZip) {
if (existsSync(this.storageRoot)) rmSync(this.storageRoot, { recursive: true, force: true });
mkdirSync(this.storageRoot, { recursive: true });
for (const name of readdirSync(this.storageRoot)) {
const full = join(this.storageRoot, name);
if (isSameOrChildPath(this.backupRoot, full)) continue;
rmSync(full, { recursive: true, force: true });
}
for (const entry of zip.getEntries()) {
if (entry.isDirectory || !entry.entryName.startsWith('storage/')) continue;
const rel = entry.entryName.slice('storage/'.length);