Elffuss BraidHub

kikocis/osiris public

c867dff8b92f · 2.4 KiBRawPermalink
1import { NextResponse } from 'next/server';
2import { isRateLimited, getClientIp } from '@/lib/ssrf-guard';
3
4// IP Geolocation + Reputation — combines multiple free sources
5export async function GET(req: Request) {
6 const { searchParams } = new URL(req.url);
7 const ip = searchParams.get('ip');
8 if (!ip) return NextResponse.json({ error: 'Missing ip parameter' }, { status: 400 });
9
10 const clientIp = getClientIp(req);
11 if (isRateLimited(clientIp, 20, 60_000)) {
12 return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 });
13 }
14
15 // Validate IP format
16 const ipv4 = /^(\d{1,3}\.){3}\d{1,3}$/;
17 const ipv6 = /^[0-9a-fA-F:]+$/;
18 if (!ipv4.test(ip) && !ipv6.test(ip)) {
19 return NextResponse.json({ error: 'Invalid IP format' }, { status: 400 });
20 }
21
22 try {
23 const results: any = { ip, timestamp: new Date().toISOString() };
24
25 // 1. ip-api.com — geolocation (free, no key)
26 try {
27 const res = await fetch(`http://ip-api.com/json/${ip}?fields=status,message,continent,country,countryCode,region,regionName,city,zip,lat,lon,timezone,isp,org,as,asname,mobile,proxy,hosting,query`, {
28 signal: AbortSignal.timeout(5000),
29 });
30 if (res.ok) {
31 const geo = await res.json();
32 if (geo.status === 'success') {
33 results.geo = {
34 country: geo.country,
35 country_code: geo.countryCode,
36 region: geo.regionName,
37 city: geo.city,
38 lat: geo.lat,
39 lon: geo.lon,
40 timezone: geo.timezone,
41 isp: geo.isp,
42 org: geo.org,
43 as_number: geo.as,
44 as_name: geo.asname,
45 is_mobile: geo.mobile,
46 is_proxy: geo.proxy,
47 is_hosting: geo.hosting,
48 };
49 }
50 }
51 } catch (e) { console.warn('[OSIRIS] Suppressed error:', e instanceof Error ? e.message : e); }
52
53 // 2. AbuseIPDB-style check via ip-api proxy flag
54 results.reputation = {
55 is_proxy: results.geo?.is_proxy || false,
56 is_hosting: results.geo?.is_hosting || false,
57 is_mobile: results.geo?.is_mobile || false,
58 risk_level: results.geo?.is_proxy ? 'HIGH' : results.geo?.is_hosting ? 'MEDIUM' : 'LOW',
59 };
60
61 return NextResponse.json(results);
62 } catch {
63 return NextResponse.json({ error: 'IP lookup failed' }, { status: 500 });
64 }
65}