Repository navigation
Expand file tree
/
Copy pathapi.js
More file actions
308 lines (255 loc) · 8.86 KB
/
Copy pathapi.js
File metadata and controls
308 lines (255 loc) · 8.86 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
const axios = require('axios');
const db = require('./db');
const { getOllamaURL, sendWebhookNotification } = require('./utils');
const rateLimits = new Map();
let rateLimitBatchTimer = null;
const rateLimitBatchQueue = new Map();
const MAX_FAILED_ATTEMPTS = 5;
const LOCKOUT_DURATION_MS = 15 * 60 * 1000;
const failedAttempts = new Map();
const healthCache = { data: null, ttl: 0 };
const CLEANUP_INTERVAL_MS = 5 * 60 * 1000;
setInterval(() => {
const now = Date.now();
for (const [apikey, info] of rateLimits) {
if (now - info.lastUsed > 60000) rateLimits.delete(apikey);
}
for (const [ip, record] of failedAttempts) {
if (record.lockedUntil && now >= record.lockedUntil) failedAttempts.delete(ip);
else if (!record.lockedUntil && now - record.firstAttempt > LOCKOUT_DURATION_MS) failedAttempts.delete(ip);
}
}, CLEANUP_INTERVAL_MS);
function getClientIp(req) {
return req.ip || req.socket?.remoteAddress || 'unknown';
}
function checkBruteForce(ip) {
const record = failedAttempts.get(ip);
if (!record) return null;
if (record.lockedUntil && Date.now() < record.lockedUntil) {
const remaining = Math.ceil((record.lockedUntil - Date.now()) / 1000);
return `Too many failed attempts. Try again in ${remaining} seconds.`;
}
if (record.lockedUntil && Date.now() >= record.lockedUntil) {
failedAttempts.delete(ip);
}
return null;
}
function recordFailedAttempt(ip) {
const now = Date.now();
const record = failedAttempts.get(ip) || { count: 0, firstAttempt: now, lockedUntil: null };
record.count += 1;
if (record.count >= MAX_FAILED_ATTEMPTS) {
record.lockedUntil = now + LOCKOUT_DURATION_MS;
console.warn(`Brute-force lockout triggered for IP ${ip} (${record.count} failed attempts)`);
}
failedAttempts.set(ip, record);
}
function clearFailedAttempts(ip) {
failedAttempts.delete(ip);
}
function extractApiKey(req) {
const authHeader = req.headers.authorization;
if (authHeader && authHeader.startsWith('Bearer ')) {
return authHeader.slice(7);
}
return null;
}
async function flushRateLimitBatch() {
const promises = [];
for (const [apikey, info] of rateLimitBatchQueue) {
promises.push(
db.run('UPDATE apiKeys SET tokens = ?, last_used = ? WHERE key = ?', [
info.tokens,
new Date(info.lastUsed).toISOString(),
apikey
]).catch(() => {})
);
}
rateLimitBatchQueue.clear();
rateLimitBatchTimer = null;
await Promise.allSettled(promises);
}
function scheduleRateLimitFlush() {
if (!rateLimitBatchTimer) {
rateLimitBatchTimer = setTimeout(flushRateLimitBatch, 3000);
}
}
async function verifyApiKey(apikey) {
if (!apikey) return null;
try {
return await db.get('SELECT * FROM apiKeys WHERE key = ?', [apikey]);
} catch (err) {
console.error('Database error during key verification:', err.message);
throw err;
}
}
async function authenticateRequest(req, res) {
const ip = getClientIp(req);
const lockoutError = checkBruteForce(ip);
if (lockoutError) {
return res.status(429).json({ error: lockoutError });
}
const apikey = extractApiKey(req);
if (!apikey) {
recordFailedAttempt(ip);
return res.status(401).json({ error: 'API key is required (use Authorization: Bearer header)' });
}
const keyInfo = await verifyApiKey(apikey);
if (!keyInfo) {
recordFailedAttempt(ip);
return res.status(403).json({ error: 'Invalid API key' });
}
clearFailedAttempts(ip);
return { apikey, keyInfo };
}
function setupRoutes(app) {
const healthHandler = async (req, res) => {
const auth = await authenticateRequest(req, res);
if (!auth || res.headersSent) return;
if (healthCache.data && Date.now() < healthCache.ttl) {
return res.json(healthCache.data);
}
let ollamaHealthy = false;
try {
const url = await getOllamaURL();
await axios.get(`${url}/api/tags`, { timeout: 5000 });
ollamaHealthy = true;
} catch {
ollamaHealthy = false;
}
healthCache.data = {
status: ollamaHealthy ? 'healthy' : 'degraded',
ollama: ollamaHealthy ? 'reachable' : 'unreachable',
timestamp: new Date().toISOString()
};
healthCache.ttl = Date.now() + 10000;
res.json(healthCache.data);
};
const generateHandler = async (req, res) => {
const auth = await authenticateRequest(req, res);
if (!auth || res.headersSent) return;
const { apikey, keyInfo } = auth;
if (keyInfo.active === 0) {
recordFailedAttempt(getClientIp(req));
return res.status(403).json({ error: 'API key is deactivated' });
}
const rateLimitError = await checkRateLimit(apikey, keyInfo);
if (rateLimitError) {
return res.status(429).json({ error: rateLimitError });
}
await handleGenerate(req, res, apikey);
};
app.get('/v1/health', healthHandler);
app.post('/v1/generate', generateHandler);
app.get('/health', healthHandler);
app.post('/generate', generateHandler);
}
async function checkRateLimit(apikey, keyInfo) {
const currentTime = Date.now();
const minute = 60000;
const rateLimit = keyInfo.rate_limit;
if (!rateLimits.has(apikey)) {
const lastUsed = keyInfo.last_used ? new Date(keyInfo.last_used).getTime() : 0;
const timeElapsed = currentTime - lastUsed;
const tokens = timeElapsed >= minute ? rateLimit : Math.min(keyInfo.tokens, rateLimit);
rateLimits.set(apikey, { tokens, lastUsed });
}
const rateLimitInfo = rateLimits.get(apikey);
const timeElapsed = currentTime - rateLimitInfo.lastUsed;
if (timeElapsed >= minute) {
rateLimitInfo.tokens = rateLimit;
rateLimitInfo.lastUsed = currentTime;
}
if (rateLimitInfo.tokens <= 0) {
return 'Rate limit exceeded. Try again later.';
}
rateLimitInfo.tokens -= 1;
rateLimitInfo.lastUsed = currentTime;
rateLimitBatchQueue.set(apikey, {
tokens: rateLimitInfo.tokens,
lastUsed: rateLimitInfo.lastUsed
});
scheduleRateLimitFlush();
return null;
}
async function handleGenerate(req, res, apikey) {
const { prompt, model, stream, images, raw } = req.body;
if (!prompt || !model) {
return res.status(400).json({ error: 'Both prompt and model are required' });
}
try {
const ollamaURL = await getOllamaURL();
const OLLAMA_API_URL = `${ollamaURL}/api/generate`;
if (stream) {
const ollamaResponse = await axios({
method: 'post',
url: OLLAMA_API_URL,
data: { model, prompt, stream: true, images, raw },
responseType: 'stream',
timeout: 300000
});
res.setHeader('Content-Type', 'application/x-ndjson');
let responseText = '';
let incomplete = '';
ollamaResponse.data.on('data', (chunk) => {
incomplete += chunk.toString();
const lines = incomplete.split('\n');
incomplete = lines.pop() || '';
for (const line of lines) {
if (!line.trim()) continue;
try {
const parsed = JSON.parse(line);
if (parsed.response) responseText += parsed.response;
} catch {}
}
});
ollamaResponse.data.on('error', (err) => {
console.error('Ollama stream error:', err.message);
if (!res.headersSent) {
res.status(502).json({ error: 'Upstream stream error' });
} else {
res.end();
}
logUsage(apikey, model);
});
res.on('close', () => {
ollamaResponse.data.destroy();
ollamaResponse.request.destroy();
});
ollamaResponse.data.on('end', () => {
logUsage(apikey, model);
sendWebhook(apikey, { prompt, model, response: responseText }, model);
});
ollamaResponse.data.pipe(res);
} else {
const ollamaResponse = await axios.post(OLLAMA_API_URL, { model, prompt, stream: false, images, raw }, {
timeout: 300000
});
logUsage(apikey, model);
sendWebhook(apikey, { prompt, model, response: ollamaResponse.data.response }, model);
res.json(ollamaResponse.data);
}
} catch (error) {
if (error.response) {
console.error('Ollama API error:', error.response.status, error.response.data);
res.status(error.response.status).json({ error: 'Ollama API error' });
} else if (error.code === 'ECONNREFUSED') {
console.error('Ollama server is not reachable:', error.message);
res.status(503).json({ error: 'Ollama server is not reachable' });
} else {
console.error('Error making request to Ollama API:', error.message);
res.status(500).json({ error: 'Error making request to Ollama API' });
}
}
}
function logUsage(apikey, model) {
db.run('INSERT INTO apiUsage (key, model) VALUES (?, ?)', [apikey, model || null])
.catch(err => console.error('Error logging API usage:', err.message));
}
function sendWebhook(apikey, payload, model) {
const responseText = payload?.response;
if (responseText) {
sendWebhookNotification(apikey, responseText);
}
}
module.exports = { setupRoutes, flushRateLimitBatch };