geoip.ts58 lines · main
| 1 | import { open, type CityResponse, type Reader } from 'maxmind'; |
| 2 | |
| 3 | import { env } from '../env.js'; |
| 4 | import { log } from './logger.js'; |
| 5 | |
| 6 | export interface GeoLookup { |
| 7 | city: string | null; |
| 8 | region: string | null; |
| 9 | country: string | null; |
| 10 | } |
| 11 | |
| 12 | let readerPromise: Promise<Reader<CityResponse> | null> | null = null; |
| 13 | |
| 14 | async function getReader(): Promise<Reader<CityResponse> | null> { |
| 15 | if (!env.BRIVEN_GEOIP_DB_PATH) return null; |
| 16 | if (!readerPromise) { |
| 17 | readerPromise = open<CityResponse>(env.BRIVEN_GEOIP_DB_PATH).catch((err: unknown) => { |
| 18 | log.warn('geoip_db_open_failed', { path: env.BRIVEN_GEOIP_DB_PATH, message: err instanceof Error ? err.message : String(err) }); |
| 19 | return null; |
| 20 | }); |
| 21 | } |
| 22 | return readerPromise; |
| 23 | } |
| 24 | |
| 25 | function isPrivateIp(ip: string): boolean { |
| 26 | if (ip === '127.0.0.1' || ip === '::1' || ip === 'localhost') return true; |
| 27 | if (ip.startsWith('10.') || ip.startsWith('192.168.')) return true; |
| 28 | if (ip.startsWith('169.254.') || ip.startsWith('fc') || ip.startsWith('fe80:')) return true; |
| 29 | if (ip.startsWith('172.')) { |
| 30 | const second = Number(ip.split('.')[1]); |
| 31 | if (second >= 16 && second <= 31) return true; |
| 32 | } |
| 33 | return false; |
| 34 | } |
| 35 | |
| 36 | // SELF-HOSTED ONLY (flndrn decision, 2026-07-05): geo lookups NEVER leave this |
| 37 | // server. There is deliberately no third-party fallback (the old ip-api.com HTTP |
| 38 | // call was removed) — an IP that the local GeoLite2 DB can't resolve returns null |
| 39 | // and the caller records the raw IP with geo left blank ("pending") until the |
| 40 | // GeoLite2-City .mmdb file is installed at BRIVEN_GEOIP_DB_PATH. |
| 41 | export async function lookupIp(ip: string | null | undefined): Promise<GeoLookup | null> { |
| 42 | if (!ip) return null; |
| 43 | if (isPrivateIp(ip)) return null; |
| 44 | const reader = await getReader(); |
| 45 | if (!reader) return null; |
| 46 | try { |
| 47 | const response = reader.get(ip); |
| 48 | if (response) { |
| 49 | const city = response.city?.names?.en ?? null; |
| 50 | const region = response.subdivisions?.[0]?.names?.en ?? null; |
| 51 | const country = response.country?.names?.en ?? response.registered_country?.names?.en ?? null; |
| 52 | if (city || region || country) return { city, region, country }; |
| 53 | } |
| 54 | } catch { |
| 55 | // Local MaxMind DB read failure — return null; caller stores the raw IP only. |
| 56 | } |
| 57 | return null; |
| 58 | } |