-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
12035 lines (10968 loc) · 427 KB
/
server.js
File metadata and controls
12035 lines (10968 loc) · 427 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
'use strict';
const express = require('express');
const compression = require('compression');
const morgan = require('morgan');
const path = require('path');
const fs = require('fs');
const os = require('os');
const zlib = require('zlib');
const { execFile, spawn } = require('child_process');
const http = require('http');
const https = require('https');
const crypto = require('crypto');
const { createProxyMiddleware } = require('http-proxy-middleware');
const WebSocket = require('ws');
const net = require('net');
const mysql = require('mysql2');
const sessions = require('./sessions');
const { generateStructureMap } = require('./lib/structure-map');
const {
widgetType, widgetLink, widgetPageLink, widgetIconName,
deltaKey, splitLabelState, widgetKey, normalizeMapping, normalizeButtongridButtons,
} = require('./lib/widget-normalizer');
const {
getCookieValueFromHeader,
buildAuthCookieValue,
parseAuthCookieValue,
} = require('./lib/auth-cookie');
const { createAuthLockoutManager } = require('./lib/auth-lockout');
const { buildOpenhabClient } = require('./lib/openhab-client');
const { getBackendRecoveryDelayMs } = require('./lib/backend-recovery-delay');
// Keep-alive agents for openHAB backend connections (eliminates TIME_WAIT buildup)
const ohHttpAgent = new http.Agent({ keepAlive: true });
const ohHttpsAgent = new https.Agent({ keepAlive: true });
function getOhAgent() {
const proto = new URL(liveConfig.ohTarget).protocol;
return proto === 'https:' ? ohHttpsAgent : ohHttpAgent;
}
const CONFIG_PATH = path.join(__dirname, 'config.js');
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
const CONTROL_CHARS_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;
const ANY_CONTROL_CHARS_RE = /[\x00-\x1F\x7F]/;
const FORBIDDEN_OBJECT_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
function authHeader() {
// Prefer API token (Bearer) for OH 3.x+, fall back to Basic Auth for OH 1.x/2.x
if (liveConfig.ohApiToken) {
return `Bearer ${liveConfig.ohApiToken}`;
}
if (!liveConfig.ohUser || !liveConfig.ohPass) return null;
const token = Buffer.from(`${liveConfig.ohUser}:${liveConfig.ohPass}`).toString('base64');
return `Basic ${token}`;
}
function stripIconVersion(pathname) {
let out = pathname;
out = out.replace(/\/v\d+\//i, '/');
out = out.replace(/\.v\d+(?=\.)/i, '');
return out;
}
function safeText(value) {
return value === null || value === undefined ? '' : String(value);
}
function isPlainObject(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function hasAnyControlChars(value) {
return ANY_CONTROL_CHARS_RE.test(value);
}
function stripControlChars(value) {
return safeText(value).replace(CONTROL_CHARS_RE, '');
}
const MONTHS_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function ordinalSuffix(n) {
if (n >= 11 && n <= 13) return n + 'th';
switch (n % 10) { case 1: return n + 'st'; case 2: return n + 'nd'; case 3: return n + 'rd'; default: return n + 'th'; }
}
function formatDT(date, fmt) {
const pad = (n) => String(n).padStart(2, '0');
const h24 = date.getHours();
const h12 = h24 % 12 || 12;
const tokens = { YYYY: date.getFullYear(), MMM: MONTHS_SHORT[date.getMonth()], Do: ordinalSuffix(date.getDate()), DD: pad(date.getDate()), HH: pad(h24), H: h24, hh: pad(h12), h: h12, mm: pad(date.getMinutes()), ss: pad(date.getSeconds()), A: h24 < 12 ? 'AM' : 'PM' };
return fmt.replace(/YYYY|MMM|Do|DD|HH|H|hh|h|mm|ss|A/g, (m) => tokens[m]);
}
function normalizeHeaderValue(value, maxLen = 1000) {
if (typeof value !== 'string') return '';
const cleaned = value.replace(/[\r\n]+/g, '').trim();
if (!cleaned) return '';
return cleaned.length > maxLen ? cleaned.slice(0, maxLen) : cleaned;
}
function formatPermissionMode(mode) {
return `0${(mode & 0o777).toString(8).padStart(3, '0')}`;
}
function parseOptionalInt(value, { min = 0, max = Number.MAX_SAFE_INTEGER } = {}) {
if (value === '' || value === null || value === undefined) return null;
if (typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value)) {
if (value < min || value > max) return NaN;
return value;
}
if (typeof value === 'string') {
const trimmed = value.trim();
if (!/^\d+$/.test(trimmed)) return NaN;
const num = Number(trimmed);
if (!Number.isFinite(num) || num < min || num > max) return NaN;
return num;
}
return NaN;
}
function isValidSha1(value) {
return typeof value === 'string' && /^[a-f0-9]{40}$/.test(value);
}
function isValidSitemapName(value) {
return typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value);
}
function normalizeVisibilityUsersInput(value) {
if (value === undefined) return { users: [], provided: false };
if (!Array.isArray(value)) return { error: 'visibilityUsers must be an array' };
if (value.length > 500) return { error: 'Too many visibilityUsers entries' };
const users = [];
const seen = new Set();
for (const entry of value) {
if (typeof entry !== 'string' || hasAnyControlChars(entry)) {
return { error: 'visibilityUsers must contain valid usernames' };
}
const username = entry.trim();
if (!/^[a-zA-Z0-9_-]{1,20}$/.test(username)) {
return { error: 'visibilityUsers must contain valid usernames' };
}
if (seen.has(username)) continue;
seen.add(username);
users.push(username);
}
return { users, provided: true };
}
function formatLogTimestamp(date) {
const pad = (value) => String(value).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}
function formatLogLine(message) {
const text = safeText(message).replace(/[\r\n]+/g, ' ').trim();
if (!text) return '';
return `${formatLogTimestamp(new Date())} | ${text}\n`;
}
function writeLogLine(filePath, message) {
const line = formatLogLine(message);
if (!line) return;
process.stdout.write(line);
if (!filePath) return;
try {
fs.appendFileSync(filePath, line);
} catch (err) {
const fallback = formatLogLine(`Failed to write log file ${filePath}: ${err.message || err}`);
if (fallback) process.stdout.write(fallback);
}
}
function describeValue(value) {
if (value === undefined) return '<undefined>';
if (value === null) return '<null>';
if (typeof value === 'string') {
const text = value.replace(/[\r\n]+/g, ' ');
return text === '' ? "''" : `'${text}'`;
}
try {
const json = JSON.stringify(value);
if (json !== undefined) return json;
} catch {
// ignore
}
return String(value);
}
function escapeHtml(value) {
const text = safeText(value);
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function configNumber(value, fallback) {
const num = Number(value);
return Number.isFinite(num) ? num : fallback;
}
function setAuthResponseHeaders(res, authInfo) {
const authenticated = authInfo && authInfo.auth === 'authenticated';
res.setHeader('X-OhProxy-Authenticated', authenticated ? 'true' : 'false');
const safeUser = authenticated ? safeText(authInfo.user).replace(/[\r\n]/g, '').trim() : '';
if (safeUser) res.setHeader('X-OhProxy-Username', safeUser);
else res.removeHeader('X-OhProxy-Username');
}
function bootLog(message) {
writeLogLine('', message);
}
function loadUserConfig() {
try {
if (!fs.existsSync(CONFIG_PATH)) return {};
delete require.cache[require.resolve(CONFIG_PATH)];
const cfg = require(CONFIG_PATH);
return cfg && typeof cfg === 'object' ? cfg : {};
} catch (err) {
if (err && err.code !== 'MODULE_NOT_FOUND') {
bootLog(`Failed to load ${CONFIG_PATH}: ${err.message || err}`);
}
return {};
}
}
function parseProxyAllowEntry(value) {
const raw = safeText(value).trim();
if (!raw) return null;
// Reject non-http/https/rtsp/rtsps schemes (must have :// to be a scheme)
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) && !/^(https?|rtsps?):\/\//i.test(raw)) return null;
const candidate = /^(https?|rtsps?):\/\//i.test(raw) ? raw : `http://${raw}`;
try {
const url = new URL(candidate);
let host = safeText(url.hostname).toLowerCase();
if (!host) return null;
// Strip brackets from IPv6 for consistent matching
if (host.startsWith('[') && host.endsWith(']')) {
host = host.slice(1, -1);
}
return { host, port: safeText(url.port) };
} catch {
return null;
}
}
function normalizeProxyAllowlist(list) {
if (!Array.isArray(list)) return [];
const out = [];
for (const entry of list) {
const parsed = parseProxyAllowEntry(entry);
if (parsed) out.push(parsed);
}
return out;
}
function targetPortForUrl(url) {
if (url.port) return url.port;
if (url.protocol === 'https:') return '443';
if (url.protocol === 'rtsp:') return '554';
if (url.protocol === 'rtsps:') return '322';
return '80';
}
function isProxyTargetAllowed(url, allowlist) {
if (!allowlist.length) return false;
const host = safeText(url.hostname).toLowerCase();
const port = targetPortForUrl(url);
for (const entry of allowlist) {
if (entry.host !== host) continue;
if (!entry.port) return true;
if (entry.port === port) return true;
}
return false;
}
function redactUrlCredentials(value) {
const text = safeText(value);
if (!text) return '';
try {
const url = new URL(text);
if (!url.username && !url.password) return text;
url.username = '';
url.password = '';
return url.toString();
} catch {
return text.replace(/\/\/[^@/]+@/g, '//');
}
}
function hashString(value) {
return crypto.createHash('sha1').update(value).digest('hex');
}
const USER_CONFIG = loadUserConfig();
const SERVER_CONFIG = USER_CONFIG.server || {};
const HTTP_CONFIG = SERVER_CONFIG.http || {};
const HTTPS_CONFIG = SERVER_CONFIG.https || {};
const SERVER_AUTH = SERVER_CONFIG.auth || {};
const SECURITY_HEADERS = SERVER_CONFIG.securityHeaders || {};
const CLIENT_CONFIG = USER_CONFIG.client || {};
const PROXY_ALLOWLIST = normalizeProxyAllowlist(SERVER_CONFIG.proxyAllowlist);
const WEBVIEW_NO_PROXY = normalizeProxyAllowlist(SERVER_CONFIG.webviewNoProxy);
const HTTP_ENABLED = typeof HTTP_CONFIG.enabled === 'boolean' ? HTTP_CONFIG.enabled : false;
const HTTPS_ENABLED = typeof HTTPS_CONFIG.enabled === 'boolean' ? HTTPS_CONFIG.enabled : false;
const HTTP_HOST = safeText(HTTP_CONFIG.host);
const HTTP_PORT = configNumber(HTTP_CONFIG.port);
const HTTPS_HOST = safeText(HTTPS_CONFIG.host);
const HTTPS_PORT = configNumber(HTTPS_CONFIG.port);
const HTTPS_CERT_FILE = safeText(HTTPS_CONFIG.certFile);
const HTTPS_KEY_FILE = safeText(HTTPS_CONFIG.keyFile);
const ALLOW_SUBNETS = SERVER_CONFIG.allowSubnets;
const TRUST_PROXY = SERVER_CONFIG.trustProxy === true;
const DENY_XFF_SUBNETS = SERVER_CONFIG.denyXFFSubnets;
const OH_TARGET = safeText(SERVER_CONFIG.openhab?.target);
const OH_USER = safeText(SERVER_CONFIG.openhab?.user || '');
const OH_PASS = safeText(SERVER_CONFIG.openhab?.pass || '');
const OH_API_TOKEN = safeText(SERVER_CONFIG.openhab?.apiToken || '');
const OPENHAB_REQUEST_TIMEOUT_MS = configNumber(SERVER_CONFIG.openhab?.timeoutMs, 15000);
const ICON_VERSION = safeText(SERVER_CONFIG.assets?.iconVersion);
const USER_AGENT = safeText(SERVER_CONFIG.userAgent);
const ASSET_VERSION = safeText(SERVER_CONFIG.assets?.assetVersion);
const APPLE_TOUCH_VERSION_RAW = safeText(SERVER_CONFIG.assets?.appleTouchIconVersion);
const APPLE_TOUCH_VERSION = APPLE_TOUCH_VERSION_RAW || '';
const ICON_SIZE = configNumber(SERVER_CONFIG.iconSize);
const ICON_CACHE_CONCURRENCY = Math.max(1, Math.floor(configNumber(SERVER_CONFIG.iconCacheConcurrency, 5)));
const ICON_CACHE_TTL_MS = Math.max(0, Math.floor(configNumber(SERVER_CONFIG.iconCacheTtlMs, 86400000)));
const DELTA_CACHE_LIMIT = configNumber(SERVER_CONFIG.deltaCacheLimit);
const GROUP_ITEMS = Array.isArray(SERVER_CONFIG.groupItems) ? SERVER_CONFIG.groupItems.map(safeText).filter(Boolean) : [];
const PROXY_LOG_LEVEL = safeText(SERVER_CONFIG.proxyMiddlewareLogLevel);
const LOG_FILE = safeText(SERVER_CONFIG.logFile);
const ACCESS_LOG = safeText(SERVER_CONFIG.accessLog);
const ACCESS_LOG_LEVEL = safeText(SERVER_CONFIG.accessLogLevel || 'all')
.trim()
.toLowerCase();
const JS_LOG_FILE = safeText(SERVER_CONFIG.jsLogFile || '');
const JS_LOG_ENABLED = SERVER_CONFIG.jsLogEnabled === true;
const SLOW_QUERY_MS = configNumber(SERVER_CONFIG.slowQueryMs, 0);
const AUTH_REALM = safeText(SERVER_AUTH.realm || 'openHAB Proxy');
const AUTH_COOKIE_NAME = safeText(SERVER_AUTH.cookieName || 'AuthStore');
const AUTH_COOKIE_DAYS = configNumber(SERVER_AUTH.cookieDays, 0);
const AUTH_COOKIE_KEY = safeText(SERVER_AUTH.cookieKey || '');
const AUTH_FAIL_NOTIFY_CMD = safeText(SERVER_AUTH.authFailNotifyCmd || '');
const AUTH_MODE = safeText(SERVER_AUTH.mode || 'basic');
const AUTH_FAIL_NOTIFY_INTERVAL_MINS = configNumber(SERVER_AUTH.authFailNotifyIntervalMins, 15);
const AUTH_LOCKOUT_THRESHOLD = 3;
const AUTH_LOCKOUT_WINDOW_MS = 10 * 60 * 1000;
const SESSION_MAX_AGE_DAYS = (() => {
const val = configNumber(SERVER_CONFIG.sessionMaxAgeDays, 14);
if (val < 1) {
console.warn(`sessionMaxAgeDays must be >= 1, got ${val}; using default 14`);
return 14;
}
return val;
})();
const AUTH_LOCKOUT_MS = 15 * 60 * 1000;
const AUTH_LOCKOUT_PRUNE_MS = 60 * 1000;
const AUTH_LOCKOUT_STALE_MS = Math.max(AUTH_LOCKOUT_MS, AUTH_LOCKOUT_WINDOW_MS);
const SECURITY_HEADERS_ENABLED = SECURITY_HEADERS.enabled !== false;
const SECURITY_HSTS = SECURITY_HEADERS.hsts || {};
const SECURITY_CSP = SECURITY_HEADERS.csp || {};
const SECURITY_REFERRER_POLICY = safeText(SECURITY_HEADERS.referrerPolicy || '');
const TASK_CONFIG = SERVER_CONFIG.backgroundTasks || {};
const SITEMAP_REFRESH_MS = configNumber(TASK_CONFIG.sitemapRefreshMs);
const STRUCTURE_MAP_REFRESH_MS = configNumber(TASK_CONFIG.structureMapRefreshMs);
const NPM_UPDATE_CHECK_MS = configNumber(TASK_CONFIG.npmUpdateCheckMs);
const LOG_ROTATION_ENABLED = SERVER_CONFIG.logRotationEnabled === true;
const WEBSOCKET_CONFIG = SERVER_CONFIG.websocket || {};
const WS_MODE = ['atmosphere', 'sse'].includes(WEBSOCKET_CONFIG.mode) ? WEBSOCKET_CONFIG.mode : 'polling';
const WS_POLLING_INTERVAL_MS = configNumber(WEBSOCKET_CONFIG.pollingIntervalMs) || 500;
const WS_POLLING_INTERVAL_BG_MS = configNumber(WEBSOCKET_CONFIG.pollingIntervalBgMs) || 2000;
const WS_ATMOSPHERE_NO_UPDATE_WARN_MS = Math.max(
0,
configNumber(WEBSOCKET_CONFIG.atmosphereNoUpdateWarnMs, 5000)
);
const BACKEND_RECOVERY_DELAY_MS = Math.max(
0,
configNumber(WEBSOCKET_CONFIG.backendRecoveryDelayMs, 0)
);
const PREVIEW_CONFIG = SERVER_CONFIG.videoPreview || {};
const VIDEO_PREVIEW_INTERVAL_MS = configNumber(PREVIEW_CONFIG.intervalMs, 900000);
const VIDEO_PREVIEW_PRUNE_HOURS = configNumber(PREVIEW_CONFIG.pruneAfterHours, 24);
const VIDEO_PREVIEW_DIR = path.join(__dirname, 'video-previews');
const VIDEO_PREVIEW_CACHE_MAX_AGE_SEC = 31536000;
const BINARIES_CONFIG = SERVER_CONFIG.binaries || {};
const BIN_FFMPEG = safeText(BINARIES_CONFIG.ffmpeg) || '/usr/bin/ffmpeg';
const BIN_CONVERT = safeText(BINARIES_CONFIG.convert) || '/usr/bin/convert';
const BIN_SHELL = safeText(BINARIES_CONFIG.shell) || '/bin/sh';
const CHART_CACHE_DIR = path.join(__dirname, 'cache', 'chart');
// Parse any openHAB chart period string to seconds.
// Supports simple (h, D, W, M, Y), multiplied (4h, 2D, 3W),
// ISO 8601 (P1Y6M, PT1H30M, P2W, P1DT12H), and past-future (2h-1h, D-1D, D-, -1h, PT1H-PT30M).
// Returns 0 for invalid/unrecognised input. Each period component is capped at 10 years.
const MAX_PERIOD_SEC = 10 * 365.25 * 86400; // ~10 years
const CHART_PERIOD_MAX_LEN = 64;
const CHART_SERVICE_RE = /^[A-Za-z0-9._-]{1,64}$/;
const CHART_LEGEND_MODES = new Set(['true', 'false']);
const CHART_BOOLEAN_TRUE = new Set(['true', '1', 'yes', 'on']);
const CHART_BOOLEAN_FALSE = new Set(['false', '0', 'no', 'off']);
function parseBasePeriodToSeconds(period) {
// Simple / multiplied: e.g. h, D, 4h, 2W, 12M
const simpleMatch = period.match(/^(\d*)([hDWMY])$/);
if (simpleMatch) {
const multiplier = simpleMatch[1] ? parseInt(simpleMatch[1], 10) : 1;
const unitSec = { h: 3600, D: 86400, W: 604800, M: 2592000, Y: 31536000 };
const sec = multiplier * unitSec[simpleMatch[2]];
return Math.min(sec, MAX_PERIOD_SEC);
}
// ISO 8601 duration: P[nY][nM][nW][nD][T[nH][nM][nS]]
const isoMatch = period.match(/^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/);
if (isoMatch) {
const [, y, mo, w, d, h, mi, s] = isoMatch;
const sec = (parseInt(y || 0) * 31536000)
+ (parseInt(mo || 0) * 2592000)
+ (parseInt(w || 0) * 604800)
+ (parseInt(d || 0) * 86400)
+ (parseInt(h || 0) * 3600)
+ (parseInt(mi || 0) * 60)
+ (parseInt(s || 0));
return sec > 0 ? Math.min(sec, MAX_PERIOD_SEC) : 0;
}
return 0;
}
function parsePeriodWindow(period) {
if (typeof period !== 'string') return null;
const raw = period.trim();
if (!raw) return null;
// Past-future format: <past>-<future>, where either side may be empty (e.g. D-, -1h).
const dashCount = (raw.match(/-/g) || []).length;
if (dashCount > 1) return null;
if (dashCount === 1) {
const [past, future] = raw.split('-');
const pastSec = past ? parseBasePeriodToSeconds(past) : 0;
const futureSec = future ? parseBasePeriodToSeconds(future) : 0;
if (past && !pastSec) return null;
if (future && !futureSec) return null;
if (!pastSec && !futureSec) return null;
return {
pastSec,
futureSec,
totalSec: pastSec + futureSec,
};
}
const baseSec = parseBasePeriodToSeconds(raw);
if (!baseSec) return null;
return {
pastSec: baseSec,
futureSec: 0,
totalSec: baseSec,
};
}
function parsePeriodToSeconds(period) {
const parsed = parsePeriodWindow(period);
return parsed ? parsed.totalSec : 0;
}
function normalizePeriodWindow(periodWindow) {
if (Number.isFinite(periodWindow) && periodWindow > 0) {
const sec = Math.floor(periodWindow);
return {
pastSec: sec,
futureSec: 0,
totalSec: sec,
};
}
if (!periodWindow || typeof periodWindow !== 'object') return null;
const pastSec = Number.isFinite(periodWindow.pastSec) && periodWindow.pastSec >= 0
? Math.floor(periodWindow.pastSec)
: 0;
const futureSec = Number.isFinite(periodWindow.futureSec) && periodWindow.futureSec >= 0
? Math.floor(periodWindow.futureSec)
: 0;
if (!pastSec && !futureSec) return null;
const totalSec = Number.isFinite(periodWindow.totalSec) && periodWindow.totalSec > 0
? Math.floor(periodWindow.totalSec)
: (pastSec + futureSec);
if (!totalSec) return null;
return {
pastSec,
futureSec,
totalSec,
};
}
function periodWindowFromPeriodString(period, fallbackSec = 86400) {
const parsed = parsePeriodWindow(period);
if (parsed) return parsed;
const fallback = normalizePeriodWindow(fallbackSec);
if (fallback) return fallback;
return {
pastSec: 86400,
futureSec: 0,
totalSec: 86400,
};
}
function periodWindowBounds(periodWindow) {
const window = normalizePeriodWindow(periodWindow) || periodWindowFromPeriodString('D');
const nowSec = Date.now() / 1000;
return {
startSec: nowSec - window.pastSec,
endSec: nowSec + window.futureSec,
window,
};
}
function periodWindowDates(periodWindow) {
const { startSec, endSec } = periodWindowBounds(periodWindow);
return {
start: new Date(startSec * 1000),
end: new Date(endSec * 1000),
};
}
function parseChartLegendMode(rawLegend) {
if (rawLegend === undefined) return 'auto';
if (typeof rawLegend !== 'string') return null;
const normalized = rawLegend.trim().toLowerCase();
if (!normalized) return null;
if (CHART_LEGEND_MODES.has(normalized)) return normalized;
return null;
}
function parseChartForceAsItem(rawForceAsItem) {
if (rawForceAsItem === undefined) return false;
if (typeof rawForceAsItem !== 'string') return null;
const normalized = rawForceAsItem.trim().toLowerCase();
if (!normalized) return null;
if (CHART_BOOLEAN_TRUE.has(normalized)) return true;
if (CHART_BOOLEAN_FALSE.has(normalized)) return false;
return null;
}
function shouldShowChartLegend(legendMode, seriesCount = 1) {
if (legendMode === 'true' || legendMode === true) return true;
if (legendMode === 'false' || legendMode === false) return false;
return Number.isFinite(seriesCount) ? seriesCount > 1 : false;
}
// Tiered cache TTL (ms) matching original h/D/W/M/Y behaviour
function chartCacheTtl(durationSec) {
if (durationSec <= 3600) return 60 * 1000; // <=1h → 1 min
if (durationSec <= 86400) return 10 * 60 * 1000; // <=1d → 10 min
if (durationSec <= 30 * 86400) return 60 * 60 * 1000; // <=30d → 1 hour
return 24 * 60 * 60 * 1000; // >30d → 1 day
}
// Snap to a "nice" x-label interval targeting ~7 labels
function chartXLabelInterval(dataDurationSec) {
const niceIntervals = [
300, 600, 900, 1800, 3600, 7200, 14400, 21600,
43200, 86400, 172800, 432000, 604800, 1209600, 2592000,
];
const target = dataDurationSec / 7;
for (const iv of niceIntervals) {
if (iv >= target) return iv;
}
return niceIntervals[niceIntervals.length - 1];
}
// Tiered sampling/rounding config for stable data hashing
function chartHashConfig(durationSec) {
if (durationSec <= 3600) return { sample: 1, decimals: 2, tsRound: 60 };
if (durationSec <= 86400) return { sample: 4, decimals: 1, tsRound: 3600 };
if (durationSec <= 604800) return { sample: 8, decimals: 1, tsRound: 86400 };
if (durationSec <= 2592000) return { sample: 16, decimals: 0, tsRound: 86400 };
return { sample: 32, decimals: 0, tsRound: 604800 };
}
// Show "Cur" stat for short durations (<=4h)
function chartShowCurStat(durationSec) {
return durationSec <= 14400;
}
const AI_CACHE_DIR = path.join(__dirname, 'cache', 'ai');
const STRUCTURE_MAP_ON_DEMAND_TIMEOUT_MS = 20000;
const STRUCTURE_MAP_ON_DEMAND_FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
const ANTHROPIC_API_KEY = safeText(SERVER_CONFIG.apiKeys?.anthropic) || '';
const AI_MODEL_IDS = [
'claude-3-haiku-20240307',
'claude-3-5-haiku-20241022',
'claude-haiku-4-5-20251001',
'claude-sonnet-4-20250514',
'claude-sonnet-4-5-20250514',
];
const AI_MODEL_PRICING = {
'claude-3-haiku-20240307': { input: 0.25, output: 1.25 },
'claude-3-5-haiku-20241022': { input: 0.80, output: 4.00 },
'claude-haiku-4-5-20251001': { input: 0.80, output: 4.00 },
'claude-sonnet-4-20250514': { input: 3.00, output: 15.00 },
'claude-sonnet-4-5-20250514': { input: 3.00, output: 15.00 },
};
const AI_MODEL = AI_MODEL_IDS.includes(safeText(SERVER_CONFIG.apiKeys?.aiModel))
? safeText(SERVER_CONFIG.apiKeys.aiModel) : 'claude-3-haiku-20240307';
const VOICE_CONFIG = SERVER_CONFIG.voice || {};
const VOICE_MODEL = (['browser', 'vosk'].includes((safeText(VOICE_CONFIG.model) || '').toLowerCase()))
? safeText(VOICE_CONFIG.model).toLowerCase() : 'browser';
const VOSK_HOST = safeText(VOICE_CONFIG.voskHost) || '';
const WEATHERBIT_CONFIG = SERVER_CONFIG.weatherbit || {};
const WEATHERBIT_API_KEY = safeText(WEATHERBIT_CONFIG.apiKey).trim();
const WEATHERBIT_LATITUDE = safeText(WEATHERBIT_CONFIG.latitude).trim();
const WEATHERBIT_LONGITUDE = safeText(WEATHERBIT_CONFIG.longitude).trim();
const WEATHERBIT_UNITS = safeText(WEATHERBIT_CONFIG.units).trim() || 'metric';
const WEATHERBIT_REFRESH_MS = configNumber(WEATHERBIT_CONFIG.refreshIntervalMs, 3600000);
const WEATHERBIT_CACHE_DIR = path.join(__dirname, 'cache', 'weatherbit');
const WEATHERBIT_FORECAST_FILE = path.join(WEATHERBIT_CACHE_DIR, 'forecast.json');
const WEATHERBIT_ICONS_DIR = path.join(WEATHERBIT_CACHE_DIR, 'icons');
const PROXY_CACHE_DIR = path.join(__dirname, 'cache', 'proxy');
const MYSQL_CONFIG = SERVER_CONFIG.mysql || {};
const MYSQL_RECONNECT_DELAY_MS = 5000;
const CMDAPI_CONFIG = SERVER_CONFIG.cmdapi || {};
const CMDAPI_ENABLED = CMDAPI_CONFIG.enabled === true;
const CMDAPI_ALLOWED_SUBNETS = Array.isArray(CMDAPI_CONFIG.allowedSubnets)
? CMDAPI_CONFIG.allowedSubnets
: [];
const CMDAPI_ALLOWED_ITEMS = Array.isArray(CMDAPI_CONFIG.allowedItems)
? CMDAPI_CONFIG.allowedItems
: [];
const CMDAPI_TIMEOUT_MS = 10000;
let mysqlConnection = null;
let mysqlConnecting = false;
let videoPreviewInitialCaptureDone = false;
const activeVideoStreams = new Map(); // Track active video streams: id -> { url, user, ip, startTime, encoding }
let videoStreamIdCounter = 0;
const authLockouts = new Map();
const authLockoutManager = createAuthLockoutManager({
state: authLockouts,
threshold: AUTH_LOCKOUT_THRESHOLD,
windowMs: AUTH_LOCKOUT_WINDOW_MS,
lockoutMs: AUTH_LOCKOUT_MS,
staleMs: AUTH_LOCKOUT_STALE_MS,
});
const authFailNotifyByIp = new Map();
function logMessage(message) {
writeLogLine(liveConfig.logFile, message);
}
function logJsError(message) {
if (!liveConfig.jsLogEnabled || !liveConfig.jsLogFile) return;
writeLogLine(liveConfig.jsLogFile, message);
}
function formatActiveVideoStreamLog(now = Date.now()) {
const count = activeVideoStreams.size;
if (count < 1) return '';
const details = [];
for (const [id, stream] of activeVideoStreams.entries()) {
const url = safeText(stream?.url).trim() || 'unknown';
const client = safeText(stream?.user).trim() || 'anonymous';
const ip = safeText(stream?.ip).trim() || 'unknown';
const encoding = safeText(stream?.encoding).trim() || 'unknown';
const startedAt = Number.isFinite(stream?.startTime) ? stream.startTime : now;
const elapsedSec = Math.max(0, Math.floor((now - startedAt) / 1000));
details.push(`#${id} ${encoding} url=${url} client=${client} ip=${ip} age=${elapsedSec}s`);
}
return `[Video] ${count} stream${count === 1 ? '' : 's'} active: ${details.join('; ')}`;
}
function getLockoutKey(ip) {
return ip || 'unknown';
}
function getLockoutRemainingSeconds(lockout, now = Date.now()) {
return authLockoutManager.remainingSeconds(lockout, now);
}
function getAuthLockout(key) {
return authLockoutManager.get(key);
}
function recordAuthFailure(key) {
return authLockoutManager.recordFailure(key);
}
function clearAuthFailures(key) {
authLockoutManager.clear(key);
}
function pruneAuthLockouts() {
authLockoutManager.prune();
}
function pruneAuthFailureNotifyState() {
const now = Date.now();
const intervalMs = Math.max(60 * 1000, (liveConfig.authFailNotifyIntervalMins || 15) * 60 * 1000);
const staleAfterMs = intervalMs * 2;
for (const [ip, lastNotify] of authFailNotifyByIp) {
const ts = Number(lastNotify) || 0;
if (!ts || now - ts > staleAfterMs) {
authFailNotifyByIp.delete(ip);
}
}
}
function logAccess(message) {
if (liveConfig.accessLogLevel === '400+') {
const match = safeText(message).match(/\s(\d{3})\s/);
const status = match ? Number(match[1]) : NaN;
if (Number.isFinite(status) && status < 400) return;
}
const line = safeText(message);
if (!line || !liveConfig.accessLog) return;
const text = line.endsWith('\n') ? line : `${line}\n`;
try {
fs.appendFileSync(liveConfig.accessLog, text);
} catch (err) {
const fallback = formatLogLine(`Failed to write log file ${liveConfig.accessLog}: ${err.message || err}`);
if (fallback) process.stdout.write(fallback);
}
}
function shouldSkipAccessLog(res) {
if (liveConfig.accessLogLevel === 'all') return false;
if (liveConfig.accessLogLevel === '400+') return (res?.statusCode || 0) < 400;
return false;
}
function ensureString(value, name, { allowEmpty = false, maxLen } = {}, errors) {
if (typeof value !== 'string') {
errors.push(`${name} must be a string but currently is ${describeValue(value)}`);
return;
}
if (!allowEmpty && value.trim() === '') {
errors.push(`${name} is required but currently is ${describeValue(value)}`);
}
if (maxLen !== undefined && value.length > maxLen) {
errors.push(`${name} must be at most ${maxLen} characters but is ${value.length}`);
}
}
function ensureNumber(value, name, { min, max, integer = true } = {}, errors) {
if (!Number.isFinite(value)) {
errors.push(`${name} must be a number but currently is ${describeValue(value)}`);
return;
}
if (integer && !Number.isInteger(value)) {
errors.push(`${name} must be an integer but currently is ${describeValue(value)}`);
return;
}
if (min !== undefined && value < min) {
errors.push(`${name} must be >= ${min} but currently is ${describeValue(value)}`);
}
if (max !== undefined && value > max) {
errors.push(`${name} must be <= ${max} but currently is ${describeValue(value)}`);
}
}
function ensureBoolean(value, name, errors) {
if (typeof value !== 'boolean') {
errors.push(`${name} must be true/false but currently is ${describeValue(value)}`);
}
}
function ensureArray(value, name, { allowEmpty = false, maxItems } = {}, errors) {
if (!Array.isArray(value)) {
errors.push(`${name} must be an array but currently is ${describeValue(value)}`);
return false;
}
if (!allowEmpty && value.length === 0) {
errors.push(`${name} must not be empty but currently is ${describeValue(value)}`);
return false;
}
if (maxItems !== undefined && value.length > maxItems) {
errors.push(`${name} must have at most ${maxItems} items but has ${value.length}`);
return false;
}
return true;
}
function ensureObject(value, name, errors) {
if (!isPlainObject(value)) {
errors.push(`${name} must be an object but currently is ${describeValue(value)}`);
return false;
}
return true;
}
function isValidIpv4(value) {
const parts = safeText(value).split('.');
if (parts.length !== 4) return false;
return parts.every((part) => /^\d+$/.test(part) && Number(part) >= 0 && Number(part) <= 255);
}
function isValidCidr(value) {
const raw = safeText(value).trim();
const parts = raw.split('/');
if (parts.length !== 2) return false;
if (!isValidIpv4(parts[0])) return false;
const mask = Number(parts[1]);
return Number.isInteger(mask) && mask >= 0 && mask <= 32;
}
function isAllowAllSubnet(value) {
return safeText(value).trim() === '0.0.0.0';
}
function isValidAllowSubnet(value) {
if (isAllowAllSubnet(value)) return true;
return isValidCidr(value);
}
function ensureCidrList(value, name, { allowEmpty = false, maxItems } = {}, errors) {
if (!ensureArray(value, name, { allowEmpty, maxItems }, errors)) return;
value.forEach((entry, index) => {
if (!isValidCidr(entry)) {
errors.push(`${name}[${index}] must be IPv4 CIDR but currently is ${describeValue(entry)}`);
}
});
}
function ensureAllowSubnets(value, name, errors, options = {}) {
const allowEmpty = options.allowEmpty === true;
if (!ensureArray(value, name, { allowEmpty, maxItems: options.maxItems }, errors)) return;
value.forEach((entry, index) => {
if (!isValidAllowSubnet(entry)) {
errors.push(`${name}[${index}] must be IPv4 CIDR or 0.0.0.0 but currently is ${describeValue(entry)}`);
}
});
}
function ensureUrl(value, name, errors) {
ensureString(value, name, { allowEmpty: false }, errors);
if (typeof value !== 'string' || value.trim() === '') return;
try {
const parsed = new URL(value);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
errors.push(`${name} must use http or https but currently is ${describeValue(value)}`);
}
} catch {
errors.push(`${name} must be a valid URL but currently is ${describeValue(value)}`);
}
}
function ensureHostOrIp(value, name, errors) {
if (typeof value !== 'string') {
errors.push(`${name} must be a string but currently is ${describeValue(value)}`);
return;
}
const trimmed = value.trim();
if (!trimmed) {
errors.push(`${name} is required but currently is ${describeValue(value)}`);
return;
}
if (trimmed === '0.0.0.0') return;
if (isValidIpv4(trimmed)) return;
// RFC 952/1123 hostname: dot-separated labels, each label alphanumeric/hyphens, max 253 chars total
if (trimmed.length > 253) {
errors.push(`${name} hostname must be at most 253 characters but is ${trimmed.length}`);
return;
}
const labels = trimmed.split('.');
const validLabel = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;
for (const label of labels) {
if (!validLabel.test(label)) {
errors.push(`${name} must be a valid IPv4 address or hostname but currently is ${describeValue(value)}`);
return;
}
}
}
function ensureAbsolutePath(value, name, errors) {
if (typeof value !== 'string') {
errors.push(`${name} must be a string but currently is ${describeValue(value)}`);
return;
}
if (value.trim() === '') {
errors.push(`${name} is required but currently is ${describeValue(value)}`);
return;
}
if (!path.isAbsolute(value)) {
errors.push(`${name} must be an absolute path but currently is ${describeValue(value)}`);
}
}
function ensureVersion(value, name, errors) {
ensureString(value, name, { allowEmpty: false }, errors);
if (typeof value !== 'string' || value.trim() === '') return;
if (!/^v\d+$/i.test(value.trim())) {
errors.push(`${name} must be in format v123 but currently is ${describeValue(value)}`);
}
}
function ensureLogPath(value, name, errors) {
ensureString(value, name, { allowEmpty: true }, errors); // Empty disables logging
if (typeof value !== 'string' || value.trim() === '') return;
if (!path.isAbsolute(value)) {
errors.push(`${name} must be an absolute path but currently is ${describeValue(value)}`);
return;
}
const dir = path.dirname(value);
if (!fs.existsSync(dir)) {
errors.push(`${name} directory does not exist for ${describeValue(value)}`);
return;
}
try {
fs.accessSync(dir, fs.constants.W_OK);
} catch {
errors.push(`${name} directory is not writable for ${describeValue(value)}`);
}
}
function ensureReadableFile(value, name, errors) {
ensureString(value, name, { allowEmpty: false }, errors);
if (typeof value !== 'string' || value.trim() === '') return;
if (!path.isAbsolute(value)) {
errors.push(`${name} must be an absolute path but currently is ${describeValue(value)}`);
return;
}
if (!fs.existsSync(value)) {
errors.push(`${name} does not exist for ${describeValue(value)}`);
return;
}
try {
fs.accessSync(value, fs.constants.R_OK);
} catch {
errors.push(`${name} is not readable for ${describeValue(value)}`);
}
}
function validateConfig() {
const errors = [];
if (ensureObject(SERVER_CONFIG.http, 'server.http', errors)) {
ensureBoolean(HTTP_CONFIG.enabled, 'server.http.enabled', errors);
if (HTTP_ENABLED) {
ensureString(HTTP_HOST, 'server.http.host', { allowEmpty: false }, errors);
ensureNumber(HTTP_PORT, 'server.http.port', { min: 1, max: 65535 }, errors);
}
}
if (ensureObject(SERVER_CONFIG.https, 'server.https', errors)) {
ensureBoolean(HTTPS_CONFIG.enabled, 'server.https.enabled', errors);
if (HTTPS_ENABLED) {
ensureString(HTTPS_HOST, 'server.https.host', { allowEmpty: false }, errors);
ensureNumber(HTTPS_PORT, 'server.https.port', { min: 1, max: 65535 }, errors);
ensureReadableFile(HTTPS_CERT_FILE, 'server.https.certFile', errors);
ensureReadableFile(HTTPS_KEY_FILE, 'server.https.keyFile', errors);
}
}
if (!HTTP_ENABLED && !HTTPS_ENABLED) {
errors.push('At least one of server.http.enabled or server.https.enabled must be true');
}
ensureAllowSubnets(ALLOW_SUBNETS, 'server.allowSubnets', errors);
if (typeof TRUST_PROXY !== 'boolean') {
errors.push(`server.trustProxy must be true or false but currently is ${describeValue(SERVER_CONFIG.trustProxy)}`);
}
ensureAllowSubnets(DENY_XFF_SUBNETS, 'server.denyXFFSubnets', errors, { allowEmpty: true });
if (ensureObject(SERVER_CONFIG.openhab, 'server.openhab', errors)) {
ensureUrl(OH_TARGET, 'server.openhab.target', errors);
ensureString(OH_USER, 'server.openhab.user', { allowEmpty: true }, errors);
ensureString(OH_PASS, 'server.openhab.pass', { allowEmpty: true }, errors);
ensureNumber(OPENHAB_REQUEST_TIMEOUT_MS, 'server.openhab.timeoutMs', { min: 0 }, errors);
}
if (ensureObject(SERVER_CONFIG.assets, 'server.assets', errors)) {
ensureVersion(ASSET_VERSION, 'server.assets.assetVersion', errors);
ensureVersion(APPLE_TOUCH_VERSION_RAW, 'server.assets.appleTouchIconVersion', errors);
ensureVersion(ICON_VERSION, 'server.assets.iconVersion', errors);
}
ensureString(USER_AGENT, 'server.userAgent', { allowEmpty: false }, errors);
ensureNumber(ICON_SIZE, 'server.iconSize', { min: 1 }, errors);
ensureNumber(SERVER_CONFIG.iconCacheConcurrency, 'server.iconCacheConcurrency', { min: 1 }, errors);
ensureNumber(DELTA_CACHE_LIMIT, 'server.deltaCacheLimit', { min: 1 }, errors);
ensureString(PROXY_LOG_LEVEL, 'server.proxyMiddlewareLogLevel', { allowEmpty: false }, errors);
ensureLogPath(LOG_FILE, 'server.logFile', errors);
ensureLogPath(ACCESS_LOG, 'server.accessLog', errors);
ensureString(ACCESS_LOG_LEVEL, 'server.accessLogLevel', { allowEmpty: false }, errors);
if (ACCESS_LOG_LEVEL !== 'all' && ACCESS_LOG_LEVEL !== '400+') {
errors.push(`server.accessLogLevel must be "all" or "400+" but currently is ${describeValue(ACCESS_LOG_LEVEL)}`);
}
ensureNumber(SLOW_QUERY_MS, 'server.slowQueryMs', { min: 0 }, errors);
if (ensureObject(SERVER_CONFIG.auth, 'server.auth', errors)) {
ensureString(AUTH_REALM, 'server.auth.realm', { allowEmpty: false }, errors);
ensureString(AUTH_COOKIE_NAME, 'server.auth.cookieName', { allowEmpty: true }, errors);
ensureNumber(AUTH_COOKIE_DAYS, 'server.auth.cookieDays', { min: 0 }, errors);
ensureString(AUTH_COOKIE_KEY, 'server.auth.cookieKey', { allowEmpty: true }, errors);
if (AUTH_COOKIE_KEY && AUTH_COOKIE_KEY.length < 32) {
errors.push(`server.auth.cookieKey must be at least 32 characters for HMAC security but is ${AUTH_COOKIE_KEY.length} characters`);
}
ensureString(SERVER_AUTH.authFailNotifyCmd, 'server.auth.authFailNotifyCmd', { allowEmpty: true }, errors);
ensureNumber(AUTH_FAIL_NOTIFY_INTERVAL_MINS, 'server.auth.authFailNotifyIntervalMins', { min: 1 }, errors);
if (AUTH_COOKIE_KEY) {
if (!AUTH_COOKIE_NAME) {