backup.js

3.5 KB v1.0
// WebDAV 备份与恢复接口
import { Router } from 'express';
import { db } from '../db.js';
import { decrypt } from '../crypto.js';
import { getRawSettings } from '../settings.js';
import { requireAuth } from '../auth.js';
import { WebDavClient } from '../backup/webdav.js';
import { getBackupClient, runBackup } from '../backup/service.js';
import {
  createLocalSafetyBackup,
  restoreSnapshot,
  unpackSnapshot,
} from '../backup/snapshot.js';

const router = Router();
router.use(requireAuth);

// 测试 WebDAV 连通性(支持使用表单中尚未保存的配置)
router.post('/test', async (req, res) => {
  try {
    const saved = getRawSettings(req.user.id).backup;
    const url = String(req.body?.webdavUrl || saved.webdavUrl || '').trim();
    const username = String(req.body?.webdavUsername ?? saved.webdavUsername ?? '');
    let password = req.body?.webdavPassword;
    if (typeof password !== 'string' || password === '') {
      password = saved.webdavPasswordEnc ? decrypt(saved.webdavPasswordEnc) : '';
    }
    if (!url) return res.status(400).json({ error: '请填写 WebDAV 地址' });

    const remotePath = String(req.body?.remotePath || saved.remotePath || 'xmail');
    const client = new WebDavClient(url, username, password);
    await client.ensureDir(remotePath);
    const items = await client.list(remotePath);
    res.json({ ok: true, files: items.filter((i) => !i.isCollection).length });
  } catch (err) {
    res.status(502).json({ error: String(err.message || err) });
  }
});

// 立即备份
router.post('/run', async (req, res) => {
  try {
    const result = await runBackup(req.user.id);
    res.json({ ok: true, ...result });
  } catch (err) {
    res.status(502).json({ error: String(err.message || err) });
  }
});

// 列出远程备份文件
router.get('/files', async (req, res) => {
  try {
    const { settings, client } = getBackupClient(req.user.id);
    const remotePath = settings.remotePath || 'xmail';
    await client.ensureDir(remotePath);
    const items = await client.list(remotePath);
    const files = items
      .filter(
        (item) =>
          !item.isCollection && item.name.startsWith('xmail-backup-') && item.name.endsWith('.json.gz')
      )
      .sort((a, b) => (b.lastModified || 0) - (a.lastModified || 0));
    res.json(files);
  } catch (err) {
    res.status(502).json({ error: String(err.message || err) });
  }
});

// 从远程备份恢复
router.post('/restore', async (req, res) => {
  const file = String(req.body?.file || '');
  const mode = req.body?.mode === 'full' ? 'full' : 'config';
  if (!/^xmail-backup-[\w.-]+\.json\.gz$/.test(file)) {
    return res.status(400).json({ error: '备份文件名不合法' });
  }

  try {
    const { settings, client } = getBackupClient(req.user.id);
    const remotePath = settings.remotePath || 'xmail';
    const buffer = await client.get(`${remotePath}/${file}`);
    const snapshot = unpackSnapshot(buffer);
    if (snapshot.user?.username && snapshot.user.username !== req.user.username) {
      return res.status(400).json({ error: '该备份属于其他用户,无法恢复' });
    }

    // 恢复前先做一次本地完整安全备份
    const safetyFile = createLocalSafetyBackup(req.user.id);
    const result = restoreSnapshot(req.user.id, snapshot, mode);
    res.json({
      ok: true,
      mode,
      safetyFile,
      sourceCreatedAt: snapshot.createdAt,
      ...result,
    });
  } catch (err) {
    res.status(502).json({ error: String(err.message || err) });
  }
});

export default router;