ardasen commited on
Commit
2c27de7
·
verified ·
1 Parent(s): 5a6c4b1

Create server.js

Browse files
Files changed (1) hide show
  1. server.js +54 -0
server.js ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const proxy = require('express-http-proxy');
3
+ const app = express();
4
+ const bodyParser = require('body-parser');
5
+ const targetUrl = 'https://api.openai.com';
6
+ const openaiKey = process.env.OPENAI_KEY;
7
+ const proxyKey = process.env.PROXY_KEY; // Your secret proxy key
8
+ const port = 7860;
9
+ const baseUrl = getExternalUrl(process.env.SPACE_ID);
10
+
11
+ app.use(bodyParser.json({ limit: '50mb' }));
12
+
13
+ // Middleware to authenticate requests with the proxy key and check the model
14
+ function authenticateProxyKeyAndModel(req, res, next) {
15
+ const providedKey = req.headers['auro']; // Assuming the key is sent in the 'x-proxy-key' header
16
+ const requestedModel = req.body.model;
17
+
18
+ // List of allowed models
19
+ const allowedModels = ['gpt-3.5-turbo', 'gpt-4-vision-preview','text-moderation-latest', 'gpt-3.5-turbo-1106'];
20
+
21
+ if (providedKey && providedKey === proxyKey && allowedModels.includes(requestedModel)) {
22
+ // If the provided key matches the expected key and the requested model is allowed, allow the request to proceed
23
+ next();
24
+ } else {
25
+ // If the key is missing or incorrect, or the model is not allowed, reject the request with an error response
26
+ res.status(401).json({ error: 'Unauthorized or invalid model' });
27
+ }
28
+ }
29
+
30
+
31
+ app.use('/api', authenticateProxyKeyAndModel, proxy(targetUrl, {
32
+ proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
33
+ // Modify the request headers if necessary
34
+ proxyReqOpts.headers['Authorization'] = 'Bearer ' + openaiKey;
35
+ return proxyReqOpts;
36
+ },
37
+ }));
38
+
39
+ app.get("/", (req, res) => {
40
+ // res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}`);
41
+ });
42
+
43
+ function getExternalUrl(spaceId) {
44
+ try {
45
+ const [username, spacename] = spaceId.split("/");
46
+ return `https://${username}-${spacename.replace(/_/g, "-")}.hf.space/api/v1`;
47
+ } catch (e) {
48
+ return "";
49
+ }
50
+ }
51
+
52
+ app.listen(port, () => {
53
+ console.log(`Reverse proxy server running on ${baseUrl}`);
54
+ });