File size: 2,074 Bytes
2889205
 
3e0d39c
2889205
7f84064
2889205
7f84064
3e0d39c
2889205
 
3e0d39c
7f84064
3e0d39c
 
 
 
7f84064
c619948
3e0d39c
 
 
 
 
 
 
 
cb34952
 
3e0d39c
 
 
 
7f84064
 
2889205
7f84064
2889205
 
 
 
3e0d39c
 
 
2889205
3e0d39c
 
2889205
3e0d39c
 
 
 
 
 
 
 
 
2889205
 
3e0d39c
2889205
3e0d39c
 
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
const express = require('express');
const proxy = require('express-http-proxy');
const bodyParser = require('body-parser');
const app = express();

const targetUrl = 'https://api.openai.com';
const openaiKey = process.env.OPENAI_KEY;
const adminPassword = 'securepassword'; // Never use hard-coded sensitive passwords in production
const port = 7860;

app.use(bodyParser.json());

// In-memory configuration "database"
let ipConfigurations = {};

// Rate limit middleware
app.use('/api', (req, res, next) => {
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  const config = ipConfigurations[ip] || { limit: 10, requestCount: 0, nextAvailableTime: Date.now() };

  if (new Date() < new Date(config.nextAvailableTime) || config.requestCount >= config.limit) {
    return res.status(429).json({
      error: true,
      message: 'You have reached your maximum request limit.',
      nextAvailableRequestTime: getNextAvailableRequestTime(config)
    });
  }

  // Increment the request count
  config.requestCount++;
  ipConfigurations[ip] = config; // Update config for the IP
  console.log(`Allowed request for ${ip}: ${config.requestCount} of ${config.limit}`);
  next();
}, proxy(targetUrl, {
  proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
    proxyReqOpts.headers['Authorization'] = 'Bearer ' + openaiKey;
    return proxyReqOpts;
  },
}));

// Admin route to update IP configurations
app.post('/admin/config', (req, res) => {
  const { password, ip, limit } = req.body;

  if (password !== adminPassword) {
    return res.status(403).send("Unauthorized");
  }

  ipConfigurations[ip] = { limit: limit, requestCount: 0, nextAvailableTime: Date.now() };
  res.send(`Configuration set for IP ${ip} with limit ${limit}`);
});

// Helper function to get next available request time
function getNextAvailableRequestTime(config) {
  const resetTime = new Date(config.nextAvailableTime);
  return resetTime.toISOString();
}

// Start the express server
app.listen(port, () => {
  console.log(`Reverse proxy server running on port ${port}.`);
});