Elffuss BraidHub

kikocis/osiris public

Merge branch 'pr-172'
Changeset7ebe85210b60dcbea3ca7f48c6b49e1da16224aff2e517cf3875f8a0eff168e8
AuthorGemini CLI <gemini@example.com> · 2026-05-28 19:14 -04:00
CommitterGemini CLI <gemini@example.com> · 2026-05-28 19:14 -04:00
Parentscecdff9260f2, 5c6bc39364ac

Browse the files at this changeset

8 files changed

modified .env.template +7 −0
@@ -66,6 +66,13 @@
6666 # Change this if 3000 is already taken on your host.
6767 OSIRIS_PORT=3000
6868
69+# Comma-separated list of public Telegram channel usernames (no @) to scrape
70+# for the "Telegram OSINT" map layer. Overrides the curated default set.
71+# Channels must have web preview enabled (most well-known OSINT channels do).
72+# Default if unset:
73+# osintdefender,insiderpaper,aljazeeraenglish,nexta_live,war_monitor
74+# OSIRIS_TELEGRAM_CHANNELS=
75+
6976 # Set by the Docker image already — override only if needed.
7077 # NODE_ENV=production
7178 # PORT=3000
modified DOCKER.md +11 −1
@@ -141,9 +141,19 @@
141141 > Keep `.env` out of version control — it is already in `.gitignore`. Only
142142 > `.env.template` (no secrets) is committed.
143143
144+### Optional runtime overrides
145+
146+| Variable | Purpose | Default |
147+|----------|---------|---------|
148+| `OSIRIS_TELEGRAM_CHANNELS` | Comma-separated list of public Telegram channel usernames (no `@`) to scrape for the **Telegram OSINT** map layer. Overrides the curated default set. | `osintdefender,insiderpaper,aljazeeraenglish,nexta_live,war_monitor` |
149+| `OSIRIS_PORT` | Host port the compose file publishes (container itself always listens on 3000). | `3000` |
150+
144151 ### Keyless sources (no configuration needed)
145152
146153 Aviation → `adsb.lol` · Satellites → `celestrak.org` (TLE) · Fires →
147154 NASA FIRMS open-data CSV · Earthquakes → USGS · Weather → NASA EONET · Space
148155 weather → NOAA SWPC · CVEs → NVD · News → public RSS / HLS streams · CCTV →
149-public traffic-authority feeds.
156+public traffic-authority feeds · Crypto (BTC) → `blockstream.info` · Crypto
157+(ETH) → `eth.blockscout.com` ([Blockscout](https://github.com/blockscout/blockscout)
158+open-source explorer) · OFAC SDN sanctions → [OpenSanctions](https://www.opensanctions.org)
159+mirror (CC-BY 4.0) · Telegram OSINT → public `t.me/s/<channel>` web preview.
modified README.md +35 −7
@@ -37,6 +37,9 @@
3737 | **Space** | Solar Weather, Satellites | NOAA SWPC, N2YO |
3838 | **Cyber** | CVE Threats, Vulnerability Scanning | NVD, Custom Scanner |
3939 | **Conflict** | 13 Active Zones | Static OSINT Intel |
40+| **Crypto** | BTC + ETH Wallet Tracing, OFAC SDN Match | blockstream.info, Blockscout, OpenSanctions |
41+| **Sanctions** | Person / Org / Vessel SDN Search | OpenSanctions (US OFAC SDN mirror) |
42+| **Telegram OSINT** | Geoparsed Posts from Public Channels | `t.me/s/<channel>` web preview |
4043
4144 ---
4245
@@ -53,14 +56,20 @@
5356 │ └──────────┘ └──────────┘ └───────────────┘ │
5457 ├─────────────────────────────────────────────────┤
5558 │ NEXT.JS API ROUTES │
56-│ /api/flights /api/earthquakes /api/cctv │
57-│ /api/news /api/fires /api/maritime │
58-│ /api/gdelt /api/satellites /api/weather │
59-│ /api/scanner /api/sentinel /api/osint/* │
59+│ /api/flights /api/earthquakes │
60+│ /api/cctv /api/news │
61+│ /api/fires /api/maritime │
62+│ /api/gdelt /api/satellites │
63+│ /api/weather /api/scanner │
64+│ /api/sentinel /api/telegram-feed │
65+│ /api/osint/* (whois, dns, ip, cve, sanctions, │
66+│ crypto, sweep, threats, …) │
6067 ├─────────────────────────────────────────────────┤
6168 │ EXTERNAL DATA SOURCES │
6269 │ OpenSky · USGS · NASA · NOAA · TfL · NVD │
6370 │ GDACS · EONET · FIRMS · N2YO · RSS Feeds │
71+│ blockstream.info · Blockscout · OpenSanctions │
72+│ t.me public previews │
6473 └─────────────────────────────────────────────────┘
6574 ```
6675
@@ -69,7 +78,7 @@
6978 ## Features
7079
7180 ### Intelligence Layers
72-- **15 toggleable data layers** with real-time entity counts
81+- **16 toggleable data layers** with real-time entity counts
7382 - **GPU-accelerated rendering** — all map data rendered via WebGL, not DOM
7483 - **Progressive loading** — data fetched on-demand when layers are activated
7584 - **Viewport-aware** — only loads relevant data for the visible region
@@ -77,16 +86,35 @@
7786 ### RECON Toolkit
7887 - **Port Scanner** — TCP connect scan with service fingerprinting
7988 - **DNS Lookup** — Full record resolution (A, AAAA, MX, NS, TXT, CNAME)
80-- **WHOIS** — Domain/IP registration data
89+- **WHOIS** — Domain/IP registration data (auto-cross-checked against OFAC SDN)
8190 - **SSL/TLS Inspector** — Certificate chain analysis
82-- **IP Intelligence** — Geolocation, ASN, and threat reputation
91+- **IP Intelligence** — Geolocation, ASN, threat reputation (auto-cross-checked against OFAC SDN)
8392 - **Vulnerability Scanner** — CVE lookup against NVD database
93+- **Crypto Wallet Trace** — BTC + ETH lookup (balance, tx history, OFAC SDN sanctions flag)
94+- **OFAC Sanctions Search** — query persons, organizations, vessels and aircraft against the US OFAC SDN list
8495
8596 ### Live Broadcast Network
8697 - **25+ live 24/7 news streams** from global broadcasters
8798 - Click any news dot on the map to open the live stream
8899 - Feeds from NBC, CBS, ABC, Sky News, Al Jazeera, France 24, NHK, WION, and more
89100
101+### Telegram OSINT Layer
102+- **Public-channel feed** scraped from the unauthenticated `t.me/s/<channel>` web preview — no Bot API token, no MTProto
103+- Default curated set of 5 channels (EN + RU/UA war reporting), overridable via `OSIRIS_TELEGRAM_CHANNELS`
104+- Posts are geoparsed against a multilingual place dictionary (EN + Cyrillic + Arabic) and plotted on the map
105+- Click any cyan dot to read the post and jump to the original on Telegram
106+
107+### Crypto Wallet Intelligence
108+- **BTC** lookups via [blockstream.info](https://blockstream.info) (Esplora API, keyless)
109+- **ETH** lookups via [Blockscout](https://github.com/blockscout/blockscout)'s public ETH instance (`eth.blockscout.com`, keyless)
110+- Every lookup is cross-checked against the OFAC SDN sanctioned-address list (mirrored from [`0xB10C/ofac-sanctioned-digital-currency-addresses`](https://github.com/0xB10C/ofac-sanctioned-digital-currency-addresses))
111+- Sanctioned wallets surface a red **SANCTIONED — OFAC SDN** badge in the RECON panel
112+
113+### OFAC SDN Cross-Check
114+- Standalone `SANCTIONS` tab in the RECON toolkit — full-text search across persons, organisations, vessels and aircraft
115+- WHOIS and IP-intel routes auto-cross-check registrant / ASN-owner names against the SDN list and surface an inline alert
116+- Data sourced from [OpenSanctions](https://www.opensanctions.org) (CC-BY 4.0) — keyless, ~7 MB cached in-memory for 24h
117+
90118 ### Conflict Zone Monitoring
91119 - **13 active conflict/tension zones** with severity-coded warning markers
92120 - Active Wars: Ukraine, Gaza, Sudan, Myanmar, DRC, Yemen
modified src/app/api/osint/ip/route.ts +20 −1
@@ -1,7 +1,10 @@
11 import { NextResponse } from 'next/server';
22 import { isRateLimited, getClientIp } from '@/lib/ssrf-guard';
3+import { matchExact, type SanctionEntry } from '@/lib/sanctions';
34
4-// IP Geolocation + Reputation — combines multiple free sources
5+// IP Geolocation + Reputation — combines multiple free sources.
6+// Cross-checks the ASN owner / ISP / org strings against the OFAC SDN
7+// list so an IP routed via a sanctioned operator surfaces a hit.
58 export async function GET(req: Request) {
69 const { searchParams } = new URL(req.url);
710 const ip = searchParams.get('ip');
@@ -58,6 +61,22 @@
5861 risk_level: results.geo?.is_proxy ? 'HIGH' : results.geo?.is_hosting ? 'MEDIUM' : 'LOW',
5962 };
6063
64+ // OFAC SDN cross-check on ASN / ISP / org strings.
65+ try {
66+ const candidates = new Set<string>();
67+ if (results.geo?.org) candidates.add(results.geo.org);
68+ if (results.geo?.isp) candidates.add(results.geo.isp);
69+ if (results.geo?.as_name) candidates.add(results.geo.as_name);
70+ const hits: Array<{ matched_value: string; entries: SanctionEntry[] }> = [];
71+ for (const value of candidates) {
72+ const entries = await matchExact(value);
73+ if (entries.length) hits.push({ matched_value: value, entries });
74+ }
75+ results.sanctions_match = hits.length
76+ ? { source: 'OFAC SDN', hits }
77+ : null;
78+ } catch (e) { console.warn('[OSIRIS] Sanctions cross-check failed:', e instanceof Error ? e.message : e); }
79+
6180 return NextResponse.json(results);
6281 } catch {
6382 return NextResponse.json({ error: 'IP lookup failed' }, { status: 500 });
added src/app/api/osint/sanctions/route.ts +65 −0
@@ -0,0 +1,65 @@
1+import { NextResponse } from 'next/server';
2+import { isRateLimited, getClientIp } from '@/lib/ssrf-guard';
3+import { search, type Schema } from '@/lib/sanctions';
4+
5+// Standalone OFAC SDN search (free, no key) backed by the OpenSanctions
6+// `us_ofac_sdn` mirror. Substring + alias-aware match, schema-filterable.
7+
8+const ALLOWED_SCHEMAS: Schema[] = [
9+ 'Person',
10+ 'Organization',
11+ 'Company',
12+ 'Vessel',
13+ 'Airplane',
14+ 'LegalEntity',
15+];
16+
17+export async function GET(req: Request) {
18+ const { searchParams } = new URL(req.url);
19+ const query = (searchParams.get('query') || '').trim();
20+ const schemaParam = searchParams.get('schema');
21+ const limit = Math.min(Math.max(parseInt(searchParams.get('limit') || '25', 10), 1), 100);
22+
23+ if (!query) {
24+ return NextResponse.json({ error: 'Missing query parameter' }, { status: 400 });
25+ }
26+ if (query.length < 4) {
27+ return NextResponse.json(
28+ { error: 'Query must be at least 4 characters' },
29+ { status: 400 }
30+ );
31+ }
32+
33+ const clientIp = getClientIp(req);
34+ if (isRateLimited(clientIp, 20, 60_000)) {
35+ return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 });
36+ }
37+
38+ let schema: Schema | undefined;
39+ if (schemaParam) {
40+ if (!ALLOWED_SCHEMAS.includes(schemaParam as Schema)) {
41+ return NextResponse.json(
42+ { error: `Invalid schema. Allowed: ${ALLOWED_SCHEMAS.join(', ')}` },
43+ { status: 400 }
44+ );
45+ }
46+ schema = schemaParam as Schema;
47+ }
48+
49+ try {
50+ const matches = await search(query, { schema, limit });
51+ return NextResponse.json({
52+ query,
53+ schema: schema ?? null,
54+ total: matches.length,
55+ matches,
56+ source: 'OpenSanctions / US OFAC SDN',
57+ timestamp: new Date().toISOString(),
58+ });
59+ } catch (e) {
60+ return NextResponse.json(
61+ { error: 'Sanctions lookup failed', detail: e instanceof Error ? e.message : String(e) },
62+ { status: 502 }
63+ );
64+ }
65+}
modified src/app/api/osint/whois/route.ts +24 −2
@@ -1,7 +1,12 @@
11 import { NextResponse } from 'next/server';
22 import { safeFetch, isRateLimited, getClientIp } from '@/lib/ssrf-guard';
3-
4-// WHOIS + Domain Intelligence via RDAP (free, standardized)
3+import { 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).
510 export async function GET(req: Request) {
611 const { searchParams } = new URL(req.url);
712 const domain = searchParams.get('domain');
@@ -86,6 +91,23 @@
8691 results.security_score = { score, max: 7, grade: score >= 5 ? 'A' : score >= 3 ? 'B' : score >= 1 ? 'C' : 'F' };
8792 } catch (e) { console.warn('[OSIRIS] Suppressed error:', e instanceof Error ? e.message : e); }
8893
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+
89111 return NextResponse.json(results);
90112 } catch {
91113 return NextResponse.json({ error: 'WHOIS lookup failed' }, { status: 500 });
modified src/components/OsintPanel.tsx +56 −3
@@ -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
10+ Maximize2, Minimize2, Gavel
1111 } from 'lucide-react';
1212
1313 const TABS = [
@@ -22,6 +22,7 @@
2222 { id: 'ssl', label: 'SSL/TLS', icon: Shield, placeholder: 'Domain name', color: '#76FF03' },
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' },
25+ { id: 'sanctions', label: 'SANCTIONS', icon: Gavel, placeholder: 'Person / org / vessel name', color: '#FF1744' },
2526 { id: 'sweep', label: 'IP SWEEP', icon: Crosshair, placeholder: 'Enter IP address (e.g. 8.8.8.8)', color: '#FF3D3D' },
2627 ];
2728
@@ -106,6 +107,7 @@
106107 case 'ssl': url = `/api/scanner?target=${encodeURIComponent(query)}&type=ssl`; break;
107108 case 'subdomains': url = `/api/scanner?target=${encodeURIComponent(query)}&type=subdomains`; break;
108109 case 'tech': url = `/api/scanner?target=${encodeURIComponent(query)}&type=tech`; break;
110+ case 'sanctions': url = `/api/osint/sanctions?query=${encodeURIComponent(query)}`; break;
109111 }
110112 const res = await fetch(url);
111113 const data = await res.json();
@@ -114,7 +116,7 @@
114116 setHistory(prev => [{ tab: activeTab, query, time: new Date().toLocaleTimeString() }, ...prev.slice(0, 9)]);
115117
116118 // Geolocate the target in the background
117- if (activeTab !== 'sweep' && activeTab !== 'vuln') {
119+ if (activeTab !== 'sweep' && activeTab !== 'vuln' && activeTab !== 'sanctions') {
118120 fetch(`/api/osint/ip?ip=${encodeURIComponent(query)}`)
119121 .then(r => r.json())
120122 .then(locData => {
@@ -155,6 +157,28 @@
155157 </span>
156158 );
157159
160+ // Surfaces an inline OFAC-SDN hit (used by the WHOIS and IP-intel routes
161+ // when their cross-check finds a sanctioned registrant / ASN owner).
162+ const SanctionsBadge = ({ match }: { match: any }) => {
163+ if (!match || !Array.isArray(match.hits) || match.hits.length === 0) return null;
164+ return (
165+ <div className="mb-2 px-2 py-2 rounded border border-red-500/40 bg-red-500/15">
166+ <div className="flex items-center gap-2 mb-1.5">
167+ <AlertTriangle className="w-3.5 h-3.5 text-red-400" />
168+ <span className="text-[10px] font-mono font-bold text-red-400 tracking-wider">
169+ SANCTIONED — {match.source || 'OFAC SDN'}
170+ </span>
171+ </div>
172+ {match.hits.slice(0, 5).map((h: any, i: number) => (
173+ <div key={i} className="text-[9px] font-mono text-red-200 break-all leading-tight">
174+ <span className="text-[var(--text-muted)]">↳ {h.matched_value}:</span>{' '}
175+ {(h.entries || []).slice(0, 2).map((e: any) => e.name).join('; ')}
176+ </div>
177+ ))}
178+ </div>
179+ );
180+ };
181+
158182 const SectionHeader = ({ title, icon: Icon, color }: { title: string; icon: any; color: string }) => (
159183 <div className="flex items-center gap-2 mt-3 mb-1.5 first:mt-0">
160184 <Icon className="w-3.5 h-3.5" style={{ color }} />
@@ -278,6 +302,7 @@
278302 return (
279303 <div>
280304 <SectionHeader title="WHOIS INTELLIGENCE" icon={FileText} color="#FFD700" />
305+ <SanctionsBadge match={r.sanctions_match} />
281306 <ResultRow label="Domain" value={r.domain_name || r.domainName || query} color="#FFD700" />
282307 <ResultRow label="Registrar" value={r.registrar} />
283308 <ResultRow label="Created" value={r.creation_date || r.createdDate} />
@@ -285,7 +310,35 @@
285310 <ResultRow label="Updated" value={r.updated_date || r.updatedDate} />
286311 <ResultRow label="Status" value={Array.isArray(r.status) ? r.status.join(', ') : r.status} />
287312 <ResultRow label="Nameservers" value={Array.isArray(r.name_servers || r.nameServers) ? (r.name_servers || r.nameServers).join(', ') : r.name_servers} />
288- {renderFallbackExcluding(['domain_name','domainName','registrar','creation_date','createdDate','expiration_date','expiresDate','updated_date','updatedDate','status','name_servers','nameServers','timestamp','cached','raw'])}
313+ {renderFallbackExcluding(['domain_name','domainName','registrar','creation_date','createdDate','expiration_date','expiresDate','updated_date','updatedDate','status','name_servers','nameServers','timestamp','cached','raw','sanctions_match'])}
314+ </div>
315+ );
316+ }
317+
318+ // ── SANCTIONS ──
319+ if (activeTab === 'sanctions') {
320+ const matches = Array.isArray(r.matches) ? r.matches : [];
321+ return (
322+ <div>
323+ <SectionHeader title="OFAC SDN SEARCH" icon={Gavel} color="#FF1744" />
324+ <ResultRow label="Query" value={r.query || query} color="#FF1744" />
325+ <ResultRow label="Source" value={r.source} />
326+ <ResultRow label="Matches" value={r.total ?? matches.length} color={matches.length ? '#FF1744' : '#00E676'} />
327+ {matches.slice(0, 20).map((m: any) => (
328+ <div key={m.id} className="mt-2 p-2 rounded border border-red-500/30 bg-red-500/5">
329+ <div className="flex items-center justify-between mb-1">
330+ <span className="text-[10px] font-mono font-bold text-red-400 break-all">{m.name}</span>
331+ <span className="text-[8px] font-mono uppercase tracking-wider text-[var(--text-muted)] ml-2 flex-shrink-0">{m.schema}</span>
332+ </div>
333+ <ResultRow label="Aliases" value={Array.isArray(m.aliases) && m.aliases.length ? m.aliases.slice(0, 4).join(' • ') : undefined} />
334+ <ResultRow label="Countries" value={Array.isArray(m.countries) && m.countries.length ? m.countries.join(', ').toUpperCase() : undefined} />
335+ <ResultRow label="Programs" value={Array.isArray(m.programs) && m.programs.length ? m.programs.slice(0, 3).join(', ') : undefined} />
336+ <ResultRow label="First Seen" value={m.first_seen ? m.first_seen.slice(0, 10) : undefined} />
337+ </div>
338+ ))}
339+ {matches.length === 0 && (
340+ <div className="mt-2 px-2 py-1.5 text-[10px] font-mono text-green-400">No OFAC SDN matches for that query.</div>
341+ )}
289342 </div>
290343 );
291344 }
added src/lib/sanctions.ts +245 −0
@@ -0,0 +1,245 @@
1+/**
2+ * OFAC SDN sanctioned-entity lookup.
3+ *
4+ * Source: [OpenSanctions](https://www.opensanctions.org/) `us_ofac_sdn`
5+ * dataset, distributed as a simple CSV under CC-BY 4.0. OpenSanctions
6+ * normalises the upstream Treasury data into a flat schema with stable
7+ * field names and an entity-type discriminator (`Person`, `Organization`,
8+ * `Vessel`, `Aircraft`, …), which is far easier to consume than the raw
9+ * SDN XML.
10+ *
11+ * The whole list (~7 MB, low-tens-of-thousands of entries) is downloaded
12+ * once on first use, parsed into normalised lookup indices, and refreshed
13+ * lazily every 24h. Concurrent requests that arrive while a fetch is in
14+ * flight wait on the same promise (single-flight) so we never pull the
15+ * file twice. If a refresh fails after the cache has gone stale we keep
16+ * serving the previous snapshot rather than leaving the route blind.
17+ */
18+
19+const SDN_CSV_URL =
20+ 'https://data.opensanctions.org/datasets/latest/us_ofac_sdn/targets.simple.csv';
21+
22+const TTL_MS = 24 * 60 * 60 * 1000;
23+
24+export type Schema =
25+ | 'Person'
26+ | 'Organization'
27+ | 'Company'
28+ | 'Vessel'
29+ | 'Airplane'
30+ | 'LegalEntity'
31+ | 'Security'
32+ | string;
33+
34+export interface SanctionEntry {
35+ id: string;
36+ schema: Schema;
37+ name: string;
38+ aliases: string[];
39+ countries: string[];
40+ programs: string[];
41+ sanctions: string;
42+ first_seen?: string;
43+ last_seen?: string;
44+}
45+
46+interface LoadedList {
47+ fetchedAt: number;
48+ entries: SanctionEntry[];
49+ /** Lower-cased, punctuation-stripped name/alias → entry. */
50+ byNormName: Map<string, SanctionEntry[]>;
51+}
52+
53+let cache: LoadedList | null = null;
54+let inflight: Promise<LoadedList> | null = null;
55+
56+/**
57+ * Lower-case, strip punctuation, collapse whitespace. Used for both index
58+ * keys and incoming query normalisation so the same string yields the
59+ * same key on both sides.
60+ */
61+export function normName(s: string): string {
62+ return s
63+ .toLowerCase()
64+ .replace(/[^\p{L}\p{N}\s]+/gu, ' ')
65+ .replace(/\s+/g, ' ')
66+ .trim();
67+}
68+
69+/**
70+ * Minimal CSV parser tolerant of double-quoted fields with embedded
71+ * commas, newlines and `""` escapes. The OpenSanctions CSV is well-formed
72+ * so we don't need a heavyweight parser — `papaparse` etc. would just
73+ * pull a dependency for the same job.
74+ */
75+function parseCsv(text: string): string[][] {
76+ const rows: string[][] = [];
77+ let field = '';
78+ let row: string[] = [];
79+ let inQuotes = false;
80+ for (let i = 0; i < text.length; i++) {
81+ const c = text[i];
82+ if (inQuotes) {
83+ if (c === '"') {
84+ if (text[i + 1] === '"') {
85+ field += '"';
86+ i++;
87+ } else {
88+ inQuotes = false;
89+ }
90+ } else {
91+ field += c;
92+ }
93+ } else if (c === '"') {
94+ inQuotes = true;
95+ } else if (c === ',') {
96+ row.push(field);
97+ field = '';
98+ } else if (c === '\n') {
99+ row.push(field);
100+ rows.push(row);
101+ row = [];
102+ field = '';
103+ } else if (c === '\r') {
104+ // ignore — handled by the \n branch
105+ } else {
106+ field += c;
107+ }
108+ }
109+ if (field.length || row.length) {
110+ row.push(field);
111+ rows.push(row);
112+ }
113+ return rows;
114+}
115+
116+async function loadList(): Promise<LoadedList> {
117+ if (cache && Date.now() - cache.fetchedAt < TTL_MS) return cache;
118+ if (inflight) return inflight;
119+
120+ inflight = (async () => {
121+ try {
122+ const res = await fetch(SDN_CSV_URL, {
123+ signal: AbortSignal.timeout(30_000),
124+ headers: { Accept: 'text/csv' },
125+ });
126+ if (!res.ok) throw new Error(`OpenSanctions HTTP ${res.status}`);
127+ const text = await res.text();
128+ const rows = parseCsv(text);
129+ if (rows.length < 2) throw new Error('OpenSanctions CSV empty');
130+
131+ const headers = rows[0];
132+ const idx = (col: string) => headers.indexOf(col);
133+ const i = {
134+ id: idx('id'),
135+ schema: idx('schema'),
136+ name: idx('name'),
137+ aliases: idx('aliases'),
138+ countries: idx('countries'),
139+ programs: idx('program_ids'),
140+ sanctions: idx('sanctions'),
141+ first_seen: idx('first_seen'),
142+ last_seen: idx('last_seen'),
143+ };
144+
145+ const entries: SanctionEntry[] = [];
146+ const byNormName = new Map<string, SanctionEntry[]>();
147+
148+ for (let r = 1; r < rows.length; r++) {
149+ const row = rows[r];
150+ if (!row[i.name]) continue;
151+ const entry: SanctionEntry = {
152+ id: row[i.id] || '',
153+ schema: row[i.schema] || 'LegalEntity',
154+ name: row[i.name],
155+ aliases: (row[i.aliases] || '').split(';').map((s) => s.trim()).filter(Boolean),
156+ countries: (row[i.countries] || '').split(';').map((s) => s.trim()).filter(Boolean),
157+ programs: (row[i.programs] || '').split(';').map((s) => s.trim()).filter(Boolean),
158+ sanctions: row[i.sanctions] || '',
159+ first_seen: i.first_seen >= 0 ? row[i.first_seen] : undefined,
160+ last_seen: i.last_seen >= 0 ? row[i.last_seen] : undefined,
161+ };
162+ entries.push(entry);
163+
164+ // Index every name + alias under its normalised form so an exact
165+ // (post-normalisation) match is O(1).
166+ const keys = new Set<string>([entry.name, ...entry.aliases].map(normName));
167+ for (const key of keys) {
168+ if (!key) continue;
169+ const list = byNormName.get(key);
170+ if (list) list.push(entry);
171+ else byNormName.set(key, [entry]);
172+ }
173+ }
174+
175+ const loaded = { fetchedAt: Date.now(), entries, byNormName };
176+ cache = loaded;
177+ return loaded;
178+ } catch (e) {
179+ if (cache) return cache;
180+ throw e;
181+ } finally {
182+ inflight = null;
183+ }
184+ })();
185+
186+ return inflight;
187+}
188+
189+/**
190+ * Strict exact-match lookup (used for inline cross-checks where false
191+ * positives must be avoided — the registrant string `"Acme"` should NOT
192+ * match `"Acme Holdings"` automatically).
193+ */
194+export async function matchExact(query: string): Promise<SanctionEntry[]> {
195+ if (!query || query.length < 3) return [];
196+ const list = await loadList();
197+ return list.byNormName.get(normName(query)) ?? [];
198+}
199+
200+/**
201+ * Substring + contains search (used for the standalone SANCTIONS tab where
202+ * the operator is explicitly probing for partial names).
203+ *
204+ * Returns up to `limit` matches, ranked: exact name match first, then
205+ * exact alias match, then substring of name, then substring of alias.
206+ */
207+export async function search(
208+ query: string,
209+ opts: { schema?: Schema; limit?: number } = {}
210+): Promise<SanctionEntry[]> {
211+ if (!query || query.length < 4) return [];
212+ const list = await loadList();
213+ const q = normName(query);
214+ const limit = opts.limit ?? 50;
215+
216+ const exactName: SanctionEntry[] = [];
217+ const exactAlias: SanctionEntry[] = [];
218+ const subName: SanctionEntry[] = [];
219+ const subAlias: SanctionEntry[] = [];
220+ const seen = new Set<string>();
221+
222+ const push = (bucket: SanctionEntry[], e: SanctionEntry) => {
223+ if (seen.has(e.id)) return;
224+ if (opts.schema && e.schema !== opts.schema) return;
225+ seen.add(e.id);
226+ bucket.push(e);
227+ };
228+
229+ for (const entry of list.entries) {
230+ const nameNorm = normName(entry.name);
231+ if (nameNorm === q) push(exactName, entry);
232+ else if (entry.aliases.some((a) => normName(a) === q)) push(exactAlias, entry);
233+ else if (nameNorm.includes(q)) push(subName, entry);
234+ else if (entry.aliases.some((a) => normName(a).includes(q))) push(subAlias, entry);
235+ if (seen.size >= limit * 4) break; // hard cap on the scan
236+ }
237+
238+ return [...exactName, ...exactAlias, ...subName, ...subAlias].slice(0, limit);
239+}
240+
241+/** Number of indexed entries, for diagnostics / `/api/health`. */
242+export async function indexSize(): Promise<number> {
243+ const list = await loadList();
244+ return list.entries.length;
245+}