# All files / src dashboard-server.ts

40.41% Statements 156/386
38.04% Branches 78/205
50% Functions 27/54
41.64% Lines 152/365

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
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725

    2x
    2x

    71x

    71x
    70x
    70x

    71x
    70x
    18x
    18x
    2x
    2x
    2x
    1x

    69x

    71x
    7x
    7x
    7x
    7x

    71x

    71x
    2x
    2x
    2x

    71x

    71x
    3x
    3x
    3x
    3x

    71x
    6x
    6x
    6x
    6x
    6x
    6x

    71x
    6x
    6x
    6x
    4x
    4x
    2x

    71x
    4x
    4x
    4x
    1x

    3x
    3x
    1x

    2x
    1x

    1x
    1x

    4x

    71x
    4x
    4x
    4x
    1x

    3x
    3x
    1x

    2x

    2x
    2x
    2x

    71x
    3x
    3x
    3x
    1x

    2x
    2x
    1x
    1x

    3x

    71x
    1x
    1x
    1x

    71x
    1x
    1x

    71x
    1x
    1x
    1x

    71x
    1x
    1x

    71x
    2x
    2x
    2x

    71x
    1x
    1x

    71x
    3x
    3x
    3x

    71x
    2x
    2x
    2x

    71x
    1x
    1x

    71x
    1x
    1x

    71x
    1x
    1x

    71x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x

    71x
    1x
    1x
    1x

    1x

    71x

    6x
    2x

    4x
    4x
    4x

    71x
    6x
    6x
    6x
    3x

    3x
    3x
    6x

    6x

    71x
    2x
    2x

    71x

     import express, { Request, Response, NextFunction, Router } from 'express';
    import { join } from 'path';
    import { spawn, execSync } from 'child_process';
    import { createServer } from 'net';
    import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync } from 'fs';
    import { homedir } from 'os';
    import { randomBytes } from 'crypto';
    import {
      getStats, getActiveSessions,
      getSessionsPaginated, getSessionDetail,
      getDailyCosts, getModelBreakdown, getTopSessions,
      exportSessions, loadPricing,
      getProviderBreakdown, getFileHotspots, getActivityHeatmap,
      getDailyTokens, getCostVelocity, getProjectBreakdown, getTokenRatios,
      getSession, getCommits, clearAllData,
      addFeedback, getFeedback,
    } from './db';
    import { getGitDiff, getCommitDiff, getGitDiffStats } from './git';
    import { getLicense, activateLicense, deactivateLicense } from '../pro/src/license';

    interface DashboardOptions {
      port?: number;
      open?: boolean;
      host?: string;
      json?: boolean;
    }

    // ── PID file management ────────────────────────────────────

    const PID_DIR = join(homedir(), '.codesession');
    const pidFilePath = (port: number) => join(PID_DIR, `dashboard-${port}.pid`);

    function writePidFile(port: number): void {
      mkdirSync(PID_DIR, { recursive: true });
      writeFileSync(pidFilePath(port), `${process.pid}\n`, 'utf-8');
    }

    function removePidFile(port: number): void {
      try { unlinkSync(pidFilePath(port)); } catch (_) { /* already gone */ }
    }

    function readOwnPid(port: number): number | null {
      const file = pidFilePath(port);
      if (!existsSync(file)) return null;
      try {
        const pid = parseInt(readFileSync(file, 'utf-8').trim(), 10);
        if (isNaN(pid) || pid <= 0) return null;
        process.kill(pid, 0); // existence check
        return pid;
      } catch (_) {
        try { unlinkSync(file); } catch (_) {}
        return null;
      }
    }

    function killOwnStaleProcess(port: number): boolean {
      const pid = readOwnPid(port);
      if (pid === null) return false;

      try {
        // Double-check the process still exists before killing
        process.kill(pid, 0);

        // Verify it's actually our process (check command line contains 'dashboard' or 'node')
        // This is a heuristic to avoid killing unrelated processes with recycled PIDs
        let cmdLine = '';
        try {
          if (process.platform === 'win32') {
            // Validate pid is a safe integer before shell interpolation
            if (!Number.isInteger(pid) || pid <= 0 || pid > 4194304) {
              removePidFile(port);
              return false;
            }
            cmdLine = execSync(`wmic process where processid=${pid} get commandline`, { timeout: 2000, encoding: 'utf-8' });
          } else {
            cmdLine = readFileSync(`/proc/${pid}/cmdline`, 'utf-8').replace(/\0/g, ' ');
          }
        } catch (_) {
          // Can't read cmdline - process might be gone or we lack permissions
          removePidFile(port);
          return false;
        }

        // Only kill if it looks like a dashboard process
        if (!cmdLine.toLowerCase().includes('dashboard') && !cmdLine.toLowerCase().includes('node')) {
          console.log(`  PID ${pid} doesn't appear to be a dashboard process, skipping kill`);
          removePidFile(port);
          return false;
        }

        if (process.platform === 'win32') {
          execSync(`taskkill /PID ${pid} /F`, { timeout: 5000 });
        } else {
          process.kill(pid, 'SIGTERM');
        }
        console.log(`  Killed previous dashboard (PID ${pid}) on port ${port}`);
        removePidFile(port);
        return true;
      } catch (_) {
        removePidFile(port);
        return false;
      }
    }

    // ── Port check ─────────────────────────────────────────────

    function isPortInUse(port: number): Promise<boolean> {
      return new Promise((resolve) => {
        const tester = createServer()
          .once('error', (err: any) => {
            if (err.code === 'EADDRINUSE') resolve(true);
            else resolve(false);
          })
          .once('listening', () => {
            tester.close(() => resolve(false));
          })
          .listen(port, '127.0.0.1');
      });
    }

    // ── API route builder ──────────────────────────────────────

    export function buildApiRouter(): Router {
      const router = Router();

      router.use((_req, res, next) => {
        res.setHeader('X-Codesession-Api-Version', '1');
        next();
      });

      router.use((req, res, next) => {
        if (req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS') {
          const origin = req.headers.origin || req.headers.referer;
          if (origin) {
            try {
              const url = new URL(origin);
              if (url.origin !== 'http://localhost:3737' && url.origin !== 'http://127.0.0.1:3737') {
                return res.status(403).json({ error: 'CSRF' });
              }
            } catch {
              return res.status(403).json({ error: 'CSRF' });
            }
          }
        }
        next();
      });

      router.get('/stats', (_req, res) => {
        try {
          const stats = getStats();
          const active = getActiveSessions();
          res.json({ ...stats, activeSessions: active.length });
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      // ── License endpoints ────────────────────────────────────

      router.get('/license', (_req, res) => {
        try {
          res.json(getLicense());
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.post('/license/activate', (req, res) => {
        try {
          const { key } = req.body;
          Eif (!key) return res.status(400).json({ success: false, error: 'Key is required' });
          const result = activateLicense(key);
          res.json(result);
        } catch (e: any) {
          res.status(500).json({ success: false, error: e.message });
        }
      });

      router.post('/license/deactivate', (_req, res) => {
        try {
          deactivateLicense();
          res.json({ success: true });
        } catch (e: any) {
          res.status(500).json({ success: false, error: e.message });
        }
      });

      router.post('/lead', async (req, res) => {
        try {
          const { email } = req.body;
          Eif (!email || !email.includes('@')) {
            return res.status(400).json({ error: 'Invalid email' });
          }

          const SUPABASE_URL = 'https://igmpvdvygkgjilakgslz.supabase.co';
          const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImlnbXB2ZHZ5Z2tnamlsYWtnc2x6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzk0NjI1ODAsImV4cCI6MjA5NTAzODU4MH0.iQMMxcRLsh1wJppUZSirsP0TKdDyzWD4aafXPJvFPFg';

          const response = await fetch(`${SUPABASE_URL}/rest/v1/leads`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'apikey': SUPABASE_ANON_KEY,
              'Authorization': `Bearer ${SUPABASE_ANON_KEY}`,
              'Prefer': 'return=minimal'
            },
            body: JSON.stringify({ email, source: 'dashboard' })
          });

          if (!response.ok) {
            throw new Error('Failed to capture lead');
          }

          res.json({ success: true });
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/sessions', (req, res) => {
        try {
          const limit = parseInt(req.query.limit as string) || 50;
          const offset = parseInt(req.query.offset as string) || 0;
          const status = (req.query.status as string) || 'all';
          const search = (req.query.search as string) || '';
          res.json(getSessionsPaginated({ limit, offset, status, search }));
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/sessions/:id', (req, res) => {
        try {
          const id = parseInt(req.params.id);
          if (isNaN(id)) return res.status(400).json({ error: 'Invalid session ID' });
          const detail = getSessionDetail(id);
          if (!detail) return res.status(404).json({ error: 'Session not found' });
          res.json(detail);
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      // ── Diff endpoints ───────────────────────────────────────

      // Session diff (all files or single file)
      router.get('/sessions/:id/diff', async (req, res) => {
        try {
          const id = parseInt(req.params.id);
          if (isNaN(id)) {
            return res.status(400).json({ error: 'Invalid session ID' });
          }

          const session = getSession(id);
          if (!session) {
            return res.status(404).json({ error: `Session ${id} not found` });
          }

          if (!session.gitRoot) {
            return res.status(400).json({ error: `Session ${id} has no git repository (not in a git directory)` });
          }

          Eif (!session.startGitHead) {
            return res.status(400).json({ error: `Session ${id} has no start git HEAD (session started before git tracking was enabled)` });
          }

          const filePath = req.query.file as string | undefined;
          const commits = getCommits(id);
          const toSha = session.status === 'active' ? null : (commits.length > 0 ? commits[commits.length - 1].hash : null);

          const diff = await getGitDiff(session.gitRoot, session.startGitHead, toSha, filePath || undefined);
          res.type('text/plain').send(diff || '(no changes)');
        } catch (e: any) {
          res.status(500).json({ error: `Failed to fetch diff: ${e.message}` });
        }
      });

      // Single commit diff
      router.get('/sessions/:id/commits/:hash/diff', async (req, res) => {
        try {
          const id = parseInt(req.params.id);
          if (isNaN(id)) {
            return res.status(400).json({ error: 'Invalid session ID' });
          }

          const session = getSession(id);
          if (!session) {
            return res.status(404).json({ error: `Session ${id} not found` });
          }

          Iif (!session.gitRoot) {
            return res.status(400).json({ error: `Session ${id} has no git repository` });
          }

          const hash = req.params.hash;
          Eif (!/^[0-9a-fA-F]{4,40}$/.test(hash)) {
            return res.status(400).json({ error: 'Invalid commit hash' });
          }
          const filePath = req.query.file as string | undefined;
          const diff = await getCommitDiff(session.gitRoot, hash, filePath || undefined);
          res.type('text/plain').send(diff || '(no changes)');
        } catch (e: any) {
          res.status(500).json({ error: `Failed to fetch commit diff: ${e.message}` });
        }
      });

      // Per-file diff stats (additions/deletions) for a session
      router.get('/sessions/:id/diff-stats', async (req, res) => {
        try {
          const id = parseInt(req.params.id);
          if (isNaN(id)) {
            return res.status(400).json({ error: 'Invalid session ID' });
          }
          const session = getSession(id);
          if (!session) return res.status(404).json({ error: 'Session not found' });
          Eif (!session.gitRoot || !session.startGitHead) {
            return res.json([]);
          }

          const commits = getCommits(id);
          const toSha = session.status === 'active' ? null : (commits.length > 0 ? commits[commits.length - 1].hash : null);

          const stats = await getGitDiffStats(session.gitRoot, session.startGitHead, toSha);
          res.json(stats);
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/daily-costs', (req, res) => {
        try {
          const days = parseInt(req.query.days as string) || 30;
          res.json(getDailyCosts(days));
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/model-breakdown', (_req, res) => {
        try {
          res.json(getModelBreakdown());
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/top-sessions', (req, res) => {
        try {
          const limit = parseInt(req.query.limit as string) || 10;
          res.json(getTopSessions(limit));
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/provider-breakdown', (_req, res) => {
        try {
          res.json(getProviderBreakdown());
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/file-hotspots', (req, res) => {
        try {
          const limit = parseInt(req.query.limit as string) || 50;
          res.json(getFileHotspots(limit));
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/activity-heatmap', (_req, res) => {
        try {
          res.json(getActivityHeatmap());
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/daily-tokens', (req, res) => {
        try {
          const days = parseInt(req.query.days as string) || 30;
          res.json(getDailyTokens(days));
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/cost-velocity', (req, res) => {
        try {
          const limit = parseInt(req.query.limit as string) || 50;
          res.json(getCostVelocity(limit));
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/projects', (_req, res) => {
        try {
          res.json(getProjectBreakdown());
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/token-ratios', (_req, res) => {
        try {
          res.json(getTokenRatios());
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/pricing', (_req, res) => {
        try {
          res.json(loadPricing());
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/export', (req, res) => {
        try {
          const format = (req.query.format as string) === 'csv' ? 'csv' : 'json';
          const limit = parseInt(req.query.limit as string) || undefined;
          const data = exportSessions(format, limit);
          const mime = format === 'csv' ? 'text/csv' : 'application/json';
          const ext = format === 'csv' ? 'csv' : 'json';
          res.setHeader('Content-Type', mime);
          res.setHeader('Content-Disposition', `attachment; filename="codesession-export.${ext}"`);
          res.send(data);
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/version', (_req, res) => {
        try {
          const pkg = require('../../package.json');
          res.json({ version: pkg.version, apiVersion: 1 });
        } catch {
          res.json({ version: 'unknown', apiVersion: 1 });
        }
      });

      router.post('/reset', (req, res) => {
        // Require explicit confirmation header to prevent accidental data loss
        if (req.headers['x-confirm-reset'] !== 'yes') {
          return res.status(400).json({ error: 'Missing X-Confirm-Reset: yes header. This action permanently deletes all session data.' });
        }
        try {
          clearAllData();
          res.json({ ok: true, message: 'All session data cleared' });
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      // ── Feedback ─────────────────────────────────────────────

      router.post('/feedback', (req, res) => {
        try {
          const { type, message, email } = req.body || {};
          if (!message || typeof message !== 'string' || message.trim().length === 0) {
            return res.status(400).json({ error: 'Message is required' });
          }
          const validTypes = ['feature', 'bug', 'general', 'question'];
          const feedbackType = validTypes.includes(type) ? type : 'general';
          const result = addFeedback({
            type: feedbackType,
            message: message.trim().slice(0, 5000),
            email: typeof email === 'string' ? email.trim().slice(0, 200) : undefined,
          });
          res.json({ ok: true, id: result.id, timestamp: result.timestamp });
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      router.get('/feedback', (_req, res) => {
        try {
          res.json(getFeedback(100));
        } catch (e: any) {
          res.status(500).json({ error: e.message });
        }
      });

      return router;
    }

    // ── Main ───────────────────────────────────────────────────

    export function startDashboard(options: DashboardOptions = {}): void {
      const port = options.port || 3737;
      const host = options.host || '127.0.0.1';
      const shouldOpen = options.open !== false;
      const jsonMode = options.json === true;
      const isExposed = host !== '127.0.0.1' && host !== 'localhost';

      // Generate session token for non-localhost binding
      const token = isExposed ? randomBytes(24).toString('base64url') : null;

      if (isExposed) {
        const msg = 'WARNING: Binding to ' + host + ' exposes session data (costs, repo activity, file paths) to your network. Use only on trusted networks.';
        if (jsonMode) {
          process.stderr.write(JSON.stringify({ warning: msg }) + '\n');
        } else {
          console.warn(`\n  ${msg}\n`);
        }
      }

      const app = express();

      // ── Security hardening (inline, no helmet dependency) ────

      app.disable('x-powered-by');

      app.use((_req: Request, res: Response, next: NextFunction) => {
        res.setHeader('X-Content-Type-Options', 'nosniff');
        res.setHeader('X-Frame-Options', 'DENY');
        res.setHeader('X-XSS-Protection', '0');
        res.setHeader('Referrer-Policy', 'no-referrer');
        res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
        if (isExposed) {
          // Strict CSP only when exposed
          res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'");
        }
        next();
      });

      // JSON body limit (4kb -- we only read, but defence-in-depth)
      app.use(express.json({ limit: '50kb' }));

      // ── CSRF protection for mutating endpoints ──────────────
      // Block cross-origin POST/PUT/DELETE requests to prevent CSRF attacks.
      // Any website could otherwise POST to http://127.0.0.1:3737/api/v1/reset.
      app.use('/api', (req: Request, res: Response, next: NextFunction) => {
        if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') {
          return next();
        }
        const origin = req.headers.origin;
        const referer = req.headers.referer;
        // Allow requests with no Origin (curl, Postman, server-to-server)
        if (!origin && !referer) return next();
        // Allow same-origin requests
        const allowed = [`http://localhost:${port}`, `http://127.0.0.1:${port}`, `http://${host}:${port}`];
        if (origin && allowed.some(a => origin.startsWith(a))) return next();
        if (referer && allowed.some(a => referer.startsWith(a))) return next();
        res.status(403).json({ error: 'Cross-origin mutating request blocked (CSRF protection)' });
      });

      // ── Token auth for non-localhost ─────────────────────────

      if (token) {
        app.use('/api', (req: Request, res: Response, next: NextFunction) => {
          const qToken = req.query.token as string | undefined;
          const hToken = req.headers.authorization?.replace(/^Bearer\s+/i, '');
          if (qToken === token || hToken === token) {
            next();
          } else {
            res.status(401).json({ error: 'Unauthorized. Provide token via ?token= or Authorization: Bearer <token>' });
          }
        });
      }

      // ── Static files with cache headers ──────────────────────

      const staticDir = join(__dirname, '../dashboard-ui');

      // Hashed assets (js/css with content hash in filename): immutable, 1 year
      app.use('/assets', express.static(join(staticDir, 'assets'), {
        maxAge: '365d',
        immutable: true,
      }));

      // index.html and other root files: no-cache (always fresh after upgrades)
      // index: false prevents serving raw index.html (SPA fallback serves injected version)
      app.use(express.static(staticDir, {
        maxAge: 0,
        index: false,
        setHeaders: (res, filePath) => {
          if (filePath.endsWith('.html')) {
            res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
          }
        },
      }));

      // ── API version header on all API responses ──────────────

      app.use('/api', (_req: Request, res: Response, next: NextFunction) => {
        res.setHeader('X-Codesession-Api-Version', '1');
        next();
      });

      // ── Mount API router at /api/v1 (canonical) and /api (compat alias) ──

      const apiRouter = buildApiRouter();
      app.use('/api/v1', apiRouter);
      app.use('/api', apiRouter);

      // ── SPA fallback ─────────────────────────────────────────

      // Read index.html once; inject token via <meta> tag (avoids CSP script-src issues)
      const indexPath = join(staticDir, 'index.html');
      let servedHtml: string;
      if (!existsSync(indexPath)) {
        // Dashboard UI hasn't been built — serve a helpful error instead of crashing
        servedHtml = `<!DOCTYPE html><html><head><title>codesession dashboard</title></head><body style="font-family:system-ui;padding:40px;color:#ccc;background:#1a1a2e">
          <h1>Dashboard not built</h1>
          <p>Run <code style="color:#00d9ff">npm run build:dashboard</code> first, then restart <code style="color:#00d9ff">cs dashboard</code>.</p>
        </body></html>`;
        if (!jsonMode) {
          console.warn('  Warning: Dashboard UI not found. Run `npm run build:dashboard` first.');
        }
      } else {
        const rawHtml = readFileSync(indexPath, 'utf-8');
        servedHtml = token
          ? rawHtml.replace('</head>', `<meta name="cs-token" content="${token}">\n</head>`)
          : rawHtml;
      }

      // Serve index.html for all known SPA routes so client-side routing works on refresh.
      // Using explicit app.get() instead of app.use() catch-all for Express 5 compatibility.
      const sendSpa = (_req: Request, res: Response) => {
        res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
        res.setHeader('Content-Type', 'text/html');
        res.send(servedHtml);
      };
      app.get('/', sendSpa);
      app.get('/sessions', sendSpa);
      app.get('/sessions/:id', sendSpa);
      app.get('/models', sendSpa);
      app.get('/insights', sendSpa);
      app.get('/alerts', sendSpa);

      // ── Port conflict handling & startup ──────────────────────

      const startServer = () => {
        const server = app.listen(port, host, () => {
          const url = `http://localhost:${port}`;

          writePidFile(port);

          const cleanup = () => { removePidFile(port); process.exit(); };
          process.on('SIGINT', cleanup);
          process.on('SIGTERM', cleanup);

          if (jsonMode) {
            const out: Record<string, any> = { url, port, pid: process.pid, host, apiVersion: 1 };
            if (token) out.token = token;
            console.log(JSON.stringify(out));
          } else {
            console.log(`\n  codesession dashboard -> ${url}`);
            if (token) {
              console.log(`  Session token: ${token}`);
              console.log(`  Authenticated URL: ${url}?token=${token}`);
            }
            console.log('  Press Ctrl+C to stop\n');
          }

          if (shouldOpen && !jsonMode) {
            const openUrl = token ? `${url}?token=${token}` : url;
            // Use spawn() with argument array to prevent command injection
            try {
              if (process.platform === 'win32') {
                spawn('cmd', ['/c', 'start', '', openUrl], { detached: true, stdio: 'ignore' }).unref();
              } else {
                const cmd = process.platform === 'darwin' ? 'open' : 'xdg-open';
                spawn(cmd, [openUrl], { detached: true, stdio: 'ignore' }).unref();
              }
            } catch (_) { /* browser open is best-effort */ }
          }
        });

        server.on('error', (err: any) => {
          if (err.code === 'EADDRINUSE') {
            if (jsonMode) {
              console.log(JSON.stringify({ error: 'EADDRINUSE', message: `Port ${port} is in use and could not be freed`, port }));
            } else {
              console.error(`\n  Port ${port} is in use and could not be freed.`);
              console.error(`  Try: cs dashboard --port ${port + 1}\n`);
            }
            process.exit(1);
          }
          throw err;
        });
      };

      isPortInUse(port).then(async (inUse) => {
        if (inUse) {
          if (!jsonMode) {
            console.log(`\n  Port ${port} is already in use -- checking for stale dashboard...`);
          }
          const killed = killOwnStaleProcess(port);
          if (killed) {
            // Wait for port to be freed, then verify it's actually free before starting
            await new Promise(resolve => setTimeout(resolve, 500));
            const stillInUse = await isPortInUse(port);
            if (!stillInUse) {
              startServer();
            } else {
              // Port still in use after kill - race condition or failed kill
              if (jsonMode) {
                console.log(JSON.stringify({ error: 'EADDRINUSE', message: `Port ${port} could not be freed`, port }));
              } else {
                console.error(`  Port ${port} could not be freed.`);
                console.error(`  Try: cs dashboard --port ${port + 1}\n`);
              }
              process.exit(1);
            }
          } else {
            if (jsonMode) {
              console.log(JSON.stringify({ error: 'EADDRINUSE', message: `Port ${port} is in use by another process (not a codesession dashboard)`, port }));
            } else {
              console.error(`  Port ${port} is in use by another process (not a codesession dashboard).`);
              console.error(`  Try: cs dashboard --port ${port + 1}\n`);
            }
            process.exit(1);
          }
        } else {
          startServer();
        }
      });
    }