Create server.js
Browse files
server.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const proxy = require('express-http-proxy');
|
| 3 |
+
const app = express();
|
| 4 |
+
const targetUrl = 'https://api.openai.com';
|
| 5 |
+
const openaiKey = process.env.OPENAI_KEY;
|
| 6 |
+
const proxyKey = process.env.PROXY_KEY; // Your secret proxy key
|
| 7 |
+
const port = 7860;
|
| 8 |
+
const baseUrl = getExternalUrl(process.env.SPACE_ID);
|
| 9 |
+
|
| 10 |
+
// Middleware to authenticate requests with the proxy key
|
| 11 |
+
function authenticateProxyKey(req, res, next) {
|
| 12 |
+
const providedKey = req.headers['auro']; // Assuming the key is sent in the 'x-proxy-key' header
|
| 13 |
+
|
| 14 |
+
if (providedKey && providedKey === proxyKey) {
|
| 15 |
+
// If the provided key matches the expected key, allow the request to proceed
|
| 16 |
+
next();
|
| 17 |
+
} else {
|
| 18 |
+
// If the key is missing or incorrect, reject the request with an error response
|
| 19 |
+
res.status(401).json({ error: 'Unauthorized' });
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
// Use express.urlencoded middleware to handle form data
|
| 24 |
+
app.use('/api', authenticateProxyKey, express.urlencoded({ extended: true }), proxy(targetUrl, {
|
| 25 |
+
proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
|
| 26 |
+
// Modify the request headers if necessary
|
| 27 |
+
proxyReqOpts.headers['Authorization'] = 'Bearer ' + openaiKey;
|
| 28 |
+
return proxyReqOpts;
|
| 29 |
+
},
|
| 30 |
+
}));
|
| 31 |
+
|
| 32 |
+
app.get("/", (req, res) => {
|
| 33 |
+
res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}`);
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
function getExternalUrl(spaceId) {
|
| 37 |
+
try {
|
| 38 |
+
const [username, spacename] = spaceId.split("/");
|
| 39 |
+
return `https://${username}-${spacename.replace(/_/g, "-")}.hf.space/api/v1`;
|
| 40 |
+
} catch (e) {
|
| 41 |
+
return "";
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
app.listen(port, () => {
|
| 46 |
+
console.log(`Reverse proxy server running on ${baseUrl}`);
|
| 47 |
+
});
|