All files / src/routes admin-backup.js

98.38% Statements 183/186
92.85% Branches 78/84
100% Functions 15/15
98.83% Lines 169/171

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355                      1x 1x 1x 1x 1x 1x   1x                   115x 115x   29x 29x         86x 86x 86x   86x       1x     1x 6x 6x     5x 4x   4x   6x 6x 6x   5x 4x   5x 5x       4x 4x 1x   4x 4x 4x 4x 2x         4x     4x   1x 1x         1x 3x 3x   2x 1x           1x 1x         1x   1x 1x   10x     1x 8x 8x   7x 7x 1x       1x   6x 1x       1x   5x     5x 5x   3x 2x   1x     2x 2x   1x         1x         1x 6x 6x   5x 1x       1x   4x   4x 4x   3x 2x   1x     1x 1x   1x       1x           30x 555x 30x 29x 555x 29x   30x 30x 58x 58x 57x 57x   30x         54x 54x 81x 81x 81x 81x 54x 54x     54x         111x 111x   111x 27x 27x       84x       84x 84x       1x 12x 12x   11x 11x 1x   10x   10x 1x         9x 1x     8x         8x       8x     7x   7x   7x 111x 111x 84x       7x             1x       1x           17x 17x   17x 16x 9x 9x 8x 8x 8x       16x 16x 7x 7x 6x 5x 5x   16x       1x 10x 10x   9x 9x   9x 17x     8x   1x 1x       1x  
/**
 * Admin backup routes — R2-based full database backups.
 *
 * GET  /api/admin/backups                   → List available backups (with manifest data)
 * POST /api/admin/backups/trigger           → Trigger immediate full backup
 * GET  /api/admin/backups/:date/:collection → Download a specific collection's backup
 * GET  /api/admin/backups/:date             → Download legacy users backup by date
 * POST /api/admin/backups/restore/:date     → Restore from backup (full/collection/missing-only)
 * POST /api/admin/backups/recover-photos    → Scan R2 and restore missing photo URLs
 */
 
const router = require('express').Router();
const { db } = require('../utils/firebase');
const { requireAdmin } = require('../middleware/auth');
const r2 = require('../utils/r2');
const backupFn = require('../cron/backups');
const log = require('../utils/log');
 
const listObjectsWithMeta = r2.listObjectsWithMetadata;
 
// ─── Helpers ─────────────────────────────────────────────────────
 
/**
 * Read and parse a JSON file from R2.
 * Returns the parsed object, or throws if not found.
 */
async function readR2Json(key) {
  let obj;
  try {
    obj = await r2.getObject(key);
  } catch (err) {
    Eif (err.name === 'NoSuchKey' || err.$metadata?.httpStatusCode === 404) {
      return null;
    }
    throw err;
  }
 
  const chunks = [];
  for await (const chunk of obj.Body) {
    chunks.push(chunk);
  }
  return JSON.parse(Buffer.concat(chunks).toString('utf-8'));
}
 
// All collections that can be restored (matches backups.js)
const RESTORABLE_COLLECTIONS = backupFn.TOP_LEVEL_COLLECTIONS;
 
// ── List available backups (full backup dates with manifests) ──
router.get('/admin/backups', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    // List all manifest files under backups/full/
    const objects = await listObjectsWithMeta('backups/full/');
    const dateMap = {};
 
    for (const obj of objects) {
      // Extract date from key: backups/full/YYYY-MM-DD/filename.json
      const parts = obj.key.replace('backups/full/', '').split('/');
      const date = parts[0];
      if (!date || !/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;
 
      if (!dateMap[date]) {
        dateMap[date] = { date, files: [], totalSize: 0, manifest: null };
      }
      dateMap[date].files.push(obj.key);
      dateMap[date].totalSize += obj.size || 0;
    }
 
    // Try to load manifest for each date
    const backups = [];
    for (const date of Object.keys(dateMap)
      .sort((a, b) => a.localeCompare(b))
      .reverse()) {
      const entry = dateMap[date];
      try {
        const manifest = await readR2Json(`backups/full/${date}/manifest.json`);
        if (manifest) {
          entry.manifest = manifest;
        }
      } catch {
        // Manifest might not exist for older backups
      }
      backups.push(entry);
    }
 
    res.json({ backups });
  } catch (err) {
    log.error('admin-backup', 'Error listing backups', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Trigger immediate full backup ──
router.post('/admin/backups/trigger', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    const result = await backupFn();
    res.json({
      message: 'Full backup completed',
      date: result.date,
      manifest: result.manifest,
    });
  } catch (err) {
    log.error('admin-backup', 'Error triggering backup', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Download a specific collection's backup ──
const BACKUP_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
// Derived from backups.js TOP_LEVEL_COLLECTIONS + subcollection backup names
const { TOP_LEVEL_COLLECTIONS, SUBCOLLECTIONS } = require('../cron/backups');
const ALLOWED_BACKUP_COLLECTIONS = new Set([
  ...TOP_LEVEL_COLLECTIONS,
  ...SUBCOLLECTIONS.map(([parent, sub]) => `${parent}_${sub}`),
]);
 
router.get('/admin/backups/:date/:collection', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    const { date, collection } = req.params;
    if (!BACKUP_DATE_REGEX.test(date)) {
      log.warn('admin-backup', 'Invalid date format in backup download', {
        date,
        uid: req.auth?.uid,
      });
      return res.status(400).json({ error: 'Invalid date format (expected YYYY-MM-DD)' });
    }
    if (!ALLOWED_BACKUP_COLLECTIONS.has(collection)) {
      log.warn('admin-backup', 'Invalid collection name in backup download', {
        collection,
        uid: req.auth?.uid,
      });
      return res.status(400).json({ error: 'Invalid collection name' });
    }
    const key = `backups/full/${date}/${collection}.json`;
 
    let obj;
    try {
      obj = await r2.getObject(key);
    } catch (err) {
      if (err.name === 'NoSuchKey' || err.$metadata?.httpStatusCode === 404) {
        return res.status(404).json({ error: `No backup found for ${collection} on ${date}` });
      }
      throw err;
    }
 
    res.set('Content-Type', 'application/json');
    obj.Body.pipe(res);
  } catch (err) {
    log.error('admin-backup', 'Error downloading collection backup', {
      date: req.params.date,
      collection: req.params.collection,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ── Download legacy users backup (backwards compat) ──
router.get('/admin/backups/:date', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    if (!BACKUP_DATE_REGEX.test(req.params.date)) {
      log.warn('admin-backup', 'Invalid date format in legacy backup download', {
        date: req.params.date,
        uid: req.auth?.uid,
      });
      return res.status(400).json({ error: 'Invalid date format (expected YYYY-MM-DD)' });
    }
    const key = `backups/users/${req.params.date}.json`;
    let obj;
    try {
      obj = await r2.getObject(key);
    } catch (err) {
      if (err.name === 'NoSuchKey' || err.$metadata?.httpStatusCode === 404) {
        return res.status(404).json({ error: `No backup found for ${req.params.date}` });
      }
      throw err;
    }
 
    res.set('Content-Type', 'application/json');
    obj.Body.pipe(res);
  } catch (err) {
    log.error('admin-backup', 'Error downloading legacy backup', {
      date: req.params.date,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
/** Full or collection restore: wipe then write. */
async function restoreFullCollection(collName, backupDocs) {
  const existingSnap = await db.collection(collName).get();
  const refs = existingSnap.docs.map((d) => d.ref);
  for (let i = 0; i < refs.length; i += 500) {
    const batch = db.batch();
    refs.slice(i, i + 500).forEach((ref) => batch.delete(ref));
    await batch.commit();
  }
  let count = 0;
  for (const backupDoc of backupDocs) {
    const { id, ...data } = backupDoc;
    if (!id) continue;
    await db.collection(collName).doc(id).set(data);
    count++;
  }
  return count;
}
 
/** Missing-only restore: only write docs that don't exist. */
async function restoreMissingOnly(collName, backupDocs) {
  let count = 0;
  for (const backupDoc of backupDocs) {
    const { id, ...data } = backupDoc;
    Iif (!id) continue;
    const existing = await db.collection(collName).doc(id).get();
    if (!existing.exists) {
      await db.collection(collName).doc(id).set(data);
      count++;
    }
  }
  return count;
}
 
/** Restore a single collection from backup. Populates results object. */
async function restoreCollection(date, collName, mode, results) {
  const key = `backups/full/${date}/${collName}.json`;
  const backupDocs = await readR2Json(key);
 
  if (backupDocs === null) {
    results[collName] = { status: 'skipped', reason: 'no backup file found' };
    return null;
  }
 
  const restoredCount =
    mode === 'full' || mode === 'collection'
      ? await restoreFullCollection(collName, backupDocs)
      : await restoreMissingOnly(collName, backupDocs);
 
  results[collName] = { status: 'restored', restoredCount, totalInBackup: backupDocs.length };
  return restoredCount;
}
 
// ── Restore from a backup ──
router.post('/admin/backups/restore/:date', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    const { date } = req.params;
    if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
      return res.status(400).json({ error: 'Invalid date format. Use YYYY-MM-DD' });
    }
    const { mode = 'missing-only', collection } = req.body;
 
    if (!['full', 'collection', 'missing-only'].includes(mode)) {
      return res
        .status(400)
        .json({ error: 'Invalid mode. Use: full, collection, or missing-only' });
    }
 
    if (mode === 'collection' && !collection) {
      return res.status(400).json({ error: 'collection is required when mode is "collection"' });
    }
 
    Iif (collection && !RESTORABLE_COLLECTIONS.includes(collection)) {
      return res.status(400).json({ error: 'Invalid collection name' });
    }
 
    // Auto-create a fresh backup before any restore
    log.info('admin-backup', 'Creating pre-restore backup', {
      date: req.params.date,
      mode: req.body.mode || 'missing-only',
    });
    await backupFn();
 
    // Determine which collections to restore
    const collectionsToRestore = mode === 'collection' ? [collection] : [...RESTORABLE_COLLECTIONS];
 
    const results = {};
 
    for (const collName of collectionsToRestore) {
      const restoredCount = await restoreCollection(date, collName, mode, results);
      if (restoredCount !== null) {
        results[collName].restoredCount = restoredCount;
      }
    }
 
    res.json({
      message: `Restore completed (mode: ${mode})`,
      mode,
      date,
      results,
    });
  } catch (err) {
    log.error('admin-backup', 'Error restoring from backup', {
      date: req.params.date,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
/** Scan an R2 folder and restore missing photo URLs to user docs. */
async function recoverPhotosFromFolder(folder, CDN_URL) {
  const field = folder === 'profiles/' ? 'profilePhotoUrl' : 'coverPhotoUrl';
  const userPhotos = {};
 
  const objects = await listObjectsWithMeta(folder);
  for (const obj of objects) {
    const parts = obj.key.split('/');
    if (parts.length < 3) continue;
    const uid = parts[1];
    Eif (!userPhotos[uid] || (obj.lastModified && obj.lastModified > userPhotos[uid].lastModified)) {
      userPhotos[uid] = { key: obj.key, lastModified: obj.lastModified };
    }
  }
 
  let recovered = 0;
  for (const [uid, photo] of Object.entries(userPhotos)) {
    const snap = await db.doc(`users/${uid}`).get();
    if (!snap.exists) continue;
    if (snap.data()[field]) continue;
    await db.doc(`users/${uid}`).update({ [field]: `${CDN_URL}/${photo.key}` });
    recovered++;
  }
  return recovered;
}
 
// ── Recover profile/cover photos from R2 ──
router.post('/admin/backups/recover-photos', async (req, res) => {
  try {
    if (requireAdmin(req, res)) return;
 
    const CDN_URL = r2.CDN_URL;
    let recovered = 0;
 
    for (const folder of ['profiles/', 'covers/']) {
      recovered += await recoverPhotosFromFolder(folder, CDN_URL);
    }
 
    res.json({ message: `Recovered ${recovered} photo URLs from R2`, recovered });
  } catch (err) {
    log.error('admin-backup', 'Error recovering photos from R2', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;