-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
server.js
402 lines (328 loc) · 11.2 KB
/
server.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
Error.stackTraceLimit = 0;
import express from 'express';
import cors from 'cors';
import fetch from 'node-fetch';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
import axios from 'axios';
import multer from 'multer';
import FormData from 'form-data';
import { generateEmbedScript } from './src/utils/embedScript.js';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const API_HOST = process.env.API_HOST;
const FLOWISE_API_KEY = process.env.FLOWISE_API_KEY;
if (!API_HOST) {
console.error('API_HOST is not set in environment variables');
process.exit(1);
}
if (!FLOWISE_API_KEY) {
console.error('FLOWISE_API_KEY is not set in environment variables');
process.exit(1);
}
const parseChatflows = () => {
try {
const chatflows = new Map();
// Get all environment variables that don't start with special prefixes
const chatflowVars = Object.entries(process.env).filter(([key]) => {
return !key.startsWith('_') &&
!key.startsWith('npm_') &&
!key.startsWith('yarn_') &&
!key.startsWith('VSCODE_') &&
key !== 'API_HOST' &&
key !== 'FLOWISE_API_KEY' &&
key !== 'PORT' &&
key !== 'HOST' &&
key !== 'BASE_URL' &&
key !== 'NODE_ENV';
});
if (chatflowVars.length === 0) {
console.error('No chatflow configurations found in environment variables');
process.exit(1);
}
const defaultDomains = process.env.NODE_ENV === 'production'
? []
: ['http://localhost:5678'];
for (const [identifier, value] of chatflowVars) {
const parts = value.split(',').map(s => s.trim());
const chatflowId = parts[0];
const configuredDomains = parts.length > 1 ? parts.slice(1) : [];
const domains = [...new Set([...defaultDomains, ...configuredDomains])];
if (!chatflowId) {
console.error(`Missing chatflow ID for ${identifier}`);
continue;
}
if (domains.includes('*')) {
console.error(`\x1b[31mError: Wildcard (*) domains are not allowed in ${identifier}. This flow will not be accessible.\x1b[0m`);
continue;
}
chatflows.set(identifier, { chatflowId, domains });
}
if (chatflows.size === 0) {
console.error('No valid chatflow configurations found');
process.exit(1);
}
return chatflows;
} catch (error) {
console.error('Failed to parse chatflow configurations:', error);
process.exit(1);
}
};
const chatflows = parseChatflows();
const getChatflowDetails = (identifier) => {
let chatflow = chatflows.get(identifier);
if (!chatflow) {
const lowerIdentifier = identifier.toLowerCase();
for (const [key, value] of chatflows.entries()) {
if (key.toLowerCase() === lowerIdentifier) {
chatflow = value;
break;
}
}
}
if (!chatflow) {
throw new Error(`Chatflow not found: ${identifier}`);
}
return chatflow;
};
const isValidUUID = (str) => {
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
return uuidPattern.test(str);
};
const isValidChatflowConfig = (value) => {
if (!value) return false;
const parts = value.split(',').map(s => s.trim());
return isValidUUID(parts[0]);
};
console.info('\x1b[36m%s\x1b[0m', 'Configured chatflows:');
chatflows.forEach((config, identifier) => {
if (isValidChatflowConfig(config.chatflowId)) {
console.info('\x1b[36m%s\x1b[0m', ` ${identifier}: ${config.chatflowId} (${config.domains.join(', ')})`);
}
});
const isValidDomain = (origin, domains) => {
if (!origin) return true;
return domains.includes(origin);
};
const app = express();
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
app.use(
cors({
origin: true,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'OPTIONS'],
allowedHeaders: ['*'],
}),
);
app.get('/', (_, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/web.js', (req, res) => {
const origin = req.headers.origin;
const allAllowedDomains = Array.from(chatflows.values()).flatMap((config) => config.domains);
if (!isValidDomain(origin, allAllowedDomains)) {
return res.status(403).send('Access Denied');
}
res.set({
'Content-Type': 'application/javascript',
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
Pragma: 'no-cache',
Expires: '0',
});
res.sendFile(path.join(__dirname, 'dist', 'web.js'));
});
const validateApiKey = (req, res, next) => {
if (req.path === '/web.js' || req.path === '/' || req.method === 'OPTIONS') {
return next();
}
if (req.path.includes('/get-upload-file')) {
return next();
}
let identifier;
const pathParts = req.path.split('/').filter(Boolean);
if (pathParts.length >= 3) {
identifier = pathParts[3];
} else {
identifier = req.query.chatflowId?.split('/')[0];
}
if (!identifier) {
return res.status(400).json({ error: 'Bad Request' });
}
let chatflow;
try {
chatflow = getChatflowDetails(identifier);
req.chatflow = chatflow;
} catch (error) {
return res.status(404).json({ error: 'Not Found' });
}
const origin = req.headers.origin;
const userAgent = req.headers['user-agent'];
const acceptLanguage = req.headers['accept-language'];
const accept = req.headers['accept'];
const secChUa = req.headers['sec-ch-ua'];
const secChUaPlatform = req.headers['sec-ch-ua-platform'];
const secChUaMobile = req.headers['sec-ch-ua-mobile'];
const secFetchMode = req.headers['sec-fetch-mode'];
const secFetchSite = req.headers['sec-fetch-site'];
if (
userAgent &&
acceptLanguage &&
accept &&
secChUa &&
secChUaPlatform &&
secChUaMobile &&
['?0', '?1'].includes(secChUaMobile) &&
secFetchMode === 'cors' &&
secFetchSite &&
['same-origin', 'same-site', 'cross-site'].includes(secFetchSite)
) {
if (isValidDomain(origin, chatflow.domains)) {
return next();
}
}
const authHeader = req.headers.authorization;
if (authHeader && authHeader.startsWith('Bearer ') && authHeader.split(' ')[1] === FLOWISE_API_KEY) {
return next();
}
return res.status(401).json({ error: 'Unauthorized' });
};
app.use(validateApiKey);
const proxyEndpoints = {
prediction: {
method: 'POST',
path: '/api/v1/prediction/:identifier',
target: '/api/v1/prediction',
},
config: {
method: 'GET',
path: '/api/v1/public-chatbotConfig/:identifier',
target: '/api/v1/public-chatbotConfig',
},
streaming: {
method: 'GET',
path: '/api/v1/chatflows-streaming/:identifier',
target: '/api/v1/chatflows-streaming',
},
files: {
method: 'GET',
path: '/api/v1/get-upload-file',
target: '/api/v1/get-upload-file',
},
};
const handleProxy = async (req, res, targetPath) => {
try {
let identifier = req.query.chatflowId?.split('/')[0] || req.path.split('/').pop() || null;
if (!identifier) {
return res.status(400).json({ error: 'Bad Request' });
}
const chatflow = getChatflowDetails(identifier);
if (!chatflow) {
return res.status(404).json({ error: 'Not Found' });
}
if (req.query.chatId && req.query.fileName) {
const url = `${API_HOST}${targetPath}?chatflowId=${chatflow.chatflowId}&chatId=${req.query.chatId}&fileName=${req.query.fileName}`;
const response = await fetch(url, {
method: req.method,
headers: {
Authorization: `Bearer ${FLOWISE_API_KEY}`,
},
});
if (!response.ok) {
console.error(`File proxy error: ${response.status} ${response.statusText}`);
return res.status(response.status).json({ error: `File proxy error: ${response.statusText}` });
}
const contentType = response.headers.get('content-type');
if (contentType) {
res.setHeader('Content-Type', contentType);
}
return response.body.pipe(res);
}
let finalPath = `${targetPath}/${chatflow.chatflowId}`;
const url = `${API_HOST}${finalPath}`;
const response = await fetch(url, {
method: req.method,
headers: {
...(req.method !== 'GET' && { 'Content-Type': 'application/json' }),
Authorization: `Bearer ${FLOWISE_API_KEY}`,
},
body: req.method !== 'GET' ? JSON.stringify(req.body) : undefined,
});
if (!response.ok) {
console.error(`Proxy error: ${response.status} ${response.statusText}`);
return res.status(response.status).json({ error: `Proxy error: ${response.statusText}` });
}
const contentType = response.headers.get('content-type');
if (contentType?.includes('image/') || contentType?.includes('audio/') || contentType?.includes('application/octet-stream')) {
res.setHeader('Content-Type', contentType);
return response.body.pipe(res);
}
if (contentType?.includes('text/event-stream')) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
return response.body.pipe(res);
}
if (contentType?.includes('application/json')) {
const data = await response.json();
return res.json(data);
}
return response.body.pipe(res);
} catch (error) {
console.error('Proxy error:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};
Object.values(proxyEndpoints).forEach(({ method, path, target }) => {
app[method.toLowerCase()](path, (req, res) => {
return handleProxy(req, res, target);
});
});
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.post('/api/v1/attachments/:identifier/:chatId', upload.array('files'), async (req, res) => {
try {
const chatId = req.params.chatId;
if (!chatId) {
return res.status(400).json({ error: 'Bad Request' });
}
if (!req.files || req.files.length === 0) {
return res.status(400).json({ error: 'Bad Request' });
}
const form = new FormData();
req.files.forEach((file) => {
form.append('files', file.buffer, {
filename: file.originalname,
contentType: file.mimetype,
});
});
const chatflow = req.chatflow;
const targetUrl = `${API_HOST}/api/v1/attachments/${chatflow.chatflowId}/${chatId}`;
const response = await axios.post(targetUrl, form, {
headers: {
...form.getHeaders(),
Authorization: `Bearer ${FLOWISE_API_KEY}`,
},
});
res.json(response.data);
} catch (error) {
console.error('Attachment upload error:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.use((_req, res) => {
res.status(404).json({ error: 'Not Found' });
});
const PORT = process.env.PORT || 3001;
const HOST = process.env.HOST || '0.0.0.0';
const server = app.listen(PORT, HOST, () => {
const addr = server.address();
if (!addr || typeof addr === 'string') return;
const baseUrl = process.env.BASE_URL ||
process.env.NODE_ENV === 'production'
? `https://${process.env.HOST || 'localhost'}`
: `http://${HOST === '0.0.0.0' ? 'localhost' : HOST}:${addr.port}`;
generateEmbedScript(baseUrl);
});