Spaces:
Running
Running
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}.`); | |
}); |