-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathutils.js
468 lines (433 loc) · 12.2 KB
/
utils.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
const fs = require('fs');
const readline = require('readline');
const crypto = require('crypto');
const axios = require('axios');
const { getDb } = require('./db');
let server;
let currentPort;
let expressApp;
function startServer(port, app) {
currentPort = port;
expressApp = app; // Store the app object
server = expressApp.listen(currentPort, () => console.log(`Server running on port ${currentPort}`));
}
function askForPort(app, startServerCallback, askForOllamaURLCallback, startCLICallback, db) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the port number for the API server: ', (port) => {
fs.writeFile('port.conf', port, (err) => {
if (err) {
console.error('Error saving port number:', err.message);
} else {
console.log(`Port number saved to port.conf: ${port}`);
currentPort = parseInt(port);
askForOllamaURLCallback(app, startServerCallback, startCLICallback, currentPort, db);
}
});
rl.close();
});
}
function askForOllamaURL(app, startServerCallback, startCLICallback, port, db) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the URL for the Ollama server (URL that your Ollama server is running on. By default it is "http://localhost:11434" so if you didnt change anything it should be that.): ', (ollamaURL) => {
fs.writeFile('ollamaURL.conf', ollamaURL, (err) => {
if (err) {
console.error('Error saving Ollama url:', err.message);
} else {
console.log(`Ollama url saved to ollamaURL.conf: ${ollamaURL}`);
startServerCallback(port, app);
startCLICallback(db);
}
});
rl.close();
});
}
function startCLI(db) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', (input) => {
const [command, argument, ...rest] = input.trim().split(' ');
const description = rest.join(' ');
switch (command) {
case 'generatekey':
generateKey(db);
break;
case 'generatekeys':
generateKeys(db, argument);
break;
case 'listkey':
listKeys(db);
break;
case 'removekey':
removeKey(db, argument);
break;
case 'addkey':
addKey(db, argument);
break;
case 'changeport':
changePort(argument);
break;
case 'changeollamaurl':
changeOllamaURL(argument);
break;
case 'ratelimit':
setRateLimit(db, argument, rest[0]);
break;
case 'addwebhook':
addWebhook(db, argument);
break;
case 'deletewebhook':
deleteWebhook(db, argument);
break;
case 'listwebhooks':
listWebhooks(db);
break;
case 'activatekey':
activateKey(db, argument);
break;
case 'deactivatekey':
deactivateKey(db, argument);
break;
case 'addkeydescription':
addKeyDescription(db, argument, description);
break;
case 'listkeydescription':
listKeyDescription(db, argument);
break;
case 'regeneratekey':
regenerateKey(db, argument);
break;
case 'activateallkeys':
activateAllKeys(db);
break;
case 'deactivateallkeys':
deactivateAllKeys(db);
break;
case 'getkeyinfo':
getKeyInfo(db, argument);
break;
case 'listinactivekeys':
listInactiveKeys(db);
break;
case 'listactivekeys':
listActiveKeys(db);
break;
case 'exit':
rl.close();
process.exit(0);
break;
default:
console.log('Unknown command');
}
});
}
function generateKey(db) {
const apiKey = crypto.randomBytes(20).toString('hex');
db.run('INSERT INTO apiKeys(key, rate_limit) VALUES(?, 10)', [apiKey], (err) => {
if (err) {
console.error('Error generating API key:', err.message);
} else {
console.log(`API key generated: ${apiKey}`);
}
});
}
function generateKeys(db, count) {
if (!count || isNaN(count)) {
console.log('Invalid number of keys');
return;
}
const numberOfKeys = parseInt(count);
for (let i = 0; i < numberOfKeys; i++) {
generateKey(db);
}
}
function listKeys(db) {
db.all('SELECT key, active, description FROM apiKeys', [], (err, rows) => {
if (err) {
console.error('Error listing API keys:', err.message);
} else {
console.log('API keys:', rows);
}
});
}
function removeKey(db, key) {
db.run('DELETE FROM apiKeys WHERE key = ?', [key], (err) => {
if (err) {
console.error('Error removing API key:', err.message);
} else {
console.log('API key removed');
}
});
}
function addKey(db, key) {
console.log('Warning: Adding your own keys may be unsafe. It is recommended to generate keys using the generatekey command.');
db.run('INSERT INTO apiKeys(key, rate_limit) VALUES(?, 10)', [key], (err) => {
if (err) {
console.error('Error adding API key:', err.message);
} else {
console.log(`API key added: ${key}`);
}
});
}
function changePort(newPort) {
if (!newPort || isNaN(newPort)) {
console.log('Invalid port number');
return;
}
const port = parseInt(newPort);
if (server) {
server.close((err) => {
if (err) {
console.error('Error closing the server:', err.message);
} else {
console.log(`Server closed on port ${currentPort}`);
updatePortAndRestart(port);
}
});
} else {
updatePortAndRestart(port);
}
}
function updatePortAndRestart(port) {
fs.writeFile('port.conf', port.toString(), (err) => {
if (err) {
console.error('Error saving port number:', err.message);
} else {
console.log(`Port number saved to port.conf: ${port}`);
if (expressApp) {
startServer(port, expressApp);
} else {
console.error('Express app not available. Unable to restart server.');
}
}
});
}
function changeOllamaURL(newURL) {
const urlPattern = /^(http|https):\/\/[^\s$.?#].[^\s]*$/gm;
if (!newURL || !urlPattern.test(newURL)) {
console.log('Invalid Ollama URL');
return;
}
const URL = newURL;
fs.writeFile('ollamaURL.conf', URL, (err) => {
if (err) {
console.error('Error saving Ollama URL:', err.message);
} else {
console.log(`Ollama URL saved to ollamaURL.conf: ${URL}`);
}
});
}
function setRateLimit(db, key, limit) {
if (!key || !limit || isNaN(limit)) {
console.log('Invalid API key or rate limit number');
return;
}
const rateLimit = parseInt(limit);
db.run('UPDATE apiKeys SET rate_limit = ? WHERE key = ?', [rateLimit, key], (err) => {
if (err) {
console.error('Error setting rate limit:', err.message);
} else {
console.log(`Rate limit set to ${rateLimit} requests per minute for API key: ${key}`);
}
});
}
function addWebhook(db, url) {
if (!url) {
console.log('Webhook URL is required');
return;
}
db.run('INSERT INTO webhooks (url) VALUES (?)', [url], (err) => {
if (err) {
console.error('Error adding webhook:', err.message);
} else {
console.log(`Webhook added: ${url}`);
}
});
}
function deleteWebhook(db, id) {
if (!id) {
console.log('Webhook ID is required');
return;
}
db.run('DELETE FROM webhooks WHERE id = ?', [id], (err) => {
if (err) {
console.error('Error deleting webhook:', err.message);
} else {
console.log('Webhook deleted');
}
});
}
function listWebhooks(db) {
db.all('SELECT id, url FROM webhooks', [], (err, rows) => {
if (err) {
console.error('Error listing webhooks:', err.message);
} else {
console.log('Webhooks:', rows);
}
});
}
function activateKey(db, key) {
db.run('UPDATE apiKeys SET active = 1 WHERE key = ?', [key], (err) => {
if (err) {
console.error('Error activating API key:', err.message);
} else {
console.log(`API key ${key} activated`);
}
});
}
function deactivateKey(db, key) {
db.run('UPDATE apiKeys SET active = 0 WHERE key = ?', [key], (err) => {
if (err) {
console.error('Error deactivating API key:', err.message);
} else {
console.log(`API key ${key} deactivated`);
}
});
}
function addKeyDescription(db, key, description) {
if (!key || !description) {
console.log('Invalid API key or description');
return;
}
db.run('UPDATE apiKeys SET description = ? WHERE key = ?', [description, key], (err) => {
if (err) {
console.error('Error adding description:', err.message);
} else {
console.log(`Description added to API key ${key}`);
}
});
}
function listKeyDescription(db, key) {
if (!key) {
console.log('Invalid API key');
return;
}
db.get('SELECT description FROM apiKeys WHERE key = ?', [key], (err, row) => {
if (err) {
console.error('Error retrieving description:', err.message);
} else {
if (row) {
console.log(`Description for API key ${key}: ${row.description}`);
} else {
console.log(`No description found for API key ${key}`);
}
}
});
}
function regenerateKey(db, oldKey) {
if (!oldKey) {
console.log('Invalid API key');
return;
}
const newApiKey = crypto.randomBytes(20).toString('hex');
db.run('UPDATE apiKeys SET key = ? WHERE key = ?', [newApiKey, oldKey], (err) => {
if (err) {
console.error('Error regenerating API key:', err.message);
} else {
console.log(`API key regenerated. New API key: ${newApiKey}`);
}
});
}
function activateAllKeys(db) {
db.run('UPDATE apiKeys SET active = 1', (err) => {
if (err) {
console.error('Error activating all API keys:', err.message);
} else {
console.log('All API keys activated');
}
});
}
function deactivateAllKeys(db) {
db.run('UPDATE apiKeys SET active = 0', (err) => {
if (err) {
console.error('Error deactivating all API keys:', err.message);
} else {
console.log('All API keys deactivated');
}
});
}
function getKeyInfo(db, key) {
db.get('SELECT * FROM apiKeys WHERE key = ?', [key], (err, row) => {
if (err) {
console.error('Error retrieving API key info:', err.message);
} else if (row) {
console.log('API key info:', row);
} else {
console.log('No API key found with the given key.');
}
});
}
function listInactiveKeys(db) {
db.all('SELECT key FROM apiKeys WHERE active = 0', [], (err, rows) => {
if (err) {
console.error('Error listing inactive API keys:', err.message);
} else {
console.log('Inactive API keys:', rows);
}
});
}
function listActiveKeys(db) {
db.all('SELECT key FROM apiKeys WHERE active = 1', [], (err, rows) => {
if (err) {
console.error('Error listing active API keys:', err.message);
} else {
console.log('Active API keys:', rows);
}
});
}
function getOllamaURL() {
return new Promise((resolve, reject) => {
if (fs.existsSync('ollamaURL.conf')) {
fs.readFile('ollamaURL.conf', 'utf8', (err, data) => {
if (err) {
reject('Error reading Ollama url from file:', err.message);
} else {
const ollamaURL = data.trim();
if (typeof ollamaURL !== 'string' || ollamaURL === '') {
reject('Invalid Ollama url in ollamaURL.conf');
} else {
resolve(ollamaURL);
}
}
});
} else {
reject('Ollama url configuration file not found');
}
});
}
function sendWebhookNotification(db, payload) {
db.all('SELECT url FROM webhooks', [], (err, rows) => {
if (err) {
console.error('Error retrieving webhooks:', err.message);
} else {
rows.forEach(row => {
const webhookPayload = {
content: JSON.stringify(payload, null, 2)
};
axios.post(row.url, webhookPayload)
.then(response => {
console.log('Webhook notification sent successfully:', response.data);
})
.catch(error => {
console.error('Error sending webhook notification:', error.message);
});
});
}
});
}
module.exports = {
startServer,
askForPort,
askForOllamaURL,
startCLI,
getOllamaURL,
sendWebhookNotification,
updatePortAndRestart
};