| 1 | /** |
| 2 | * ═══════════════════════════════════════════════════════════════ |
| 3 | * OSIRIS — AI Intelligence Briefing Endpoint |
| 4 | * POST /api/ai/briefing |
| 5 | * Generates structured threat briefings via Gemini |
| 6 | * ═══════════════════════════════════════════════════════════════ |
| 7 | */ |
| 8 | |
| 9 | import { NextRequest, NextResponse } from 'next/server'; |
| 10 | import { |
| 11 | createGeminiClient, |
| 12 | rotateApiKey, |
| 13 | generateBriefing, |
| 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 | setInterval(() => { |
| 50 | const now = Date.now(); |
| 51 | for (const [ip, entry] of rateLimitMap.entries()) { |
| 52 | if (now > entry.resetAt) { |
| 53 | rateLimitMap.delete(ip); |
| 54 | } |
| 55 | } |
| 56 | }, 120_000); |
| 57 | |
| 58 | /* ───────────────────────────────────────────────────────────── |
| 59 | Environment Key Collection |
| 60 | ───────────────────────────────────────────────────────────── */ |
| 61 | |
| 62 | function getEnvApiKeys(): string[] { |
| 63 | const keys: string[] = []; |
| 64 | for (let i = 1; i <= 8; i++) { |
| 65 | const key = process.env[`GEMINI_API_KEY_${i}`]; |
| 66 | if (key && key.trim().length > 0) { |
| 67 | keys.push(key.trim()); |
| 68 | } |
| 69 | } |
| 70 | return keys; |
| 71 | } |
| 72 | |
| 73 | /* ───────────────────────────────────────────────────────────── |
| 74 | Request / Response types |
| 75 | ───────────────────────────────────────────────────────────── */ |
| 76 | |
| 77 | interface BriefingRequestBody { |
| 78 | context: IntelligenceContext; |
| 79 | } |
| 80 | |
| 81 | interface BriefingResponse { |
| 82 | briefing: string; |
| 83 | generatedAt: string; |
| 84 | } |
| 85 | |
| 86 | interface ErrorResponse { |
| 87 | error: string; |
| 88 | code: string; |
| 89 | retryAfter?: number; |
| 90 | } |
| 91 | |
| 92 | /* ───────────────────────────────────────────────────────────── |
| 93 | POST Handler |
| 94 | ───────────────────────────────────────────────────────────── */ |
| 95 | |
| 96 | export async function POST( |
| 97 | request: NextRequest |
| 98 | ): Promise<NextResponse<BriefingResponse | ErrorResponse>> { |
| 99 | const ip = |
| 100 | request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || |
| 101 | request.headers.get('x-real-ip') || |
| 102 | 'unknown'; |
| 103 | |
| 104 | const rateCheck = checkRateLimit(ip); |
| 105 | if (!rateCheck.allowed) { |
| 106 | return NextResponse.json( |
| 107 | { |
| 108 | error: 'Rate limit exceeded. Maximum 5 requests per minute.', |
| 109 | code: 'RATE_LIMITED', |
| 110 | retryAfter: Math.ceil(rateCheck.resetIn / 1000), |
| 111 | }, |
| 112 | { |
| 113 | status: 429, |
| 114 | headers: { |
| 115 | 'Retry-After': String(Math.ceil(rateCheck.resetIn / 1000)), |
| 116 | 'X-RateLimit-Remaining': '0', |
| 117 | }, |
| 118 | } |
| 119 | ); |
| 120 | } |
| 121 | |
| 122 | const userKey = request.headers.get('x-gemini-key')?.trim(); |
| 123 | let apiKey: string; |
| 124 | |
| 125 | if (userKey && userKey.length > 0) { |
| 126 | apiKey = userKey; |
| 127 | } else { |
| 128 | const envKeys = getEnvApiKeys(); |
| 129 | if (envKeys.length === 0) { |
| 130 | return NextResponse.json( |
| 131 | { |
| 132 | error: |
| 133 | 'No Gemini API key configured. Set GEMINI_API_KEY_1 in environment or provide a key via the settings panel.', |
| 134 | code: 'NO_API_KEY', |
| 135 | }, |
| 136 | { status: 503 } |
| 137 | ); |
| 138 | } |
| 139 | apiKey = rotateApiKey(envKeys); |
| 140 | } |
| 141 | |
| 142 | let body: BriefingRequestBody; |
| 143 | try { |
| 144 | body = (await request.json()) as BriefingRequestBody; |
| 145 | } catch { |
| 146 | return NextResponse.json( |
| 147 | { error: 'Invalid JSON in request body.', code: 'INVALID_BODY' }, |
| 148 | { status: 400 } |
| 149 | ); |
| 150 | } |
| 151 | |
| 152 | if (!body.context) { |
| 153 | return NextResponse.json( |
| 154 | { error: 'Intelligence context is required.', code: 'MISSING_CONTEXT' }, |
| 155 | { status: 400 } |
| 156 | ); |
| 157 | } |
| 158 | |
| 159 | try { |
| 160 | const client = createGeminiClient(apiKey); |
| 161 | const briefing = await generateBriefing(client, body.context); |
| 162 | |
| 163 | return NextResponse.json( |
| 164 | { |
| 165 | briefing, |
| 166 | generatedAt: new Date().toISOString(), |
| 167 | }, |
| 168 | { |
| 169 | headers: { |
| 170 | 'X-RateLimit-Remaining': String(rateCheck.remaining), |
| 171 | }, |
| 172 | } |
| 173 | ); |
| 174 | } catch (err: unknown) { |
| 175 | const message = err instanceof Error ? err.message : 'Unknown Gemini API error'; |
| 176 | |
| 177 | if (message.includes('API_KEY_INVALID') || message.includes('API key not valid')) { |
| 178 | return NextResponse.json( |
| 179 | { error: 'Invalid Gemini API key. Please check your configuration.', code: 'INVALID_KEY' }, |
| 180 | { status: 401 } |
| 181 | ); |
| 182 | } |
| 183 | |
| 184 | if (message.includes('RESOURCE_EXHAUSTED') || message.includes('quota')) { |
| 185 | return NextResponse.json( |
| 186 | { |
| 187 | error: 'Gemini API quota exhausted. Try again later or provide your own API key.', |
| 188 | code: 'QUOTA_EXHAUSTED', |
| 189 | }, |
| 190 | { status: 429 } |
| 191 | ); |
| 192 | } |
| 193 | |
| 194 | if (message.includes('SAFETY')) { |
| 195 | return NextResponse.json( |
| 196 | { |
| 197 | error: 'Response blocked by Gemini safety filters. Try again.', |
| 198 | code: 'SAFETY_BLOCKED', |
| 199 | }, |
| 200 | { status: 422 } |
| 201 | ); |
| 202 | } |
| 203 | |
| 204 | console.error('[OSIRIS AI] Briefing error:', message); |
| 205 | return NextResponse.json( |
| 206 | { error: 'Briefing generation failed. Please try again.', code: 'BRIEFING_FAILED' }, |
| 207 | { status: 500 } |
| 208 | ); |
| 209 | } |
| 210 | } |