ardasen commited on
Commit
cd88b34
·
1 Parent(s): 375874e

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +23 -93
server.js CHANGED
@@ -1,120 +1,50 @@
1
  const express = require('express');
2
  const proxy = require('express-http-proxy');
3
- const FormData = require('form-data');
4
- const https = require('https');
5
- const url = require('url');
6
- const bodyParser = require('body-parser'); // Add bodyParser to parse request body
7
- var multer = require('multer')();
8
  const app = express();
 
9
  const targetUrl = 'https://api.openai.com';
10
  const openaiKey = process.env.OPENAI_KEY;
11
- const proxyKey = process.env.PROXY_KEY;
12
  const port = 7860;
13
  const baseUrl = getExternalUrl(process.env.SPACE_ID);
14
 
15
- app.use(bodyParser.json({ limit: '50mb' })); // Use bodyParser to parse JSON request body
16
 
17
- function authenticateProxyKey(req, res, next) {
18
- const providedKey = req.headers['auro'];
 
 
19
 
20
- if (providedKey && providedKey === proxyKey) {
 
21
  next();
22
  } else {
23
- res.status(401).json({ error: 'Unauthorized' });
 
24
  }
25
  }
26
 
27
- app.use('/api', (req, res, next) => {
28
- if (req.method === 'POST') {
29
- console.log(`Incoming POST Request to ${req.originalUrl}`);
30
- console.log('Request Headers:', req.headers);
31
- console.log('Request Body:', req.body);
32
- console.log('Query Parameters:', req.query);
33
- }
34
- next();
35
- });
36
-
37
-
38
- app.post('/api/proxy', multer.single('fileFieldName'), async (req, res) => {
39
- const audioBase64 = req.fileFieldName; // Get audio data from the request body
40
-
41
- if (!audioBase64) {
42
- res.status(400).json({ error: 'Missing audio data' });
43
- return;
44
- }
45
-
46
- const audioBuffer = Buffer.from(audioBase64, 'base64');
47
-
48
- const headers = {
49
- auro: openaiKey,
50
- 'Content-Type': 'multipart/form-data',
51
- };
52
-
53
- const form = new FormData();
54
-
55
- // Append the audio data as a buffer with the appropriate content type
56
- form.append('fileFieldName', audioBuffer, {
57
- filename: 'audioFile',
58
- contentType: 'audio/m4a',
59
- });
60
-
61
- // Append other form fields
62
- form.append('model', 'whisper-1');
63
- form.append('response_format', 'text');
64
 
65
- const requestOptions = {
66
- method: 'POST',
67
- headers,
68
- path: '/audio/transcriptions',
69
- host: targetUrl.replace('https://', ''),
70
- port: 443,
71
- };
72
-
73
- try {
74
- const request = https.request(requestOptions, (response) => {
75
- let data = '';
76
-
77
- response.on('data', (chunk) => {
78
- data += chunk;
79
- });
80
-
81
- response.on('end', () => {
82
- if (response.statusCode === 200) {
83
- res.status(200).json({ transcription: data });
84
- } else {
85
- res.status(response.statusCode).json({ error: data });
86
- }
87
- });
88
- });
89
-
90
- form.pipe(request);
91
-
92
- request.on('error', (error) => {
93
- console.error(error);
94
- res.status(500).json({ error: 'Internal Server Error' });
95
- });
96
-
97
- request.end();
98
- } catch (error) {
99
- console.error(error);
100
- res.status(500).json({ error: 'Internal Server Error' });
101
- }
102
  });
103
 
104
-
105
  function getExternalUrl(spaceId) {
106
  try {
107
- const [username, spacename] = spaceId.split('/');
108
- return `https://${username}-${spacename.replace(/_/g, '-')}.hf.space/api/v1`;
109
  } catch (e) {
110
- return '';
111
  }
112
  }
113
 
114
- app.get('/', (req, res) => {
115
- res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}`);
116
- });
117
-
118
  app.listen(port, () => {
119
  console.log(`Reverse proxy server running on ${baseUrl}`);
120
  });
 
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
+ if (providedKey && providedKey === proxyKey && requestedModel === 'gpt-3.5-turbo') {
19
+ // If the provided key matches the expected key and the requested model is 'gpt-3.5', allow the request to proceed
20
  next();
21
  } else {
22
+ // If the key is missing or incorrect, or the model is not 'gpt-3.5', reject the request with an error response
23
+ res.status(401).json({ error: 'Unauthorized or invalid model' });
24
  }
25
  }
26
 
27
+ app.use('/api', authenticateProxyKeyAndModel, proxy(targetUrl, {
28
+ proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
29
+ // Modify the request headers if necessary
30
+ proxyReqOpts.headers['Authorization'] = 'Bearer ' + openaiKey;
31
+ return proxyReqOpts;
32
+ },
33
+ }));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ app.get("/", (req, res) => {
36
+ // res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  });
38
 
 
39
  function getExternalUrl(spaceId) {
40
  try {
41
+ const [username, spacename] = spaceId.split("/");
42
+ return `https://${username}-${spacename.replace(/_/g, "-")}.hf.space/api/v1`;
43
  } catch (e) {
44
+ return "";
45
  }
46
  }
47
 
 
 
 
 
48
  app.listen(port, () => {
49
  console.log(`Reverse proxy server running on ${baseUrl}`);
50
  });