Ayeantics commited on
Commit
3e0d39c
·
verified ·
1 Parent(s): a627ace

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +36 -35
server.js CHANGED
@@ -1,38 +1,35 @@
1
  const express = require('express');
2
  const proxy = require('express-http-proxy');
 
3
  const app = express();
4
 
5
  const targetUrl = 'https://api.openai.com';
6
  const openaiKey = process.env.OPENAI_KEY;
 
7
  const port = 7860;
8
- const baseUrl = getExternalUrl(process.env.SPACE_ID);
9
 
10
- let requestDetails = []; // Store details of each request
11
- let ipRequestCounts = {}; // Dictionary to keep track of requests per IP
12
 
 
 
 
 
13
  app.use('/api', (req, res, next) => {
14
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
15
- const currentCount = ipRequestCounts[ip] || 0;
16
-
17
- if (currentCount >= 10) {
18
- // Send a more generic message without mentioning IP-based limitation
19
- return res.status(429).send('You reached 10 message limit. Contact me on reddit for more.');
 
 
 
20
  }
21
 
22
- // Increment request counter for the IP
23
- ipRequestCounts[ip] = currentCount + 1;
24
-
25
- // Log request with timestamp
26
- const timestamp = new Date().toISOString();
27
- const requestData = {
28
- requestNumber: ipRequestCounts[ip],
29
- ip: ip,
30
- timestamp: timestamp,
31
- text: req.method + ' ' + req.url
32
- };
33
- requestDetails.push(requestData);
34
- console.log(`Request ${requestData.requestNumber} on ${requestData.timestamp} from IP ${requestData.ip} with text "${requestData.text}"`);
35
-
36
  next();
37
  }, proxy(targetUrl, {
38
  proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
@@ -41,21 +38,25 @@ app.use('/api', (req, res, next) => {
41
  },
42
  }));
43
 
44
- app.get("/", (req, res) => {
45
- let requestsInfo = requestDetails.map(detail =>
46
- `Request ${detail.requestNumber} on ${detail.timestamp} from IP ${detail.ip} with text "${detail.text}"`).join('<br>');
47
- res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}.<br><br>${requestsInfo}`);
48
- });
49
 
50
- function getExternalUrl(spaceId) {
51
- try {
52
- const [username, spacename] = spaceId.split("/");
53
- return `https://${username}-${spacename.replace(/_/g, "-")}.hf.space/api/v1`;
54
- } catch (e) {
55
- return "";
56
  }
 
 
 
 
 
 
 
 
 
57
  }
58
 
 
59
  app.listen(port, () => {
60
- console.log(`Reverse proxy server running on ${baseUrl}.`);
61
- });
 
1
  const express = require('express');
2
  const proxy = require('express-http-proxy');
3
+ const bodyParser = require('body-parser');
4
  const app = express();
5
 
6
  const targetUrl = 'https://api.openai.com';
7
  const openaiKey = process.env.OPENAI_KEY;
8
+ const adminPassword = 'securepassword'; // Never use hard-coded sensitive passwords in production
9
  const port = 7860;
 
10
 
11
+ app.use(bodyParser.json());
 
12
 
13
+ // In-memory configuration "database"
14
+ let ipConfigurations = {};
15
+
16
+ // Rate limit middleware
17
  app.use('/api', (req, res, next) => {
18
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
19
+ const config = ipConfigurations[ip] || { limit: 10, requestCount: 0, nextAvailableTime: Date.now() };
20
+
21
+ if (new Date() < new Date(config.nextAvailableTime) || config.requestCount >= config.limit) {
22
+ return res.status(429).json({
23
+ error: true,
24
+ message: 'You have reached your maximum request limit.',
25
+ nextAvailableRequestTime: getNextAvailableRequestTime(config)
26
+ });
27
  }
28
 
29
+ // Increment the request count
30
+ config.requestCount++;
31
+ ipConfigurations[ip] = config; // Update config for the IP
32
+ console.log(`Allowed request for ${ip}: ${config.requestCount} of ${config.limit}`);
 
 
 
 
 
 
 
 
 
 
33
  next();
34
  }, proxy(targetUrl, {
35
  proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
 
38
  },
39
  }));
40
 
41
+ // Admin route to update IP configurations
42
+ app.post('/admin/config', (req, res) => {
43
+ const { password, ip, limit } = req.body;
 
 
44
 
45
+ if (password !== adminPassword) {
46
+ return res.status(403).send("Unauthorized");
 
 
 
 
47
  }
48
+
49
+ ipConfigurations[ip] = { limit: limit, requestCount: 0, nextAvailableTime: Date.now() };
50
+ res.send(`Configuration set for IP ${ip} with limit ${limit}`);
51
+ });
52
+
53
+ // Helper function to get next available request time
54
+ function getNextAvailableRequestTime(config) {
55
+ const resetTime = new Date(config.nextAvailableTime);
56
+ return resetTime.toISOString();
57
  }
58
 
59
+ // Start the express server
60
  app.listen(port, () => {
61
+ console.log(`Reverse proxy server running on port ${port}.`);
62
+ });