Elffuss BraidHub

kikocis/osiris public

Merge branch 'pr-170' into master, resolving OsintPanel conflicts
Changeset647577cc870874bf021e58559d1804f76c226f7f12dda6ff1d83ae709e44fb35
AuthorGemini CLI <gemini@example.com> · 2026-05-28 19:15 -04:00
CommitterGemini CLI <gemini@example.com> · 2026-05-28 19:15 -04:00
Parents7ebe85210b60, 3e02f6434d6c

Browse the files at this changeset

3 files changed

added src/app/api/osint/crypto/route.ts +179 −0
@@ -0,0 +1,179 @@
1+import { NextResponse } from 'next/server';
2+import { isRateLimited, getClientIp } from '@/lib/ssrf-guard';
3+import { isSanctioned } from '@/lib/ofac-crypto';
4+
5+// Crypto wallet intelligence — BTC via blockstream.info, ETH via Blockscout
6+// (free, no key for either). Cross-checks the OFAC SDN sanctioned crypto
7+// address lists and flags hits with the source so the UI can warn the user.
8+
9+const BTC_RE = /^([13][a-km-zA-HJ-NP-Z1-9]{25,34}|bc1[ac-hj-np-z02-9]{11,87})$/;
10+const ETH_RE = /^0x[a-fA-F0-9]{40}$/;
11+
12+type Chain = 'BTC' | 'ETH';
13+
14+function detectChain(addr: string): Chain | null {
15+ if (ETH_RE.test(addr)) return 'ETH';
16+ if (BTC_RE.test(addr)) return 'BTC';
17+ return null;
18+}
19+
20+async function lookupBTC(address: string) {
21+ const res = await fetch(`https://blockstream.info/api/address/${address}`, {
22+ signal: AbortSignal.timeout(8000),
23+ headers: { Accept: 'application/json' },
24+ });
25+ if (!res.ok) throw new Error(`blockstream HTTP ${res.status}`);
26+ const d = await res.json();
27+
28+ const chainStats = d.chain_stats || {};
29+ const memStats = d.mempool_stats || {};
30+ const funded = (chainStats.funded_txo_sum || 0) + (memStats.funded_txo_sum || 0);
31+ const spent = (chainStats.spent_txo_sum || 0) + (memStats.spent_txo_sum || 0);
32+ const txCount = (chainStats.tx_count || 0) + (memStats.tx_count || 0);
33+ const balanceSats = funded - spent;
34+
35+ // Blockstream `/txs` returns at most the latest 25 confirmed txs per call.
36+ // For high-volume addresses this means `first_seen` reflects the start of
37+ // the most recent activity window rather than the absolute first tx —
38+ // good enough for a quick lookup, full history is a future enhancement.
39+ let firstSeen: string | undefined;
40+ let lastSeen: string | undefined;
41+ try {
42+ const txRes = await fetch(`https://blockstream.info/api/address/${address}/txs`, {
43+ signal: AbortSignal.timeout(8000),
44+ });
45+ if (txRes.ok) {
46+ const txs = (await txRes.json()) as Array<{ status?: { block_time?: number } }>;
47+ const times = txs.map((t) => t.status?.block_time).filter((t): t is number => !!t);
48+ if (times.length) {
49+ lastSeen = new Date(Math.max(...times) * 1000).toISOString();
50+ firstSeen = new Date(Math.min(...times) * 1000).toISOString();
51+ }
52+ }
53+ } catch (e) {
54+ console.warn('[OSIRIS] BTC tx history fetch failed:', e instanceof Error ? e.message : e);
55+ }
56+
57+ return {
58+ chain: 'BTC' as const,
59+ balance: (balanceSats / 1e8).toFixed(8),
60+ balance_unit: 'BTC',
61+ balance_satoshis: balanceSats,
62+ tx_count: txCount,
63+ total_received: (funded / 1e8).toFixed(8),
64+ total_sent: (spent / 1e8).toFixed(8),
65+ first_seen: firstSeen,
66+ last_seen: lastSeen,
67+ explorer: `https://blockstream.info/address/${address}`,
68+ };
69+}
70+
71+// ETH lookup via Blockscout — open source, keyless explorer
72+// (https://github.com/blockscout/blockscout). Uses the Etherscan-compatible
73+// v1 API for balance + tx history and the v2 counters endpoint for tx_count.
74+const BLOCKSCOUT_BASE = 'https://eth.blockscout.com';
75+
76+async function lookupETH(address: string) {
77+ const [balRes, firstTxRes, lastTxRes, countersRes] = await Promise.all([
78+ fetch(`${BLOCKSCOUT_BASE}/api?module=account&action=balance&address=${address}`, {
79+ signal: AbortSignal.timeout(8000),
80+ }),
81+ fetch(`${BLOCKSCOUT_BASE}/api?module=account&action=txlist&address=${address}&page=1&offset=1&sort=asc`, {
82+ signal: AbortSignal.timeout(8000),
83+ }),
84+ fetch(`${BLOCKSCOUT_BASE}/api?module=account&action=txlist&address=${address}&page=1&offset=1&sort=desc`, {
85+ signal: AbortSignal.timeout(8000),
86+ }),
87+ fetch(`${BLOCKSCOUT_BASE}/api/v2/addresses/${address}/counters`, {
88+ signal: AbortSignal.timeout(8000),
89+ }),
90+ ]);
91+
92+ if (!balRes.ok) throw new Error(`blockscout balance HTTP ${balRes.status}`);
93+ const balData = await balRes.json();
94+ const weiStr: string = balData?.result || '0';
95+ const wei = BigInt(/^\d+$/.test(weiStr) ? weiStr : '0');
96+ const eth = Number(wei) / 1e18;
97+
98+ let firstSeen: string | undefined;
99+ let lastSeen: string | undefined;
100+ if (firstTxRes.ok) {
101+ const d = await firstTxRes.json();
102+ const ts = d?.result?.[0]?.timeStamp;
103+ if (ts) firstSeen = new Date(Number(ts) * 1000).toISOString();
104+ }
105+ if (lastTxRes.ok) {
106+ const d = await lastTxRes.json();
107+ const ts = d?.result?.[0]?.timeStamp;
108+ if (ts) lastSeen = new Date(Number(ts) * 1000).toISOString();
109+ }
110+
111+ let txCount = 0;
112+ if (countersRes.ok) {
113+ const d = await countersRes.json();
114+ if (d?.transactions_count) txCount = parseInt(d.transactions_count, 10) || 0;
115+ }
116+
117+ return {
118+ chain: 'ETH' as const,
119+ balance: eth.toFixed(8),
120+ balance_unit: 'ETH',
121+ balance_wei: wei.toString(),
122+ tx_count: txCount,
123+ first_seen: firstSeen,
124+ last_seen: lastSeen,
125+ explorer: `${BLOCKSCOUT_BASE}/address/${address}`,
126+ };
127+}
128+
129+export async function GET(req: Request) {
130+ const { searchParams } = new URL(req.url);
131+ const address = (searchParams.get('address') || '').trim();
132+ const chainParam = (searchParams.get('chain') || 'auto').toUpperCase();
133+
134+ if (!address) {
135+ return NextResponse.json({ error: 'Missing address parameter' }, { status: 400 });
136+ }
137+
138+ const clientIp = getClientIp(req);
139+ if (isRateLimited(clientIp, 20, 60_000)) {
140+ return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 });
141+ }
142+
143+ let chain: Chain | null;
144+ if (chainParam === 'AUTO') {
145+ chain = detectChain(address);
146+ } else if (chainParam === 'BTC' || chainParam === 'ETH') {
147+ chain = chainParam;
148+ const valid = chain === 'BTC' ? BTC_RE.test(address) : ETH_RE.test(address);
149+ if (!valid) {
150+ return NextResponse.json({ error: `Invalid ${chain} address format` }, { status: 400 });
151+ }
152+ } else {
153+ return NextResponse.json({ error: 'Unsupported chain (use BTC, ETH, or auto)' }, { status: 400 });
154+ }
155+
156+ if (!chain) {
157+ return NextResponse.json({ error: 'Unrecognized address format' }, { status: 400 });
158+ }
159+
160+ try {
161+ const [data, sanctions] = await Promise.all([
162+ chain === 'BTC' ? lookupBTC(address) : lookupETH(address),
163+ isSanctioned(address, chain),
164+ ]);
165+
166+ return NextResponse.json({
167+ address,
168+ ...data,
169+ sanctioned: sanctions.sanctioned,
170+ sanctions: sanctions.sanctioned ? { source: sanctions.source, list: chain } : null,
171+ timestamp: new Date().toISOString(),
172+ });
173+ } catch (e) {
174+ return NextResponse.json(
175+ { error: 'Crypto lookup failed', detail: e instanceof Error ? e.message : String(e) },
176+ { status: 502 }
177+ );
178+ }
179+}
modified src/components/OsintPanel.tsx +39 −2
@@ -7,7 +7,7 @@
77 ChevronDown, ChevronUp, Loader2, AlertTriangle, Server,
88 Wifi, Lock, MapPin, Bug, Code, Layers, Network, Fingerprint,
99 CheckCircle, XCircle, Clock, ExternalLink, Crosshair,
10- Maximize2, Minimize2, Gavel
10+ Maximize2, Minimize2, Gavel, Bitcoin
1111 } from 'lucide-react';
1212
1313 const TABS = [
@@ -23,6 +23,7 @@
2323 { id: 'subdomains', label: 'SUBDOMAINS', icon: Layers, placeholder: 'Domain to enumerate', color: '#00BCD4' },
2424 { id: 'tech', label: 'TECH DETECT', icon: Fingerprint, placeholder: 'URL to fingerprint', color: '#9C27B0' },
2525 { id: 'sanctions', label: 'SANCTIONS', icon: Gavel, placeholder: 'Person / org / vessel name', color: '#FF1744' },
26+ { id: 'crypto', label: 'CRYPTO TRACE', icon: Bitcoin, placeholder: 'BTC or ETH address', color: '#F7931A' },
2627 { id: 'sweep', label: 'IP SWEEP', icon: Crosshair, placeholder: 'Enter IP address (e.g. 8.8.8.8)', color: '#FF3D3D' },
2728 ];
2829
@@ -108,6 +109,7 @@
108109 case 'subdomains': url = `/api/scanner?target=${encodeURIComponent(query)}&type=subdomains`; break;
109110 case 'tech': url = `/api/scanner?target=${encodeURIComponent(query)}&type=tech`; break;
110111 case 'sanctions': url = `/api/osint/sanctions?query=${encodeURIComponent(query)}`; break;
112+ case 'crypto': url = `/api/osint/crypto?address=${encodeURIComponent(query)}`; break;
111113 }
112114 const res = await fetch(url);
113115 const data = await res.json();
@@ -116,7 +118,7 @@
116118 setHistory(prev => [{ tab: activeTab, query, time: new Date().toLocaleTimeString() }, ...prev.slice(0, 9)]);
117119
118120 // Geolocate the target in the background
119- if (activeTab !== 'sweep' && activeTab !== 'vuln' && activeTab !== 'sanctions') {
121+ if (activeTab !== 'sweep' && activeTab !== 'vuln' && activeTab !== 'sanctions' && activeTab !== 'crypto') {
120122 fetch(`/api/osint/ip?ip=${encodeURIComponent(query)}`)
121123 .then(r => r.json())
122124 .then(locData => {
@@ -401,6 +403,41 @@
401403 );
402404 }
403405
406+ // ── CRYPTO ──
407+ if (activeTab === 'crypto') {
408+ const sanctioned = !!r.sanctioned;
409+ return (
410+ <div>
411+ <SectionHeader title="CRYPTO WALLET INTELLIGENCE" icon={Bitcoin} color="#F7931A" />
412+ {sanctioned && (
413+ <div className="mb-2 px-2 py-1.5 rounded border border-red-500/40 bg-red-500/15 flex items-center gap-2">
414+ <AlertTriangle className="w-3.5 h-3.5 text-red-400" />
415+ <span className="text-[10px] font-mono font-bold text-red-400 tracking-wider">
416+ SANCTIONED — {r.sanctions?.source || 'OFAC SDN'}
417+ </span>
418+ </div>
419+ )}
420+ <ResultRow label="Address" value={r.address} color="#F7931A" />
421+ <ResultRow label="Chain" value={r.chain} color={r.chain === 'BTC' ? '#F7931A' : '#627EEA'} />
422+ <ResultRow label="Balance" value={`${r.balance} ${r.balance_unit}`} />
423+ <ResultRow label="TX Count" value={r.tx_count} />
424+ {r.total_received !== undefined && <ResultRow label="Total Recv" value={`${r.total_received} ${r.balance_unit}`} />}
425+ {r.total_sent !== undefined && <ResultRow label="Total Sent" value={`${r.total_sent} ${r.balance_unit}`} />}
426+ <ResultRow label="First Seen" value={r.first_seen} />
427+ <ResultRow label="Last Seen" value={r.last_seen} />
428+ {r.explorer && (
429+ <div className="mt-2">
430+ <a href={r.explorer} target="_blank" rel="noopener noreferrer"
431+ className="inline-flex items-center gap-1 text-[10px] font-mono text-[#F7931A] hover:underline">
432+ <ExternalLink className="w-2.5 h-2.5" /> Open in block explorer
433+ </a>
434+ </div>
435+ )}
436+ {renderFallbackExcluding(['address','chain','balance','balance_unit','balance_satoshis','balance_wei','tx_count','total_received','total_sent','first_seen','last_seen','explorer','sanctioned','sanctions','timestamp'])}
437+ </div>
438+ );
439+ }
440+
404441 // Fallback for other tools
405442 return renderFallback();
406443 };
added src/lib/ofac-crypto.ts +68 −0
@@ -0,0 +1,68 @@
1+/**
2+ * OFAC sanctioned crypto address lookup.
3+ *
4+ * Source: the community-maintained mirror at
5+ * https://github.com/0xB10C/ofac-sanctioned-digital-currency-addresses, which
6+ * tracks the Treasury SDN list additions/removals as flat per-chain JSON
7+ * arrays. The raw lists are small (low-tens of KB) so we load them whole and
8+ * keep a lowercased `Set` for O(1) membership checks.
9+ *
10+ * The cache is filled lazily on the first lookup per chain and refreshed
11+ * every 24h. A second concurrent request that arrives while a fetch is in
12+ * flight waits on the same promise (single-flight) to avoid duplicate work.
13+ * If a refresh fails after the cache has gone stale we keep serving the
14+ * previous snapshot rather than blinding the route — a false negative on
15+ * brand-new sanctions is preferable to a sudden gap in coverage.
16+ */
17+
18+const SOURCES: Record<string, string> = {
19+ BTC: 'https://raw.githubusercontent.com/0xB10C/ofac-sanctioned-digital-currency-addresses/lists/sanctioned_addresses_BTC.json',
20+ ETH: 'https://raw.githubusercontent.com/0xB10C/ofac-sanctioned-digital-currency-addresses/lists/sanctioned_addresses_ETH.json',
21+};
22+
23+const TTL_MS = 24 * 60 * 60 * 1000;
24+
25+type ChainList = { fetchedAt: number; set: Set<string> };
26+const cache: Record<string, ChainList> = {};
27+const inflight: Record<string, Promise<ChainList> | undefined> = {};
28+
29+async function loadList(chain: 'BTC' | 'ETH'): Promise<ChainList> {
30+ const cached = cache[chain];
31+ if (cached && Date.now() - cached.fetchedAt < TTL_MS) return cached;
32+ if (inflight[chain]) return inflight[chain]!;
33+
34+ inflight[chain] = (async () => {
35+ try {
36+ const res = await fetch(SOURCES[chain], { signal: AbortSignal.timeout(8000) });
37+ if (!res.ok) throw new Error(`OFAC list ${chain} HTTP ${res.status}`);
38+ const arr = (await res.json()) as string[];
39+ const set = new Set(arr.map((a) => a.toLowerCase()));
40+ const entry = { fetchedAt: Date.now(), set };
41+ cache[chain] = entry;
42+ return entry;
43+ } catch (e) {
44+ // On failure, keep stale data if any to avoid leaving the route blind.
45+ if (cached) return cached;
46+ throw e;
47+ } finally {
48+ inflight[chain] = undefined;
49+ }
50+ })();
51+
52+ return inflight[chain]!;
53+}
54+
55+export async function isSanctioned(
56+ address: string,
57+ chain: 'BTC' | 'ETH'
58+): Promise<{ sanctioned: boolean; source?: string }> {
59+ try {
60+ const list = await loadList(chain);
61+ if (list.set.has(address.toLowerCase())) {
62+ return { sanctioned: true, source: 'OFAC SDN' };
63+ }
64+ return { sanctioned: false };
65+ } catch {
66+ return { sanctioned: false };
67+ }
68+}