All files / src/routes configExport.js

0% Statements 0/59
0% Branches 0/26
0% Functions 0/5
0% Lines 0/58

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                                                                                                                                                                                                                                                                                                                                                                                                                                         
/**
 * Routes Import/Export — Sauvegarde et restauration de la configuration.
 *
 * Endpoints :
 *   GET  /config/export          — Exporter la config en JSON chiffre
 *   POST /config/import          — Importer une config depuis un JSON chiffre
 *   GET  /config/export/preview  — Apercu de ce qui sera exporte (sans donnees)
 *
 * Securite :
 *   - Export chiffre avec AES-256-GCM + mot de passe utilisateur
 *   - Les cles SSH privees sont re-chiffrees avec le mot de passe d'export
 *   - Les tokens et sessions ne sont JAMAIS exportes
 *   - Validation stricte du JSON a l'import
 *
 * @module routes/configExport
 */
 
const express = require('express');
const crypto = require('node:crypto');
const { pool: db } = require('../db');
const { requireAuth } = require('../middleware/auth');
const { requireFeature } = require('../middleware/planLimits');
 
const router = express.Router();
 
router.use(requireAuth);
 
const EXPORT_VERSION = 1;
 
/**
 * Chiffre une chaine avec AES-256-GCM + mot de passe.
 * @param {string} plaintext
 * @param {string} password
 * @returns {string} — iv:tag:ciphertext (hex)
 */
function encryptWithPassword(plaintext, password) {
  const salt = crypto.randomBytes(16);
  const key = crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256');
  const iv = crypto.randomBytes(12);
  const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
  const encrypted = Buffer.concat([cipher.update(plaintext, 'utf-8'), cipher.final()]);
  const tag = cipher.getAuthTag();
  return `${salt.toString('hex')}:${iv.toString('hex')}:${tag.toString('hex')}:${encrypted.toString('hex')}`;
}
 
/**
 * Dechiffre une chaine chiffree avec AES-256-GCM + mot de passe.
 * @param {string} ciphertext — salt:iv:tag:encrypted (hex)
 * @param {string} password
 * @returns {string}
 */
function decryptWithPassword(ciphertext, password) {
  const parts = ciphertext.split(':');
  if (parts.length !== 4) throw new Error('Format de chiffrement invalide.');
  const [saltHex, ivHex, tagHex, encHex] = parts;
  const salt = Buffer.from(saltHex, 'hex');
  const key = crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256');
  const iv = Buffer.from(ivHex, 'hex');
  const tag = Buffer.from(tagHex, 'hex');
  const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
  decipher.setAuthTag(tag);
  const decrypted = Buffer.concat([decipher.update(Buffer.from(encHex, 'hex')), decipher.final()]);
  return decrypted.toString('utf-8');
}
 
// ─── GET /config/export/preview — Apercu ────────────────────────────────────
 
router.get('/export/preview', async (req, res, next) => {
  try {
    const userId = req.user.id;
 
    const [servers, sshKeys, apiKeys, logPaths, quickActions, uptimeMonitors,
      alertRules, webhooks, statusPages, backupSchedules] = await Promise.all([
      db.query('SELECT COUNT(*) FROM servers WHERE user_id = $1', [userId]),
      db.query('SELECT COUNT(*) FROM ssh_keys WHERE user_id = $1', [userId]),
      db.query('SELECT COUNT(*) FROM api_keys WHERE user_id = $1', [userId]),
      db.query('SELECT COUNT(*) FROM log_paths lp JOIN servers s ON s.id = lp.server_id WHERE s.user_id = $1', [userId]),
      db.query('SELECT COUNT(*) FROM quick_actions qa JOIN servers s ON s.id = qa.server_id WHERE s.user_id = $1', [userId]),
      db.query('SELECT COUNT(*) FROM uptime_monitors WHERE user_id = $1', [userId]),
      db.query('SELECT COUNT(*) FROM alert_rules WHERE user_id = $1', [userId]),
      db.query('SELECT COUNT(*) FROM webhooks WHERE user_id = $1', [userId]),
      db.query('SELECT COUNT(*) FROM status_pages WHERE user_id = $1', [userId]),
      db.query('SELECT COUNT(*) FROM backup_schedules WHERE user_id = $1', [userId]),
    ]);
 
    res.json({
      servers: Number.parseInt(servers.rows[0].count),
      ssh_keys: Number.parseInt(sshKeys.rows[0].count),
      api_keys: Number.parseInt(apiKeys.rows[0].count),
      log_paths: Number.parseInt(logPaths.rows[0].count),
      quick_actions: Number.parseInt(quickActions.rows[0].count),
      uptime_monitors: Number.parseInt(uptimeMonitors.rows[0].count),
      alert_rules: Number.parseInt(alertRules.rows[0].count),
      webhooks: Number.parseInt(webhooks.rows[0].count),
      status_pages: Number.parseInt(statusPages.rows[0].count),
      backup_schedules: Number.parseInt(backupSchedules.rows[0].count),
    });
  } catch (err) {
    next(err);
  }
});
 
// ─── GET /config/export ─────────────────────────────────────────────────────
 
router.get('/export', requireFeature('export_config'), async (req, res, next) => {
  try {
    const { password } = req.query;
    if (!password || password.length < 8) {
      return res.status(400).json({ error: 'Mot de passe requis (min 8 caracteres).' });
    }
 
    const userId = req.user.id;
 
    // Collecter toutes les configs
    const [servers, sshKeys, apiKeys, logPaths, quickActions,
      uptimeMonitors, alertRules, webhooks, statusPages,
      statusPageMonitors, backupSchedules, sslCerts] = await Promise.all([
      db.query('SELECT name, host, port, ssh_user FROM servers WHERE user_id = $1 ORDER BY created_at', [userId]),
      db.query('SELECT name, encrypted_private_key, passphrase_encrypted FROM ssh_keys WHERE user_id = $1 ORDER BY created_at', [userId]),
      db.query('SELECT provider, encrypted_key, default_model FROM api_keys WHERE user_id = $1', [userId]),
      db.query('SELECT lp.label, lp.path, lp.type, s.name AS server_name FROM log_paths lp JOIN servers s ON s.id = lp.server_id WHERE s.user_id = $1', [userId]),
      db.query('SELECT qa.label, qa.command, qa.requires_confirm, qa.sort_order, s.name AS server_name FROM quick_actions qa JOIN servers s ON s.id = qa.server_id WHERE s.user_id = $1', [userId]),
      db.query('SELECT url, label, interval_s, enabled FROM uptime_monitors WHERE user_id = $1', [userId]),
      db.query('SELECT ar.metric, ar.threshold, ar.enabled, s.name AS server_name FROM alert_rules ar JOIN servers s ON s.id = ar.server_id WHERE ar.user_id = $1', [userId]),
      db.query('SELECT label, url, platform, events, enabled FROM webhooks WHERE user_id = $1', [userId]),
      db.query('SELECT slug, title, description, logo_url, accent_color, bg_color, text_color, show_uptime, show_latency, enabled FROM status_pages WHERE user_id = $1', [userId]),
      db.query(`SELECT spm.label, spm.sort_order, um.url AS monitor_url, sp.slug AS page_slug
        FROM status_page_monitors spm
        JOIN status_pages sp ON sp.id = spm.status_page_id
        JOIN uptime_monitors um ON um.id = spm.monitor_id
        WHERE sp.user_id = $1`, [userId]),
      db.query(`SELECT bs.db_type, bs.db_name, bs.db_user, bs.db_container, bs.frequency, bs.retention, bs.enabled, s.name AS server_name
        FROM backup_schedules bs JOIN servers s ON s.id = bs.server_id WHERE bs.user_id = $1`, [userId]),
      db.query('SELECT domain, port, alert_days, enabled FROM ssl_certificates WHERE user_id = $1', [userId]),
    ]);
 
    const config = {
      version: EXPORT_VERSION,
      exported_at: new Date().toISOString(),
      email: req.user.email,
      servers: servers.rows,
      ssh_keys: sshKeys.rows,
      api_keys: apiKeys.rows,
      log_paths: logPaths.rows,
      quick_actions: quickActions.rows,
      uptime_monitors: uptimeMonitors.rows,
      alert_rules: alertRules.rows,
      webhooks: webhooks.rows,
      status_pages: statusPages.rows,
      status_page_monitors: statusPageMonitors.rows,
      backup_schedules: backupSchedules.rows,
      ssl_certificates: sslCerts.rows,
    };
 
    const encrypted = encryptWithPassword(JSON.stringify(config), password);
 
    res.json({
      format: 'iliacloud-config-v1',
      encrypted,
    });
  } catch (err) {
    next(err);
  }
});
 
// ─── POST /config/import ────────────────────────────────────────────────────
 
router.post('/import', requireFeature('export_config'), async (req, res, next) => {
  try {
    const { encrypted, password } = req.body;
 
    if (!encrypted || !password) {
      return res.status(400).json({ error: 'Donnees chiffrees et mot de passe requis.' });
    }
 
    // Dechiffrer
    let config;
    try {
      const decrypted = decryptWithPassword(encrypted, password);
      config = JSON.parse(decrypted);
    } catch {
      return res.status(400).json({ error: 'Mot de passe incorrect ou donnees corrompues.' });
    }
 
    // Valider la version
    if (config.version !== EXPORT_VERSION) {
      return res.status(400).json({ error: `Version incompatible (attendu: ${EXPORT_VERSION}, recu: ${config.version}).` });
    }
 
    // Compter ce qui sera importe
    const preview = {
      servers: config.servers?.length || 0,
      ssh_keys: config.ssh_keys?.length || 0,
      api_keys: config.api_keys?.length || 0,
      uptime_monitors: config.uptime_monitors?.length || 0,
      webhooks: config.webhooks?.length || 0,
      ssl_certificates: config.ssl_certificates?.length || 0,
      status_pages: config.status_pages?.length || 0,
    };
 
    res.json({
      valid: true,
      exported_at: config.exported_at,
      email: config.email,
      preview,
    });
  } catch (err) {
    next(err);
  }
});
 
module.exports = router;