-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig-editor.js
More file actions
3041 lines (2773 loc) · 131 KB
/
Copy pathconfig-editor.js
File metadata and controls
3041 lines (2773 loc) · 131 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
/**
* BBSFirewall - Web-based configuration editor
*
* An HTTPS admin UI, on its own port and its own TLS certificate, for editing
* the .env file and the whitelist / blocklist / trustedhosts list files without
* shelling into the box. Two independent gates protect it:
*
* 1. Trusted-host allowlist - TRUSTEDHOSTS.TXT (IPv4/IPv6 CIDR). An address
* that is not listed never gets past the socket handler. An empty or
* missing list denies everyone.
* 2. Login session - username/password from .env, checked with a
* constant-time compare, exchanged for a random session cookie
* (HttpOnly, Secure, SameSite=Strict) with idle and absolute timeouts.
*
* Mutating requests additionally require a per-session CSRF token header.
*
* A missing or unreadable certificate logs an error and skips the editor; the
* telnet proxy and everything else keep running.
*
* The request router keeps every /api/* route in one place so a future
* key-authenticated management API can be added alongside the browser routes.
*
* https://github.com/SysopNetwork/BBSFirewall
*/
const https = require('https');
const net = require('net');
const fs = require('fs');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const { promisify } = require('util');
const { execFile, execFileSync } = require('child_process');
const execFileAsync = promisify(execFile);
const logger = require('./logger');
const { config } = require('./config');
const trustedhosts = require('./trustedhosts');
const views = require('./config-editor-ui');
const metrics = require('./metrics');
const security = require('./security');
const updater = require('./updater');
const webRedirect = require('./web-redirect');
const log = logger.getLogger('config-editor');
const ABSOLUTE_SESSION_MS = 12 * 60 * 60 * 1000; // hard cap regardless of activity
const LOGIN_MAX_FAILS = 5;
const LOGIN_LOCK_MS = 15 * 60 * 1000;
const MFA_MAX_FAILS = 5;
const MFA_LOCK_MS = 15 * 60 * 1000;
const MAX_BODY_BYTES = 512 * 1024;
const ENV_BACKUPS_KEPT = 15;
const ENV_BACKUP_DIRNAME = 'ENVBACKUPS';
const ACTION_TIMEOUT_MS = 240 * 1000; // long-running shell actions (certbot, geoip)
const SESSION_STORE = path.join(__dirname, '.config-editor-sessions.json');
// __Host- prefix: the browser only accepts this cookie when it is Secure, has
// Path=/ and carries no Domain attribute — which is exactly how it is set.
const COOKIE_NAME = '__Host-bbsfw_admin';
const TOKEN_RE = /^[0-9a-f]{64}$/;
const SECRET_FILE_MODE = 0o600;
// Site branding assets. A fixed, small map (not a general static-file route)
// so there is no path-traversal surface — pathname is looked up, never joined
// onto a filesystem path.
const STATIC_ASSETS = {
'/favicon.ico': { file: path.join(__dirname, 'assets', 'favicon.ico'), type: 'image/x-icon' },
'/assets/logo.svg': { file: path.join(__dirname, 'assets', 'logo-dark.svg'), type: 'image/svg+xml' },
'/assets/logo-light.svg': { file: path.join(__dirname, 'assets', 'logo-light.svg'), type: 'image/svg+xml' },
};
let server = null; // the https.Server (services connections handed to it by muxServer)
let muxServer = null; // the net.Server that actually listens on CONFIG_EDITOR_PORT
let sweepTimer = null;
let lastCpuSample = null; // for CPU-% deltas
let lastNetSample = null; // for network throughput deltas
let proxyHeaderWarned = false;
let firewallInstance = null; // set by startConfigEditorServer(firewall) — see /status handler
const sessions = new Map(); // token -> { username, ip, created, lastSeen, csrf, mfaVerified }
const loginFails = new Map(); // ip -> { count, until } — browser login
const apiFails = new Map(); // ip -> { count, until } — management API key (kept separate
// so a dashboard flooding a bad key can't lock a human admin
// out of the web UI from the same source IP)
const mfaFails = new Map(); // ip -> { count, until } — MFA code/backup-code attempts,
// kept separate so guessing MFA codes can't also burn through
// the (looser) password-lockout budget for the same IP
const busy = new Set(); // in-flight mutating operations (one at a time)
// ---------------------------------------------------------------------------
// .env field schema — drives the settings form. Keys not listed here are still
// preserved on save (the writer works off the raw file), they just do not get
// a dedicated widget.
// ---------------------------------------------------------------------------
const ENV_SCHEMA = [
{ name: 'Network', icon: 'network',
help: 'Where the firewall listens for callers and which BBS it forwards them to.',
fields: [
{ key: 'LISTEN_PORT', type: 'port', label: 'Telnet listen port', def: '23', required: true,
help: 'TCP port callers connect to. 23 is standard telnet; ports below 1024 need the process to run as root.' },
{ key: 'BACKEND_HOST', type: 'string', label: 'Backend host', def: '127.0.0.1', required: true,
help: 'Hostname or IP of the BBS the firewall forwards accepted connections to.' },
{ key: 'BACKEND_PORT', type: 'port', label: 'Backend port', def: '23', required: true,
help: 'Port the BBS listens on (usually 23 for telnet).' },
{ key: 'ENCODING_DETECTION', type: 'bool', label: 'Encoding-based backend routing', def: 'false',
help: 'Send UTF-8 and CP437 callers to different backend ports.',
helpLong: 'When on, the firewall guesses the caller’s character encoding and routes CP437 (DOS/ANSI) clients to BACKEND_PORT_CP437 and UTF-8 clients to BACKEND_PORT_UTF8, instead of the single BACKEND_PORT. Only reliable for SSH callers (telnet gives nothing to sniff, so telnet always uses the CP437 port).' },
{ key: 'BACKEND_PORT_CP437', type: 'port', label: 'CP437 backend port', def: '2323',
help: 'Backend port for CP437/DOS clients when encoding routing is on.' },
{ key: 'BACKEND_PORT_UTF8', type: 'port', label: 'UTF-8 backend port', def: '2423',
help: 'Backend port for UTF-8/Unicode clients when encoding routing is on.' },
]},
{ name: 'Connection Limits', icon: 'limit',
help: 'Caps on how many connections the firewall will carry at once.',
fields: [
{ key: 'MAX_CONNECTIONS', type: 'int', label: 'Max total connections', def: '100', required: true,
help: 'Hard ceiling on simultaneous connections across all callers. New connections past this are dropped immediately.' },
{ key: 'MAX_CONNECTIONS_PER_IP', type: 'int', label: 'Max connections per IP (0 = unlimited)', def: '3', required: true,
help: 'How many simultaneous connections one IP may hold. 0 disables the per-IP cap. Whitelisted IPs are exempt.' },
{ key: 'CONNECTION_TIMEOUT', type: 'int', label: 'Idle timeout (ms, 0 = off)', def: '300000', required: true,
help: 'Drop a connection after this many milliseconds with no traffic. 300000 = 5 minutes. 0 disables it.' },
]},
{ name: 'Country Blocking', icon: 'globe',
help: 'Refuse callers by country using a local MaxMind GeoLite2 database. Needs the database downloaded (see the Tools tab) and a MaxMind license key.',
fields: [
{ key: 'MAXMIND_LICENSE_KEY', type: 'secret', label: 'MaxMind license key', def: '',
help: 'Free key from maxmind.com. Once set (and saved), use the Tools tab to download or update the GeoIP database.' },
{ key: 'BLOCKED_COUNTRIES', type: 'csv', label: 'Blocked country codes', def: '',
help: 'Comma-separated ISO 3166-1 alpha-2 codes, e.g. CN,RU,KP,IR. Callers geolocated to one of these are refused.' },
{ key: 'BLOCK_UNKNOWN_COUNTRIES', type: 'bool', label: 'Block when country is unknown', def: 'false',
help: 'Also refuse callers whose IP cannot be geolocated. Off by default so unusual-but-legitimate IPs still get through.' },
]},
{ name: 'IP Lists', icon: 'list',
help: 'Files listing IPs/CIDRs. Edit their contents in the Whitelist / Blocklist sections below.',
fields: [
{ key: 'WHITELIST_PATH', type: 'string', label: 'Whitelist file path', def: './whitelist.txt',
help: 'IPs in this file bypass every firewall rule — rate limit, per-IP cap, country block, and the blocklist.' },
{ key: 'BLOCKLIST_PATH', type: 'string', label: 'Blocklist file path', def: './blocklist.txt',
help: 'IPs in this file are refused outright, permanently, unless also whitelisted.' },
]},
{ name: 'Rate Limiting', icon: 'gauge',
help: 'Flood protection: temporarily block an IP that reconnects too fast.',
fields: [
{ key: 'RATE_LIMIT_ENABLED', type: 'bool', label: 'Enable rate limiting', def: 'true', required: true,
help: 'Master switch for the sliding-window flood protection below.' },
{ key: 'MAX_CONNECTIONS_PER_WINDOW', type: 'int', label: 'Max attempts per window', def: '10', required: true,
help: 'Connection attempts one IP may make within the window before it is temporarily blocked.' },
{ key: 'RATE_LIMIT_WINDOW_MS', type: 'int', label: 'Window length (ms)', def: '60000', required: true,
help: 'Length of the sliding window, in milliseconds. 60000 = 1 minute. Minimum 1000.' },
{ key: 'RATE_LIMIT_BLOCK_DURATION_MS', type: 'int', label: 'Block duration (ms)', def: '300000', required: true,
help: 'How long an IP stays blocked after tripping the limit. 300000 = 5 minutes.' },
]},
{ name: 'Auto-Block Triggers', icon: 'alert',
help: 'Scan the first bytes a caller sends for known bot / scanner / exploit strings and blacklist the source IP on a match. Edit the pattern list in the Triggers section below. Whitelisted IPs are never auto-blocked.',
fields: [
{ key: 'TRIGGER_BLOCK_ENABLED', type: 'bool', label: 'Enable auto-block on trigger match', def: 'false',
help: 'Off by default. A real caller who sends one of these strings in the first few bytes would be blocked too — keep the list tight.' },
{ key: 'TRIGGER_LIST_PATH', type: 'string', label: 'Trigger list file', def: './triggers.txt',
help: 'One pattern per line. Plain text = case-insensitive substring; /regex/flags = JS regex; \\xNN \\r \\n \\t \\0 escapes work in plain patterns (for binary probes).' },
{ key: 'TRIGGER_SCAN_BYTES', type: 'int', label: 'Bytes scanned per connection', def: '1024',
help: 'Only the first N bytes the caller sends are checked (16-65536). Scanners send their probe immediately; a real session sails past this and is never scanned again.' },
{ key: 'TRIGGER_BLOCK_MODE', type: 'enum', label: 'Block mode', def: 'blocklist', options: ['blocklist', 'temp'],
help: 'blocklist = append the IP to blocklist.txt permanently (also blocked in memory right away). temp = in-memory block only, for the duration below.' },
{ key: 'TRIGGER_BLOCK_DURATION_MS', type: 'int', label: 'Temp block duration (ms)', def: '86400000',
help: 'Used when mode is temp. 86400000 = 24 hours.' },
]},
{ name: 'PROXY Protocol', icon: 'exchange',
help: 'Optional way to tell the backend the real caller IP.',
fields: [
{ key: 'PROXY_PROTOCOL_ENABLED', type: 'bool', label: 'Send PROXY Protocol v1 to telnet backend', def: 'false',
help: 'Prepend a PROXY v1 header so the BBS sees the caller’s IP instead of the firewall’s.',
helpLong: 'Only enable this if the backend BBS (or a companion module) understands PROXY Protocol v1. Sent to a backend that does not, the header is read as session garbage and every connection breaks.' },
]},
{ name: 'Web Redirect', icon: 'redirect',
help: 'Optional tiny web server so browsers that hit the firewall’s IP get bounced to your real site. Use the Tools tab to issue a Let’s Encrypt certificate for port 443.',
fields: [
{ key: 'WEB_REDIRECT_ENABLED', type: 'bool', label: 'Enable HTTP (port 80) redirect', def: 'false',
help: 'Serve a 301 redirect on port 80. Also serves Let’s Encrypt ACME challenges for cert issuance.' },
{ key: 'WEB_REDIRECT_URL', type: 'string', label: 'Redirect destination URL', def: '',
help: 'Where to send visitors, e.g. https://www.yourbbs.com. Used by both the HTTP and HTTPS redirect.' },
{ key: 'HTTPS_REDIRECT_ENABLED', type: 'bool', label: 'Enable HTTPS (port 443) redirect', def: 'false',
help: 'Also redirect on port 443. Requires the certificate paths below.' },
{ key: 'HTTPS_REDIRECT_PORT', type: 'port', label: 'HTTPS redirect port', def: '443',
help: 'Port for the HTTPS redirect listener.' },
{ key: 'HTTPS_CERT_PATH', type: 'string', label: 'HTTPS redirect cert path', def: './certs/fullchain.pem',
help: 'Path to the fullchain PEM for the port-443 redirect. setup-certs.sh / the Tools tab write this.' },
{ key: 'HTTPS_KEY_PATH', type: 'string', label: 'HTTPS redirect key path', def: './certs/privkey.pem',
help: 'Path to the private key PEM for the port-443 redirect.' },
{ key: 'HTTPS_CERT_DOMAIN', type: 'string', label: 'Redirect cert domain', def: '',
help: 'Public hostname (DNS must point here) the Tools tab issues the port-443 Let’s Encrypt certificate for.' },
{ key: 'HTTPS_CERT_EMAIL', type: 'string', label: 'Redirect cert contact email', def: '',
help: 'Optional. Certbot sends expiry warnings here.' },
]},
{ name: 'Config Editor', icon: 'lock',
help: 'This admin UI. Changing the port or certificate takes effect after a restart. The admin ' +
'username/password and MFA are no longer set here — run "node setup-admin.js" once to create the ' +
'account, then use Security Settings (top-right of the header) to change the password or enable MFA.',
fields: [
{ key: 'CONFIG_EDITOR_ENABLED', type: 'bool', label: 'Enable this editor', def: 'false', required: true,
help: 'Turn the editor on. Disabling it here means you cannot get back in without SSH.' },
{ key: 'CONFIG_EDITOR_PORT', type: 'port', label: 'Editor listen port', def: '8443', required: true,
help: 'HTTPS port for this UI. Must differ from LISTEN_PORT and the SSH port.' },
{ key: 'CONFIG_EDITOR_BIND', type: 'string', label: 'Bind address', def: '0.0.0.0',
help: '0.0.0.0 listens on every interface; set a specific IP to limit it, or 127.0.0.1 to require an SSH tunnel.' },
{ key: 'CONFIG_EDITOR_CERT_PATH', type: 'string', label: 'Editor cert path', def: './certs/config-editor/fullchain.pem',
help: 'Fullchain PEM for this UI’s HTTPS. Written by setup-config-cert.sh / the Tools tab.' },
{ key: 'CONFIG_EDITOR_KEY_PATH', type: 'string', label: 'Editor key path', def: './certs/config-editor/privkey.pem',
help: 'Private key PEM for this UI’s HTTPS.' },
{ key: 'CONFIG_EDITOR_CERT_DOMAIN', type: 'string', label: 'Editor cert domain', def: '',
help: 'Public hostname the Tools tab issues this UI’s Let’s Encrypt certificate for.' },
{ key: 'CONFIG_EDITOR_CERT_EMAIL', type: 'string', label: 'Editor cert contact email', def: '',
help: 'Optional certbot contact email for the editor certificate.' },
{ key: 'CONFIG_EDITOR_TRUSTEDHOSTS_PATH', type: 'string', label: 'Trusted hosts file path', def: './trustedhosts.txt',
help: 'File of IPs/CIDRs allowed to reach this UI at all. Edit its contents in the Trusted Hosts section below. Empty = nobody.' },
{ key: 'CONFIG_EDITOR_SESSION_TIMEOUT_MS', type: 'int', label: 'Session idle timeout (ms)', def: '1800000',
help: 'Log an idle admin out after this long. 1800000 = 30 minutes. Minimum 60000.' },
{ key: 'CONFIG_EDITOR_HTTP_REDIRECT_ENABLED', type: 'bool', label: 'Redirect plain HTTP to HTTPS', def: 'true',
help: 'On by default. When a browser hits this editor’s port with plain http:// (no TLS), answer with a 301 to the https:// URL instead of failing the handshake (ERR_EMPTY_RESPONSE). Same port — no extra listener. Set false to just drop such requests.' },
{ key: 'REBOOT_ENABLED', type: 'bool', label: 'Allow full server reboot', def: 'false',
help: 'Off by default. Adds a "Reboot server" button to the Tools tab for Global Admin accounts — a full OS reboot, not just an app restart.',
helpLong: 'Meaningfully higher risk than the always-available "Restart firewall" button: that one restarts the BBSFirewall process (always SSH-recoverable in seconds); this one reboots the whole host, which is unreachable for several minutes and, if the box does not actually come back on its own, can need your hosting provider\'s own console to recover. Turning this on does not remove the other safety rails — it is only reachable by a Global Admin account, requires typing "REBOOT" to confirm, and is still refused at request time unless BBSFirewall can confirm pm2 has a working boot-time service on this host. Leave this off unless you specifically want that recovery option available.' },
]},
{ name: 'Management API', icon: 'key',
help: 'Key-authenticated REST access to everything on this page (config, list files, restart, tools, stats) for a remote dashboard. Rides on this editor’s HTTPS port under /api/*, so the editor must be enabled. Authenticated by the bearer key below; optionally restricted by source IP in the API Trusted Hosts section below. This is a separate lane — an API caller does NOT need to be in trustedhosts.txt.',
fields: [
{ key: 'API_ENABLED', type: 'bool', label: 'Enable the management API', def: 'false',
help: 'Needs this config editor enabled — the API has no listener of its own.' },
{ key: 'API_KEY', type: 'secret', label: 'API bearer key', def: '',
help: 'Sent by clients as "Authorization: Bearer <key>" or "X-API-Key: <key>". Minimum 24 characters. Restart to apply a change.' },
{ key: 'API_TRUSTEDHOSTS_PATH', type: 'string', label: 'API IP allowlist file', def: './api-trustedhosts.txt',
help: 'IPs/CIDRs allowed to call the API. Edit its contents in the API Trusted Hosts section below. Empty or missing = any IP may call (the key still applies).' },
]},
{ name: 'Logging', icon: 'file',
help: 'Console verbosity and per-proxy log files (on by default).',
fields: [
{ key: 'LOG_LEVEL', type: 'enum', label: 'Console log level', def: 'info', options: ['debug', 'info', 'warn', 'error'],
help: 'How much the process prints to its stdout/pm2 log. debug is very noisy.' },
{ key: 'LOG_FILE_ENABLED', type: 'bool', label: 'Enable per-proxy file logging', def: 'true',
help: 'Write a daily-rotated log file per proxy service under the log directory. On by default; old files are pruned automatically (see Retention below).' },
{ key: 'LOG_DIR', type: 'string', label: 'Log directory', def: './logs',
help: 'Base directory for the per-proxy log folders.' },
{ key: 'LOG_FILE_LEVEL', type: 'enum', label: 'Default file log level', def: 'connections',
options: ['off', 'blocked', 'connections', 'info', 'debug'],
help: 'Event detail written to the files. Each level includes the ones before it: blocked → connections → info → debug.' },
{ key: 'LOG_RETENTION_DAYS', type: 'int', label: 'Log retention (days)', def: '30',
help: 'Delete rotated log files older than this many days. 1-3650 (10 years). Checked once a day, so a lowered value can take up to 24h to take effect.' },
]},
{ name: 'SSH', icon: 'terminal',
help: 'Optional SSH front door on its own port. Pick a mode below — the two modes do very different things.',
fields: [
{ key: 'SSH_MODE', type: 'enum', label: 'SSH mode', def: 'off', options: ['off', 'terminate', 'passthrough'],
help: 'off = no SSH listener. terminate = the firewall IS the SSH server. passthrough = the firewall is a plain pipe to a backend that runs its own SSH.',
helpLong: 'TERMINATE — the firewall speaks SSH itself, accepts any username/password, decrypts the session, and opens a plain telnet connection to BACKEND_HOST:BACKEND_PORT. Use this when the BBS only does telnet. Needs an SSH host key (generate one on the Tools tab) and a cipher list for old terminal clients. Encoding detection works here. Trade-offs: no public-key / passwordless login, no SFTP, and Zmodem/Ymodem file transfers are unreliable over the bridge — the firewall→backend hop is plain telnet.\n\nPASSTHROUGH — the firewall does NOT decrypt anything. It runs the same IP-layer checks as the telnet proxy (whitelist, blocklist, rate limit, country block, per-IP cap) and forwards the still-encrypted stream to a backend that runs its own SSH daemon (SSH_BACKEND_HOST:SSH_BACKEND_PORT). Preserves public-key login, SFTP, and reliable file transfers because the client is really talking to the backend’s sshd. No host key or cipher settings needed here; encoding detection is off (nothing to sniff).\n\nRule of thumb: backend is telnet-only → terminate. Backend already has sshd → passthrough.' },
{ key: 'SSH_LISTEN_PORT', type: 'port', label: 'SSH listen port', def: '2222',
help: 'Port the SSH front door listens on (both modes use this).' },
{ key: 'SSH_HOST_KEY', type: 'string', label: 'SSH host key path', def: './ssh_host_key',
help: 'terminate mode only. Path to the firewall’s SSH private host key. Generate one on the Tools tab if you do not have it.' },
{ key: 'SSH_BACKEND_HOST', type: 'string', label: 'SSH backend host', def: '',
help: 'passthrough mode only. The backend that runs its own SSH server. Defaults to BACKEND_HOST if left unset.' },
{ key: 'SSH_BACKEND_PORT', type: 'port', label: 'SSH backend port', def: '22',
help: 'passthrough mode only. Port of the backend SSH daemon.' },
{ key: 'SSH_PROXY_PROTOCOL', type: 'bool', label: 'Send PROXY Protocol v1 to SSH backend', def: 'false',
help: 'passthrough mode only. Prepend a PROXY v1 header for the backend sshd. Only enable if that sshd understands it — a plain SSH server drops the handshake otherwise.' },
]},
];
const SCHEMA_KEYS = new Set(ENV_SCHEMA.flatMap((s) => s.fields.map((f) => f.key)));
// key -> field def, for doSave's "blank means keep the current secret" handling
// and buildConfigPayload's redaction below.
const SCHEMA_FIELDS = new Map(ENV_SCHEMA.flatMap((s) => s.fields.map((f) => [f.key, f])));
// ---------------------------------------------------------------------------
// .env parsing / writing
// ---------------------------------------------------------------------------
const ENV_LINE_RE = /^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
function stripEnvValue(raw) {
let v = raw.trim();
if (v.length >= 2 &&
((v[0] === '"' && v[v.length - 1] === '"') || (v[0] === "'" && v[v.length - 1] === "'"))) {
const quote = v[0];
v = v.slice(1, -1);
if (quote === '"') {
v = v.replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
return v;
}
// unquoted: cut an inline comment introduced by whitespace + '#'
const m = v.match(/\s#/);
if (m) v = v.slice(0, m.index).trim();
return v;
}
function serializeEnvValue(v) {
if (/[\r\n]/.test(v)) throw new Error('value must not contain a newline');
if (v === '') return '';
if (/^\s|\s$|[#"'`\\$]/.test(v)) {
return '"' + v.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
}
return v;
}
// Parse .env text into { active: {K:v}, commented: {K:v} }.
function parseEnvText(text) {
const active = {};
const commented = {};
for (const line of text.split(/\r?\n/)) {
const m = line.match(ENV_LINE_RE);
if (!m) continue;
const key = m[3];
const val = stripEnvValue(m[4]);
if (m[2]) {
if (!(key in commented) && !(key in active)) commented[key] = val;
} else {
active[key] = val;
}
}
return { active, commented };
}
// Apply { KEY: { value, enabled } } to raw .env text, preserving comments and
// layout. enabled=false comments the line out; new keys are appended.
function applyEnvUpdates(originalText, updates) {
const eol = originalText.includes('\r\n') ? '\r\n' : '\n';
const lines = originalText.split(/\r?\n/);
const handled = new Set();
for (let i = 0; i < lines.length; i++) {
const m = lines[i].match(ENV_LINE_RE);
if (!m) continue;
const key = m[3];
if (!(key in updates)) continue;
const indent = m[1];
const u = updates[key];
if (handled.has(key)) {
// A later duplicate definition — neutralise it so there is no ambiguity.
if (!m[2]) lines[i] = `${indent}# ${key}=${m[4].trim()}`;
continue;
}
handled.add(key);
if (u.enabled === false) {
const keep = (u.value !== undefined && u.value !== '') ? serializeEnvValue(u.value) : m[4].trim();
lines[i] = `${indent}# ${key}=${keep}`;
} else {
lines[i] = `${indent}${key}=${serializeEnvValue(u.value == null ? '' : String(u.value))}`;
}
}
const appended = [];
for (const [key, u] of Object.entries(updates)) {
if (handled.has(key)) continue;
if (u.enabled === false) continue;
if (u.value == null || u.value === '') continue;
appended.push(`${key}=${serializeEnvValue(String(u.value))}`);
}
if (appended.length) {
if (lines.length && lines[lines.length - 1].trim() !== '') lines.push('');
lines.push('# ---------------------------------------------------------------------------');
lines.push('# Added by the BBSFirewall config editor');
lines.push('# ---------------------------------------------------------------------------');
lines.push(...appended);
}
return lines.join(eol);
}
// ---------------------------------------------------------------------------
// Small inline validation (fast feedback). The authoritative check is a child
// `node -e "require('./config').validateConfig()"` against the written file.
// ---------------------------------------------------------------------------
function inlineValidate(map) {
const errors = [];
const asInt = (k) => (map[k] && map[k].enabled !== false ? Number(map[k].value) : undefined);
const port = (k, label) => {
const v = asInt(k);
if (v === undefined || map[k].value === '') return;
if (!Number.isInteger(v) || v < 1 || v > 65535) errors.push(`${label} must be an integer 1-65535`);
};
port('LISTEN_PORT', 'LISTEN_PORT');
port('BACKEND_PORT', 'BACKEND_PORT');
port('CONFIG_EDITOR_PORT', 'CONFIG_EDITOR_PORT');
port('SSH_LISTEN_PORT', 'SSH_LISTEN_PORT');
port('HTTPS_REDIRECT_PORT', 'HTTPS_REDIRECT_PORT');
if (map.CONFIG_EDITOR_PORT && map.LISTEN_PORT &&
map.CONFIG_EDITOR_PORT.value && map.LISTEN_PORT.value &&
Number(map.CONFIG_EDITOR_PORT.value) === Number(map.LISTEN_PORT.value)) {
errors.push('CONFIG_EDITOR_PORT must differ from LISTEN_PORT');
}
if (map.SSH_MODE && !['off', 'terminate', 'passthrough'].includes(map.SSH_MODE.value)) {
errors.push('SSH_MODE must be one of: off, terminate, passthrough');
}
const retentionDays = asInt('LOG_RETENTION_DAYS');
if (retentionDays !== undefined && map.LOG_RETENTION_DAYS.value !== '' &&
(!Number.isInteger(retentionDays) || retentionDays < 1 || retentionDays > 3650)) {
errors.push('LOG_RETENTION_DAYS must be an integer 1-3650');
}
return errors;
}
// Pull the human-readable lines out of a failed validateConfig() child. Its
// stderr is a full Node stack trace wrapped around the message we want.
function extractValidationErrors(err) {
const stderr = (err && err.stderr && err.stderr.toString()) || '';
// Anchor on the thrown message line ("Error: Configuration validation
// failed:"), not the identical text in Node's code-frame echo above it.
const m = stderr.match(/\bError:\s*Configuration validation failed:\r?\n/);
if (m) {
const after = stderr.slice(m.index + m[0].length);
const lines = [];
for (const raw of after.split(/\r?\n/)) {
const line = raw.trim();
if (!line) continue;
if (/^at\s/.test(line) || line.startsWith('Node.js v') || line === '^') break;
lines.push(line);
}
if (lines.length) return lines.join('\n');
}
if (err && err.signal === 'SIGTERM') return 'validation timed out';
return (err && err.message) || 'unknown validation error';
}
// ---------------------------------------------------------------------------
// helpers
// ---------------------------------------------------------------------------
function clientIp(req) {
const raw = (req.socket && req.socket.remoteAddress) || '';
return raw.replace(/^::ffff:/i, '');
}
// Neutralise control characters before putting attacker-influenced text (a
// submitted username) into a log line, so it cannot forge log entries.
function sanitizeForLog(s) {
return String(s == null ? '' : s).replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 200);
}
// Simple one-at-a-time lock for mutating operations (save, restart, the Tools
// actions). Each spawns a subprocess and/or rewrites files; overlapping runs
// invite corruption and resource exhaustion.
function acquire(res, name) {
if (busy.has(name)) {
sendJson(res, 429, { error: `A "${name}" operation is already running — wait for it to finish.` });
return false;
}
busy.add(name);
return true;
}
function release(name) { busy.delete(name); }
function chmodQuiet(p, mode) {
try { fs.chmodSync(p, mode); } catch (_) { /* best effort (e.g. Windows) */ }
}
function safeEqual(a, b) {
const ab = Buffer.from(String(a), 'utf8');
const bb = Buffer.from(String(b), 'utf8');
if (ab.length !== bb.length) {
crypto.timingSafeEqual(ab, ab);
return false;
}
return crypto.timingSafeEqual(ab, bb);
}
function parseCookies(req) {
const out = {};
const raw = req.headers.cookie;
if (!raw) return out;
for (const part of raw.split(';')) {
const idx = part.indexOf('=');
if (idx === -1) continue;
let val = part.slice(idx + 1).trim();
try { val = decodeURIComponent(val); } catch (_) { /* malformed %xx — keep raw */ }
out[part.slice(0, idx).trim()] = val;
}
return out;
}
function readBody(req) {
return new Promise((resolve, reject) => {
let size = 0;
const chunks = [];
req.on('data', (c) => {
size += c.length;
if (size > MAX_BODY_BYTES) {
reject(new Error('request body too large'));
req.destroy();
return;
}
chunks.push(c);
});
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function sendJson(res, status, obj) {
const body = JSON.stringify(obj);
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
'Cache-Control': 'no-store',
});
res.end(body);
}
// Render an HTML page with a fresh per-response script nonce, so the CSP can
// use 'nonce-...' for scripts instead of 'unsafe-inline'. buildHtml(nonce) must
// put nonce="<nonce>" on the single inline <script>.
function sendPage(res, status, buildHtml) {
const nonce = crypto.randomBytes(16).toString('base64url');
const html = buildHtml(nonce);
res.writeHead(status, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': Buffer.byteLength(html),
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'no-referrer',
'Content-Security-Policy':
`default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src 'self'; ` +
"connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
});
res.end(html);
}
// Cached on first read: these files ship with the release and never change
// while the process runs, so there's no point re-reading disk on every hit.
const staticAssetCache = new Map();
function serveStaticAsset(res, pathname) {
const asset = STATIC_ASSETS[pathname];
if (!asset) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
return res.end('Not found');
}
let data = staticAssetCache.get(pathname);
if (!data) {
try {
data = fs.readFileSync(asset.file);
} catch (_) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
return res.end('Not found');
}
staticAssetCache.set(pathname, data);
}
res.writeHead(200, {
'Content-Type': asset.type,
'Content-Length': data.length,
'Cache-Control': 'public, max-age=86400',
'X-Content-Type-Options': 'nosniff',
});
res.end(data);
}
function redirect(res, location) {
res.writeHead(302, { Location: location, 'Cache-Control': 'no-store' });
res.end();
}
function cookieHeader(token, maxAgeSec) {
const parts = [
`${COOKIE_NAME}=${token}`,
'Path=/',
'HttpOnly',
'Secure',
'SameSite=Strict',
];
if (maxAgeSec === 0) parts.push('Max-Age=0');
return parts.join('; ');
}
// ---------------------------------------------------------------------------
// session management
// ---------------------------------------------------------------------------
// mfaVerified starts false when the account has MFA enabled (the router
// gate below then restricts this session to the MFA-verify/logout routes
// until it passes) and true otherwise, so the gate is a no-op when MFA is
// off.
//
// `role` ('master_admin'/'firewall_admin') is captured once here, the same "decided at
// login, never re-checked" pattern mfaVerified already uses above - the only
// way it can go stale is the account being deleted out from under the
// session, and handleDeleteAccount revokes that account's sessions directly.
//
// `mfaSetupRequired` (v1.4): true only when the account's MFA is OFF but its
// per-account policy (`mfaRequired`, set by a master_admin) demands it - see
// handleLoginPost. Mutually exclusive with the mfaVerified gate in practice
// (that gate only ever fires when MFA is already ON), but kept as its own
// flag rather than overloading mfaVerified, since "must verify an existing
// factor" and "must enroll a new one" need different allowed routes below.
function createSession(username, ip, mfaVerified, role, mfaSetupRequired) {
const token = crypto.randomBytes(32).toString('hex');
const csrf = crypto.randomBytes(32).toString('hex');
const now = Date.now();
sessions.set(token, {
username, ip, created: now, lastSeen: now, csrf,
mfaVerified: !!mfaVerified, role: role || 'master_admin', mfaSetupRequired: !!mfaSetupRequired,
});
return { token, csrf };
}
// Signs out every OTHER session belonging to `username` (own account only -
// NOT a global sign-everyone-out, now that more than one admin account can
// exist). Pass `exceptToken: null` to revoke every session for that user,
// including their own (used when deleting an account outright).
function revokeOtherSessionsForUser(username, exceptToken) {
for (const [token, s] of sessions) {
if (token !== exceptToken && s.username === username) sessions.delete(token);
}
}
function getSession(req) {
const token = parseCookies(req)[COOKIE_NAME];
if (!token || !TOKEN_RE.test(token)) return null;
const s = sessions.get(token);
if (!s) return null;
const now = Date.now();
if (now - s.lastSeen > config.configEditor.sessionTimeoutMs ||
now - s.created > ABSOLUTE_SESSION_MS ||
s.ip !== clientIp(req)) {
sessions.delete(token);
return null;
}
s.lastSeen = now;
return { token, ...s };
}
function destroySession(req) {
const token = parseCookies(req)[COOKIE_NAME];
if (token) sessions.delete(token);
}
function sweepSessions() {
const now = Date.now();
for (const [token, s] of sessions) {
if (now - s.lastSeen > config.configEditor.sessionTimeoutMs ||
now - s.created > ABSOLUTE_SESSION_MS) {
sessions.delete(token);
}
}
for (const [ip, f] of loginFails) {
if (now > f.until) loginFails.delete(ip);
}
for (const [ip, f] of apiFails) {
if (now > f.until) apiFails.delete(ip);
}
for (const [ip, f] of mfaFails) {
if (now > f.until) mfaFails.delete(ip);
}
}
function isLocked(map, ip, maxFails = LOGIN_MAX_FAILS) {
const f = map.get(ip);
if (!f) return false;
if (Date.now() > f.until) { map.delete(ip); return false; }
return f.count >= maxFails;
}
function recordFail(map, ip, lockMs = LOGIN_LOCK_MS) {
const f = map.get(ip) || { count: 0, until: 0 };
f.count += 1;
f.until = Date.now() + lockMs;
map.set(ip, f);
}
const loginLocked = (ip) => isLocked(loginFails, ip);
const recordLoginFail = (ip) => recordFail(loginFails, ip);
const apiLocked = (ip) => isLocked(apiFails, ip);
const recordApiFail = (ip) => recordFail(apiFails, ip);
const mfaLocked = (ip) => isLocked(mfaFails, ip, MFA_MAX_FAILS);
const recordMfaFail = (ip) => recordFail(mfaFails, ip, MFA_LOCK_MS);
// ---------------------------------------------------------------------------
// runtime status
// ---------------------------------------------------------------------------
let pm2Available = null;
// Only a SUCCESSFUL detection is cached (permanently — pm2 isn't going to
// vanish once found). A failure is never cached: the startup warm-up call
// below is fire-and-forget, so a request landing in the first instant after
// boot can race it and see pm2Available still null; spawning the pm2 CLI can
// also just be transiently slow right after this process itself restarted
// (small/busy box). Caching that as a permanent "not found" wedged the
// Restart button with a false "pm2 was not found on this host" for the rest
// of the process's life — observed for real, not just in theory.
async function hasPm2() {
if (pm2Available) return true;
try {
await execFileAsync('pm2', ['-v'], { timeout: 4000 });
pm2Available = true;
return true;
} catch (_) {
return false;
}
}
// Used to gate /api/reboot: a full OS reboot is only safe to offer when pm2
// will actually bring BBSFirewall back up on its own. Three independent
// signals, each checked separately rather than collapsed into one boolean, so
// the UI can tell an admin WHICH part is missing instead of just "no":
// 1. enabled — `pm2 startup` installed a systemd unit (pm2-<user>) and it's
// enabled to start at boot. A unit can exist but not be enabled, or
// belong to a different user than the one pm2 runs as now.
// 2. active — that unit is running right now, not just enabled-but-dead.
// 3. appSaved — this app is actually IN pm2's saved process list
// (~/.pm2/dump.pm2, or $PM2_HOME/dump.pm2), which is what the boot unit
// actually resurrects. enabled+active with the app missing from the dump
// (e.g. `pm2 start` without a later `pm2 save`) would still come back up
// as an empty pm2 with nothing running — the single most likely way this
// whole check gives a false "safe."
// `ok` (enabled && active) is the HARD gate used to block the reboot — a
// reliable systemd-level signal. `appSaved` is best-effort/advisory only: it
// depends on locating and parsing pm2's dump file correctly, which is a
// weaker assumption (different PM2_HOME, unreadable file, format drift), so a
// null/false appSaved surfaces as a warning in the UI rather than also
// blocking the request — "do our best to check pm2," not "assume the worst
// when one advisory probe can't read a file." Not cached like hasPm2()/
// hasCertbot() — this can legitimately flip mid-session (an admin fixing it
// after a first blocked attempt), and it only ever runs right before a
// reboot, never on a hot path.
async function pm2StartupStatus() {
const appName = config.configEditor.pm2AppName || 'bbsfirewall';
const status = { unit: null, enabled: false, active: false, appSaved: null, appName };
try {
const { stdout } = await execFileAsync(
'systemctl', ['list-unit-files', '--type=service', '--no-legend'], { timeout: 4000 },
);
const m = stdout.match(/^(pm2-\S+\.service)\s+enabled/m);
if (m) { status.unit = m[1]; status.enabled = true; }
} catch (_) { /* systemctl unavailable/failed — leave enabled:false */ }
if (status.unit) {
try {
const { stdout } = await execFileAsync('systemctl', ['is-active', status.unit], { timeout: 4000 });
status.active = stdout.trim() === 'active';
} catch (_) { /* is-active exits non-zero for inactive states — leave active:false */ }
}
try {
const dumpPath = path.join(process.env.PM2_HOME || path.join(os.homedir(), '.pm2'), 'dump.pm2');
const dump = JSON.parse(fs.readFileSync(dumpPath, 'utf-8'));
status.appSaved = Array.isArray(dump)
&& dump.some((p) => (p && (p.name || (p.pm2_env && p.pm2_env.name))) === appName);
} catch (_) { status.appSaved = null; /* couldn't check — unknown, not necessarily bad */ }
status.ok = status.enabled && status.active;
return status;
}
function humanUptime(sec) {
sec = Math.floor(sec);
const d = Math.floor(sec / 86400); sec -= d * 86400;
const h = Math.floor(sec / 3600); sec -= h * 3600;
const m = Math.floor(sec / 60); sec -= m * 60;
return [d && `${d}d`, h && `${h}h`, m && `${m}m`, `${sec}s`].filter(Boolean).join(' ');
}
let cachedVersion = null;
function appVersion() {
if (cachedVersion !== null) return cachedVersion;
try {
cachedVersion = String(require('./package.json').version || '');
} catch (_) {
cachedVersion = '';
}
return cachedVersion;
}
function readFileSafe(p) {
try {
return { content: fs.readFileSync(path.resolve(p), 'utf-8'), exists: true };
} catch (err) {
if (err.code === 'ENOENT') return { content: '', exists: false };
return { content: '', exists: false, error: err.message };
}
}
// Read the value of one key from the .env file (fresh from disk, so a value the
// admin just saved but hasn't restarted into is still seen).
function envFileValue(key) {
try {
const parsed = parseEnvText(fs.readFileSync(path.resolve(config.configEditor.envPath), 'utf-8'));
return parsed.active[key];
} catch (_) {
return undefined;
}
}
// --- health probes (folded into /api/config) ---------------------------------
function geoipStatus() {
const dbPath = path.join(__dirname, 'data', 'GeoLite2-Country.mmdb');
const out = { dbPath, exists: false, sizeBytes: 0, ageDays: null, licenseKeySet: false };
out.licenseKeySet = !!(envFileValue('MAXMIND_LICENSE_KEY') || '').trim();
try {
const st = fs.statSync(dbPath);
out.exists = true;
out.sizeBytes = st.size;
out.ageDays = Math.floor((Date.now() - st.mtimeMs) / 86400000);
} catch (_) { /* not downloaded yet */ }
return out;
}
// These two probes shell out (`ssh-keygen -l`, `openssl x509`). /api/config
// folds them in via buildHealth(), and an API client may poll it — so cache the
// results briefly. Tools actions that change a key/cert call invalidateHealthCache().
const HEALTH_CACHE_TTL_MS = 4000;
let sshHostKeyCache = null; // { at, value }
let certInfoCache = new Map(); // resolved path -> { at, value }
function invalidateHealthCache() {
sshHostKeyCache = null;
certInfoCache = new Map();
}
async function sshHostKeyStatus() {
if (sshHostKeyCache && Date.now() - sshHostKeyCache.at < HEALTH_CACHE_TTL_MS) {
return sshHostKeyCache.value;
}
const value = await sshHostKeyStatusFresh();
sshHostKeyCache = { at: Date.now(), value };
return value;
}
async function sshHostKeyStatusFresh() {
const keyPath = path.resolve(envFileValue('SSH_HOST_KEY') || config.sshHostKey || './ssh_host_key');
const out = { path: keyPath, exists: false, fingerprint: null, type: null };
try {
fs.statSync(keyPath);
out.exists = true;
try {
const { stdout } = await execFileAsync('ssh-keygen', ['-l', '-f', keyPath], { timeout: 4000 });
const r = stdout.toString().trim();
// "3072 SHA256:abc... comment (RSA)"
const m = r.match(/^(\d+)\s+(\S+)\s+.*\((\w+)\)\s*$/);
if (m) { out.fingerprint = m[2]; out.type = m[3]; }
else out.fingerprint = r;
} catch (_) { /* ssh-keygen missing or unreadable key */ }
} catch (_) { /* no key yet */ }
return out;
}
async function certInfo(certPath) {
const abs = certPath ? path.resolve(certPath) : '';
const cached = certInfoCache.get(abs);
if (cached && Date.now() - cached.at < HEALTH_CACHE_TTL_MS) return cached.value;
const value = await certInfoFresh(certPath);
certInfoCache.set(abs, value);
return value;
}
async function certInfoFresh(certPath) {
const out = { path: certPath, exists: false, subject: null, notAfter: null, daysLeft: null, selfSigned: null };
let abs;
try { abs = path.resolve(certPath); fs.statSync(abs); out.exists = true; }
catch (_) { return out; }
try {
const { stdout } = await execFileAsync('openssl', ['x509', '-in', abs, '-noout', '-subject', '-issuer', '-enddate'],
{ timeout: 4000 });
const txt = stdout.toString();
const sub = txt.match(/^subject=(.*)$/m);
const iss = txt.match(/^issuer=(.*)$/m);
const end = txt.match(/^notAfter=(.*)$/m);
if (sub) out.subject = sub[1].trim();
if (end) {
out.notAfter = end[1].trim();
const t = Date.parse(out.notAfter);
if (!Number.isNaN(t)) out.daysLeft = Math.round((t - Date.now()) / 86400000);
}
if (sub && iss) out.selfSigned = sub[1].trim() === iss[1].trim();
} catch (_) { /* openssl missing */ }
return out;
}
let certbotAvailable = null;
// Same reasoning as hasPm2() above — only a successful detection sticks.
async function hasCertbot() {
if (certbotAvailable) return true;
try {
await execFileAsync('certbot', ['--version'], { timeout: 5000 });
certbotAvailable = true;
return true;
} catch (_) {
return false;
}
}
// Runs the shelled-out probes concurrently — each is a separate child process,
// so there is no reason to make a caller wait for them one after another (that
// used to serialize up to ~4 blocking execFileSync calls behind /api/config,
// stalling the Settings tab and header version behind whichever probe was
// slowest AND blocking the Node event loop for every other connection while
// any one of them ran).
async function buildHealth() {
const ce = config.configEditor;
const rebootEnabled = !!config.configEditor.rebootEnabled;
const [sshHostKey, editorCert, redirectCert, certbotInstalled, pm2Startup] = await Promise.all([
sshHostKeyStatus(),
certInfo(envFileValue('CONFIG_EDITOR_CERT_PATH') || ce.certPath),
certInfo(envFileValue('HTTPS_CERT_PATH') || config.httpsCertPath),
hasCertbot(),
rebootEnabled && process.platform === 'linux' ? pm2StartupStatus() : Promise.resolve(null),
]);
return {
geoip: geoipStatus(),
sshHostKey,
certs: { editor: editorCert, redirect: redirectCert },
certbotInstalled,
domains: {
editor: envFileValue('CONFIG_EDITOR_CERT_DOMAIN') || '',
redirect: envFileValue('HTTPS_CERT_DOMAIN') || '',
},
sshMode: envFileValue('SSH_MODE') || config.sshMode || 'off',
platform: process.platform,
rebootEnabled,
pm2Startup,
};
}
// ---------------------------------------------------------------------------
// /api/config — current values for the form
// ---------------------------------------------------------------------------
// Fast and synchronous except for hasPm2(), whose successful result is cached
// (warmed at startup — see startConfigEditorServer) so this stays non-blocking
// in practice; a not-yet-warmed or transiently-failed check just re-runs next
// call rather than wedging the result. Health data (ssh-keygen/openssl/certbot probes)
// lives behind the separate /api/health endpoint so a slow probe never delays
// the Settings sections or the header version — see buildHealth().
async function buildConfigPayload(session) {
const secrets = security.readSecrets(session.username);
const envPath = path.resolve(config.configEditor.envPath);
let envText = '';
try { envText = fs.readFileSync(envPath, 'utf-8'); } catch (_) {}
const parsed = parseEnvText(envText);
const sections = ENV_SCHEMA.map((sec) => ({
name: sec.name,
help: sec.help || null,
icon: sec.icon || null,
fields: sec.fields.map((f) => {
const active = Object.prototype.hasOwnProperty.call(parsed.active, f.key);
const rawValue = active ? parsed.active[f.key] : (f.required ? (parsed.commented[f.key] || f.def || '') : '');
const isSecret = f.type === 'secret';
return {
key: f.key,
type: f.type,
label: f.label,
help: f.help || null,
helpLong: f.helpLong || null,
required: !!f.required,
options: f.options || null,
enabled: f.required ? true : active,
// A secret's actual value never reaches the browser, for ANY
// session (this used to send it in plaintext to every authenticated
// role, including firewall_admin, even though the Management API
// key it can hold has full admin power and bypasses MFA entirely -
// found in review 2026-09-23). Write-only from here on, same as the
// admin password itself: doSave() below treats a blank submission as
// "leave the current key alone," not "clear it." hasValue tells the
// UI whether one is already set, without revealing what it is.
value: isSecret ? '' : rawValue,
hasValue: isSecret ? !!rawValue : undefined,
placeholder: !active ? (parsed.commented[f.key] || f.def || '') : '',
};
}),
}));
const files = {};
for (const [name, p] of [
['whitelist', config.whitelistPath || './whitelist.txt'],
['blocklist', config.blocklistPath || './blocklist.txt'],
['trustedhosts', config.configEditor.trustedHostsPath || './trustedhosts.txt'],
['triggers', config.triggerBlock.listPath || './triggers.txt'],
['apihosts', config.api.trustedHostsPath || './api-trustedhosts.txt'],
['statushosts', config.status.trustedHostsPath || './status-trustedhosts.txt'],
]) {
const r = readFileSafe(p);
files[name] = { path: p, content: r.content, exists: r.exists };
}
return {
csrf: session.csrf,
username: session.username,
sections,
files,
status: {
pid: process.pid,
version: appVersion(),
uptimeHuman: humanUptime(process.uptime()),
pm2: await hasPm2(),