import { isPrivateIpAddress } from '@admin/utils/auth/is-private-ip-address' const LOCATION_LOOKUP_URL = 'https://ipwho.is' const LOCATION_CACHE_SECONDS = 60 * 60 * 24 const LOCATION_LOOKUP_TIMEOUT_MS = 2500 interface LocationLookupResponse { success?: boolean city?: string region?: string country?: string country_code?: string } async function lookupLocation(ipAddress: string): Promise { try { const response = await fetch(`${LOCATION_LOOKUP_URL}/${encodeURIComponent(ipAddress)}`, { headers: { accept: 'application/json' }, next: { revalidate: LOCATION_CACHE_SECONDS }, signal: AbortSignal.timeout(LOCATION_LOOKUP_TIMEOUT_MS) }) if (!response.ok) { return null } const data = (await response.json()) as LocationLookupResponse if (data.success === false) { return null } const place = data.city || data.region || data.country if (!place) { return null } return data.country_code ? `${place}, ${data.country_code}` : place } catch { return null } } export async function getSessionLocations( ipAddresses: Array ): Promise> { const locations = new Map() const publicAddresses = new Set() for (const ipAddress of ipAddresses) { if (!ipAddress) { continue } if (isPrivateIpAddress(ipAddress)) { locations.set(ipAddress, 'Local network') continue } publicAddresses.add(ipAddress) } const results = await Promise.all( [...publicAddresses].map( async (ipAddress) => [ipAddress, await lookupLocation(ipAddress)] as const ) ) for (const [ipAddress, location] of results) { if (location) { locations.set(ipAddress, location) } } return locations }