| 1 | /** |
| 2 | * ═══════════════════════════════════════════════════════════════ |
| 3 | * OSIRIS — AI Intelligence Analysis Endpoint |
| 4 | * POST /api/ai/analyze |
| 5 | * Rate-limited, multi-key Gemini integration |
| 6 | * ═══════════════════════════════════════════════════════════════ |
| 7 | */ |
| 8 | |
| 9 | import { NextRequest, NextResponse } from 'next/server'; |
| 10 | import { |
| 11 | createGeminiClient, |
| 12 | rotateApiKey, |
| 13 | analyzeIntelligence, |
| 14 | type IntelligenceContext, |
| 15 | } from '@/lib/ai-engine'; |
| 16 | |
| 17 | export const dynamic = 'force-dynamic'; |
| 18 | |
| 19 | /* ───────────────────────────────────────────────────────────── |
| 20 | Rate Limiter — 5 requests per minute per IP |
| 21 | ───────────────────────────────────────────────────────────── */ |
| 22 | |
| 23 | interface RateLimitEntry { |
| 24 | count: number; |
| 25 | resetAt: number; |
| 26 | } |
| 27 | |
| 28 | const rateLimitMap = new Map<string, RateLimitEntry>(); |
| 29 | const RATE_LIMIT_MAX = 5; |
| 30 | const RATE_LIMIT_WINDOW_MS = 60_000; |
| 31 | |
| 32 | function checkRateLimit(ip: string): { allowed: boolean; remaining: number; resetIn: number } { |
| 33 | const now = Date.now(); |
| 34 | const entry = rateLimitMap.get(ip); |
| 35 | |
| 36 | if (!entry || now > entry.resetAt) { |
| 37 | rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS }); |
| 38 | return { allowed: true, remaining: RATE_LIMIT_MAX - 1, resetIn: RATE_LIMIT_WINDOW_MS }; |
| 39 | } |
| 40 | |
| 41 | if (entry.count >= RATE_LIMIT_MAX) { |
| 42 | return { allowed: false, remaining: 0, resetIn: entry.resetAt - now }; |
| 43 | } |
| 44 | |
| 45 | entry.count++; |
| 46 | return { allowed: true, remaining: RATE_LIMIT_MAX - entry.count, resetIn: entry.resetAt - now }; |
| 47 | } |
| 48 | |
| 49 | // Periodic cleanup to prevent memory leaks |
| 50 | setInterval(() => { |
| 51 | const now = Date.now(); |
| 52 | for (const [ip, entry] of rateLimitMap.entries()) { |
| 53 | if (now > entry.resetAt) { |
| 54 | rateLimitMap.delete(ip); |
| 55 | } |
| 56 | } |
| 57 | }, 120_000); |
| 58 | |
| 59 | /* ───────────────────────────────────────────────────────────── |
| 60 | Collect API keys from environment |
| 61 | ───────────────────────────────────────────────────────────── */ |
| 62 | |
| 63 | function getEnvApiKeys(): string[] { |
| 64 | const keys: string[] = []; |
| 65 | for (let i = 1; i <= 8; i++) { |
| 66 | const key = process.env[`GEMINI_API_KEY_${i}`]; |
| 67 | if (key && key.trim().length > 0) { |
| 68 | keys.push(key.trim()); |
| 69 | } |
| 70 | } |
| 71 | return keys; |
| 72 | } |
| 73 | |
| 74 | /* ───────────────────────────────────────────────────────────── |
| 75 | Request / Response types |
| 76 | ───────────────────────────────────────────────────────────── */ |
| 77 | |
| 78 | interface AnalyzeRequestBody { |
| 79 | query: string; |
| 80 | context: IntelligenceContext; |
| 81 | } |
| 82 | |
| 83 | interface AnalyzeResponse { |
| 84 | analysis: string; |
| 85 | model: string; |
| 86 | timestamp: string; |
| 87 | } |
| 88 | |
| 89 | interface ErrorResponse { |
| 90 | error: string; |
| 91 | code: string; |
| 92 | retryAfter?: number; |
| 93 | } |
| 94 | |
| 95 | /* ───────────────────────────────────────────────────────────── |
| 96 | POST Handler |
| 97 | ───────────────────────────────────────────────────────────── */ |
| 98 | |
| 99 | export async function POST( |
| 100 | request: NextRequest |
| 101 | ): Promise<NextResponse<AnalyzeResponse | ErrorResponse>> { |
| 102 | // Extract client IP |
| 103 | const ip = |
| 104 | request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || |
| 105 | request.headers.get('x-real-ip') || |
| 106 | 'unknown'; |
| 107 | |
| 108 | // Rate limit check |
| 109 | const rateCheck = checkRateLimit(ip); |
| 110 | if (!rateCheck.allowed) { |
| 111 | return NextResponse.json( |
| 112 | { |
| 113 | error: 'Rate limit exceeded. Maximum 5 requests per minute.', |
| 114 | code: 'RATE_LIMITED', |
| 115 | retryAfter: Math.ceil(rateCheck.resetIn / 1000), |
| 116 | }, |
| 117 | { |
| 118 | status: 429, |
| 119 | headers: { |
| 120 | 'Retry-After': String(Math.ceil(rateCheck.resetIn / 1000)), |
| 121 | 'X-RateLimit-Remaining': '0', |
| 122 | 'X-RateLimit-Reset': String(Math.ceil(rateCheck.resetIn / 1000)), |
| 123 | }, |
| 124 | } |
| 125 | ); |
| 126 | } |
| 127 | |
| 128 | // Determine API key — user-provided header takes priority |
| 129 | const userKey = request.headers.get('x-gemini-key')?.trim(); |
| 130 | let apiKey: string; |
| 131 | |
| 132 | if (userKey && userKey.length > 0) { |
| 133 | apiKey = userKey; |
| 134 | } else { |
| 135 | const envKeys = getEnvApiKeys(); |
| 136 | if (envKeys.length === 0) { |
| 137 | return NextResponse.json( |
| 138 | { |
| 139 | error: |
| 140 | 'No Gemini API key configured. Set GEMINI_API_KEY_1 in environment or provide a key via the settings panel.', |
| 141 | code: 'NO_API_KEY', |
| 142 | }, |
| 143 | { status: 503 } |
| 144 | ); |
| 145 | } |
| 146 | apiKey = rotateApiKey(envKeys); |
| 147 | } |
| 148 | |
| 149 | // Parse request body |
| 150 | let body: AnalyzeRequestBody; |
| 151 | try { |
| 152 | body = (await request.json()) as AnalyzeRequestBody; |
| 153 | } catch { |
| 154 | return NextResponse.json( |
| 155 | { error: 'Invalid JSON in request body.', code: 'INVALID_BODY' }, |
| 156 | { status: 400 } |
| 157 | ); |
| 158 | } |
| 159 | |
| 160 | if (!body.query || typeof body.query !== 'string' || body.query.trim().length === 0) { |
| 161 | return NextResponse.json( |
| 162 | { error: 'Query field is required and must be a non-empty string.', code: 'MISSING_QUERY' }, |
| 163 | { status: 400 } |
| 164 | ); |
| 165 | } |
| 166 | |
| 167 | if (!body.context) { |
| 168 | return NextResponse.json( |
| 169 | { error: 'Intelligence context is required.', code: 'MISSING_CONTEXT' }, |
| 170 | { status: 400 } |
| 171 | ); |
| 172 | } |
| 173 | |
| 174 | // Call Gemini |
| 175 | try { |
| 176 | const client = createGeminiClient(apiKey); |
| 177 | const analysis = await analyzeIntelligence(client, body.context, body.query.trim()); |
| 178 | |
| 179 | return NextResponse.json( |
| 180 | { |
| 181 | analysis, |
| 182 | model: 'gemini-2.0-flash', |
| 183 | timestamp: new Date().toISOString(), |
| 184 | }, |
| 185 | { |
| 186 | headers: { |
| 187 | 'X-RateLimit-Remaining': String(rateCheck.remaining), |
| 188 | }, |
| 189 | } |
| 190 | ); |
| 191 | } catch (err: unknown) { |
| 192 | const message = err instanceof Error ? err.message : 'Unknown Gemini API error'; |
| 193 | |
| 194 | // Detect specific Gemini error types |
| 195 | if (message.includes('API_KEY_INVALID') || message.includes('API key not valid')) { |
| 196 | return NextResponse.json( |
| 197 | { error: 'Invalid Gemini API key. Please check your configuration.', code: 'INVALID_KEY' }, |
| 198 | { status: 401 } |
| 199 | ); |
| 200 | } |
| 201 | |
| 202 | if (message.includes('RESOURCE_EXHAUSTED') || message.includes('quota')) { |
| 203 | return NextResponse.json( |
| 204 | { |
| 205 | error: 'Gemini API quota exhausted. Try again later or provide your own API key.', |
| 206 | code: 'QUOTA_EXHAUSTED', |
| 207 | }, |
| 208 | { status: 429 } |
| 209 | ); |
| 210 | } |
| 211 | |
| 212 | if (message.includes('SAFETY')) { |
| 213 | return NextResponse.json( |
| 214 | { |
| 215 | error: 'Response blocked by Gemini safety filters. Try rephrasing your query.', |
| 216 | code: 'SAFETY_BLOCKED', |
| 217 | }, |
| 218 | { status: 422 } |
| 219 | ); |
| 220 | } |
| 221 | |
| 222 | console.error('[OSIRIS AI] Analysis error:', message); |
| 223 | return NextResponse.json( |
| 224 | { error: 'Intelligence analysis failed. Please try again.', code: 'ANALYSIS_FAILED' }, |
| 225 | { status: 500 } |
| 226 | ); |
| 227 | } |
| 228 | } |