fix(restore): survive large backups, disk-full and proxy limits

- extract restore helpers into lib/restore.js (space check, tar entry
  filter, temp dir sweep)
- reject tar entries outside staging and symlinks/hardlinks
- map ENOSPC/EQUOT to 507 with clear messages, keep data_restored flag
  when files fail after commit
- raise request timeout using BACKUP_UPLOAD_LIMIT_MB and expose
  backup_upload_limit_mb via public settings
- upload restore archive via XHR with progress, size pre-check and
  readable server errors in settings UI
- document large-archive restore on a remote server
This commit is contained in:
dev
2026-10-21 17:58:46 +03:00
parent d33bf62a7d
commit 19f63a4064
6 changed files with 257 additions and 54 deletions
+100 -30
View File
@@ -35,6 +35,7 @@ const {
restoredCounts,
isSupportedBackupVersion,
} = require('./backup-restore');
const { assertRestoreSpace, isDiskFullError, tarEntryFilter, sweepRestoreTempDirs } = require('./lib/restore');
const https = require('https');
const path = require('path');
@@ -5284,6 +5285,7 @@ app.get('/api/public-settings', apiLimiter, async (_, res) => {
out.photo_ai_enabled = PHOTO_AI_URL ? 'true' : 'false';
out.upload_file_limit_mb = String(UPLOAD_FILE_LIMIT_MB);
out.upload_total_limit_mb = String(UPLOAD_TOTAL_LIMIT_MB);
out.backup_upload_limit_mb = String(BACKUP_UPLOAD_LIMIT_MB);
res.json(out);
});
@@ -5879,13 +5881,14 @@ async function aiCorrectText(text, profileOverride) {
}
}
const BACKUP_UPLOAD_LIMIT_MB = parseInt(process.env.BACKUP_UPLOAD_LIMIT_MB || '500', 10);
const BACKUP_UPLOAD_LIMIT_MB = Math.max(1, parseInt(process.env.BACKUP_UPLOAD_LIMIT_MB || '500', 10) || 500);
const BACKUP_ARCHIVE_EXT = /\.(?:tar\.gz|tgz|gz)$/i;
const uploadBackup = multer({
storage: multer.diskStorage({
destination: (_, __, cb) => {
destination: (req, __, cb) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-up-'));
req._uploadDir = dir;
cb(null, dir);
},
filename: (_, file, cb) => {
@@ -6084,7 +6087,8 @@ setInterval(() => { pruneBackupTickets(); sweepBackupStorage(); }, 60 * 1000).un
function cleanupUpload(req) {
try {
if (req?.file?.destination) fs.rmSync(req.file.destination, { recursive: true, force: true });
const dir = req?.file?.destination || req?._uploadDir;
if (dir) fs.rmSync(dir, { recursive: true, force: true });
} catch {}
}
@@ -6114,8 +6118,9 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
if (!req.file) return res.status(400).json({ error: 'backup file required' });
let data;
let legacyPhotos = [];
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-rst-'));
let staging;
try {
staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-rst-'));
const head = await peekGunzip(req.file.path, 8);
if (head && head[0] === 0x7b) {
const buf = await fs.promises.readFile(req.file.path);
@@ -6123,18 +6128,31 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
data = JSON.parse(gunz.toString('utf8'));
legacyPhotos = data.photos || [];
} else {
await tar.x({ file: req.file.path, cwd: staging });
assertRestoreSpace(staging, req.file.size);
await tar.x({ file: req.file.path, cwd: staging, filter: tarEntryFilter(staging) });
if (!fs.existsSync(path.join(staging, 'data.json')) && fs.existsSync(path.join(staging, 'db.sql.gz'))) {
fs.rmSync(staging, { recursive: true, force: true });
cleanupUpload(req);
return res.status(400).json({ error: 'Это архив скрипта scripts/backup.sh (db.sql.gz + _uploads) — восстанавливайте его через scripts/restore.sh. Для веб-восстановления скачайте архив в Настройках админки.' });
}
if (!fs.existsSync(path.join(staging, 'data.json'))) {
fs.rmSync(staging, { recursive: true, force: true });
cleanupUpload(req);
return res.status(400).json({ error: 'В архиве нет data.json — это не архив веб-бэкапа из админки.' });
}
data = JSON.parse(fs.readFileSync(path.join(staging, 'data.json'), 'utf8'));
}
} catch {
fs.rmSync(staging, { recursive: true, force: true });
} catch (e) {
if (staging) fs.rmSync(staging, { recursive: true, force: true });
cleanupUpload(req);
return res.status(400).json({ error: 'Неверный файл бэкапа' });
console.error('Restore unpack failed:', e);
if (e && e.code === 'RESTORE_NO_SPACE') {
return res.status(507).json({ error: e.message + '. Освободите место на сервере и повторите восстановление.' });
}
if (isDiskFullError(e)) {
return res.status(507).json({ error: 'Не хватает свободного места на сервере для распаковки архива. Освободите место и повторите восстановление.' });
}
return res.status(400).json({ error: 'Неверный файл бэкапа: архив повреждён или скачался не полностью' });
}
const formatVersion = Number(data && data.version);
if (!isSupportedBackupVersion(data)) {
@@ -6150,7 +6168,15 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
cleanupUpload(req);
return res.status(400).json({ error: 'Неверный формат бэкапа: ' + e.message });
}
const client = await pool.connect();
let client;
try {
client = await pool.connect();
} catch (e) {
fs.rmSync(staging, { recursive: true, force: true });
cleanupUpload(req);
console.error('Restore connect failed:', e);
return res.status(503).json({ error: 'Не удалось подключиться к базе данных: ' + e.message });
}
try {
await client.query('BEGIN');
await client.query('DELETE FROM notification_reads');
@@ -6438,37 +6464,74 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
await client.query('ROLLBACK').catch(() => {});
fs.rmSync(staging, { recursive: true, force: true });
cleanupUpload(req);
console.error('Restore failed:', e.message);
console.error('Restore failed:', e);
if (isDiskFullError(e)) {
return res.status(507).json({ error: 'Не хватает свободного места для записи данных (база данных или диск сервера). Освободите место и повторите восстановление.' });
}
return res.status(500).json({ error: 'Ошибка восстановления: ' + e.message });
} finally {
client.release();
}
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
if (legacyPhotos.length) {
for (const p of legacyPhotos) {
if (!p.path || !SAFE_NAME.test(p.path)) continue;
await storage.put(p.path, Buffer.from(p.data, 'base64'));
try {
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
if (legacyPhotos.length) {
for (const p of legacyPhotos) {
if (!p.path || !SAFE_NAME.test(p.path)) continue;
await storage.put(p.path, Buffer.from(p.data, 'base64'));
}
} else {
await storage.uploadTree(path.join(staging, 'uploads'));
}
} else {
await storage.uploadTree(path.join(staging, 'uploads'));
} catch (e) {
fs.rmSync(staging, { recursive: true, force: true });
cleanupUpload(req);
console.error('Restore files failed:', e);
const reason = isDiskFullError(e)
? 'на сервере закончилось свободное место'
: e.message;
return res.status(500).json({
error: `Данные в базе восстановлены, но файлы из архива загрузить не удалось: ${reason}. Устраните причину и повторите восстановление тем же архивом.`,
data_restored: true,
});
}
fs.rmSync(staging, { recursive: true, force: true });
cleanupUpload(req);
await sweepOrphanedUploads().catch(err => console.error('Upload sweep:', err));
await loadBans().catch(err => console.error('Bans reload:', err));
await ensureFirstAdmin().catch(err => console.error('First admin:', err));
await logAudit(req, 'backup.restore', { format_version: formatVersion });
await pushNotification({
type: 'backup.restore',
title: 'Восстановление из бэкапа завершено',
body: `Данные заменены архивом · пользователь ${req.user.username}`,
link: 'settings.html',
adminOnly: true,
});
try {
await sweepOrphanedUploads().catch(err => console.error('Upload sweep:', err));
await loadBans().catch(err => console.error('Bans reload:', err));
await ensureFirstAdmin().catch(err => console.error('First admin:', err));
await logAudit(req, 'backup.restore', { format_version: formatVersion });
await pushNotification({
type: 'backup.restore',
title: 'Восстановление из бэкапа завершено',
body: `Данные заменены архивом · пользователь ${req.user.username}`,
link: 'settings.html',
adminOnly: true,
});
} catch (e) {
console.error('Restore post-processing failed:', e);
}
invalidateAll();
res.json({ ok: true, format_version: formatVersion, restored: restoredCounts(ndata) });
});
app.use('/api/restore', (err, req, res, next) => {
cleanupUpload(req);
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({
error: `Архив больше допустимых ${BACKUP_UPLOAD_LIMIT_MB} МБ. Увеличьте BACKUP_UPLOAD_LIMIT_MB или восстанавливайте большой архив на самом сервере, минуя прокси.`,
});
}
return res.status(400).json({ error: 'Не удалось загрузить архив: ' + err.message });
}
if (err && /Not allowed extension/i.test(err.message || '')) {
return res.status(400).json({ error: 'Неверный тип файла: нужен архив .tar.gz, .tgz или .gz' });
}
console.error('Restore upload failed:', err);
next(err);
});
// --- Share links ---
function normDates(o) {
if (o && o.date_from) o.date_from = o.date_from instanceof Date ? o.date_from.toISOString().slice(0, 10) : String(o.date_from).slice(0, 10);
@@ -13106,8 +13169,11 @@ const certPath = path.join(__dirname, 'certs', 'cert.pem');
const keyPath = path.join(__dirname, 'certs', 'key.pem');
function tuneServer(srv) {
srv.requestTimeout = UPLOAD_REQUEST_TIMEOUT_MS;
srv.headersTimeout = UPLOAD_REQUEST_TIMEOUT_MS + 60000;
const explicit = parseInt(process.env.UPLOAD_REQUEST_TIMEOUT_MS || '0', 10);
srv.requestTimeout = explicit
? Math.max(300000, explicit)
: Math.max(UPLOAD_REQUEST_TIMEOUT_MS, BACKUP_UPLOAD_LIMIT_MB * 7500);
srv.headersTimeout = srv.requestTimeout + 60000;
return srv;
}
@@ -13120,6 +13186,10 @@ if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
}
(async () => {
try {
const removed = sweepRestoreTempDirs();
if (removed) console.log('Stale restore temp dirs removed:', removed);
} catch (err) { console.error('Restore temp sweep:', err); }
try { await cache.connect(); } catch (err) { console.error('Redis connect:', err); }
try { await ensureBranchesTable(); } catch (err) { console.error('Branches table:', err); }
try { await ensureUsersAndFirstAdmin(); } catch (err) { console.error('Users table:', err); }