Create server.js
Browse files
server.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const proxy = require('express-http-proxy');
|
| 3 |
+
const bodyParser = require('body-parser');
|
| 4 |
+
const rateLimit = require('express-rate-limit');
|
| 5 |
+
const requestIp = require('request-ip');
|
| 6 |
+
|
| 7 |
+
const app = express();
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
const proxyKey = process.env.PROXY_KEY; // Your secret proxy key
|
| 11 |
+
const adminKey = process.env.ADMIN_KEY; // Your admin key for securing the proxy key endpoint
|
| 12 |
+
const port = 7860;
|
| 13 |
+
const baseUrl = getExternalUrl(process.env.SPACE_ID);
|
| 14 |
+
|
| 15 |
+
app.use(bodyParser.json({ limit: '50mb' }));
|
| 16 |
+
app.set('trust proxy', 1);
|
| 17 |
+
|
| 18 |
+
// Rate limiting middleware
|
| 19 |
+
const limiter = rateLimit({
|
| 20 |
+
windowMs: 15 * 60 * 1000, // 15 minutes
|
| 21 |
+
max: 50, // limit each IP to 50 requests per windowMs
|
| 22 |
+
keyGenerator: (req, res) => req.ip,
|
| 23 |
+
handler: (req, res) => {
|
| 24 |
+
res.status(429).json({
|
| 25 |
+
message: "Too many requests. Please try again later. You can retry after 15 minutes.",
|
| 26 |
+
});
|
| 27 |
+
},
|
| 28 |
+
});
|
| 29 |
+
|
| 30 |
+
// Apply the rate limiter to all requests
|
| 31 |
+
app.use(limiter);
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
// Endpoint to get the proxy key
|
| 35 |
+
app.get('/get-proxy-key', (req, res) => {
|
| 36 |
+
const providedAdminKey = req.headers['admin-key'];
|
| 37 |
+
|
| 38 |
+
if (providedAdminKey && providedAdminKey === adminKey) {
|
| 39 |
+
res.json({ proxyKey });
|
| 40 |
+
} else {
|
| 41 |
+
res.status(403).json({ error: 'Forbidden' });
|
| 42 |
+
}
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
// Health check endpoint
|
| 47 |
+
app.get("/", (req, res) => {
|
| 48 |
+
res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}`);
|
| 49 |
+
});
|
| 50 |
+
|
| 51 |
+
// Helper function to get the external URL
|
| 52 |
+
function getExternalUrl(spaceId) {
|
| 53 |
+
try {
|
| 54 |
+
const [username, spacename] = spaceId.split("/");
|
| 55 |
+
return `https://${username}-${spacename.replace(/_/g, "-")}.hf.space/api/v1`;
|
| 56 |
+
} catch (e) {
|
| 57 |
+
return "";
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// Start the server
|
| 62 |
+
app.listen(port, () => {
|
| 63 |
+
console.log(`Reverse proxy server running on ${baseUrl}`);
|
| 64 |
+
});
|