Files
DC_CMS/server/site-backup.mjs
DCCONSTRUCTIONS 5ea737318b
DC CMS qualification / qualify (push) Successful in 1m57s
feat(cms): download portable backups from site settings
2026-11-05 22:37:55 +03:00

102 lines
6.4 KiB
JavaScript

import { constants } from 'node:fs';
import { lstat, mkdtemp, open, readdir, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { crc32 } from 'node:zlib';
const excluded = new Set(['.git', '.cms-backups', '.trash', 'node_modules', '.DS_Store', '__MACOSX']);
const skip = name => excluded.has(name) || name.startsWith('._') || name === '.env' || name.startsWith('.env.') || name.endsWith('.secrets.json');
const fail = (message, status = 409) => Object.assign(new Error(message), { status });
const signature = s => `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;
const MAX_BYTES = 2 * 1024 ** 3;
// STORE is intentional: site media is already compressed. Write in bounded
// chunks rather than loading hundreds of MB into the CMS process or blocking it.
export async function createSiteBackup(root, { required = [], signal } = {}) {
async function scan(directory = root, prefix = '') {
signal?.throwIfAborted();
const directoryStat = await lstat(directory);
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) throw fail('Бэкап сайта с символическими ссылками не поддерживается');
const result = [];
for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name, 'en'))) {
if (skip(entry.name)) continue;
const path = join(directory, entry.name), name = prefix + entry.name;
if (entry.name.includes('\\') || Buffer.byteLength(name) > 65535) throw fail('Недопустимый путь в сайте');
if (entry.isSymbolicLink()) throw fail('Бэкап сайта с символическими ссылками не поддерживается');
if (entry.isDirectory()) result.push(...await scan(path, name + '/'));
else if (entry.isFile()) {
const info = await lstat(path, { bigint: true });
result.push({ name, path, size: Number(info.size), stamp: signature(info), modified: new Date(Number(info.mtimeMs)) });
} else throw fail('Бэкап поддерживает только обычные файлы и папки');
}
return result;
}
const files = await scan();
if (!files.length || files.length > 60000 || files.reduce((n, f) => n + f.size, 0) > MAX_BYTES) throw fail('Бэкап поддерживает сайты до 2 ГБ и 60 000 файлов', 413);
if (required.some(name => !files.some(file => file.name === name))) throw fail('Сайт неполный: отсутствуют файлы для восстановления');
const temp = await mkdtemp(join(tmpdir(), 'dc-cms-backup-'));
const cleanup = () => rm(temp, { recursive: true, force: true });
const path = join(temp, 'site.zip');
let output;
try {
output = await open(path, 'wx', 0o600);
let offset = 0;
const directory = [];
async function write(data, position = offset) {
let written = 0;
while (written < data.length) {
signal?.throwIfAborted();
const result = await output.write(data, written, data.length - written, position + written);
if (!result.bytesWritten) throw fail('Не удалось записать бэкап', 500);
written += result.bytesWritten;
}
offset = Math.max(offset, position + written);
}
for (const file of files) {
signal?.throwIfAborted();
const input = await open(file.path, constants.O_RDONLY | constants.O_NOFOLLOW);
try {
if (signature(await input.stat({ bigint: true })) !== file.stamp) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
const name = Buffer.from(file.name), start = offset, date = file.modified;
const dosTime = (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1);
const dosDate = ((Math.min(2107, Math.max(1980, date.getFullYear())) - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
const header = Buffer.alloc(30);
header.writeUInt32LE(0x04034b50, 0); header.writeUInt16LE(20, 4); header.writeUInt16LE(0x800, 6);
header.writeUInt16LE(dosTime, 10); header.writeUInt16LE(dosDate, 12);
header.writeUInt32LE(file.size, 18); header.writeUInt32LE(file.size, 22); header.writeUInt16LE(name.length, 26);
await write(header); await write(name);
let checksum = 0, bytes = 0;
for await (const chunk of input.createReadStream({ autoClose: false, highWaterMark: 256 * 1024 })) {
bytes += chunk.length;
if (bytes > file.size) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
checksum = crc32(chunk, checksum); await write(chunk);
}
if (bytes !== file.size || signature(await input.stat({ bigint: true })) !== file.stamp) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
header.writeUInt32LE(checksum, 14); await write(header, start);
const central = Buffer.alloc(46);
central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6);
header.copy(central, 8, 6, 28); central.writeUInt32LE(start, 42);
directory.push(central, name);
} finally { await input.close(); }
}
const after = await scan();
if (JSON.stringify(after.map(f => [f.name, f.stamp])) !== JSON.stringify(files.map(f => [f.name, f.stamp]))) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
const directoryStart = offset;
for (const data of directory) await write(data);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(offset - directoryStart, 12); end.writeUInt32LE(directoryStart, 16);
await write(end);
await output.close(); output = null;
return { path, size: offset, files: files.length, cleanup };
} catch (error) {
await output?.close(); await cleanup(); throw error;
}
}
export function siteBackupFilename(projectId, now = new Date()) {
const date = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Moscow', year: 'numeric', month: '2-digit', day: '2-digit' }).format(now);
const id = String(projectId).replace(/[^a-zA-Z0-9-]/g, '').replace(/-/g, '_').toUpperCase() || 'SITE';
return `NODEDC_SITE_${date}_${id}_TECH.zip`;
}