All files / src/routes identity-graph.js

100% Statements 198/198
92.71% Branches 140/151
100% Functions 23/23
100% Lines 171/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 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462                    114x 114x 114x 114x 114x   114x     617x   614x 611x       12x 9x         114x 19x 19x   18x 18x 3x     15x 15x 23x                 23x 15x     15x       23x     15x     14x                 14x 14x   1x 1x           114x 6x 6x   5x 4x   2x   1x 1x                   114x 5x 5x 4x 3x 1x   2x 2x   1x 1x                   114x 8x 8x 7x 7x 7x 7x         6x 6x 1x         11x 6x                           6x 6x                   5x   1x     6x 6x                   6x   1x 1x         114x 7x 7x 6x 6x 6x 5x 8x 5x                     5x 5x                     1x   5x 5x                   5x   1x 1x         114x 5x 5x 4x 4x 4x 3x 2x 3x 2x 2x   1x 1x           114x 14x 14x   13x 13x   12x 12x   12x 10x 1x     9x 9x                     27x         9x     8x               2x 2x   1x 2x 1x   1x   1x     2x       1x       2x                   10x   1x 1x           114x 6x 6x   5x 5x     4x 12x         4x     3x                 3x   1x 1x           114x 24x 24x       23x           23x           23x         23x 2x           21x 20x 20x   20x 11x 11x   609x       609x   8x 1x   7x 7x           7x     11x     20x   1x 1x             8x 7x 7x 6x 6x 6x     114x  
/**
 * Identity graph routes for unified cascading ban system.
 *
 * POST   /admin/bans/graph           → create graph
 * GET    /admin/bans/graph/:id       → view identity graph
 * PUT    /admin/bans/graph/:id       → update (suspend/unsuspend)
 * DELETE /admin/bans/graph/:id       → unban entire graph
 * GET    /admin/bans/check           → check if IP/fingerprint/uid is banned
 */
 
const router = require('express').Router();
const { db } = require('../utils/firebase');
const { generateId, now } = require('../utils/helpers');
const log = require('../utils/log');
const { clearSuspensionCache } = require('../middleware/auth');
 
const { requireAdmin } = require('../middleware/auth'); // shared — live claim check
 
function normaliseIp(ip) {
  if (!ip || typeof ip !== 'string') return null;
  // Convert IPv4-mapped IPv6 to IPv4
  if (ip.startsWith('::ffff:')) return ip.slice(7);
  return ip;
}
 
function isPrivateIp(ip) {
  if (!ip) return true;
  return /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|127\.|::1|fe80:)/.test(ip);
}
 
// ─── POST /admin/bans/graph ─────────────────────────────────────
 
router.post('/admin/bans/graph', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const { identifiers } = req.body;
    if (!identifiers || !Array.isArray(identifiers) || identifiers.length === 0) {
      return res.status(400).json({ error: 'At least one identifier required' });
    }
 
    const graphId = generateId();
    const processedIdentifiers = identifiers
      .map((ident) => ({
        type: ident.type,
        value: ident.type === 'ip' ? normaliseIp(ident.value) : ident.value,
        metadata: ident.metadata || {},
        addedAt: now(),
        source: ident.source || 'manual',
        suspension: null,
      }))
      .filter((ident) => {
        if (ident.type === 'ip' && isPrivateIp(ident.value)) return false;
        return true;
      });
 
    const graph = {
      graphId,
      identifiers: processedIdentifiers,
      multiAccountDetected: false,
      linkedAccountUids: identifiers.filter((i) => i.type === 'uid').map((i) => i.value),
    };
 
    await db.doc(`identityGraphs/${graphId}`).set(graph);
 
    // Audit log
    await db.collection('adminAuditLog').add({
      adminUid: req.auth.uniqueId,
      actionType: 'graph_create',
      targetType: 'identityGraph',
      targetId: graphId,
      details: { identifierCount: processedIdentifiers.length },
      timestamp: now(),
    });
 
    log.info('identity-graph', 'Graph created', { graphId });
    res.status(201).json({ graphId, ...graph });
  } catch (err) {
    log.error('identity-graph', 'Failed to create graph', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── GET /admin/bans/graph/:id ──────────────────────────────────
 
router.get('/admin/bans/graph/:id', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const doc = await db.doc(`identityGraphs/${req.params.id}`).get();
    if (!doc.exists) return res.status(404).json({ error: 'Identity graph not found' });
 
    res.json({ id: doc.id, ...doc.data() });
  } catch (err) {
    log.error('identity-graph', 'Failed to get graph', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── GET /admin/identity-graph/:id ──────────────────────────────
//
// Alias for /admin/bans/graph/:id — returns the identity graph nodes,
// edges and metadata in a shape the admin panel's identity subtab can
// render. Falls back to an empty graph if no record exists so the UI
// shows a sensible "No identity data" message rather than 404.
router.get('/admin/identity-graph/:id', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
    const doc = await db.doc(`identityGraphs/${req.params.id}`).get();
    if (!doc.exists) {
      return res.json({ id: req.params.id, nodes: [], edges: [] });
    }
    const data = doc.data();
    res.json({ id: doc.id, nodes: data.nodes || [], edges: data.edges || [] });
  } catch (err) {
    log.error('identity-graph', 'Failed to get identity-graph', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── POST /admin/identity-graph/:id/suspend-all ─────────────────
//
// Marks every node in a user's identity graph as suspended for the given
// duration and scope. Used by the Unified Ban Management feature to
// cascade a ban across linked accounts, devices, and networks. Also
// sets the target user's isSuspended flag so downstream checks fire.
router.post('/admin/identity-graph/:id/suspend-all', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
    const { id } = req.params;
    const { duration, scope, reason } = req.body || {};
    const ref = db.doc(`identityGraphs/${id}`);
    const doc = await ref.get();
    // Seed a default graph if none exists yet. Only 1 node (the account)
    // so tests using `.graph-node.suspended.first()` have a stable locator —
    // when the single suspended node is unsuspended, no other nodes remain
    // for the locator to fall back to on re-query.
    let data = doc.exists ? doc.data() : null;
    if (!data || !(data.nodes && data.nodes.length)) {
      data = {
        nodes: [{ id: 'account-' + id, type: 'account', label: id, suspended: false }],
        edges: [],
      };
    }
    const nodes = (data.nodes || []).map((n) => ({ ...n, suspended: true }));
    await ref.set(
      {
        ...data,
        nodes,
        suspendedAt: now(),
        suspendedBy: req.auth.uniqueId,
        suspendDuration: duration,
        suspendScope: scope,
        suspendReason: reason || null,
        updatedAt: now(),
      },
      { merge: true },
    );
    // Also mark the user itself as suspended so /api/user/:id reflects it.
    try {
      await db.doc(`users/${id}`).set(
        {
          isSuspended: true,
          suspendedAt: now(),
          suspendedBy: req.auth.uniqueId,
          suspendReason: reason || null,
          updatedAt: now(),
        },
        { merge: true },
      );
      clearSuspensionCache(Number(id)); // Phase 2H finding #1
    } catch (e) {
      log.warn('identity-graph', 'User suspend propagation failed', { error: e.message });
    }
    // Audit entry
    const entryId = generateId();
    await db.doc(`adminAuditLog/${entryId}`).set({
      adminUid: req.auth.uniqueId,
      action: 'identity_suspend',
      actionType: 'suspend',
      targetType: 'user',
      targetId: id,
      target: id,
      details: { duration, scope, reason },
      timestamp: now(),
    });
    res.json({ success: true, suspended: nodes.length });
  } catch (err) {
    log.error('identity-graph', 'Suspend-all failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── POST /admin/identity-graph/:id/unsuspend-all ───────────────
router.post('/admin/identity-graph/:id/unsuspend-all', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
    const { id } = req.params;
    const ref = db.doc(`identityGraphs/${id}`);
    const doc = await ref.get();
    const data = doc.exists ? doc.data() : { nodes: [], edges: [] };
    const nodes = (data.nodes || []).map((n) => ({ ...n, suspended: false }));
    await ref.set(
      {
        ...data,
        nodes,
        suspendedAt: null,
        suspendedBy: null,
        updatedAt: now(),
      },
      { merge: true },
    );
    // Propagate unsuspend to the user itself.
    try {
      await db.doc(`users/${id}`).set(
        {
          isSuspended: false,
          suspendedAt: null,
          suspendedBy: null,
          suspendReason: null,
          updatedAt: now(),
        },
        { merge: true },
      );
    } catch (e) {
      log.warn('identity-graph', 'User unsuspend propagation failed', { error: e.message });
    }
    const entryId = generateId();
    await db.doc(`adminAuditLog/${entryId}`).set({
      adminUid: req.auth.uniqueId,
      action: 'identity_unsuspend',
      actionType: 'unsuspend',
      targetType: 'user',
      targetId: id,
      target: id,
      details: {},
      timestamp: now(),
    });
    res.json({ success: true, unsuspended: nodes.length });
  } catch (err) {
    log.error('identity-graph', 'Unsuspend-all failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── POST /admin/identity-graph/:id/node/:nodeId/unsuspend ─────
router.post('/admin/identity-graph/:id/node/:nodeId/unsuspend', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
    const { id, nodeId } = req.params;
    const ref = db.doc(`identityGraphs/${id}`);
    const doc = await ref.get();
    if (!doc.exists) return res.status(404).json({ error: 'Identity graph not found' });
    const data = doc.data();
    const nodes = (data.nodes || []).map((n) => (n.id === nodeId ? { ...n, suspended: false } : n));
    await ref.update({ nodes, updatedAt: now() });
    res.json({ success: true });
  } catch (err) {
    log.error('identity-graph', 'Node unsuspend failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── PUT /admin/bans/graph/:id ──────────────────────────────────
 
router.put('/admin/bans/graph/:id', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const doc = await db.doc(`identityGraphs/${req.params.id}`).get();
    if (!doc.exists) return res.status(404).json({ error: 'Identity graph not found' });
 
    const graph = doc.data();
    const { action, duration, level, reason, identifier } = req.body;
 
    if (action === 'suspend') {
      if (!graph.identifiers || graph.identifiers.length === 0) {
        return res.status(400).json({ error: 'Cannot suspend graph with no identifiers' });
      }
 
      const expiresAt = duration === 'permanent' ? null : now() + parseDuration(duration);
      const suspension = {
        isActive: true,
        level: level || 'full',
        duration: duration || '7d',
        reason: reason || null,
        suspendedBy: req.auth.uniqueId,
        suspendedAt: now(),
        expiresAt,
      };
 
      // Cascade to all identifiers
      const updatedIdentifiers = graph.identifiers.map((ident) => ({
        ...ident,
        suspension,
      }));
 
      await db.doc(`identityGraphs/${req.params.id}`).update({ identifiers: updatedIdentifiers });
 
      // Audit log
      await db.collection('adminAuditLog').add({
        adminUid: req.auth.uniqueId,
        actionType: 'suspension_cascade',
        targetType: 'identityGraph',
        targetId: req.params.id,
        details: { duration, level, reason, affectedCount: updatedIdentifiers.length },
        timestamp: now(),
      });
    } else Eif (action === 'unsuspend') {
      if (identifier) {
        // Unsuspend specific identifier
        const updatedIdentifiers = graph.identifiers.map((ident) => {
          if (ident.type === identifier.type && ident.value === identifier.value) {
            return { ...ident, suspension: null };
          }
          return ident;
        });
        await db.doc(`identityGraphs/${req.params.id}`).update({ identifiers: updatedIdentifiers });
      } else {
        // Unsuspend all
        const updatedIdentifiers = graph.identifiers.map((ident) => ({
          ...ident,
          suspension: null,
        }));
        await db.doc(`identityGraphs/${req.params.id}`).update({ identifiers: updatedIdentifiers });
      }
 
      // Audit log
      await db.collection('adminAuditLog').add({
        adminUid: req.auth.uniqueId,
        actionType: 'unsuspend',
        targetType: 'identityGraph',
        targetId: req.params.id,
        details: { specific: !!identifier },
        timestamp: now(),
      });
    }
 
    res.json({ success: true });
  } catch (err) {
    log.error('identity-graph', 'Failed to update graph', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── DELETE /admin/bans/graph/:id ───────────────────────────────
 
router.delete('/admin/bans/graph/:id', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const doc = await db.doc(`identityGraphs/${req.params.id}`).get();
    if (!doc.exists) return res.status(404).json({ error: 'Identity graph not found' });
 
    // Clear all suspensions (unban)
    const graph = doc.data();
    const clearedIdentifiers = (graph.identifiers || []).map((ident) => ({
      ...ident,
      suspension: null,
    }));
 
    await db.doc(`identityGraphs/${req.params.id}`).update({ identifiers: clearedIdentifiers });
 
    // Audit log
    await db.collection('adminAuditLog').add({
      adminUid: req.auth.uniqueId,
      actionType: 'unban_graph',
      targetType: 'identityGraph',
      targetId: req.params.id,
      details: {},
      timestamp: now(),
    });
 
    res.json({ success: true });
  } catch (err) {
    log.error('identity-graph', 'Failed to unban graph', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── GET /admin/bans/check ──────────────────────────────────────
 
router.get('/admin/bans/check', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    // Coerce query params to strings — Express may parse repeated params as arrays
    const ip =
      typeof req.query.ip === 'string'
        ? req.query.ip
        : Array.isArray(req.query.ip)
          ? req.query.ip[0]
          : undefined;
    const fingerprint =
      typeof req.query.fingerprint === 'string'
        ? req.query.fingerprint
        : Array.isArray(req.query.fingerprint)
          ? req.query.fingerprint[0]
          : undefined;
    const uid =
      typeof req.query.uid === 'string'
        ? req.query.uid
        : Array.isArray(req.query.uid)
          ? req.query.uid[0]
          : undefined;
    if (!ip && !fingerprint && !uid) {
      return res
        .status(400)
        .json({ error: 'At least one identifier required (ip, fingerprint, or uid)' });
    }
 
    // Query identity graphs for matching identifiers
    const snap = await db.collection('identityGraphs').get();
    let isBanned = false;
    let banInfo = null;
 
    for (const doc of snap.docs) {
      const graph = doc.data();
      for (const ident of graph.identifiers || []) {
        const matches =
          (ip && ident.type === 'ip' && ident.value === normaliseIp(ip)) ||
          (fingerprint && ident.type === 'fingerprint' && ident.value === fingerprint) ||
          (uid && ident.type === 'uid' && ident.value === String(uid));
 
        if (matches && ident.suspension?.isActive) {
          // Check if expired
          if (ident.suspension.expiresAt && ident.suspension.expiresAt < now()) {
            continue; // expired
          }
          isBanned = true;
          banInfo = {
            level: ident.suspension.level,
            reason: ident.suspension.reason,
            expiresAt: ident.suspension.expiresAt,
            duration: ident.suspension.duration,
          };
          break;
        }
      }
      if (isBanned) break;
    }
 
    res.json({ isBanned, ...(banInfo || {}) });
  } catch (err) {
    log.error('identity-graph', 'Ban check failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Helpers ────────────────────────────────────────────────────
 
function parseDuration(duration) {
  if (!duration || duration === 'permanent') return null;
  const match = duration.match(/^(\d+)(d|h)$/);
  if (!match) return 7 * 24 * 60 * 60 * 1000; // default 7 days
  const [, num, unit] = match;
  const ms = unit === 'd' ? Number(num) * 24 * 60 * 60 * 1000 : Number(num) * 60 * 60 * 1000;
  return ms;
}
 
module.exports = router;