All files / src server.ts

82.52% Statements 85/103
87.87% Branches 29/33
64.28% Functions 9/14
83.83% Lines 83/99

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 1672x 2x 2x 2x     2x 2x   2x 2x 2x   2x 12x   12x 112x   112x 104x 104x 104x 104x 1x 1x 1x       103x 103x 103x 118x 118x 118x 1x 1x     103x 103x 102x 1x 1x 1x     101x 101x 101x 101x           8x 1x 1x 7x 1x 1x 6x 5x 5x 4x   5x 5x 5x 1x 1x 1x   4x 3x 1x 1x 1x   2x           1x 1x   2x 1x     1x           1x   1x 1x                 1x 1x       12x         12x 12x                   12x 9x     12x 12x       12x 12x                                     12x 12x   12x  
import * as http from 'http';
import * as net from 'net';
import * as fs from 'fs';
import * as path from 'path';
import { AgentManager } from './agent';
import { SeraphConfig } from './config';
import { register } from './metrics';
import * as chat from './chat';
 
const requestCounts = new Map<string, number>();
const RATE_LIMIT_WINDOW = 60000; // 1 minute
const RATE_LIMIT_MAX_REQUESTS = 100; // Max requests per window
 
export function startServer(config: SeraphConfig, agentManager: AgentManager) {
  setInterval(() => requestCounts.clear(), RATE_LIMIT_WINDOW);
 
  const server = http.createServer(async (req, res) => {
    const clientIp = req.socket.remoteAddress;
 
    if (req.url === '/logs' && req.method === 'POST') {
      if (clientIp) {
        const requestCount = (requestCounts.get(clientIp) || 0) + 1;
        requestCounts.set(clientIp, requestCount);
        if (requestCount > RATE_LIMIT_MAX_REQUESTS) {
          res.writeHead(429, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ status: 'error', message: 'Too Many Requests' }));
          return;
        }
      }
 
      const MAX_PAYLOAD_SIZE = 1024 * 1024; // 1MB
      let body = '';
      req.on('data', chunk => {
        Iif (res.headersSent) return;
        body += chunk.toString();
        if (body.length > MAX_PAYLOAD_SIZE) {
          res.writeHead(413, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ status: 'error', message: 'Payload Too Large' }));
        }
      });
      req.on('end', () => {
        if (res.headersSent) return;
        if (typeof body !== 'string' || body.trim() === '') {
          res.writeHead(400, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ status: 'error', message: 'Invalid log format. Log must be a non-empty string.' }));
          return;
        }
        
        try {
          agentManager.dispatch(body);
          res.writeHead(202, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ status: 'accepted' }));
        } catch (error) {
          res.writeHead(400, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ status: 'error', message: 'Invalid log format.' }));
        }
      });
    } else if (req.url === '/status' && req.method === 'GET') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ status: 'ok' }));
    } else if (req.url === '/metrics' && req.method === 'GET') {
      res.setHeader('Content-Type', register.contentType);
      res.end(await register.metrics());
    } else if (req.url === '/chat' && req.method === 'POST') {
      let body = '';
      req.on('data', (chunk) => {
        body += chunk.toString();
      });
      req.on('end', async () => {
        try {
          if (!body) {
            res.writeHead(400, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ status: 'error', message: 'message is required' }));
            return;
          }
          const { message } = JSON.parse(body);
          if (!message) {
            res.writeHead(400, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ status: 'error', message: 'message is required' }));
            return;
          }
          const response = await chat.chat(
            message,
            config,
            [], // No MCP tools available in server mode
            agentManager.getRecentLogs(),
          );
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end(response);
        } catch (error: any) {
          if (error instanceof SyntaxError) {
            res.writeHead(400, {
              'Content-Type': 'application/json',
            });
            res.end(
              JSON.stringify({
                status: 'error',
                message: 'Invalid JSON format',
              }),
            );
            return;
          }
          res.writeHead(500, { 'Content-Type': 'application/json' });
          res.end(
            JSON.stringify({
              status: 'error',
              message: 'Internal Server Error',
            }),
          );
        }
      });
    } else {
      res.writeHead(404, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ status: 'error', message: 'Not Found' }));
    }
  });
 
  server.listen(config.port, () => {
    // The listening message is now in index.ts to avoid duplication
  });
 
  // IPC server
  const ipcSocketPath = path.join(process.cwd(), '.seraph.sock');
  const ipcServer = net.createServer((socket) => {
    socket.on('data', (data) => {
      const message = data.toString();
      Iif (message === 'get_logs') {
        socket.write(JSON.stringify(agentManager.getRecentLogs()));
      }
    });
  });
 
  // Clean up old socket file
  if (fs.existsSync(ipcSocketPath)) {
    fs.unlinkSync(ipcSocketPath);
  }
 
  ipcServer.listen(ipcSocketPath, () => {
    console.log('IPC server started');
  });
 
  // Graceful shutdown
  let isShuttingDown = false;
  const shutdown = () => {
    Iif (isShuttingDown) return;
    isShuttingDown = true;
 
    console.log('Shutting down gracefully...');
    
    server.close(() => {
      console.log('HTTP server closed.');
    });
 
    ipcServer.close(() => {
      console.log('IPC server closed.');
      Iif (fs.existsSync(ipcSocketPath)) {
        fs.unlinkSync(ipcSocketPath);
        console.log('IPC socket file removed.');
      }
    });
  };
 
  process.on('SIGTERM', shutdown);
  process.on('SIGINT', shutdown); // Also handle Ctrl+C
 
  return server;
}