Elffuss BraidHub

kikocis/osiris public

master · 5.0 KiBRawPermalink
1import { NextResponse } from 'next/server';
2import { safeFetch, isRateLimited, getClientIp } from '@/lib/ssrf-guard';
3import { matchExact, type SanctionEntry } from '@/lib/sanctions';
4
5// WHOIS + Domain Intelligence via RDAP (free, standardized).
6// Cross-checks any registrant / org names returned by RDAP against the
7// OFAC SDN list so a sanctioned registrant surfaces alongside the WHOIS
8// metadata (still keyless — the SDN snapshot is sourced from the open
9// OpenSanctions mirror).
10export async function GET(req: Request) {
11 const { searchParams } = new URL(req.url);
12 const domain = searchParams.get('domain');
13 if (!domain) return NextResponse.json({ error: 'Missing domain parameter' }, { status: 400 });
14
15 const clientIp = getClientIp(req);
16 if (isRateLimited(clientIp, 20, 60_000)) {
17 return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 });
18 }
19
20 if (!/^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(domain)) {
21 return NextResponse.json({ error: 'Invalid domain format' }, { status: 400 });
22 }
23
24 try {
25 const results: any = { domain, timestamp: new Date().toISOString() };
26
27 // RDAP (Registration Data Access Protocol) — successor to WHOIS
28 try {
29 const res = await fetch(`https://rdap.org/domain/${encodeURIComponent(domain)}`, {
30 signal: AbortSignal.timeout(8000),
31 headers: { 'Accept': 'application/json' },
32 });
33 if (res.ok) {
34 const data = await res.json();
35 results.rdap = {
36 handle: data.handle,
37 name: data.ldhName,
38 status: data.status,
39 events: (data.events || []).map((e: any) => ({
40 action: e.eventAction,
41 date: e.eventDate,
42 })),
43 nameservers: (data.nameservers || []).map((ns: any) => ns.ldhName),
44 entities: (data.entities || []).map((e: any) => ({
45 handle: e.handle,
46 roles: e.roles,
47 name: e.vcardArray?.[1]?.find((v: any) => v[0] === 'fn')?.[3],
48 org: e.vcardArray?.[1]?.find((v: any) => v[0] === 'org')?.[3],
49 })).filter((e: any) => e.name || e.org),
50 };
51
52 // Extract key dates
53 const events = results.rdap.events || [];
54 results.registration = events.find((e: any) => e.action === 'registration')?.date;
55 results.expiration = events.find((e: any) => e.action === 'expiration')?.date;
56 results.last_changed = events.find((e: any) => e.action === 'last changed')?.date;
57 }
58 } catch (e) { console.warn('[OSIRIS] Suppressed error:', e instanceof Error ? e.message : e); }
59
60 // HTTP headers for tech fingerprinting — go through safeFetch so the
61 // attacker can't aim a HEAD request at internal infrastructure with a
62 // hostname that resolves to a reserved range, or chain a redirect from a
63 // public host to one. Redirects are followed manually with re-validation.
64 try {
65 const res = await safeFetch(`https://${domain}`, {
66 method: 'HEAD',
67 signal: AbortSignal.timeout(5000),
68 maxRedirects: 3,
69 });
70 const headers: Record<string, string> = {};
71 ['server', 'x-powered-by', 'x-frame-options', 'strict-transport-security',
72 'content-security-policy', 'x-content-type-options', 'x-xss-protection',
73 'referrer-policy', 'permissions-policy'].forEach(h => {
74 const v = res.headers.get(h);
75 if (v) headers[h] = v;
76 });
77 results.http = {
78 status: res.status,
79 headers,
80 redirected: res.redirected,
81 final_url: res.url,
82 };
83
84 // Security score
85 let score = 0;
86 if (headers['strict-transport-security']) score += 2;
87 if (headers['content-security-policy']) score += 2;
88 if (headers['x-frame-options']) score += 1;
89 if (headers['x-content-type-options']) score += 1;
90 if (headers['referrer-policy']) score += 1;
91 results.security_score = { score, max: 7, grade: score >= 5 ? 'A' : score >= 3 ? 'B' : score >= 1 ? 'C' : 'F' };
92 } catch (e) { console.warn('[OSIRIS] Suppressed error:', e instanceof Error ? e.message : e); }
93
94 // OFAC SDN cross-check on RDAP entity names/orgs.
95 try {
96 const candidates = new Set<string>();
97 for (const ent of results.rdap?.entities ?? []) {
98 if (ent.name) candidates.add(ent.name);
99 if (ent.org) candidates.add(ent.org);
100 }
101 const hits: Array<{ matched_value: string; entries: SanctionEntry[] }> = [];
102 for (const value of candidates) {
103 const entries = await matchExact(value);
104 if (entries.length) hits.push({ matched_value: value, entries });
105 }
106 results.sanctions_match = hits.length
107 ? { source: 'OFAC SDN', hits }
108 : null;
109 } catch (e) { console.warn('[OSIRIS] Sanctions cross-check failed:', e instanceof Error ? e.message : e); }
110
111 return NextResponse.json(results);
112 } catch {
113 return NextResponse.json({ error: 'WHOIS lookup failed' }, { status: 500 });
114 }
115}