-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
321 lines (278 loc) · 11.5 KB
/
Copy pathserver.ts
File metadata and controls
321 lines (278 loc) · 11.5 KB
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
import express from 'express';
import path from 'path';
import { createServer as createViteServer } from 'vite';
import dotenv from 'dotenv';
// Load environment variables from .env file
dotenv.config();
async function startServer() {
const app = express();
const PORT = 3000;
// Enable JSON request body parsing
app.use(express.json());
// ==========================================
// ONLINE / INTERNET-DEPENDENT ENDPOINTS
// ==========================================
// Endpoint to check which API keys are loaded from the server-side .env file
// This informs the frontend if it can run online with pre-configured keys.
app.get('/api/ai-config', (req, res) => {
res.json({
gemini: !!process.env.GEMINI_API_KEY,
openai: !!process.env.OPENAI_API_KEY,
claude: !!process.env.CLAUDE_API_KEY || !!process.env.ANTHROPIC_API_KEY,
openrouter: !!process.env.OPENROUTER_API_KEY,
huggingface: !!process.env.HUGGINGFACE_API_KEY,
nvidia: !!process.env.NVIDIA_API_KEY,
});
});
// Proxy endpoint to perform AI queries on the server.
// INTERNET REQUIRED: This endpoint connects to external LLM APIs (Google, OpenAI, Anthropic, etc.)
// It resolves CORS issues and hides user keys in the .env file.
app.post('/api/ai', async (req, res) => {
try {
const { provider, model, prompt, history = [], apiKey: clientApiKey, baseUrl } = req.body;
if (!provider) {
return res.status(400).json({ error: 'Provider is required.' });
}
// 1. Resolve API key: Priority to server-side .env, fallback to client-sent key
let resolvedApiKey = '';
switch (provider) {
case 'gemini':
resolvedApiKey = process.env.GEMINI_API_KEY || clientApiKey || '';
break;
case 'openai':
resolvedApiKey = process.env.OPENAI_API_KEY || clientApiKey || '';
break;
case 'claude':
resolvedApiKey = process.env.CLAUDE_API_KEY || process.env.ANTHROPIC_API_KEY || clientApiKey || '';
break;
case 'openrouter':
resolvedApiKey = process.env.OPENROUTER_API_KEY || clientApiKey || '';
break;
case 'huggingface':
resolvedApiKey = process.env.HUGGINGFACE_API_KEY || clientApiKey || '';
break;
case 'nvidia':
resolvedApiKey = process.env.NVIDIA_API_KEY || clientApiKey || '';
break;
case 'ollama':
resolvedApiKey = clientApiKey || ''; // Ollama usually does not require a key
break;
}
if (provider !== 'ollama' && !resolvedApiKey) {
return res.status(401).json({
error: `API Key for ${provider.toUpperCase()} is not set in the server's .env file and was not provided in the client settings.`,
});
}
const messages = [...history, { role: 'user', content: prompt }];
// 2. Query the respective provider via server-to-server request
switch (provider) {
case 'gemini': {
const targetModel = model || 'gemini-2.5-flash';
const url = `https://generativelanguage.googleapis.com/v1beta/models/${targetModel}:generateContent?key=${resolvedApiKey}`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: messages.map((msg: any) => ({
role: msg.role === 'assistant' ? 'model' : 'user',
parts: [{ text: msg.content }],
})),
}),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err?.error?.message || `Gemini API Error: ${response.statusText}`);
}
const data: any = await response.json();
const text = data?.candidates?.[0]?.content?.parts?.[0]?.text;
if (!text) throw new Error('No response content returned from Gemini.');
return res.json({ text });
}
case 'openai': {
const targetUrl = `${baseUrl || 'https://api.openai.com/v1'}/chat/completions`;
const targetModel = model || 'gpt-4o-mini';
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${resolvedApiKey}`,
},
body: JSON.stringify({
model: targetModel,
messages: messages.map((msg: any) => ({
role: msg.role === 'assistant' ? 'assistant' : 'user',
content: msg.content,
})),
}),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err?.error?.message || `OpenAI API Error: ${response.statusText}`);
}
const data: any = await response.json();
const text = data?.choices?.[0]?.message?.content || '';
return res.json({ text });
}
case 'claude': {
const targetUrl = 'https://api.anthropic.com/v1/messages';
const targetModel = model || 'claude-3-5-sonnet-20241022';
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-api-key': resolvedApiKey,
'anthropic-version': '2023-06-01',
},
body: JSON.stringify({
model: targetModel,
max_tokens: 1024,
messages: messages.map((msg: any) => ({
role: msg.role === 'assistant' ? 'assistant' : 'user',
content: msg.content,
})),
}),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err?.error?.message || `Claude API Error: ${response.statusText}`);
}
const data: any = await response.json();
const text = data?.content?.[0]?.text || '';
return res.json({ text });
}
case 'openrouter': {
const targetUrl = `${baseUrl || 'https://openrouter.ai/api/v1'}/chat/completions`;
const targetModel = model || 'google/gemini-2.5-flash';
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${resolvedApiKey}`,
'X-Title': 'Kali Linux Simulator Web OS',
},
body: JSON.stringify({
model: targetModel,
messages: messages.map((msg: any) => ({
role: msg.role === 'assistant' ? 'assistant' : 'user',
content: msg.content,
})),
}),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err?.error?.message || `OpenRouter API Error: ${response.statusText}`);
}
const data: any = await response.json();
const text = data?.choices?.[0]?.message?.content || '';
return res.json({ text });
}
case 'huggingface': {
const targetModel = model || 'meta-llama/Llama-3.3-70B-Instruct';
const targetUrl = `${baseUrl || 'https://api-inference.huggingface.co/models'}/${targetModel}`;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${resolvedApiKey}`,
},
body: JSON.stringify({
inputs: prompt,
parameters: {
max_new_tokens: 512,
return_full_text: false,
},
}),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err?.error?.message || `Hugging Face API Error: ${response.statusText}`);
}
const data: any = await response.json();
let text = '';
if (Array.isArray(data) && data[0]?.generated_text) {
text = data[0].generated_text;
} else {
text = JSON.stringify(data);
}
return res.json({ text });
}
case 'nvidia': {
const targetUrl = `${baseUrl || 'https://integrate.api.nvidia.com/v1'}/chat/completions`;
const targetModel = model || 'meta/llama-3.1-405b-instruct';
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${resolvedApiKey}`,
},
body: JSON.stringify({
model: targetModel,
messages: messages.map((msg: any) => ({
role: msg.role === 'assistant' ? 'assistant' : 'user',
content: msg.content,
})),
max_tokens: 1024,
}),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err?.error?.message || `Nvidia API Error: ${response.statusText}`);
}
const data: any = await response.json();
const text = data?.choices?.[0]?.message?.content || '';
return res.json({ text });
}
case 'ollama': {
// OFFLINE: Local Ollama runs on localhost. The server can proxy it or connect locally.
const cleanBaseUrl = (baseUrl || 'http://localhost:11434').replace(/\/$/, '');
const url = `${cleanBaseUrl}/api/chat`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: model || 'llama3',
messages: messages.map((msg: any) => ({
role: msg.role === 'assistant' ? 'assistant' : 'user',
content: msg.content,
})),
stream: false,
}),
});
if (!response.ok) {
throw new Error(`Ollama Error: Failed to connect to ${cleanBaseUrl}. Make sure your local Ollama is running and CORS is enabled.`);
}
const data: any = await response.json();
const text = data?.message?.content || '';
return res.json({ text });
}
default:
return res.status(400).json({ error: `Unknown provider: ${provider}` });
}
} catch (err: any) {
console.error('Server-side AI Proxy Error:', err);
return res.status(500).json({ error: err.message || 'An internal server error occurred.' });
}
});
// ==========================================
// VITE DEVELOPMENT MIDDLEWARE / STATIC FILES
// ==========================================
if (process.env.NODE_ENV !== 'production') {
// Development mode: Run Vite middleware
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
// Production mode: Serve built static files from /dist
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`[Kali Server] Listening on http://localhost:${PORT} in ${process.env.NODE_ENV || 'development'} mode`);
});
}
startServer();