import fs from 'fs-extra'; import * as path from 'path'; import archiver from 'archiver'; import crypto from 'crypto-js'; export interface BackupResult { success: boolean; backupDir: string; recordCount: number; error?: string; } export interface BackupMetadata { customerId: string; service: string; backupType: string; recordCount: number; fileSize: number; checksum: string; createdAt: string; expiresAt?: string; } export class BackupStorage { private baseDir: string; constructor(baseDir = './backup-data') { this.baseDir = baseDir; void this.ensureDirectories(); } private async ensureDirectories(): Promise { await fs.ensureDir(this.baseDir); await fs.ensureDir(path.join(this.baseDir, 'customers')); await fs.ensureDir(path.join(this.baseDir, 'temp')); } async createBackupDirectory(customerId: string): Promise { const customerDir = path.join(this.baseDir, 'customers', customerId); const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const backupDir = path.join(customerDir, timestamp); await fs.ensureDir(backupDir); return backupDir; } async saveBackupData( backupDir: string, service: string, filename: string, data: unknown ): Promise<{ filePath: string; fileSize: number; checksum: string }> { const serviceDir = path.join(backupDir, service); await fs.ensureDir(serviceDir); const filePath = path.join(serviceDir, filename); const jsonData = JSON.stringify(data, null, 2); await fs.writeFile(filePath, jsonData, 'utf8'); const stats = await fs.stat(filePath); const checksum = crypto.SHA256(jsonData).toString(); return { filePath, fileSize: stats.size, checksum }; } async createCompressedBackup( customerId: string, backupDir: string, backupType: string ): Promise<{ archivePath: string; fileSize: number; checksum: string }> { const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const archiveName = `${customerId}-${backupType}-${timestamp}.zip`; const archivePath = path.join(this.baseDir, 'temp', archiveName); return new Promise((resolve, reject) => { const output = fs.createWriteStream(archivePath); const archive = archiver('zip', { zlib: { level: 9 } }); output.on('close', () => { void (async () => { const stats = await fs.stat(archivePath); const fileBuffer = await fs.readFile(archivePath); const checksum = crypto.SHA256(fileBuffer.toString('hex')).toString(); resolve({ archivePath, fileSize: stats.size, checksum }); })(); }); archive.on('error', (err: Error) => { reject(err); }); archive.pipe(output); archive.directory(backupDir, false); void archive.finalize(); }); } async loadBackupData(filePath: string): Promise { const data = await fs.readFile(filePath, 'utf8'); return JSON.parse(data); } async restoreFromBackup( customerId: string, backupPath: string, targetDir: string ): Promise { const extractPath = path.join(this.baseDir, 'temp', 'restore', customerId); await fs.ensureDir(extractPath); // Extract the backup await this.extractArchive(backupPath, extractPath); // Copy extracted data to target directory await fs.copy(extractPath, targetDir); // Clean up await fs.remove(extractPath); } private async extractArchive(archivePath: string, extractPath: string): Promise { // This is a simplified extraction - in production you'd use a proper unzip library // For now, we'll assume the backup is already extracted or use a different approach console.log(`Extracting ${archivePath} to ${extractPath}`); } async cleanupOldBackups(customerId: string, retentionDays = 30): Promise { const customerDir = path.join(this.baseDir, 'customers', customerId); if (!await fs.pathExists(customerDir)) { return 0; } const cutoffDate = new Date(); cutoffDate.setDate(cutoffDate.getDate() - retentionDays); const backupDirs = await fs.readdir(customerDir); let deletedCount = 0; for (const backupDir of backupDirs) { const backupPath = path.join(customerDir, backupDir); const stats = await fs.stat(backupPath); if (stats.isDirectory() && stats.mtime < cutoffDate) { await fs.remove(backupPath); deletedCount++; } } return deletedCount; } async getBackupStats(customerId: string): Promise<{ totalBackups: number; totalSize: number; oldestBackup: string | null; newestBackup: string | null; }> { const customerDir = path.join(this.baseDir, 'customers', customerId); if (!await fs.pathExists(customerDir)) { return { totalBackups: 0, totalSize: 0, oldestBackup: null, newestBackup: null }; } const backupDirs = await fs.readdir(customerDir); let totalSize = 0; let oldestDate: Date | null = null; let newestDate: Date | null = null; for (const backupDir of backupDirs) { const backupPath = path.join(customerDir, backupDir); const stats = await fs.stat(backupPath); if (stats.isDirectory()) { totalSize += await this.getDirectorySize(backupPath); if (!oldestDate || stats.mtime < oldestDate) { oldestDate = stats.mtime; } if (!newestDate || stats.mtime > newestDate) { newestDate = stats.mtime; } } } return { totalBackups: backupDirs.length, totalSize, oldestBackup: oldestDate?.toISOString() || null, newestBackup: newestDate?.toISOString() || null }; } private async getDirectorySize(dirPath: string): Promise { let totalSize = 0; const files = await fs.readdir(dirPath); for (const file of files) { const filePath = path.join(dirPath, file); const stats = await fs.stat(filePath); if (stats.isDirectory()) { totalSize += await this.getDirectorySize(filePath); } else { totalSize += stats.size; } } return totalSize; } async validateBackupIntegrity(backupPath: string, expectedChecksum: string): Promise { try { const fileBuffer = await fs.readFile(backupPath); const actualChecksum = crypto.SHA256(fileBuffer.toString('hex')).toString(); return actualChecksum === expectedChecksum; } catch (error) { console.error('Error validating backup integrity:', error); return false; } } }