Elffuss BraidHub

kikocis/osiris public

master · 3.3 KiBRawPermalink
1import { NextResponse } from 'next/server';
2import { parseIPv4, isPrivateOrReserved } from '@/lib/osint-utils';
3
4export const dynamic = 'force-dynamic';
5
6interface RateLimitEntry {
7 timestamps: number[];
8}
9
10const rateLimitMap = new Map<string, RateLimitEntry>();
11const RATE_LIMIT_WINDOW_MS = 60_000;
12const RATE_LIMIT_MAX = 5;
13
14function checkRateLimit(requesterIp: string): boolean {
15 const now = Date.now();
16 const entry = rateLimitMap.get(requesterIp);
17
18 if (!entry) {
19 rateLimitMap.set(requesterIp, { timestamps: [now] });
20 return true;
21 }
22
23 entry.timestamps = entry.timestamps.filter((t) => now - t < RATE_LIMIT_WINDOW_MS);
24
25 if (entry.timestamps.length >= RATE_LIMIT_MAX) {
26 return false;
27 }
28
29 entry.timestamps.push(now);
30 return true;
31}
32
33export async function GET(req: Request) {
34 const { searchParams } = new URL(req.url);
35
36 // --- 1. IP Validation ---
37 const ip = searchParams.get('ip');
38 if (!ip) {
39 return NextResponse.json({ error: 'Missing ip parameter' }, { status: 400 });
40 }
41
42 const octets = parseIPv4(ip);
43 if (!octets) {
44 return NextResponse.json({ error: 'Invalid IPv4 address format' }, { status: 400 });
45 }
46
47 if (isPrivateOrReserved(octets)) {
48 return NextResponse.json(
49 { error: 'Private and reserved IP ranges are not allowed' },
50 { status: 400 },
51 );
52 }
53
54 const cidrParam = searchParams.get('cidr');
55 let cidr = 24;
56 if (cidrParam) {
57 cidr = parseInt(cidrParam, 10);
58 if (isNaN(cidr) || cidr < 24 || cidr > 32) {
59 return NextResponse.json(
60 { error: 'CIDR must be between 24 and 32' },
61 { status: 400 },
62 );
63 }
64 }
65
66 // --- 2. Rate Limiting ---
67 const forwarded = req.headers.get('x-forwarded-for');
68 const requesterIp = forwarded?.split(',')[0]?.trim() || '127.0.0.1';
69
70 if (!checkRateLimit(requesterIp)) {
71 return NextResponse.json(
72 { error: 'Rate limit exceeded.' },
73 { status: 429 },
74 );
75 }
76
77 try {
78 // --- 3. Geolocation ---
79 const geoRes = await fetch(
80 `http://ip-api.com/json/${ip}?fields=status,message,country,countryCode,region,regionName,city,lat,lon,isp,org,as,proxy,hosting`,
81 { signal: AbortSignal.timeout(5000) },
82 );
83
84 if (!geoRes.ok) {
85 return NextResponse.json(
86 { error: 'Geolocation service unavailable' },
87 { status: 502 },
88 );
89 }
90
91 const geoData = await geoRes.json();
92 if (geoData.status === 'fail') {
93 return NextResponse.json(
94 { error: `Geolocation failed: ${geoData.message || 'Unknown error'}` },
95 { status: 422 },
96 );
97 }
98
99 const center = {
100 lat: geoData.lat as number,
101 lng: geoData.lon as number,
102 city: geoData.city as string,
103 region: geoData.regionName as string,
104 country: geoData.country as string,
105 countryCode: geoData.countryCode as string,
106 isp: geoData.isp as string,
107 asn: (geoData.as as string) || '',
108 org: (geoData.org as string) || '',
109 };
110
111 return NextResponse.json({
112 center,
113 target_ip: ip,
114 cidr
115 }, {
116 headers: {
117 'Cache-Control': 'no-cache, no-store, must-revalidate',
118 Pragma: 'no-cache',
119 Expires: '0',
120 },
121 });
122 } catch (err) {
123 console.error('[OSIRIS] Sweep Init error:', err instanceof Error ? err.message : err);
124 return NextResponse.json({ error: 'Sweep initialization failed' }, { status: 500 });
125 }
126}