File size: 1,791 Bytes
f2c71b4
 
93bcb1c
cd88b34
a3db9d3
d101f54
cd88b34
f2c71b4
a3db9d3
f2c71b4
cd88b34
93bcb1c
cd88b34
 
 
 
f2c71b4
cd88b34
 
f2c71b4
 
cd88b34
 
f2c71b4
 
 
cd88b34
 
 
 
 
 
 
e82d0de
cd88b34
 
a3db9d3
f2c71b4
a3db9d3
 
cd88b34
 
a3db9d3
cd88b34
f2c71b4
a3db9d3
 
363354f
a3db9d3
363354f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const express = require('express');
const proxy = require('express-http-proxy');
const app = express();
const bodyParser = require('body-parser');
const targetUrl = 'https://api.openai.com';
const openaiKey = process.env.OPENAI_KEY;
const proxyKey = process.env.PROXY_KEY; // Your secret proxy key
const port = 7860;
const baseUrl = getExternalUrl(process.env.SPACE_ID);

app.use(bodyParser.json({ limit: '50mb' }));

// Middleware to authenticate requests with the proxy key and check the model
function authenticateProxyKeyAndModel(req, res, next) {
  const providedKey = req.headers['auro']; // Assuming the key is sent in the 'x-proxy-key' header
  const requestedModel = req.body.model;

  if (providedKey && providedKey === proxyKey && requestedModel === 'gpt-3.5-turbo') {
    // If the provided key matches the expected key and the requested model is 'gpt-3.5', allow the request to proceed
    next();
  } else {
    // If the key is missing or incorrect, or the model is not 'gpt-3.5', reject the request with an error response
    res.status(401).json({ error: 'Unauthorized or invalid model' });
  }
}

app.use('/api', authenticateProxyKeyAndModel, proxy(targetUrl, {
  proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
    // Modify the request headers if necessary
    proxyReqOpts.headers['Authorization'] = 'Bearer ' + openaiKey;
    return proxyReqOpts;
  },
}));

app.get("/", (req, res) => {
  // res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}`);
});

function getExternalUrl(spaceId) {
  try {
    const [username, spacename] = spaceId.split("/");
    return `https://${username}-${spacename.replace(/_/g, "-")}.hf.space/api/v1`;
  } catch (e) {
    return "";
  }
}

app.listen(port, () => {
  console.log(`Reverse proxy server running on ${baseUrl}`);
});