Ayeantics commited on
Commit
65e323a
·
verified ·
1 Parent(s): 71c1ee6

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +40 -56
server.js CHANGED
@@ -1,3 +1,4 @@
 
1
  const express = require('express');
2
  const proxy = require('express-http-proxy');
3
  const app = express();
@@ -7,72 +8,55 @@ const openaiKey = process.env.OPENAI_KEY;
7
  const port = 7860;
8
  const baseUrl = getExternalUrl(process.env.SPACE_ID);
9
 
10
- let requestDetails = [];
11
- let ipRequestCounts = {};
12
 
13
- // Declare the proxy as middleware which can be reused
14
- const openAiProxy = proxy(targetUrl, {
15
- proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
16
- proxyReqOpts.headers['Authorization'] = 'Bearer ' + openaiKey;
17
- return proxyReqOpts;
18
- },
19
- userResDecorator: (proxyRes, proxyResData, userReq, userRes) => {
20
- const data = proxyResData.toString('utf8');
21
- if (proxyRes.statusCode === 429) {
22
- // Handling at userResDecorator might be skipped based on your situation, thus handling it later
23
- return data;
24
- }
25
- return data; // Pass through all other non-429 responses
26
- }
27
- });
28
-
29
- // Apply rate limiting and API proxying
30
  app.use('/api', (req, res, next) => {
31
- const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
32
- const currentCount = ipRequestCounts[ip] || 0;
33
-
34
- if (currentCount >= 1) {
35
- res.status(429).send('You have reached your request limit of 1 message. Please contact support for more details.');
36
- return;
37
- }
38
-
39
- ipRequestCounts[ip] = currentCount + 1;
40
- const timestamp = new Date().toISOString();
41
- const requestData = {
42
- requestNumber: ipRequestCounts[ip],
43
- ip: ip,
44
- timestamp: timestamp,
45
- text: req.method + ' ' + req.url
46
- };
47
- requestDetails.push(requestData);
48
- console.log(`Request ${requestData.requestNumber} from IP ${requestData.ip} on ${requestData.timestamp}`);
49
-
50
- next();
51
- }, openAiProxy);
52
-
53
- // Modify proxy responses after the proxy has finished
54
- app.use('/api', function(req, res, next) {
55
- res.on('finish', function() {
56
- if (res.statusCode === 429 && !res.headersSent) {
57
- res.status(429).json({
58
- message: 'Custom message for 429 status.'
59
- });
60
- }
61
- });
62
- next();
63
- });
64
 
65
  app.get("/", (req, res) => {
66
- let requestsInfo = requestDetails.map(detail =>
67
- `Request ${detail.requestNumber} from IP ${detail.ip} on ${detail.timestamp}`).join('<br>');
68
- res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}.<br><br>${requestsInfo}`);
69
  });
70
 
71
  function getExternalUrl(spaceId) {
 
72
  const [username, spacename] = spaceId.split("/");
73
  return `https://${username}-${spacename.replace(/_/g, "-")}.hf.space/api/v1`;
 
 
 
74
  }
75
 
76
  app.listen(port, () => {
77
- console.log(`Reverse proxy server running on ${baseUrl}.`);
78
  });
 
1
+ avatar
2
  const express = require('express');
3
  const proxy = require('express-http-proxy');
4
  const app = express();
 
8
  const port = 7860;
9
  const baseUrl = getExternalUrl(process.env.SPACE_ID);
10
 
11
+ let requestDetails = []; // Store details of each request
12
+ let ipRequestCounts = {}; // Dictionary to keep track of requests per IP
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  app.use('/api', (req, res, next) => {
15
+ const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
16
+ const currentCount = ipRequestCounts[ip] || 0;
17
+
18
+ if (currentCount >= 10) {
19
+ // Send a more generic message without mentioning IP-based limitation
20
+ return res.status(429).send('You reached 10 message limit. Contact me on reddit for more.');
21
+ }
22
+
23
+ // Increment request counter for the IP
24
+ ipRequestCounts[ip] = currentCount + 1;
25
+
26
+ // Log request with timestamp
27
+ const timestamp = new Date().toISOString();
28
+ const requestData = {
29
+ requestNumber: ipRequestCounts[ip],
30
+ ip: ip,
31
+ timestamp: timestamp,
32
+ text: req.method + ' ' + req.url
33
+ };
34
+ requestDetails.push(requestData);
35
+ console.log(`Request ${requestData.requestNumber} on ${requestData.timestamp} from IP ${requestData.ip} with method "${req.method}" and text "${requestData.text}"`);
36
+
37
+ next();
38
+ }, proxy(targetUrl, {
39
+ proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
40
+ proxyReqOpts.headers['Authorization'] = 'Bearer ' + openaiKey;
41
+ return proxyReqOpts;
42
+ },
43
+ }));
 
 
 
 
44
 
45
  app.get("/", (req, res) => {
46
+ let requestsInfo = requestDetails.map(detail =>
47
+ `Request ${detail.requestNumber} on ${detail.timestamp} from IP ${detail.ip} with text "${detail.text}"`).join('<br>');
48
+ res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}.<br><br>${requestsInfo}`);
49
  });
50
 
51
  function getExternalUrl(spaceId) {
52
+ try {
53
  const [username, spacename] = spaceId.split("/");
54
  return `https://${username}-${spacename.replace(/_/g, "-")}.hf.space/api/v1`;
55
+ } catch (e) {
56
+ return "";
57
+ }
58
  }
59
 
60
  app.listen(port, () => {
61
+ console.log(`Reverse proxy server running on ${baseUrl}.`);
62
  });