All files / src/routes admin-bans.js

100% Statements 147/147
96.87% Branches 62/64
100% Functions 14/14
100% Lines 140/140

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                        2x 2x 2x     2x 56x 49x   2x   2x 2x 2x                 20x 9x 9x 9x 8x         2x 5x 5x         4x   4x 4x 4x   4x 4x 4x   4x   1x 1x           2x 13x 13x 13x 12x   11x   11x                     10x                     10x 10x 10x 3x 3x 3x   2x 2x       10x   1x 1x           2x 17x 17x   17x 17x 2x   15x 2x 13x     12x 12x 12x 1x   11x 1x   10x 1x     9x 9x   9x                       8x                     8x 8x 8x 3x 3x 3x   2x 2x       8x   1x 1x           2x 2x 2x   1x             1x   1x       1x           2x 2x 2x   1x             1x   1x       1x           2x 7x 7x 7x 7x   7x               6x 6x 6x 24x 20x 5x 5x         6x   6x                 6x 6x 6x   2x 2x     6x           1x       1x           2x 3x 3x 3x 3x   3x               2x 2x 2x 4x 4x 2x 2x         2x 2x 2x 4x 4x 2x 2x         2x   1x       1x       2x  
/**
 * Admin ban routes — device/network ban CRUD, bulk unban.
 *
 * GET    /admin/bans                  → List all active bans
 * POST   /admin/bans/device           → Ban a device
 * POST   /admin/bans/network          → Ban a network (ip/subnet/asn)
 * DELETE /admin/bans/device/:deviceId → Unban device
 * DELETE /admin/bans/network/:banId   → Unban network
 * POST   /admin/bans/unban-all/:uniqueId → Remove all bans for a user
 * GET    /admin/bans/user/:uniqueId     → Get all bans for a user
 */
 
const router = require('express').Router();
const { db } = require('../utils/firebase');
const { requireAdmin } = require('../middleware/auth');
 
// Phase 2H finding #2 dedup: scope admin guard by path prefix.
const _adminGuardWrapper = async (req, res, next) => {
  if (await requireAdmin(req, res)) return;
  next();
};
router.use('/admin/bans', _adminGuardWrapper);
 
const { generateId, now } = require('../utils/helpers');
const { sendSystemPm } = require('../utils/system-pm');
const log = require('../utils/log');
 
// ─── Helpers ─────────────────────────────────────────────────────
 
/**
 * Parse a duration string (e.g. '24h', '7d', '30d', 'permanent') into
 * an ISO-8601 expiry timestamp, or null for permanent bans.
 */
function parseExpiry(duration) {
  if (!duration || duration === 'permanent') return null;
  const units = { h: 3600000, d: 86400000 };
  const match = duration.match(/^(\d+)([hd])$/);
  if (!match) return null;
  return new Date(Date.now() + Number.parseInt(match[1], 10) * units[match[2]]).toISOString();
}
 
// ─── List all active bans ────────────────────────────────────────
 
router.get('/admin/bans', async (req, res) => {
  try {
    const [deviceSnap, networkSnap] = await Promise.all([
      db.collection('deviceBans').get(),
      db.collection('networkBans').get(),
    ]);
 
    const nowMs = Date.now();
 
    const deviceBans = deviceSnap.docs
      .map((d) => ({ id: d.id, ...d.data() }))
      .filter((b) => !b.expiresAt || new Date(b.expiresAt).getTime() > nowMs);
 
    const networkBans = networkSnap.docs
      .map((d) => ({ id: d.id, ...d.data() }))
      .filter((b) => !b.expiresAt || new Date(b.expiresAt).getTime() > nowMs);
 
    res.json({ deviceBans, networkBans });
  } catch (err) {
    log.error('admin-bans', 'Error listing bans', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Ban a device ────────────────────────────────────────────────
 
router.post('/admin/bans/device', async (req, res) => {
  try {
    const { deviceId, reason, duration, linkedUniqueId } = req.body || {};
    if (!deviceId) return res.status(400).json({ error: 'deviceId is required' });
    if (!reason) return res.status(400).json({ error: 'reason is required' });
 
    const expiresAt = parseExpiry(duration);
 
    await db.doc(`deviceBans/${deviceId}`).set({
      deviceId,
      reason,
      duration: duration || 'permanent',
      expiresAt,
      linkedUniqueId: linkedUniqueId || null,
      createdAt: now(),
      createdBy: req.auth.uid,
    });
 
    // Audit log
    await db.doc(`adminAuditLog/${generateId()}`).set({
      adminId: req.auth.uid,
      action: 'BAN_DEVICE',
      targetDeviceId: deviceId,
      details: `Reason: ${reason}, Duration: ${duration || 'permanent'}`,
      createdAt: now(),
    });
 
    // Send system PM if linked to a user (non-blocking). Track failure so
    // the admin UI's PartialFailureToast.buildPartialFailureMessage() can
    // surface it via the standard `pms: { failed, total }` shape.
    let pmFailed = 0;
    let pmTotal = 0;
    if (linkedUniqueId) {
      pmTotal = 1;
      try {
        await sendSystemPm(linkedUniqueId, 'A restriction has been placed on your account.');
      } catch (e) {
        log.warn('system-pm', 'Failed to send', { uniqueId: linkedUniqueId, error: e.message });
        pmFailed = 1;
      }
    }
 
    res.json({ success: true, pms: { failed: pmFailed, total: pmTotal } });
  } catch (err) {
    log.error('admin-bans', 'Error banning device', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Ban a network ───────────────────────────────────────────────
 
router.post('/admin/bans/network', async (req, res) => {
  try {
    const { type, value, reason, duration, linkedUniqueId } = req.body || {};
 
    const validTypes = ['ip', 'subnet', 'asn'];
    if (!type || !validTypes.includes(type)) {
      return res.status(400).json({ error: 'type must be one of: ip, subnet, asn' });
    }
    if (!value || typeof value !== 'string')
      return res.status(400).json({ error: 'value is required' });
    if (!reason) return res.status(400).json({ error: 'reason is required' });
 
    // Validate format based on type
    const IP_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
    const CIDR_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}$/;
    if (type === 'ip' && !IP_REGEX.test(value)) {
      return res.status(400).json({ error: 'Invalid IP address format' });
    }
    if (type === 'subnet' && !CIDR_REGEX.test(value)) {
      return res.status(400).json({ error: 'Invalid CIDR subnet format (e.g. 192.168.0.0/24)' });
    }
    if (type === 'asn' && !/^\d+$/.test(value)) {
      return res.status(400).json({ error: 'ASN must be numeric' });
    }
 
    const banId = generateId();
    const expiresAt = parseExpiry(duration);
 
    await db.doc(`networkBans/${banId}`).set({
      type,
      value,
      reason,
      duration: duration || 'permanent',
      expiresAt,
      linkedUniqueId: linkedUniqueId || null,
      createdAt: now(),
      createdBy: req.auth.uid,
    });
 
    // Audit log
    await db.doc(`adminAuditLog/${generateId()}`).set({
      adminId: req.auth.uid,
      action: 'BAN_NETWORK',
      targetValue: value,
      details: `Type: ${type}, Reason: ${reason}, Duration: ${duration || 'permanent'}`,
      createdAt: now(),
    });
 
    // Send system PM if linked to a user (non-blocking). Track failure so
    // the admin UI's PartialFailureToast.buildPartialFailureMessage() can
    // surface it via the standard `pms: { failed, total }` shape.
    let pmFailed = 0;
    let pmTotal = 0;
    if (linkedUniqueId) {
      pmTotal = 1;
      try {
        await sendSystemPm(linkedUniqueId, 'A restriction has been placed on your account.');
      } catch (e) {
        log.warn('system-pm', 'Failed to send', { uniqueId: linkedUniqueId, error: e.message });
        pmFailed = 1;
      }
    }
 
    res.json({ success: true, pms: { failed: pmFailed, total: pmTotal } });
  } catch (err) {
    log.error('admin-bans', 'Error banning network', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Unban device ────────────────────────────────────────────────
 
router.delete('/admin/bans/device/:deviceId', async (req, res) => {
  try {
    await db.doc(`deviceBans/${req.params.deviceId}`).delete();
 
    await db.doc(`adminAuditLog/${generateId()}`).set({
      adminId: req.auth.uid,
      action: 'UNBAN_DEVICE',
      targetDeviceId: req.params.deviceId,
      createdAt: now(),
    });
 
    res.json({ success: true });
  } catch (err) {
    log.error('admin-bans', 'Error unbanning device', {
      deviceId: req.params.deviceId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Unban network ───────────────────────────────────────────────
 
router.delete('/admin/bans/network/:banId', async (req, res) => {
  try {
    await db.doc(`networkBans/${req.params.banId}`).delete();
 
    await db.doc(`adminAuditLog/${generateId()}`).set({
      adminId: req.auth.uid,
      action: 'UNBAN_NETWORK',
      targetBanId: req.params.banId,
      createdAt: now(),
    });
 
    res.json({ success: true });
  } catch (err) {
    log.error('admin-bans', 'Error unbanning network', {
      banId: req.params.banId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Unban all for user ──────────────────────────────────────────
 
router.post('/admin/bans/unban-all/:uniqueId', async (req, res) => {
  try {
    const uniqueId = req.params.uniqueId;
    const numericId = Number(uniqueId);
    const stringId = String(uniqueId);
 
    const [deviceSnapStr, deviceSnapNum, networkSnapStr, networkSnapNum] = await Promise.all([
      db.collection('deviceBans').where('linkedUniqueId', '==', stringId).get(),
      db.collection('deviceBans').where('linkedUniqueId', '==', numericId).get(),
      db.collection('networkBans').where('linkedUniqueId', '==', stringId).get(),
      db.collection('networkBans').where('linkedUniqueId', '==', numericId).get(),
    ]);
 
    // Deduplicate by doc id in case both queries match the same doc
    const seen = new Set();
    const allDocs = [];
    for (const snap of [deviceSnapStr, deviceSnapNum, networkSnapStr, networkSnapNum]) {
      for (const d of snap.docs) {
        if (!seen.has(d.id)) {
          seen.add(d.id);
          allDocs.push(d);
        }
      }
    }
 
    await Promise.all(allDocs.map((d) => d.ref.delete()));
 
    await db.doc(`adminAuditLog/${generateId()}`).set({
      adminId: req.auth.uid,
      action: 'UNBAN_ALL',
      targetUserId: uniqueId,
      details: `Removed ${allDocs.length} ban(s)`,
      createdAt: now(),
    });
 
    // Send system PM about restriction lifted. Track failure for admin UI.
    let pmFailed = 0;
    try {
      await sendSystemPm(uniqueId, 'A restriction on your account has been lifted.');
    } catch (e) {
      log.warn('system-pm', 'Failed to send', { uniqueId, error: e.message });
      pmFailed = 1;
    }
 
    res.json({
      success: true,
      removed: allDocs.length,
      pms: { failed: pmFailed, total: 1 },
    });
  } catch (err) {
    log.error('admin-bans', 'Error unbanning all for user', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Get bans for user ───────────────────────────────────────────
 
router.get('/admin/bans/user/:uniqueId', async (req, res) => {
  try {
    const uniqueId = req.params.uniqueId;
    const numericId = Number(uniqueId);
    const stringId = String(uniqueId);
 
    const [deviceSnapStr, deviceSnapNum, networkSnapStr, networkSnapNum] = await Promise.all([
      db.collection('deviceBans').where('linkedUniqueId', '==', stringId).get(),
      db.collection('deviceBans').where('linkedUniqueId', '==', numericId).get(),
      db.collection('networkBans').where('linkedUniqueId', '==', stringId).get(),
      db.collection('networkBans').where('linkedUniqueId', '==', numericId).get(),
    ]);
 
    // Deduplicate by doc id in case both queries match the same doc
    const seenDevice = new Set();
    const deviceBans = [];
    for (const snap of [deviceSnapStr, deviceSnapNum]) {
      for (const d of snap.docs) {
        if (!seenDevice.has(d.id)) {
          seenDevice.add(d.id);
          deviceBans.push({ id: d.id, ...d.data() });
        }
      }
    }
 
    const seenNetwork = new Set();
    const networkBans = [];
    for (const snap of [networkSnapStr, networkSnapNum]) {
      for (const d of snap.docs) {
        if (!seenNetwork.has(d.id)) {
          seenNetwork.add(d.id);
          networkBans.push({ id: d.id, ...d.data() });
        }
      }
    }
 
    res.json({ deviceBans, networkBans });
  } catch (err) {
    log.error('admin-bans', 'Error getting bans for user', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;