File size: 875 Bytes
c775351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const http = require('http');
const originalCreateServer = http.createServer;

http.createServer = function() {
  const server = originalCreateServer.apply(this, arguments);
  const originalEmit = server.emit;
  
  server.emit = function(type, req, res) {
    if (type === 'request') {
      const authHeader = req.headers.authorization;
      const apiKey = process.env.API_KEY;
      
      if (!apiKey) {
        console.warn('API_KEY environment variable is not set');
        return originalEmit.apply(this, arguments);
      }
      
      if (!authHeader || authHeader !== 'Bearer ' + apiKey) {
        res.writeHead(401, {'Content-Type': 'application/json'});
        res.end(JSON.stringify({error: 'Unauthorized: Invalid API key'}));
        return true;
      }
    }
    return originalEmit.apply(this, arguments);
  };
  
  return server;
};

module.exports = {};