| 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 | } |