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
+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);