| 1 | |
| 2 | import { NextResponse } from 'next/server'; |
| 3 | import { stealthFetch } from '@/lib/stealthFetch'; |
| 4 | |
| 5 | /** |
| 6 | * OSIRIS — Flight Data API |
| 7 | * Fetches real-time aircraft positions from adsb.lol (no API key required) |
| 8 | * Covers 6 global regions for maximum coverage |
| 9 | */ |
| 10 | |
| 11 | const REGIONS = [ |
| 12 | { lat: 39.8, lon: -98.5, dist: 2000 }, // North America |
| 13 | { lat: 50.0, lon: 15.0, dist: 2000 }, // Europe |
| 14 | { lat: 35.0, lon: 105.0, dist: 2000 }, // Asia |
| 15 | { lat: -25.0, lon: 133.0, dist: 2000 }, // Australia |
| 16 | { lat: 0.0, lon: 20.0, dist: 2500 }, // Africa |
| 17 | { lat: -15.0, lon: -60.0, dist: 2000 }, // South America |
| 18 | ]; |
| 19 | |
| 20 | // Helicopter type codes |
| 21 | const HELI_TYPES = new Set([ |
| 22 | 'R22','R44','R66','B06','B06T','B204','B205','B206','B212','B222','B230', |
| 23 | 'B407','B412','B427','B429','B430','B505','B525', |
| 24 | 'AS32','AS35','AS50','AS55','AS65', |
| 25 | 'EC20','EC25','EC30','EC35','EC45','EC55','EC75', |
| 26 | 'H125','H130','H135','H145','H155','H160','H175','H215','H225', |
| 27 | 'S55','S58','S61','S64','S70','S76','S92', |
| 28 | 'A109','A119','A139','A169','A189','AW09', |
| 29 | 'MD52','MD60','MDHI','MD90','NOTR', |
| 30 | 'B47G','HUEY','GAMA','CABR','EXE', |
| 31 | ]); |
| 32 | |
| 33 | // Private jet types |
| 34 | const PRIVATE_JET_TYPES = new Set([ |
| 35 | 'G150','G200','G280','GLEX','G500','G550','G600','G650','G700', |
| 36 | 'GLF2','GLF3','GLF4','GLF5','GLF6','GL5T','GL7T','GV','GIV', |
| 37 | 'CL30','CL35','CL60','BD70','BD10', |
| 38 | 'C25A','C25B','C25C','C500','C510','C525','C550','C560','C56X','C680','C700','C750', |
| 39 | 'E35L','E50P','E55P','E545','E550', |
| 40 | 'FA50','FA7X','FA8X','F900','F2TH', |
| 41 | 'LJ35','LJ40','LJ45','LJ60','LJ70','LJ75', |
| 42 | 'PC12','PC24','TBM7','TBM8','TBM9', |
| 43 | 'PRM1','SF50','EA50','VLJ', |
| 44 | ]); |
| 45 | |
| 46 | // Military type indicators |
| 47 | const MILITARY_INDICATORS = new Set([ |
| 48 | 'C17','C5M','C130','C30J','KC10','KC46','KC35','E3CF','E3TF','E8A', |
| 49 | 'B1B','B2','B52','F16','F15','F18','F22','F35','A10','F117', |
| 50 | 'RC135','E6B','P8A','P3','MQ9','RQ4','U2','EP3','RC12', |
| 51 | 'V22','CH47','UH60','AH64','AH1Z','MV22', |
| 52 | 'EUFI','RFAL','TORD','TYP','GR4', |
| 53 | ]); |
| 54 | |
| 55 | const AIRLINE_CODE_RE = /^([A-Z]{3})\d/; |
| 56 | |
| 57 | async function fetchRegion(region: typeof REGIONS[0]): Promise<any[]> { |
| 58 | try { |
| 59 | const url = `https://api.adsb.lol/v2/lat/${region.lat}/lon/${region.lon}/dist/${region.dist}`; |
| 60 | const res = await stealthFetch(url, { |
| 61 | signal: AbortSignal.timeout(12000), |
| 62 | }); |
| 63 | if (res.ok) { |
| 64 | const data = await res.json(); |
| 65 | return data.ac || []; |
| 66 | } |
| 67 | } catch (e) { |
| 68 | console.warn(`Region fetch failed for lat=${region.lat}:`, e); |
| 69 | } |
| 70 | return []; |
| 71 | } |
| 72 | |
| 73 | function classifyFlight(f: any) { |
| 74 | const modelUpper = (f.t || '').toUpperCase(); |
| 75 | const flightStr = (f.flight || '').trim().toUpperCase(); |
| 76 | const dbFlags = (f.dbFlags || 0); |
| 77 | |
| 78 | // Skip fixed structures |
| 79 | if (modelUpper === 'TWR') return null; |
| 80 | |
| 81 | const lat = f.lat; |
| 82 | const lon = f.lon; |
| 83 | if (lat == null || lon == null) return null; |
| 84 | |
| 85 | const callsign = flightStr || f.hex || 'UNKNOWN'; |
| 86 | const altRaw = f.alt_baro; |
| 87 | const altMeters = typeof altRaw === 'number' ? altRaw * 0.3048 : 0; |
| 88 | const speedKnots = typeof f.gs === 'number' ? Math.round(f.gs * 10) / 10 : null; |
| 89 | const heading = f.track || 0; |
| 90 | const isHeli = HELI_TYPES.has(modelUpper); |
| 91 | const isGrounded = typeof altRaw === 'number' && altRaw < 100; |
| 92 | |
| 93 | // Extract airline code |
| 94 | const airlineMatch = AIRLINE_CODE_RE.exec(callsign); |
| 95 | const airlineCode = airlineMatch ? airlineMatch[1] : ''; |
| 96 | |
| 97 | // Classification |
| 98 | let category: 'commercial' | 'private' | 'jet' | 'military' = 'commercial'; |
| 99 | if (dbFlags & 1 || MILITARY_INDICATORS.has(modelUpper) || (f.flight || '').match(/^(RCH|KING|DUKE|EVAC|JAKE|REACH|CONVOY)\d/i)) { |
| 100 | category = 'military'; |
| 101 | } else if (PRIVATE_JET_TYPES.has(modelUpper)) { |
| 102 | category = 'jet'; |
| 103 | } else if (!airlineCode && modelUpper && !['A319','A320','A321','A332','A333','A339','A343','A359','A388','B737','B738','B739','B38M','B39M','B752','B753','B763','B764','B772','B77L','B77W','B788','B789','B78X','E170','E175','E190','E195','CRJ7','CRJ9','AT43','AT72','DH8D'].includes(modelUpper)) { |
| 104 | category = 'private'; |
| 105 | } |
| 106 | |
| 107 | return { |
| 108 | callsign, |
| 109 | lat: Math.round(lat * 100000) / 100000, |
| 110 | lng: Math.round(lon * 100000) / 100000, |
| 111 | alt: Math.round(altMeters), |
| 112 | heading: Math.round(heading), |
| 113 | speed_knots: speedKnots, |
| 114 | model: f.t || 'Unknown', |
| 115 | icao24: f.hex || '', |
| 116 | registration: f.r || 'N/A', |
| 117 | squawk: f.squawk || '', |
| 118 | airline_code: airlineCode, |
| 119 | aircraft_category: isHeli ? 'heli' : 'plane', |
| 120 | category, |
| 121 | grounded: isGrounded, |
| 122 | nac_p: f.nac_p, |
| 123 | type: 'flight', |
| 124 | }; |
| 125 | } |
| 126 | |
| 127 | // In-memory cache to prevent global fan-out abuse |
| 128 | // NOTE (Issue #110): This cache is per-isolate in serverless environments (Vercel). |
| 129 | // Multiple isolates may each hold their own cache, but this is acceptable because: |
| 130 | // 1. It coalesces concurrent requests within the same isolate |
| 131 | // 2. It prevents hammering adsb.lol which would cause rate-limit bans |
| 132 | // For a globally shared cache, migrate to Vercel KV or similar persistent store. |
| 133 | let cachedData: any = null; |
| 134 | let lastFetchTime = 0; |
| 135 | const CACHE_TTL = 45000; // 45 seconds cache window |
| 136 | let fetchPromise: Promise<any> | null = null; |
| 137 | |
| 138 | export async function GET() { |
| 139 | const now = Date.now(); |
| 140 | |
| 141 | // Return cached data if within TTL |
| 142 | if (cachedData && now - lastFetchTime < CACHE_TTL) { |
| 143 | return NextResponse.json(cachedData, { |
| 144 | headers: { 'Cache-Control': 'public, s-maxage=30, stale-while-revalidate=60' }, |
| 145 | }); |
| 146 | } |
| 147 | |
| 148 | // Coalesce concurrent requests: wait for the active fetch rather than starting a new one |
| 149 | if (fetchPromise) { |
| 150 | try { |
| 151 | const data = await fetchPromise; |
| 152 | return NextResponse.json(data, { |
| 153 | headers: { 'Cache-Control': 'public, s-maxage=30, stale-while-revalidate=60' }, |
| 154 | }); |
| 155 | } catch { |
| 156 | // Fallback to error if the pending fetch failed |
| 157 | return NextResponse.json({ error: 'Failed to fetch flight data' }, { status: 500 }); |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | const JAMMING_NACAP_THRESHOLD = 4; |
| 162 | |
| 163 | // Start new global fetch |
| 164 | fetchPromise = (async () => { |
| 165 | // Fetch all 6 regions in parallel |
| 166 | const regionResults = await Promise.allSettled( |
| 167 | REGIONS.map(r => fetchRegion(r)) |
| 168 | ); |
| 169 | |
| 170 | const allRaw: any[] = []; |
| 171 | const seenHex = new Set<string>(); |
| 172 | |
| 173 | for (const result of regionResults) { |
| 174 | if (result.status === 'fulfilled') { |
| 175 | for (const ac of result.value) { |
| 176 | const hex = (ac.hex || '').toLowerCase().trim(); |
| 177 | if (hex && !seenHex.has(hex)) { |
| 178 | seenHex.add(hex); |
| 179 | allRaw.push(ac); |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | // Classify all flights |
| 186 | const commercial: any[] = []; |
| 187 | const privateFl: any[] = []; |
| 188 | const jets: any[] = []; |
| 189 | const military: any[] = []; |
| 190 | const gpsJamming: any[] = []; |
| 191 | |
| 192 | for (const raw of allRaw) { |
| 193 | const flight = classifyFlight(raw); |
| 194 | if (!flight) continue; |
| 195 | |
| 196 | // GPS jamming detection |
| 197 | if (typeof flight.nac_p === 'number' && flight.nac_p <= JAMMING_NACAP_THRESHOLD && !flight.grounded) { |
| 198 | gpsJamming.push({ |
| 199 | lat: flight.lat, |
| 200 | lng: flight.lng, |
| 201 | nac_p: flight.nac_p, |
| 202 | callsign: flight.callsign, |
| 203 | }); |
| 204 | } |
| 205 | |
| 206 | switch (flight.category) { |
| 207 | case 'military': military.push(flight); break; |
| 208 | case 'jet': jets.push(flight); break; |
| 209 | case 'private': privateFl.push(flight); break; |
| 210 | default: commercial.push(flight); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | // Aggregate GPS jamming zones (grid-based) |
| 215 | const jammingZones = aggregateJamming(gpsJamming, JAMMING_NACAP_THRESHOLD); |
| 216 | |
| 217 | return { |
| 218 | commercial_flights: commercial, |
| 219 | private_flights: privateFl, |
| 220 | private_jets: jets, |
| 221 | military_flights: military, |
| 222 | gps_jamming: jammingZones, |
| 223 | total: allRaw.length, |
| 224 | timestamp: new Date().toISOString(), |
| 225 | }; |
| 226 | })(); |
| 227 | |
| 228 | try { |
| 229 | const data = await fetchPromise; |
| 230 | cachedData = data; |
| 231 | lastFetchTime = Date.now(); |
| 232 | fetchPromise = null; |
| 233 | |
| 234 | return NextResponse.json(data, { |
| 235 | headers: { |
| 236 | 'Cache-Control': 'public, s-maxage=30, stale-while-revalidate=60', |
| 237 | }, |
| 238 | }); |
| 239 | } catch (error) { |
| 240 | console.error('Flight fetch error:', error); |
| 241 | fetchPromise = null; |
| 242 | return NextResponse.json( |
| 243 | { error: 'Failed to fetch flight data' }, |
| 244 | { status: 500 } |
| 245 | ); |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | function aggregateJamming(points: any[], threshold: number) { |
| 250 | if (points.length === 0) return []; |
| 251 | const grid = new Map<string, { lat: number; lng: number; count: number; total_nac_p: number }>(); |
| 252 | const GRID_SIZE = 2; // degrees |
| 253 | |
| 254 | for (const p of points) { |
| 255 | const gLat = Math.floor(p.lat / GRID_SIZE) * GRID_SIZE; |
| 256 | const gLng = Math.floor(p.lng / GRID_SIZE) * GRID_SIZE; |
| 257 | const key = `${gLat},${gLng}`; |
| 258 | |
| 259 | if (!grid.has(key)) { |
| 260 | grid.set(key, { lat: gLat + GRID_SIZE / 2, lng: gLng + GRID_SIZE / 2, count: 0, total_nac_p: 0 }); |
| 261 | } |
| 262 | const cell = grid.get(key)!; |
| 263 | cell.count++; |
| 264 | cell.total_nac_p += p.nac_p; |
| 265 | } |
| 266 | |
| 267 | return Array.from(grid.values()) |
| 268 | .filter(z => z.count >= 3) // Minimum 3 aircraft with degraded NACp |
| 269 | .map(z => ({ |
| 270 | lat: z.lat, |
| 271 | lng: z.lng, |
| 272 | severity: Math.round((1 - (z.total_nac_p / z.count) / threshold) * 100), |
| 273 | count: z.count, |
| 274 | })); |
| 275 | } |
| 276 | |