const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); require('dotenv').config({ path: path.resolve(process.cwd(), '.env') }); const express = require('express'); const PORT = Number(process.env.PORT || 8080); const ADMIN_TOKEN = process.env.ADMIN_TOKEN || 'change-me'; const MODEL_BACKEND = process.env.MODEL_BACKEND || 'openai-compatible'; const MODEL_NAME = process.env.MODEL_NAME || 'Llama-3.1-8B-Instruct'; const OLLAMA_BASE_URL = process.env.OLLAMA_BASE_URL || 'http://127.0.0.1:11434'; const OPENAI_BASE_URL = process.env.OPENAI_BASE_URL || ''; const OPENAI_API_KEY = process.env.OPENAI_API_KEY || ''; const STORE_PATH = path.resolve(process.cwd(), process.env.PROMPT_STORE_PATH || './data/prompts.json'); const REQUEST_LOG_PATH = path.resolve(process.cwd(), './data/request-log.jsonl'); function nowIso() { return new Date().toISOString(); } function uid(prefix) { return `${prefix}_${crypto.randomBytes(8).toString('hex')}`; } function hashToken(token) { return crypto.createHash('sha256').update(String(token)).digest('hex'); } function normalizeOriginPattern(value) { return String(value || '').trim(); } function parseAllowedOrigins(value) { if (!value || typeof value !== 'string') { return ['*']; } return value .split(',') .map((x) => normalizeOriginPattern(x)) .filter(Boolean); } const DEFAULT_STORE = { defaultPromptId: 'default', prompts: { default: { id: 'default', name: 'Default Assistant', systemPrompt: 'Du bist ein hilfreicher, präziser Assistent. Antworte knapp, korrekt und ohne unnötige Ausschweifungen.', temperature: 0.4, maxTokens: 800 } }, apiKeys: [], settings: { requireApiKey: true, allowedOrigins: parseAllowedOrigins(process.env.ALLOWED_ORIGINS || '*'), defaultRateLimitPerMin: Number(process.env.DEFAULT_RATE_LIMIT_PER_MIN || 60) } }; function ensureFileDir(filepath) { const dir = path.dirname(filepath); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } } function ensureStore() { ensureFileDir(STORE_PATH); if (!fs.existsSync(STORE_PATH)) { const bootKey = `sk_${crypto.randomBytes(18).toString('base64url')}`; const bootStore = JSON.parse(JSON.stringify(DEFAULT_STORE)); bootStore.apiKeys.push({ id: uid('key'), name: 'extension-default', tokenHash: hashToken(bootKey), enabled: true, rateLimitPerMin: bootStore.settings.defaultRateLimitPerMin, createdAt: nowIso(), lastUsedAt: null }); fs.writeFileSync(STORE_PATH, JSON.stringify(bootStore, null, 2), 'utf8'); const bootInfoPath = path.resolve(process.cwd(), './data/bootstrap-credentials.txt'); fs.writeFileSync( bootInfoPath, `Created: ${nowIso()}\nAdmin token: ${ADMIN_TOKEN}\nInitial API key: ${bootKey}\n`, 'utf8' ); console.log(`Bootstrap credentials written to: ${bootInfoPath}`); } } function readStore() { ensureStore(); try { const parsed = JSON.parse(fs.readFileSync(STORE_PATH, 'utf8')); return { defaultPromptId: parsed.defaultPromptId || 'default', prompts: parsed.prompts || DEFAULT_STORE.prompts, apiKeys: Array.isArray(parsed.apiKeys) ? parsed.apiKeys : [], settings: { requireApiKey: typeof parsed.settings?.requireApiKey === 'boolean' ? parsed.settings.requireApiKey : DEFAULT_STORE.settings.requireApiKey, allowedOrigins: Array.isArray(parsed.settings?.allowedOrigins) ? parsed.settings.allowedOrigins : DEFAULT_STORE.settings.allowedOrigins, defaultRateLimitPerMin: Number(parsed.settings?.defaultRateLimitPerMin || DEFAULT_STORE.settings.defaultRateLimitPerMin) } }; } catch (_error) { return JSON.parse(JSON.stringify(DEFAULT_STORE)); } } let storeCache = readStore(); function persistStore() { ensureFileDir(STORE_PATH); fs.writeFileSync(STORE_PATH, JSON.stringify(storeCache, null, 2), 'utf8'); } function appendRequestLog(entry) { ensureFileDir(REQUEST_LOG_PATH); fs.appendFileSync(REQUEST_LOG_PATH, `${JSON.stringify(entry)}\n`, 'utf8'); } function authAdmin(req, res, next) { const bearer = (req.headers.authorization || '').replace(/^Bearer\s+/i, ''); const token = bearer || req.headers['x-admin-token']; if (!token || token !== ADMIN_TOKEN) { return res.status(401).json({ error: 'unauthorized' }); } next(); } function matchOrigin(origin, pattern) { if (pattern === '*') { return true; } if (pattern.endsWith('*')) { return origin.startsWith(pattern.slice(0, -1)); } return origin === pattern; } function corsMiddleware(req, res, next) { const origin = req.headers.origin; const allowed = storeCache.settings.allowedOrigins || ['*']; if (!origin) { if (req.method === 'OPTIONS') { return res.status(204).end(); } return next(); } const isAllowed = allowed.some((pattern) => matchOrigin(origin, String(pattern))); if (!isAllowed) { if (req.path.startsWith('/v1') || req.path.startsWith('/admin')) { return res.status(403).json({ error: 'origin_not_allowed' }); } return next(); } res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Vary', 'Origin'); res.setHeader('Access-Control-Allow-Headers', 'content-type, authorization, x-admin-token'); res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS'); if (req.method === 'OPTIONS') { return res.status(204).end(); } next(); } const rateState = new Map(); function authApi(req, res, next) { if (!storeCache.settings.requireApiKey) { return next(); } const bearer = (req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim(); if (!bearer) { return res.status(401).json({ error: 'api_key_required' }); } const tokenHash = hashToken(bearer); const keyObj = storeCache.apiKeys.find((k) => k.enabled && k.tokenHash === tokenHash); if (!keyObj) { return res.status(401).json({ error: 'invalid_api_key' }); } const now = Date.now(); const bucket = rateState.get(keyObj.id) || { startMs: now, count: 0 }; if (now - bucket.startMs >= 60_000) { bucket.startMs = now; bucket.count = 0; } const limit = Number(keyObj.rateLimitPerMin || storeCache.settings.defaultRateLimitPerMin || 60); bucket.count += 1; rateState.set(keyObj.id, bucket); if (bucket.count > limit) { return res.status(429).json({ error: 'rate_limit_exceeded', limit_per_min: limit }); } keyObj.lastUsedAt = nowIso(); persistStore(); req.apiKey = { id: keyObj.id, name: keyObj.name }; next(); } function sanitizeMessages(messages) { if (!Array.isArray(messages)) { return []; } return messages .map((m) => ({ role: String(m.role || '').trim(), content: typeof m.content === 'string' ? m.content : String(m.content || '') })) .filter((m) => ['system', 'user', 'assistant', 'tool'].includes(m.role) && m.content.length > 0) .slice(-40); } function withSystemPrompt(systemPrompt, messages) { const payload = sanitizeMessages(messages); return [{ role: 'system', content: systemPrompt }, ...payload.filter((x) => x.role !== 'system')]; } function resolveSystemPrompt(basePrompt, overridePrompt) { if (typeof overridePrompt !== 'string') { return basePrompt; } const trimmed = overridePrompt.trim(); if (!trimmed) { return basePrompt; } return trimmed.slice(0, 16000); } async function callOllama({ model, messages, temperature, maxTokens }) { const response = await fetch(`${OLLAMA_BASE_URL}/api/chat`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ model, stream: false, options: { temperature, num_predict: maxTokens }, messages }) }); if (!response.ok) { const text = await response.text(); throw new Error(`ollama_${response.status}: ${text}`); } const data = await response.json(); return { content: data?.message?.content || '', usage: data?.prompt_eval_count ? { prompt_tokens: data.prompt_eval_count, completion_tokens: data.eval_count || 0, total_tokens: (data.prompt_eval_count || 0) + (data.eval_count || 0) } : null }; } async function callOpenAICompatible({ model, messages, temperature, maxTokens }) { if (!OPENAI_BASE_URL || !OPENAI_API_KEY) { throw new Error('openai_backend_not_configured'); } const requestedModel = String(model || '').trim(); const candidates = [requestedModel]; if (requestedModel.toLowerCase() === 'llama-3.1-8b-instruct') { candidates.push('meta-llama/llama-3.1-8b-instruct'); candidates.push('meta-llama-3.1-8b-instruct'); } const uniqueCandidates = [...new Set(candidates.filter(Boolean))]; let lastError = 'openai_compatible_unknown_error'; for (let i = 0; i < uniqueCandidates.length; i += 1) { const candidateModel = uniqueCandidates[i]; const response = await fetch(`${OPENAI_BASE_URL.replace(/\/$/, '')}/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${OPENAI_API_KEY}` }, body: JSON.stringify({ model: candidateModel, messages, temperature, max_tokens: maxTokens }) }); if (response.ok) { const data = await response.json(); return { content: data?.choices?.[0]?.message?.content || '', usage: data?.usage || null }; } const text = await response.text(); lastError = `openai_compatible_${response.status}: ${text}`; const isModelError = response.status === 400 && /model/i.test(text); const hasNextCandidate = i < uniqueCandidates.length - 1; if (!(isModelError && hasNextCandidate)) { throw new Error(lastError); } } throw new Error(lastError); } async function infer({ model, messages, temperature, maxTokens }) { if (MODEL_BACKEND === 'openai-compatible') { return callOpenAICompatible({ model, messages, temperature, maxTokens }); } return callOllama({ model, messages, temperature, maxTokens }); } function publicStoreInfo() { return { defaultPromptId: storeCache.defaultPromptId, prompts: Object.fromEntries( Object.entries(storeCache.prompts || {}).map(([id, p]) => [id, { id, name: p.name }]) ), settings: { requireApiKey: storeCache.settings.requireApiKey, allowedOrigins: storeCache.settings.allowedOrigins, defaultRateLimitPerMin: storeCache.settings.defaultRateLimitPerMin } }; } const app = express(); app.disable('x-powered-by'); app.use(express.json({ limit: '2mb' })); app.use(corsMiddleware); app.use(express.static(path.resolve(process.cwd(), 'public'))); app.get('/health', (_req, res) => { res.json({ ok: true, backend: MODEL_BACKEND, model: MODEL_NAME, time: nowIso() }); }); app.get('/v1/models', authApi, (_req, res) => { res.json({ object: 'list', data: [{ id: MODEL_NAME, object: 'model', created: Math.floor(Date.now() / 1000), owned_by: MODEL_BACKEND }] }); }); app.get('/v1/prompts', authApi, (_req, res) => { res.json(publicStoreInfo()); }); app.post('/v1/chat', authApi, async (req, res) => { try { const { input, promptId, model, temperature, maxTokens, systemPromptOverride } = req.body || {}; if (!input || typeof input !== 'string') { return res.status(400).json({ error: 'input_required' }); } const promptCfg = storeCache.prompts[promptId || storeCache.defaultPromptId]; if (!promptCfg) { return res.status(400).json({ error: 'prompt_not_found' }); } const effectiveSystemPrompt = resolveSystemPrompt(promptCfg.systemPrompt, systemPromptOverride); const out = await infer({ model: model || MODEL_NAME, messages: withSystemPrompt(effectiveSystemPrompt, [{ role: 'user', content: input }]), temperature: Number.isFinite(Number(temperature)) ? Number(temperature) : promptCfg.temperature, maxTokens: Number.isFinite(Number(maxTokens)) ? Number(maxTokens) : promptCfg.maxTokens }); appendRequestLog({ ts: nowIso(), route: '/v1/chat', promptId: promptCfg.id, systemPromptOverridden: effectiveSystemPrompt !== promptCfg.systemPrompt, model: model || MODEL_NAME, keyId: req.apiKey?.id || null, inputChars: input.length, outputChars: out.content.length }); res.json({ ok: true, promptId: promptCfg.id, model: model || MODEL_NAME, content: out.content, usage: out.usage }); } catch (error) { res.status(500).json({ error: 'inference_failed', detail: String(error.message || error) }); } }); app.post('/v1/chat/completions', authApi, async (req, res) => { try { const { messages, promptId, model, temperature, max_tokens, stream, systemPromptOverride } = req.body || {}; if (stream) { return res.status(400).json({ error: 'stream_not_supported_in_this_build' }); } const cleanMessages = sanitizeMessages(messages); if (cleanMessages.length === 0) { return res.status(400).json({ error: 'messages_required' }); } const promptCfg = storeCache.prompts[promptId || storeCache.defaultPromptId]; if (!promptCfg) { return res.status(400).json({ error: 'prompt_not_found' }); } const usedModel = model || MODEL_NAME; const effectiveSystemPrompt = resolveSystemPrompt(promptCfg.systemPrompt, systemPromptOverride); const out = await infer({ model: usedModel, messages: withSystemPrompt(effectiveSystemPrompt, cleanMessages), temperature: Number.isFinite(Number(temperature)) ? Number(temperature) : promptCfg.temperature, maxTokens: Number.isFinite(Number(max_tokens)) ? Number(max_tokens) : promptCfg.maxTokens }); appendRequestLog({ ts: nowIso(), route: '/v1/chat/completions', promptId: promptCfg.id, systemPromptOverridden: effectiveSystemPrompt !== promptCfg.systemPrompt, model: usedModel, keyId: req.apiKey?.id || null, inputMsgs: cleanMessages.length, outputChars: out.content.length }); res.json({ id: `chatcmpl_${Date.now()}`, object: 'chat.completion', created: Math.floor(Date.now() / 1000), model: usedModel, prompt_id: promptCfg.id, choices: [ { index: 0, finish_reason: 'stop', message: { role: 'assistant', content: out.content } } ], usage: out.usage }); } catch (error) { res.status(500).json({ error: 'inference_failed', detail: String(error.message || error) }); } }); app.get('/admin/state', authAdmin, (_req, res) => { const maskedKeys = (storeCache.apiKeys || []).map((k) => ({ id: k.id, name: k.name, enabled: Boolean(k.enabled), rateLimitPerMin: Number(k.rateLimitPerMin || 60), createdAt: k.createdAt, lastUsedAt: k.lastUsedAt })); res.json({ prompts: storeCache.prompts, defaultPromptId: storeCache.defaultPromptId, settings: storeCache.settings, apiKeys: maskedKeys, backend: MODEL_BACKEND, model: MODEL_NAME }); }); app.put('/admin/prompts/:id', authAdmin, (req, res) => { const id = String(req.params.id || '').trim(); if (!/^[a-zA-Z0-9_-]{2,64}$/.test(id)) { return res.status(400).json({ error: 'invalid_prompt_id' }); } const { name, systemPrompt, temperature, maxTokens, setDefault } = req.body || {}; if (!systemPrompt || typeof systemPrompt !== 'string') { return res.status(400).json({ error: 'systemPrompt_required' }); } storeCache.prompts[id] = { id, name: String(name || id).slice(0, 80), systemPrompt: systemPrompt.slice(0, 16000), temperature: Number.isFinite(Number(temperature)) ? Number(temperature) : 0.4, maxTokens: Number.isFinite(Number(maxTokens)) ? Number(maxTokens) : 800 }; if (setDefault) { storeCache.defaultPromptId = id; } persistStore(); res.json({ ok: true, prompt: storeCache.prompts[id], defaultPromptId: storeCache.defaultPromptId }); }); app.delete('/admin/prompts/:id', authAdmin, (req, res) => { const id = String(req.params.id || '').trim(); if (!storeCache.prompts[id]) { return res.status(404).json({ error: 'prompt_not_found' }); } if (id === storeCache.defaultPromptId) { return res.status(400).json({ error: 'cannot_delete_default_prompt' }); } delete storeCache.prompts[id]; persistStore(); res.json({ ok: true }); }); app.post('/admin/keys', authAdmin, (req, res) => { const name = String(req.body?.name || '').trim(); if (!name) { return res.status(400).json({ error: 'name_required' }); } const token = `sk_${crypto.randomBytes(18).toString('base64url')}`; const entry = { id: uid('key'), name: name.slice(0, 80), tokenHash: hashToken(token), enabled: true, rateLimitPerMin: Number(req.body?.rateLimitPerMin || storeCache.settings.defaultRateLimitPerMin || 60), createdAt: nowIso(), lastUsedAt: null }; storeCache.apiKeys.push(entry); persistStore(); res.json({ ok: true, key: { id: entry.id, name: entry.name, token, enabled: entry.enabled, rateLimitPerMin: entry.rateLimitPerMin, createdAt: entry.createdAt } }); }); app.patch('/admin/keys/:id', authAdmin, (req, res) => { const id = String(req.params.id || '').trim(); const key = storeCache.apiKeys.find((k) => k.id === id); if (!key) { return res.status(404).json({ error: 'key_not_found' }); } if (typeof req.body?.enabled === 'boolean') { key.enabled = req.body.enabled; } if (Number.isFinite(Number(req.body?.rateLimitPerMin))) { key.rateLimitPerMin = Number(req.body.rateLimitPerMin); } persistStore(); res.json({ ok: true, key: { id: key.id, name: key.name, enabled: key.enabled, rateLimitPerMin: key.rateLimitPerMin, createdAt: key.createdAt, lastUsedAt: key.lastUsedAt } }); }); app.delete('/admin/keys/:id', authAdmin, (req, res) => { const id = String(req.params.id || '').trim(); const idx = storeCache.apiKeys.findIndex((k) => k.id === id); if (idx < 0) { return res.status(404).json({ error: 'key_not_found' }); } storeCache.apiKeys.splice(idx, 1); persistStore(); res.json({ ok: true }); }); app.put('/admin/settings', authAdmin, (req, res) => { const { requireApiKey, allowedOrigins, defaultRateLimitPerMin } = req.body || {}; if (typeof requireApiKey === 'boolean') { storeCache.settings.requireApiKey = requireApiKey; } if (Array.isArray(allowedOrigins)) { storeCache.settings.allowedOrigins = allowedOrigins.map((x) => normalizeOriginPattern(x)).filter(Boolean); if (storeCache.settings.allowedOrigins.length === 0) { storeCache.settings.allowedOrigins = ['*']; } } if (Number.isFinite(Number(defaultRateLimitPerMin))) { storeCache.settings.defaultRateLimitPerMin = Number(defaultRateLimitPerMin); } persistStore(); res.json({ ok: true, settings: storeCache.settings }); }); app.post('/admin/reload', authAdmin, (_req, res) => { storeCache = readStore(); res.json({ ok: true }); }); app.use((err, _req, res, _next) => { res.status(500).json({ error: 'internal_error', detail: String(err?.message || err) }); }); app.listen(PORT, () => { console.log(`Selfhosted AI API listening on http://localhost:${PORT}`); console.log(`Backend: ${MODEL_BACKEND} | Model: ${MODEL_NAME}`); });