-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
1908 lines (1777 loc) · 82.5 KB
/
Copy pathserver.ts
File metadata and controls
1908 lines (1777 loc) · 82.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Kafka, type Producer } from "kafkajs";
import * as dgram from "node:dgram";
import { LAN_IFACE, OPN_RANGES, PAGE_QUERIES, WAN_IFACE } from "./queries";
import { log, logThrottled } from "./logger";
// ─── Process-level safety net (register once, before anything else runs) ───
// unhandledRejection: log + CONTINUE (a single dropped promise must not take the
// KPI publisher / NetFlow collector down). uncaughtException: log + exit(1) so
// k8s/systemd restarts into a known-good state.
process.on("unhandledRejection", (reason) => {
log.error("unhandledRejection", {
err: String((reason as Error)?.message ?? reason),
stack: (reason as Error)?.stack,
});
});
process.on("uncaughtException", (err) => {
log.error("uncaughtException", { err: err.message, stack: err.stack });
process.exit(1);
});
// Standard 500 responder: log the failure (route + err + stack) BEFORE replying.
// The browser read path must never fail silently again.
function respond500(route: string, e: unknown, req: Request): Response {
log.error("request handler failed", {
route,
err: String((e as Error)?.message ?? e),
stack: (e as Error)?.stack,
});
return Response.json({ error: (e as Error).message }, { status: 500, headers: corsHeaders(req.headers.get("origin")) });
}
const CLICKHOUSE_URL = process.env.CLICKHOUSE_URL || "http://localhost:8123";
const PORT = parseInt(process.env.PORT || "3005");
// Your firewall's API base, e.g. https://203.0.113.1/api — REQUIRED for the
// OPNsense-backed routes and collectors; everything else degrades gracefully.
const OPN_URL = process.env.OPN_URL || "";
// Secrets come from the environment (k8s Secret `glm-firewall-secrets` in-cluster,
// or /etc/glm-firewall-api.env via the systemd EnvironmentFile on a bare host).
const OPN_KEY = process.env.OPN_KEY || "";
const OPN_SECRET = process.env.OPN_SECRET || "";
const OPN_AUTH = "Basic " + btoa(`${OPN_KEY}:${OPN_SECRET}`);
const KAFKA_BROKERS = (process.env.KAFKA_BROKERS || "localhost:9092").split(",");
const KAFKA_TOPIC = process.env.KAFKA_TOPIC || "opnsense-stats";
// Optional SASL/SCRAM-SHA-512 + TLS for the authenticated Kafka listeners
// (KAFKA-SECURITY-ROADMAP.md Tier 2). Unset env = plaintext dial, same
// dual-mode convention as the Go clients.
const KAFKA_SASL_USERNAME = process.env.KAFKA_SASL_USERNAME || "";
const KAFKA_SASL_PASSWORD = process.env.KAFKA_SASL_PASSWORD || "";
const KAFKA_CA_FILE = process.env.KAFKA_CA_FILE || "";
const KPI_INTERVAL = 10_000;
const CORS_ORIGINS = (process.env.CORS_ORIGINS || "http://localhost:5173,https://monitor.example.com").split(",");
// ─── CrowdSec LAPI (direct HTTP, no SSH) ───
// e.g. http://203.0.113.1:8080 — unset disables the CrowdSec checks.
const CS_LAPI_URL = process.env.CS_LAPI_URL || "";
const CS_BOUNCER_KEY = process.env.CS_BOUNCER_KEY || "";
async function csLapiGet(path: string) {
const resp = await fetch(`${CS_LAPI_URL}${path}`, {
headers: { "X-Api-Key": CS_BOUNCER_KEY },
});
return resp.json();
}
// ─── CrowdSec CAPI ban count cache (CAPI updates every ~2h, no need to poll faster) ───
// Split by origin: CAPI/lists = community blocklist (defense strength, not a threat
// signal); anything else (crowdsec/cscli) = a LOCAL detection triggered by our own
// logs — those are the actionable ones.
const CS_COMMUNITY_ORIGINS = new Set(["CAPI", "lists"]);
let csCache = {
total: 0,
community: 0,
local: 0,
localDecisions: [] as Array<Record<string, unknown>>,
sample: [] as Array<Record<string, unknown>>,
updatedAt: 0,
};
const CS_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
async function getCrowdsecSplit(): Promise<typeof csCache> {
if (!CS_LAPI_URL) return csCache;
if (Date.now() - csCache.updatedAt < CS_CACHE_TTL) return csCache;
try {
const decisions = await csLapiGet("/v1/decisions") as Array<Record<string, unknown>> | null;
const all = Array.isArray(decisions) ? decisions : [];
const local = all.filter(d => !CS_COMMUNITY_ORIGINS.has(String(d.origin)));
csCache = {
total: all.length,
community: all.length - local.length,
local: local.length,
localDecisions: local.slice(0, 50),
sample: all.slice(0, 10),
updatedAt: Date.now(),
};
return csCache;
} catch (e) {
logThrottled("crowdsec-split", 60_000, "warn", "CrowdSec LAPI fetch failed, serving cached decisions", {
err: String((e as Error)?.message ?? e),
});
return csCache;
}
}
async function getCrowdsecBanCount(): Promise<number> {
return (await getCrowdsecSplit()).total;
}
// ─── Benign-context rules (verdict suppression + scorer exclusions) ───
// Site-specific: source prefixes whose P2P/VPN churn dominates NetFlow and
// matches low-confidence blocklists constantly (the nature of public peer
// swarms, not compromise). Comma-separated, e.g. "10.0.50.,10.193." for a
// torrent VLAN and its WireGuard tunnel. Empty = no suppression.
const VPN_SRC_PREFIXES = (process.env.VPN_SRC_PREFIXES || "").split(",").map(s => s.trim()).filter(Boolean);
const TORRENT_PORTS = new Set([51413, 51414]);
const isTorrentPort = (p: number) => (p >= 6881 && p <= 6999) || TORRENT_PORTS.has(p);
const isVpnSource = (ip: string) => VPN_SRC_PREFIXES.some(pre => ip.startsWith(pre));
// Push-notification keepalives (Google FCM 5228-5230) beacon by design.
const PUSH_KEEPALIVE_PORTS = new Set([5228, 5229, 5230]);
// ng_netflow chops long-lived flows at its active timeout (~30 min), so continuous
// connections re-export on a metronome and score as "perfectly regular beacons".
const isFlowTimerArtifact = (intervalSec: number) => intervalSec >= 1400 && intervalSec <= 2200;
// Domains whose subdomains are random-looking BY DESIGN (CDN hashes, per-device
// hostnames) plus your own zones (add them via DNS_BENIGN_EXTRA, comma-separated).
// Suffix match on the registered domain.
const DNS_BENIGN_SUFFIXES = [
"plex.direct", "amazonaws.com", "steamserver.net", "mozgcp.net", "akadns.net",
"googlevideo.com", "gvt1.com", "spotify.com", "cloudfront.net", "akamaiedge.net",
"example.com", "in-addr.arpa", "ip6.arpa",
"svc", "cluster.local", // k8s service DNS spilling to Unbound
...(process.env.DNS_BENIGN_EXTRA || "").split(",").map(s => s.trim().toLowerCase()).filter(Boolean),
];
const isBenignDomain = (domain: string) => {
const d = (domain || "").toLowerCase();
return DNS_BENIGN_SUFFIXES.some(suf => d === suf || d.endsWith("." + suf));
};
// Known-benign egress IDS patterns: signature substring + destination CIDR.
// Heavy git-over-SSH to GitHub trips the "SSH Scan OUTBOUND" rate heuristic daily.
const ipToUint = (ip: string): number => {
const p = ip.split(".").map(Number);
return p.length === 4 && p.every(n => n >= 0 && n <= 255)
? ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]) >>> 0 : -1;
};
const inCidr = (ip: string, cidr: string): boolean => {
const [base, bitsStr] = cidr.split("/");
const bits = Number(bitsStr);
const ipN = ipToUint(ip), baseN = ipToUint(base);
if (ipN < 0 || baseN < 0) return false;
const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
return (ipN & mask) === (baseN & mask);
};
const BENIGN_EGRESS_IDS: Array<{ sig: string; cidr: string; label: string }> = [
{ sig: "SSH Scan OUTBOUND", cidr: "140.82.112.0/20", label: "git-over-SSH to GitHub" },
];
// Guard for `INTERVAL ${range}` interpolation on the new endpoint.
const parseRange = (raw: string | null, fallback: string) => {
const r = (raw || "").trim().toUpperCase();
return /^\d{1,4} (MINUTE|HOUR|DAY)S?$/.test(r) ? r : fallback;
};
// ─── CORS helper ───
function corsHeaders(origin?: string | null): Record<string, string> {
const allowed = origin && CORS_ORIGINS.includes(origin) ? origin : CORS_ORIGINS[0];
return {
"Access-Control-Allow-Origin": allowed,
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
}
// ─── GeoIP cache ───
const geoCache = new Map<string, Record<string, unknown>>();
const GEO_TTL = 24 * 60 * 60 * 1000;
// ─── OPNsense API helpers ───
async function opnGet(path: string) {
if (!OPN_URL) throw new Error("OPN_URL not configured");
const resp = await fetch(`${OPN_URL}${path}`, {
headers: { Authorization: OPN_AUTH },
// Bun-specific TLS option for self-signed certs
tls: { rejectUnauthorized: false },
});
return resp.json();
}
async function opnPost(path: string, body?: Record<string, unknown>) {
if (!OPN_URL) throw new Error("OPN_URL not configured");
const resp = await fetch(`${OPN_URL}${path}`, {
method: "POST",
headers: { Authorization: OPN_AUTH, "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
// Bun-specific TLS option for self-signed certs
tls: { rejectUnauthorized: false },
});
return resp.json();
}
// ─── ClickHouse query helpers ───
// chQuery is the writable path — ONLY for internal jobs (refreshThreatFeeds
// needs CREATE/TRUNCATE/EXCHANGE/DROP, KPI polling is trusted). Everything a
// browser request can trigger goes through chQueryRO: readonly=1 makes
// ClickHouse itself reject INSERT/ALTER/DDL regardless of what the SQL says.
async function chRun(sql: string, readonly: boolean) {
// Throttle key derived from the query shape (chRun has no name); one line per
// distinct failing query per minute so a broken read path is visible but not spammy.
const norm = sql.replace(/\s+/g, " ").trim();
const throttleKey = "chRun:" + norm.slice(0, 100);
let resp: Response;
try {
resp = await fetch(`${CLICKHOUSE_URL}/?default_format=JSONEachRow${readonly ? "&readonly=1" : ""}`, {
method: "POST",
body: sql,
});
} catch (e) {
logThrottled(throttleKey, 60_000, "error", "ClickHouse request failed (unreachable)", {
err: String((e as Error)?.message ?? e), query: norm.slice(0, 200),
});
return { error: String((e as Error)?.message ?? e), data: [] };
}
const text = await resp.text();
if (!resp.ok) {
logThrottled(throttleKey, 60_000, "error", "ClickHouse query failed", {
status: resp.status, err: text.slice(0, 500), query: norm.slice(0, 200),
});
return { error: text, data: [] };
}
const rows = text.trim()
? text.trim().split("\n").map((l) => JSON.parse(l))
: [];
return { data: rows };
}
const chQuery = (sql: string) => chRun(sql, false);
const chQueryRO = (sql: string) => chRun(sql, true);
// ─── GeoIP enrichment handler ───
async function handleGeoEnrich(req: Request): Promise<Response> {
try {
const { ips = [] } = (await req.json()) as { ips: string[] };
const results: Record<string, unknown>[] = [];
const toFetch: string[] = [];
for (const ip of ips) {
const cached = geoCache.get(ip);
if (cached && Date.now() - (cached._cachedAt as number) < GEO_TTL) {
results.push(cached);
} else {
toFetch.push(ip);
}
}
if (toFetch.length > 0) {
for (let i = 0; i < toFetch.length; i += 100) {
const chunk = toFetch.slice(i, i + 100);
const resp = await fetch("http://ip-api.com/batch", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(chunk),
});
const data = (await resp.json()) as Array<Record<string, unknown>>;
for (const d of data) {
if (d.status !== "success") continue;
const entry = {
ip: d.query, country: d.country, cc: d.countryCode,
city: d.city, region: d.regionName, lat: d.lat, lon: d.lon,
isp: d.isp, org: d.org, as: d.as, _cachedAt: Date.now(),
};
geoCache.set(d.query as string, entry);
results.push(entry);
}
}
}
return Response.json(results, { headers: corsHeaders(req.headers.get("origin")) });
} catch (e: unknown) {
return respond500("/api/geo/enrich", e, req);
}
}
// ─── Kafka producer ───
let kafkaProducer: Producer | null = null;
async function initKafka() {
try {
const kafka = new Kafka({
clientId: "glm-firewall-api",
brokers: KAFKA_BROKERS,
...(KAFKA_CA_FILE
? { ssl: { ca: [await Bun.file(KAFKA_CA_FILE).text()] } }
: {}),
...(KAFKA_SASL_USERNAME
? {
sasl: {
mechanism: "scram-sha-512" as const,
username: KAFKA_SASL_USERNAME,
password: KAFKA_SASL_PASSWORD,
},
}
: {}),
});
kafkaProducer = kafka.producer();
await kafkaProducer.connect();
log.info("Kafka connected", {
brokers: KAFKA_BROKERS.join(","),
topic: KAFKA_TOPIC,
sasl: KAFKA_SASL_USERNAME || undefined,
tls: KAFKA_CA_FILE ? true : undefined,
});
} catch (e) {
log.error("Kafka init failed (KPI publishing disabled until restart)", {
err: String((e as Error)?.message ?? e), stack: (e as Error)?.stack,
});
kafkaProducer = null;
}
}
// ─── KPI polling queries (subset for Kafka publishing) ───
const PUB_FILTER = `AND NOT (src_ip LIKE '192.168.%' OR src_ip LIKE '10.%' OR (src_ip >= '172.16.0.0' AND src_ip <= '172.31.255.255') OR src_ip LIKE '224.%' OR src_ip LIKE '169.254.%' OR src_ip LIKE '0.%' OR src_ip LIKE '255.%' OR src_ip LIKE '127.%')`;
function kpiQueries(): string[] {
return [
// 0: CPU (last 5 min avg)
`SELECT 100-avg(fields['usage_idle']) AS v FROM opnsense.telegraf_metrics WHERE measurement='cpu' AND tags['cpu']='cpu-total' AND timestamp>now()-INTERVAL 5 MINUTE`,
// 1: Memory
`SELECT avg(fields['used_percent']) AS v FROM opnsense.telegraf_metrics WHERE measurement='mem' AND timestamp>now()-INTERVAL 5 MINUTE`,
// 2: Disk
`SELECT avg(fields['used_percent']) AS v FROM opnsense.telegraf_metrics WHERE measurement='disk' AND timestamp>now()-INTERVAL 5 MINUTE`,
// 3: Temperatures
`SELECT tags['sensor'] AS sensor,argMax(fields['degrees'],timestamp) AS deg FROM opnsense.telegraf_metrics WHERE measurement='temperature' AND timestamp>now()-INTERVAL 5 MINUTE GROUP BY sensor`,
// 4: WAN bandwidth (last 2 points for delta)
`SELECT timestamp AS t,fields['bytes_recv'] AS rx,fields['bytes_sent'] AS tx FROM opnsense.telegraf_metrics WHERE measurement='net' AND tags['interface']='${WAN_IFACE}' AND timestamp>now()-INTERVAL 1 MINUTE ORDER BY timestamp DESC LIMIT 2`,
// 5: LAN bandwidth (last 2 points for delta)
`SELECT timestamp AS t,fields['bytes_recv'] AS rx,fields['bytes_sent'] AS tx FROM opnsense.telegraf_metrics WHERE measurement='net' AND tags['interface']='${LAN_IFACE}' AND timestamp>now()-INTERVAL 1 MINUTE ORDER BY timestamp DESC LIMIT 2`,
// 6: Blocked count (last hour)
`SELECT count() AS cnt FROM opnsense.firewall_logs WHERE action='block' ${PUB_FILTER} AND timestamp>now()-INTERVAL 1 HOUR`,
// 7: Total events (last hour)
`SELECT count() AS cnt FROM opnsense.firewall_logs WHERE timestamp>now()-INTERVAL 1 HOUR`,
// 8: PF states
`SELECT argMax(fields['entries'],timestamp) AS current, argMax(fields['state-limit'],timestamp) AS lim FROM opnsense.telegraf_metrics WHERE measurement='pf' AND timestamp>now()-INTERVAL 5 MINUTE`,
// 9: Gateways
`SELECT tags['gateway_name'] AS gw,avg(fields['delay']) AS delay,avg(fields['loss']) AS loss,argMax(fields['status'],timestamp) AS status FROM opnsense.telegraf_metrics WHERE measurement='gateways' AND timestamp>now()-INTERVAL 5 MINUTE GROUP BY gw`,
// 10: Uptime
`SELECT fields['uptime'] AS v FROM opnsense.telegraf_metrics WHERE measurement='system' AND timestamp>now()-INTERVAL 5 MINUTE ORDER BY timestamp DESC LIMIT 1`,
// 11: DNS stats from ClickHouse (last hour)
`SELECT sum(total) AS total, sum(blocked) AS blocked, max(blocklist_size) AS blocklist_size FROM opnsense.dns_stats WHERE timestamp>now()-INTERVAL 1 HOUR`,
];
}
async function publishKpis() {
if (!kafkaProducer) {
logThrottled("kpi-no-producer", 60_000, "warn", "Skipping KPI publish: Kafka producer not connected", {});
return;
}
try {
const results = await Promise.all(kpiQueries().map(chQuery));
// Extract KPIs
const cpuUsage = results[0]?.data?.[0]?.v ?? 0;
const memoryUsage = results[1]?.data?.[0]?.v ?? 0;
const diskUsage = results[2]?.data?.[0]?.v ?? 0;
const temps = (results[3]?.data || []) as Array<{ sensor: string; deg: number }>;
// OPNsense uses tz0 (thermal zone) — take max of all sensors
const allDegs = temps.map(t => Number(t.deg)).filter(d => !isNaN(d));
const cpuTemp = allDegs.length > 0 ? Math.max(...allDegs) : 0;
const acpiTemp = 0; // OPNsense only has tz0, no separate ACPI sensor
// Bandwidth: delta between 2 most recent points (bytes/sec * 8 = bps)
const wanPts = (results[4]?.data || []) as Array<{ t: string; rx: number; tx: number }>;
let wanDownBps = 0, wanUpBps = 0;
if (wanPts.length >= 2) {
const dt = (new Date(wanPts[0].t).getTime() - new Date(wanPts[1].t).getTime()) / 1000;
if (dt > 0) {
wanDownBps = Math.max(0, ((wanPts[0].rx - wanPts[1].rx) * 8) / dt);
wanUpBps = Math.max(0, ((wanPts[0].tx - wanPts[1].tx) * 8) / dt);
}
}
const lanPts = (results[5]?.data || []) as Array<{ t: string; rx: number; tx: number }>;
let lanDownBps = 0, lanUpBps = 0;
if (lanPts.length >= 2) {
const dt = (new Date(lanPts[0].t).getTime() - new Date(lanPts[1].t).getTime()) / 1000;
if (dt > 0) {
lanDownBps = Math.max(0, ((lanPts[0].rx - lanPts[1].rx) * 8) / dt);
lanUpBps = Math.max(0, ((lanPts[0].tx - lanPts[1].tx) * 8) / dt);
}
}
const blockedCount = Number(results[6]?.data?.[0]?.cnt ?? 0);
const totalEvents = Number(results[7]?.data?.[0]?.cnt ?? 0);
const blockRate = totalEvents > 0 ? (blockedCount / totalEvents * 100) : 0;
const pfCurrent = Number(results[8]?.data?.[0]?.current ?? 0);
const pfLimit = Number(results[8]?.data?.[0]?.lim ?? 0);
const gws = (results[9]?.data || []) as Array<{ gw: string; delay: number; loss: number; status: number }>;
const wanGw = gws.find(g => g.gw === "WAN_GW");
const uptime = Number(results[10]?.data?.[0]?.v ?? 0);
const dnsData = results[11]?.data?.[0] as { total?: number; blocked?: number; blocklist_size?: number } | undefined;
// Also fetch live DNS totals from OPNsense API for current numbers
let dnsTotals = { total: 0, blocked: 0, blocklistSize: 0 };
try {
const dnsResp = await opnGet("/unbound/overview/totals/60") as { total?: number; blocked?: { total?: number }; blocklist_size?: number };
dnsTotals = {
total: dnsResp.total || Number(dnsData?.total ?? 0),
blocked: dnsResp.blocked?.total || Number(dnsData?.blocked ?? 0),
blocklistSize: dnsResp.blocklist_size || Number(dnsData?.blocklist_size ?? 0),
};
} catch (e) {
logThrottled("kpi-dns-totals", 60_000, "warn", "OPNsense DNS totals fetch failed, using ClickHouse fallback", {
err: String((e as Error)?.message ?? e),
});
dnsTotals = {
total: Number(dnsData?.total ?? 0),
blocked: Number(dnsData?.blocked ?? 0),
blocklistSize: Number(dnsData?.blocklist_size ?? 0),
};
}
// CrowdSec CAPI ban count (cached, refreshes every 5 min via LAPI)
const crowdsecBans = await getCrowdsecBanCount();
const kpiMessage = {
timestamp: new Date().toISOString(),
system: {
cpuUsage: Number(Number(cpuUsage).toFixed(1)),
memoryUsage: Number(Number(memoryUsage).toFixed(1)),
diskUsage: Number(Number(diskUsage).toFixed(1)),
cpuTemp: Number(Number(cpuTemp).toFixed(1)),
acpiTemp: Number(Number(acpiTemp).toFixed(1)),
uptime: Math.round(uptime),
},
firewall: {
blockedCount,
blockRate: Number(blockRate.toFixed(1)),
pfStates: pfCurrent,
pfStateLimit: pfLimit,
},
bandwidth: {
wanDownBps: Math.round(wanDownBps),
wanUpBps: Math.round(wanUpBps),
lanDownBps: Math.round(lanDownBps),
lanUpBps: Math.round(lanUpBps),
},
dns: {
totalQueries: dnsTotals.total,
blockedQueries: dnsTotals.blocked,
blockRate: dnsTotals.total > 0 ? Number(((dnsTotals.blocked / dnsTotals.total) * 100).toFixed(1)) : 0,
blocklistSize: dnsTotals.blocklistSize,
},
crowdsec: { activeBans: crowdsecBans },
gateway: {
delay: wanGw ? Number(Number(wanGw.delay).toFixed(1)) : 0,
loss: wanGw ? Number(Number(wanGw.loss).toFixed(1)) : 0,
status: wanGw ? (wanGw.status === 1 ? "online" : "offline") : "unknown",
},
};
await kafkaProducer.send({
topic: KAFKA_TOPIC,
messages: [{ value: JSON.stringify(kpiMessage) }],
});
} catch (e) {
logThrottled("kpi-publish", 60_000, "error", "KPI publish failed", {
err: String((e as Error)?.message ?? e), stack: (e as Error)?.stack,
});
}
}
// ─── Security verdict ───
// Replaces the client-side 0-100 "threat score" (permanently pinned ~15/CRITICAL
// because every input measured internet background noise or the defenses doing
// their job). The verdict escalates only on actionable evidence; benign patterns
// are suppressed WITH visible counts so the UI can show what was filtered and why.
interface Finding {
severity: "action" | "review";
check: string;
title: string;
detail: string;
count: number;
lastSeen?: string;
}
interface CheckStatus {
id: string;
label: string;
status: "ok" | "findings" | "stale";
detail: string;
suppressed: number;
}
// Post-NAT egress logs on the WAN interface carry this src (the firewall's own
// WAN address behind an upstream router, if any). Empty = the WAN-src special
// case never applies.
const WAN_SRC_IP = process.env.WAN_SRC_IP || "";
async function computeVerdict(range: string) {
const [
egress, beacons, dnsAnoms, idsSev1, idsEgress, idsTotal,
gateways, pf, freshness, blocked, fwTotal, nfTotal, dnsCounts, feeds,
] = await Promise.all([
chQueryRO(`
SELECT fl.src_ip AS src_ip, fl.dst_ip AS dst_ip, fl.dst_port AS dst_port,
ti.source AS source, ti.confidence AS confidence, count() AS cnt,
formatDateTime(max(fl.timestamp),'%Y-%m-%d %H:%i:%S') AS last_seen
FROM opnsense.firewall_logs fl
INNER JOIN opnsense.threat_intel ti ON fl.dst_ip = ti.ip
WHERE fl.action='pass' AND fl.direction='out' AND fl.timestamp > now() - INTERVAL ${range}
GROUP BY src_ip, dst_ip, dst_port, source, confidence
ORDER BY confidence DESC, cnt DESC LIMIT 200`),
chQueryRO(`
SELECT src_ip, dst_ip, dst_port, beacon_score, connection_count,
interval_mode, total_bytes,
formatDateTime(last_seen,'%Y-%m-%d %H:%i:%S') AS last_seen_fmt
FROM opnsense.beacon_scores FINAL
WHERE beacon_score >= 0.7 AND last_seen > now() - INTERVAL ${range}
ORDER BY beacon_score DESC LIMIT 500`),
chQueryRO(`
SELECT anomaly_type, client_ip, domain,
max(query_count) AS query_count, max(avg_entropy) AS entropy,
max(avg_subdomain_len) AS sub_len, count() AS occurrences,
formatDateTime(max(detected_at),'%Y-%m-%d %H:%i:%S') AS last_seen
FROM opnsense.dns_anomalies
WHERE detected_at > now() - INTERVAL ${range}
GROUP BY anomaly_type, client_ip, domain
ORDER BY occurrences DESC LIMIT 200`),
chQueryRO(`
SELECT alert_signature, alert_category, src_ip, dst_ip, count() AS cnt,
formatDateTime(max(timestamp),'%Y-%m-%d %H:%i:%S') AS last_seen
FROM opnsense.suricata_alerts
WHERE alert_severity = 1 AND timestamp > now() - INTERVAL ${range}
GROUP BY alert_signature, alert_category, src_ip, dst_ip
ORDER BY cnt DESC LIMIT 100`),
chQueryRO(`
SELECT alert_signature, alert_category, src_ip, dst_ip, count() AS cnt,
formatDateTime(max(timestamp),'%Y-%m-%d %H:%i:%S') AS last_seen
FROM opnsense.suricata_alerts
WHERE alert_severity > 1 AND timestamp > now() - INTERVAL ${range}
AND positionCaseInsensitive(alert_signature, 'OUTBOUND') > 0
GROUP BY alert_signature, alert_category, src_ip, dst_ip
ORDER BY cnt DESC LIMIT 100`),
chQueryRO(`SELECT count() AS cnt, uniqExact(src_ip) AS srcs FROM opnsense.suricata_alerts WHERE timestamp > now() - INTERVAL ${range}`),
chQueryRO(`SELECT tags['gateway_name'] AS gw, avg(fields['delay']) AS delay, avg(fields['loss']) AS loss, argMax(fields['status'],timestamp) AS status FROM opnsense.telegraf_metrics WHERE measurement='gateways' AND timestamp>now()-INTERVAL 5 MINUTE GROUP BY gw`),
chQueryRO(`SELECT argMax(fields['entries'],timestamp) AS current, argMax(fields['state-limit'],timestamp) AS lim FROM opnsense.telegraf_metrics WHERE measurement='pf' AND timestamp>now()-INTERVAL 5 MINUTE`),
chQueryRO(`
SELECT 'firewall_logs' AS src, toUnixTimestamp(toDateTime(max(timestamp))) AS last FROM opnsense.firewall_logs
UNION ALL SELECT 'netflow', toUnixTimestamp(toDateTime(max(timestamp))) FROM opnsense.netflow
UNION ALL SELECT 'telegraf_metrics', toUnixTimestamp(toDateTime(max(timestamp))) FROM opnsense.telegraf_metrics
UNION ALL SELECT 'dns_queries', toUnixTimestamp(toDateTime(max(timestamp))) FROM opnsense.dns_queries
UNION ALL SELECT 'suricata_alerts', toUnixTimestamp(toDateTime(max(timestamp))) FROM opnsense.suricata_alerts
UNION ALL SELECT 'threat_intel', toUnixTimestamp(toDateTime(max(inserted_at))) FROM opnsense.threat_intel`),
chQueryRO(`SELECT count() AS cnt, uniqExact(src_ip) AS srcs FROM opnsense.firewall_logs WHERE action='block' ${PUB_FILTER} AND timestamp > now() - INTERVAL ${range}`),
chQueryRO(`SELECT count() AS cnt FROM opnsense.firewall_logs WHERE timestamp > now() - INTERVAL ${range}`),
chQueryRO(`SELECT count() AS cnt FROM opnsense.netflow WHERE timestamp > now() - INTERVAL ${range}`),
chQueryRO(`SELECT count() AS total, countIf(is_blocked=1) AS blocked FROM opnsense.dns_queries WHERE timestamp > now() - INTERVAL ${range}`),
chQueryRO(`SELECT source, count() AS ips FROM opnsense.threat_intel GROUP BY source`),
]);
const findings: Finding[] = [];
const checks: CheckStatus[] = [];
const fmtMB = (b: number) => b >= 1048576 ? `${(b / 1048576).toFixed(1)} MB` : `${(b / 1024).toFixed(1)} KB`;
// A failed query must not read as a quiet, healthy check.
const queryErrors = [
["egress-intel", egress], ["beacons", beacons], ["dns", dnsAnoms],
["ids", idsSev1], ["ids", idsEgress], ["ids", idsTotal],
["infra", gateways], ["infra", pf], ["telemetry", freshness],
].filter(([, r]) => (r as { error?: string }).error);
if (queryErrors.length > 0) {
const failedChecks = [...new Set(queryErrors.map(([id]) => id as string))];
findings.push({
severity: "review", check: "telemetry",
title: `Verdict degraded: ${queryErrors.length} check quer${queryErrors.length === 1 ? "y" : "ies"} failed`,
detail: `affected: ${failedChecks.join(", ")} — treat those checks as blind, not clean`,
count: queryErrors.length,
});
log.error("Verdict computed on degraded data: check queries failed", {
failed: failedChecks.join(","),
errors: queryErrors.map(([id, r]) => `${id}: ${(r as { error?: string }).error?.slice(0, 200)}`).join(" | "),
});
}
// 1. Egress vs threat intel — the highest-value signal.
let egSuppressed = 0;
for (const m of (egress.data as Array<Record<string, unknown>>)) {
const conf = Number(m.confidence), port = Number(m.dst_port), cnt = Number(m.cnt);
if (conf >= 5) {
findings.push({
severity: "action", check: "egress-intel",
title: `${m.src_ip} connected out to known C2 ${m.dst_ip}:${port}`,
detail: `${cnt} allowed outbound connection(s) to an IP on the ${m.source} botnet C2 list (confidence ${conf}/5)`,
count: cnt, lastSeen: String(m.last_seen),
});
} else if ((isVpnSource(String(m.src_ip)) || m.src_ip === WAN_SRC_IP) && (port >= 1024 || port === 0)) {
// Low-confidence feed hit on an ephemeral/high port (or port 0 = ICMP/GRE)
// from the VPN path or post-NAT WAN src — the signature of torrent peers
// that also attacked someone's SSH once. Not attributable, not actionable.
egSuppressed++;
} else {
findings.push({
severity: "review", check: "egress-intel",
title: `${m.src_ip} → ${m.dst_ip}:${port} is on the ${m.source} blocklist`,
detail: `${cnt} allowed outbound connection(s) to a listed IP on a well-known service port`,
count: cnt, lastSeen: String(m.last_seen),
});
}
}
const egFound = findings.filter(f => f.check === "egress-intel").length;
checks.push({
id: "egress-intel", label: "Egress intel",
status: egFound ? "findings" : "ok",
detail: egFound ? `${egFound} match(es) need eyes` : `no outbound traffic to high-confidence bad IPs`,
suppressed: egSuppressed,
});
// 2. Beacons — only non-VPN, non-torrent, non-flow-timer, high-score survive.
let bcVpn = 0, bcTimer = 0, bcMedium = 0;
for (const b of (beacons.data as Array<Record<string, unknown>>)) {
const port = Number(b.dst_port), ivl = Number(b.interval_mode), score = Number(b.beacon_score);
if (isVpnSource(String(b.src_ip)) || isTorrentPort(port) || PUSH_KEEPALIVE_PORTS.has(port)) { bcVpn++; continue; }
if (isFlowTimerArtifact(ivl)) { bcTimer++; continue; }
if (score >= 0.85) {
findings.push({
severity: "review", check: "beacons",
title: `${b.src_ip} calls ${b.dst_ip}:${port} every ~${Math.max(1, Math.round(ivl / 60))} min`,
detail: `beacon score ${score.toFixed(2)}, ${b.connection_count} connections, ${fmtMB(Number(b.total_bytes))} total — regular enough to look like automated check-in`,
count: Number(b.connection_count), lastSeen: String(b.last_seen_fmt),
});
} else {
bcMedium++;
}
}
const bcFound = findings.filter(f => f.check === "beacons").length;
checks.push({
id: "beacons", label: "Beacons",
status: bcFound ? "findings" : "ok",
detail: bcFound ? `${bcFound} regular call-out pattern(s)` : bcMedium ? `${bcMedium} medium-score pattern(s), none high` : "no suspicious call-out rhythms",
suppressed: bcVpn + bcTimer,
});
// 3. DNS anomalies — distinct (type, client, domain); benign suffixes suppressed.
let dnsSuppressed = 0;
for (const a of (dnsAnoms.data as Array<Record<string, unknown>>)) {
const type = String(a.anomaly_type);
// Benign-by-design domains, plus rows that don't meet the current detector
// bar (older rows predate the query-count floor; real exfil needs volume).
if (type === "tunneling" && (
isBenignDomain(String(a.domain)) ||
Number(a.query_count) < 10 ||
(Number(a.entropy) <= 4.2 && Number(a.sub_len) <= 45)
)) { dnsSuppressed++; continue; }
const label = type === "tunneling"
? `DNS tunneling pattern: ${a.client_ip} → ${a.domain}`
: type === "dga"
? `DGA-like lookups from ${a.client_ip}`
: `DNS volume spike from ${a.client_ip}`;
findings.push({
severity: "review", check: "dns",
title: label,
detail: type === "tunneling"
? `entropy ${Number(a.entropy).toFixed(1)}, avg subdomain ${Math.round(Number(a.sub_len))} chars, ${a.query_count} queries (${a.occurrences} detection(s))`
: type === "dga"
? `many unique domains with >50% NXDOMAIN (${a.occurrences} detection(s))`
: `${a.query_count} queries in 5 min (${a.occurrences} detection(s))`,
count: Number(a.query_count), lastSeen: String(a.last_seen),
});
}
const dnsFound = findings.filter(f => f.check === "dns").length;
checks.push({
id: "dns", label: "DNS",
status: dnsFound ? "findings" : "ok",
detail: dnsFound ? `${dnsFound} unusual pattern(s)` : "query patterns look normal",
suppressed: dnsSuppressed,
});
// 4. IDS — severity-1 and egress-direction alerts only; inbound scan/DROP-list
// noise is defense activity, not a finding.
for (const s of (idsSev1.data as Array<Record<string, unknown>>)) {
const cat = String(s.alert_category).toLowerCase();
const hot = cat.includes("malware") || cat.includes("trojan") || cat.includes("command");
findings.push({
severity: hot ? "action" : "review", check: "ids",
title: `IDS priority-1: ${s.alert_signature}`,
detail: `${s.cnt}× ${s.src_ip} → ${s.dst_ip} (${s.alert_category})`,
count: Number(s.cnt), lastSeen: String(s.last_seen),
});
}
let idsEgressSuppressed = 0;
for (const s of (idsEgress.data as Array<Record<string, unknown>>)) {
const sig = String(s.alert_signature);
if (BENIGN_EGRESS_IDS.some(b => sig.includes(b.sig) && inCidr(String(s.dst_ip), b.cidr))) {
idsEgressSuppressed++;
continue;
}
findings.push({
severity: "review", check: "ids",
title: `Outbound IDS alert: ${s.alert_signature}`,
detail: `${s.cnt}× ${s.src_ip} → ${s.dst_ip} — traffic leaving the network tripped a signature`,
count: Number(s.cnt), lastSeen: String(s.last_seen),
});
}
const idsFound = findings.filter(f => f.check === "ids").length;
const idsNoise = Number((idsTotal.data?.[0] as Record<string, unknown>)?.cnt ?? 0);
checks.push({
id: "ids", label: "IDS",
status: idsFound ? "findings" : "ok",
detail: idsFound
? `${idsFound} alert group(s) beyond perimeter noise`
: idsEgressSuppressed
? `only perimeter noise + ${idsEgressSuppressed} known-benign egress pattern(s)`
: "only inbound scan/blocklist noise",
suppressed: Math.max(0, idsNoise - findings.filter(f => f.check === "ids").reduce((s, f) => s + f.count, 0)),
});
// 5. CrowdSec — local detections (our logs tripped a scenario) are findings;
// the community blocklist size is defense strength.
const cs = await getCrowdsecSplit();
for (const d of cs.localDecisions.slice(0, 20)) {
findings.push({
severity: "review", check: "crowdsec",
title: `CrowdSec local detection: ${d.value} (${d.scenario})`,
detail: `${d.type} for ${d.duration}, origin ${d.origin} — our own logs triggered this, not the community feed`,
count: 1,
});
}
checks.push({
id: "crowdsec", label: "CrowdSec",
status: cs.local > 0 ? "findings" : "ok",
detail: cs.local > 0 ? `${cs.local} local decision(s)` : `no local detections; ${cs.community.toLocaleString()} community IPs pre-banned`,
suppressed: 0,
});
// 6. Infrastructure health.
const pfRow = pf.data?.[0] as Record<string, unknown> | undefined;
const pfCur = Number(pfRow?.current ?? 0), pfLim = Number(pfRow?.lim ?? 0);
for (const g of (gateways.data as Array<Record<string, unknown>>)) {
const loss = Number(g.loss), delay = Number(g.delay), status = Number(g.status);
if (status !== 1 || loss > 2 || delay > 100) {
findings.push({
severity: status !== 1 ? "action" : "review", check: "infra",
title: status !== 1 ? `Gateway ${g.gw} is offline` : `Gateway ${g.gw} degraded`,
detail: `delay ${delay.toFixed(1)} ms, loss ${loss.toFixed(1)}%`,
count: 1,
});
}
}
if (pfLim > 0 && pfCur / pfLim > 0.8) {
findings.push({
severity: "review", check: "infra",
title: "pf state table above 80%",
detail: `${pfCur.toLocaleString()} of ${pfLim.toLocaleString()} states in use`,
count: pfCur,
});
}
const infraFound = findings.filter(f => f.check === "infra").length;
checks.push({
id: "infra", label: "Infra",
status: infraFound ? "findings" : "ok",
detail: infraFound ? `${infraFound} issue(s)` : "gateways healthy, state table normal",
suppressed: 0,
});
// 7. Telemetry freshness — a quiet detector must not read as a safe network.
const nowSec = Math.floor(Date.now() / 1000);
const staleLimits: Record<string, number> = {
firewall_logs: 900, netflow: 900, telegraf_metrics: 900, dns_queries: 900,
suricata_alerts: 28 * 3600, threat_intel: 26 * 3600,
};
const staleSources: string[] = [];
for (const f of (freshness.data as Array<{ src: string; last: number }>)) {
const age = nowSec - Number(f.last);
if (age > (staleLimits[f.src] ?? 900)) {
staleSources.push(`${f.src} (${Math.round(age / 3600)}h old)`);
}
}
if (staleSources.length > 0) {
findings.push({
severity: "review", check: "telemetry",
title: `Monitoring blind spot: ${staleSources.length} source(s) stale`,
detail: staleSources.join(", ") + " — the verdict can't see what isn't flowing",
count: staleSources.length,
});
}
checks.push({
id: "telemetry", label: "Telemetry",
status: staleSources.length ? "stale" : "ok",
detail: staleSources.length ? staleSources.join(", ") : "all six sources current",
suppressed: 0,
});
findings.sort((a, b) => (a.severity === b.severity ? b.count - a.count : a.severity === "action" ? -1 : 1));
const status = findings.some(f => f.severity === "action") ? "action"
: findings.length > 0 ? "review" : "clear";
const headline = status === "action"
? "Possible compromise indicator — act on the findings below."
: status === "review"
? `${findings.length} item${findings.length === 1 ? "" : "s"} worth a look. No confirmed compromise signals.`
: "No signs of compromise. Perimeter noise is normal and being blocked.";
const blockedRow = blocked.data?.[0] as Record<string, unknown> | undefined;
const dnsRow = dnsCounts.data?.[0] as Record<string, unknown> | undefined;
const eventsAnalyzed =
Number((fwTotal.data?.[0] as Record<string, unknown>)?.cnt ?? 0) +
Number((nfTotal.data?.[0] as Record<string, unknown>)?.cnt ?? 0) +
Number(dnsRow?.total ?? 0) + idsNoise;
return {
status, headline, findings, checks,
defense: {
blockedProbes: Number(blockedRow?.cnt ?? 0),
uniqueScanSources: Number(blockedRow?.srcs ?? 0),
idsAlerts: idsNoise,
idsSources: Number((idsTotal.data?.[0] as Record<string, unknown>)?.srcs ?? 0),
crowdsecCommunity: cs.community,
crowdsecLocal: cs.local,
dnsQueries: Number(dnsRow?.total ?? 0),
dnsBlocked: Number(dnsRow?.blocked ?? 0),
intelFeeds: feeds.data,
},
eventsAnalyzed,
range,
generatedAt: new Date().toISOString(),
};
}
// ─── HTTP server ───
Bun.serve({
port: PORT,
hostname: "0.0.0.0",
idleTimeout: 30,
routes: {
// Named-query batch — the ONLY ClickHouse read path for the browser.
// Replaces the raw-SQL /api/query[/batch] routes this service once had:
// the client names a registered query + range key; the server owns the SQL.
"/api/data/batch": {
async POST(req: Request) {
try {
const { queries } = (await req.json()) as { queries: Array<{ name: string; range?: string }> };
if (!Array.isArray(queries) || queries.length === 0 || queries.length > 50) {
logThrottled("batch-bad-request", 60_000, "warn", "Rejected /api/data/batch request", {
route: "/api/data/batch", reason: "queries must be a non-empty array (max 50)",
count: Array.isArray(queries) ? queries.length : "not-array",
});
return Response.json({ error: "queries must be a non-empty array (max 50)" }, { status: 400, headers: corsHeaders(req.headers.get("origin")) });
}
const results: Record<string, { data: Record<string, unknown>[]; error?: string }> = {};
await Promise.all(queries.map(async ({ name, range }) => {
const build = PAGE_QUERIES[name];
const rangeCfg = OPN_RANGES[range || "1h"];
if (!build || !rangeCfg) {
results[name] = { data: [], error: !build ? `unknown query: ${name}` : `unknown range: ${range}` };
return;
}
results[name] = await chQueryRO(build(rangeCfg));
}));
return Response.json({ results }, { headers: corsHeaders(req.headers.get("origin")) });
} catch (e: unknown) {
return respond500("/api/data/batch", e, req);
}
},
},
"/api/geo/enrich": {
POST: handleGeoEnrich,
},
"/api/ids/alerts": {
async GET(req: Request) {
try {
const data = await opnPost("/ids/service/query_alerts", { current: 1, rowCount: 50 });
return Response.json(data, { headers: corsHeaders(req.headers.get("origin")) });
} catch (e: unknown) {
return respond500("/api/ids/alerts", e, req);
}
},
},
"/api/dns/totals": {
async GET(req: Request) {
try {
return Response.json(await opnGet("/unbound/overview/totals/60"), { headers: corsHeaders(req.headers.get("origin")) });
} catch (e: unknown) {
return respond500("/api/dns/totals", e, req);
}
},
},
"/api/dns/rolling": {
async GET(req: Request) {
try {
return Response.json(await opnGet("/unbound/overview/_rolling/10"), { headers: corsHeaders(req.headers.get("origin")) });
} catch (e: unknown) {
return respond500("/api/dns/rolling", e, req);
}
},
},
"/api/dns/overrides": {
async GET(req: Request) {
try {
const data = await opnPost("/unbound/settings/searchHostOverride", {});
return Response.json(data, { headers: corsHeaders(req.headers.get("origin")) });
} catch (e: unknown) {
log.warn("OPNsense host-override lookup failed, returning empty rows", {
route: "/api/dns/overrides", err: String((e as Error)?.message ?? e),
});
return Response.json({ rows: [] }, { status: 500, headers: corsHeaders(req.headers.get("origin")) });
}
},
},
"/api/crowdsec/stats": {
async GET(req: Request) {
try {
const cs = await getCrowdsecSplit();
return Response.json({
decisions: cs.sample,
totalCount: cs.total,
communityCount: cs.community,
localCount: cs.local,
localDecisions: cs.localDecisions,
}, { headers: corsHeaders(req.headers.get("origin")) });
} catch (e: unknown) {
log.warn("CrowdSec stats request failed, returning empty payload", {
route: "/api/crowdsec/stats", err: String((e as Error)?.message ?? e),
});
return Response.json({ decisions: [], totalCount: 0, communityCount: 0, localCount: 0, localDecisions: [] }, { headers: corsHeaders(req.headers.get("origin")) });
}
},
},
"/api/suricata/alerts": {
async GET(req: Request) {
try {
const url = new URL(req.url);
const range = parseRange(url.searchParams.get("range"), "24 HOUR");
const [alerts, bySeverity, topSigs, total] = await Promise.all([
chQueryRO(`
SELECT formatDateTime(timestamp,'%Y-%m-%d %H:%i:%S') AS ts,
src_ip, dst_ip, src_port, dst_port, protocol,
alert_action, alert_signature, alert_category,
alert_severity, alert_sid
FROM opnsense.suricata_alerts
WHERE timestamp > now() - INTERVAL ${range}
ORDER BY timestamp DESC LIMIT 100
`),
chQueryRO(`
SELECT alert_severity, count() AS cnt
FROM opnsense.suricata_alerts
WHERE timestamp > now() - INTERVAL ${range}
GROUP BY alert_severity ORDER BY alert_severity
`),
chQueryRO(`
SELECT alert_signature, alert_category, alert_severity,
count() AS cnt
FROM opnsense.suricata_alerts
WHERE timestamp > now() - INTERVAL ${range}
GROUP BY alert_signature, alert_category, alert_severity
ORDER BY cnt DESC LIMIT 10
`),
chQueryRO(`
SELECT count() AS total
FROM opnsense.suricata_alerts
WHERE timestamp > now() - INTERVAL ${range}
`),
]);
return Response.json({
alerts: alerts.data,
by_severity: bySeverity.data,
top_signatures: topSigs.data,
total: Number(total.data[0]?.total ?? 0),
}, { headers: corsHeaders(req.headers.get("origin")) });
} catch (e: unknown) {
return respond500("/api/suricata/alerts", e, req);
}
},
},
"/api/suricata/report": {
async GET(req: Request) {
try {
const url = new URL(req.url);
const range = parseRange(url.searchParams.get("range"), "24 HOUR");
const result = await chQueryRO(`
SELECT formatDateTime(timestamp,'%Y-%m-%d %H:%i:%S') AS ts,
src_ip, dst_ip, src_port, dst_port, protocol,
alert_action, alert_signature, alert_category,
alert_severity, alert_sid
FROM opnsense.suricata_alerts
WHERE timestamp > now() - INTERVAL ${range}
ORDER BY timestamp DESC
`);