-
-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathserver.ts
More file actions
9214 lines (8114 loc) · 345 KB
/
server.ts
File metadata and controls
9214 lines (8114 loc) · 345 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import databaseService, { DbMessage } from '../services/database.js';
import { MeshMessage } from '../types/message.js';
import meshtasticManager from './meshtasticManager.js';
import meshtasticProtobufService from './meshtasticProtobufService.js';
import protobufService from './protobufService.js';
import { VirtualNodeServer } from './virtualNodeServer.js';
// Make meshtasticManager available globally for routes that need it
(global as any).meshtasticManager = meshtasticManager;
import { createRequire } from 'module';
import { logger } from '../utils/logger.js';
import { normalizeTriggerPatterns } from '../utils/autoResponderUtils.js';
import { getSessionMiddleware } from './auth/sessionConfig.js';
import { initializeWebSocket } from './services/webSocketService.js';
import { initializeOIDC } from './auth/oidcAuth.js';
import { optionalAuth, requireAuth, requirePermission, requireAdmin, hasPermission } from './auth/authMiddleware.js';
import { apiLimiter } from './middleware/rateLimiters.js';
import { setupAccessLogger } from './middleware/accessLogger.js';
import { getEnvironmentConfig, resetEnvironmentConfig } from './config/environment.js';
import { pushNotificationService } from './services/pushNotificationService.js';
import { appriseNotificationService } from './services/appriseNotificationService.js';
import { deviceBackupService } from './services/deviceBackupService.js';
import { backupFileService } from './services/backupFileService.js';
import { backupSchedulerService } from './services/backupSchedulerService.js';
import { databaseMaintenanceService } from './services/databaseMaintenanceService.js';
import { systemBackupService } from './services/systemBackupService.js';
import { systemRestoreService } from './services/systemRestoreService.js';
import { duplicateKeySchedulerService } from './services/duplicateKeySchedulerService.js';
import { solarMonitoringService } from './services/solarMonitoringService.js';
import { newsService } from './services/newsService.js';
import { inactiveNodeNotificationService } from './services/inactiveNodeNotificationService.js';
import { serverEventNotificationService } from './services/serverEventNotificationService.js';
import { autoDeleteByDistanceService } from './services/autoDeleteByDistanceService.js';
import { getUserNotificationPreferencesAsync, saveUserNotificationPreferencesAsync, applyNodeNamePrefixAsync } from './utils/notificationFiltering.js';
import { upgradeService } from './services/upgradeService.js';
import { enhanceNodeForClient, filterNodesByChannelPermission, checkNodeChannelAccess } from './utils/nodeEnhancer.js';
import { dynamicCspMiddleware, refreshTileHostnameCache } from './middleware/dynamicCsp.js';
import { generateAnalyticsScript, AnalyticsProvider } from './utils/analyticsScriptGenerator.js';
import { PortNum } from './constants/meshtastic.js';
import settingsRoutes, { setSettingsCallbacks } from './routes/settingsRoutes.js';
const require = createRequire(import.meta.url);
const packageJson = require('../../package.json');
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Load .env file in development mode
// dotenv/config automatically loads .env from project root
// This must run before getEnvironmentConfig() is called
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line @typescript-eslint/no-require-imports
require('dotenv/config');
// Reset cached environment config to ensure .env values are loaded
resetEnvironmentConfig();
logger.info('📄 Loaded .env file from project root (if present)');
}
// Load environment configuration (after .env is loaded)
const env = getEnvironmentConfig();
/**
* Gets the scripts directory path.
* In development, uses relative path from project root (data/scripts).
* In production, uses absolute path (/data/scripts).
*/
const getScriptsDirectory = (): string => {
if (env.isDevelopment) {
// In development, use relative path from project root
const projectRoot = path.resolve(__dirname, '../../');
const devScriptsDir = path.join(projectRoot, 'data', 'scripts');
// Ensure directory exists
if (!fs.existsSync(devScriptsDir)) {
fs.mkdirSync(devScriptsDir, { recursive: true });
logger.info(`📁 Created scripts directory: ${devScriptsDir}`);
}
return devScriptsDir;
}
// In production, use absolute path
return '/data/scripts';
};
/**
* Converts a script path to the actual file system path.
* Handles both /data/scripts/... (stored format) and actual file paths.
*/
const resolveScriptPath = (scriptPath: string): string | null => {
// Validate script path (security check)
if (!scriptPath.startsWith('/data/scripts/') || scriptPath.includes('..')) {
logger.error(`🚫 Invalid script path: ${scriptPath}`);
return null;
}
const scriptsDir = getScriptsDirectory();
const filename = path.basename(scriptPath);
const resolvedPath = path.join(scriptsDir, filename);
// Additional security: ensure resolved path is within scripts directory
const normalizedResolved = path.normalize(resolvedPath);
const normalizedScriptsDir = path.normalize(scriptsDir);
if (!normalizedResolved.startsWith(normalizedScriptsDir)) {
logger.error(`🚫 Script path resolves outside scripts directory: ${scriptPath}`);
return null;
}
return normalizedResolved;
};
const app = express();
const PORT = env.port;
const BASE_URL = env.baseUrl;
const serverStartTime = Date.now();
// Custom JSON replacer to handle BigInt values
const jsonReplacer = (_key: string, value: any) => {
if (typeof value === 'bigint') {
return value.toString();
}
return value;
};
// Override JSON.stringify to handle BigInt
const originalStringify = JSON.stringify;
JSON.stringify = function (value, replacer?: any, space?: any) {
if (replacer) {
return originalStringify(value, replacer, space);
}
return originalStringify(value, jsonReplacer, space);
};
// Trust proxy configuration for reverse proxy deployments
// When behind a reverse proxy (nginx, Traefik, etc.), this allows Express to:
// - Read X-Forwarded-* headers to determine the actual client protocol/IP
// - Set secure cookies correctly when the proxy terminates HTTPS
if (env.trustProxyProvided) {
app.set('trust proxy', env.trustProxy);
logger.debug(`✅ Trust proxy configured: ${env.trustProxy}`);
} else if (env.isProduction) {
// Default: trust first proxy in production (common reverse proxy setup)
app.set('trust proxy', 1);
logger.debug('ℹ️ Trust proxy defaulted to 1 hop (production mode)');
}
// Security: Helmet.js for HTTP security headers
// Use relaxed settings in development to avoid HTTPS enforcement
// For Quick Start: default to HTTP-friendly (no HSTS) even in production
// Only enable HSTS when COOKIE_SECURE explicitly set to 'true'
// CSP is handled dynamically by dynamicCspMiddleware to support custom tile servers
const helmetConfig =
env.isProduction && env.cookieSecure
? {
contentSecurityPolicy: false, // Handled by dynamicCspMiddleware
hsts: {
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true,
},
frameguard: {
action: 'deny' as const,
},
noSniff: true,
xssFilter: true,
// Send origin as Referer for cross-origin requests (e.g. map tile fetches).
// Helmet defaults to no-referrer which violates OSM tile usage policy.
referrerPolicy: { policy: 'strict-origin-when-cross-origin' as const },
}
: {
// Development or HTTP-only: no HSTS
contentSecurityPolicy: false, // Handled by dynamicCspMiddleware
hsts: false, // Disable HSTS when not using secure cookies or in development
crossOriginOpenerPolicy: false, // Disable COOP for HTTP - browser ignores it on non-HTTPS anyway
frameguard: {
action: 'deny' as const,
},
noSniff: true,
xssFilter: true,
referrerPolicy: { policy: 'strict-origin-when-cross-origin' as const },
};
app.use(helmet(helmetConfig));
// Dynamic CSP middleware - adds custom tile server hostnames from database
app.use(dynamicCspMiddleware(env.isProduction, env.cookieSecure));
// Security: CORS configuration with allowed origins
const getAllowedOrigins = () => {
const origins = [...env.allowedOrigins];
// Always allow localhost in development
if (env.isDevelopment) {
origins.push('http://localhost:3000', 'http://localhost:5173', 'http://localhost:8080');
}
return origins.length > 0 ? origins : ['http://localhost:3000'];
};
// Embed origin cache (refreshes every 60 seconds)
let embedOriginsCache: string[] = [];
let embedOriginsCacheTime = 0;
const EMBED_ORIGINS_CACHE_TTL = 60000;
/** Convert protobuf bytes (Uint8Array, Buffer, byte array, or object) to base64 string */
function bytesToBase64(key: any): string {
if (key instanceof Uint8Array || Buffer.isBuffer(key)) {
return Buffer.from(key).toString('base64');
}
if (key && typeof key === 'object' && key.type === 'Buffer' && Array.isArray(key.data)) {
return Buffer.from(key.data).toString('base64');
}
if (Array.isArray(key)) {
return Buffer.from(key).toString('base64');
}
if (typeof key === 'string') {
return key;
}
// Handle generic iterables/objects with byte data (e.g., protobuf Bytes wrappers)
if (key && typeof key === 'object') {
try {
return Buffer.from(Object.values(key) as number[]).toString('base64');
} catch {
// fall through
}
}
logger.warn('Unknown admin key format:', typeof key, key);
return '';
}
function refreshEmbedOriginsCache(): void {
databaseService.embedProfiles.getAllAsync().then(profiles => {
embedOriginsCache = [...new Set(
profiles.filter(p => p.enabled).flatMap(p => p.allowedOrigins)
)];
embedOriginsCacheTime = Date.now();
}).catch(() => {
// On error, keep stale cache
});
}
function getEmbedAllowedOrigins(): string[] {
if (Date.now() - embedOriginsCacheTime < EMBED_ORIGINS_CACHE_TTL) {
return embedOriginsCache;
}
// Fire async lookup, use stale cache until it resolves
refreshEmbedOriginsCache();
return embedOriginsCache;
}
app.use(
cors({
origin: (origin, callback) => {
const allowedOrigins = getAllowedOrigins();
// Allow requests with no origin (mobile apps, Postman, same-origin)
if (!origin) return callback(null, true);
if (allowedOrigins.includes(origin) || allowedOrigins.includes('*')) {
return callback(null, true);
}
// Check embed profile origins
const embedOrigins = getEmbedAllowedOrigins();
if (embedOrigins.includes(origin) || embedOrigins.includes('*')) {
return callback(null, true);
}
logger.warn(`CORS request blocked from origin: ${origin}`);
callback(new Error('Not allowed by CORS'));
},
credentials: true,
optionsSuccessStatus: 200,
allowedHeaders: ['Content-Type', 'X-CSRF-Token', 'Authorization'],
})
);
// Access logging for fail2ban (optional, configured via ACCESS_LOG_ENABLED)
const accessLogger = setupAccessLogger();
if (accessLogger) {
app.use(accessLogger);
}
// Security: Request body size limits
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true, parameterLimit: 1000 }));
// Session middleware (shared with WebSocket for authentication)
const sessionMiddleware = getSessionMiddleware();
app.use(sessionMiddleware);
// Security: CSRF protection middleware
import { csrfTokenMiddleware, csrfProtection, csrfTokenEndpoint } from './middleware/csrf.js';
app.use(csrfTokenMiddleware); // Generate and attach tokens to all requests
// csrfProtection applied to API routes below (after CSRF token endpoint)
// Initialize OIDC if configured
initializeOIDC()
.then(enabled => {
if (enabled) {
logger.debug('✅ OIDC authentication enabled');
} else {
logger.debug('ℹ️ OIDC authentication disabled (not configured)');
}
})
.catch(error => {
logger.error('Failed to initialize OIDC:', error);
});
// Function to initialize virtual node server after config capture is complete
async function initializeOrRefreshVirtualNodeServer(): Promise<void> {
// If already initialized, refresh all connected clients with fresh config
// This handles physical node reconnection: clients get updated channel/config data
// through the proper sendInitialConfig() flow (fixes #1567)
if ((global as any).virtualNodeServer) {
logger.info('Virtual node server already initialized, refreshing connected clients with fresh config');
try {
await ((global as any).virtualNodeServer as VirtualNodeServer).refreshAllClients();
} catch (error) {
logger.error('❌ Failed to refresh virtual node clients:', error);
}
return;
}
if (env.enableVirtualNode) {
try {
const virtualNodeServer = new VirtualNodeServer({
port: env.virtualNodePort,
meshtasticManager: meshtasticManager,
allowAdminCommands: env.virtualNodeAllowAdminCommands,
});
await virtualNodeServer.start();
logger.info(`🌐 Virtual node server started on port ${env.virtualNodePort}`);
// Store reference for cleanup
(global as any).virtualNodeServer = virtualNodeServer;
} catch (error) {
logger.error('❌ Failed to start virtual node server:', error);
logger.warn('⚠️ Continuing without virtual node server');
}
} else {
logger.debug('Virtual node server disabled (ENABLE_VIRTUAL_NODE=false)');
}
}
// Register callback to initialize virtual node server when config capture completes
// On first connection: starts the virtual node server
// On reconnection: refreshes all connected clients with fresh config data
meshtasticManager.registerConfigCaptureCompleteCallback(initializeOrRefreshVirtualNodeServer);
// ========== Bootstrap Restore Logic ==========
// Check for RESTORE_FROM_BACKUP environment variable and restore if set
// This MUST happen before services start (per ARCHITECTURE_LESSONS.md)
// IMPORTANT: We mark restore as started immediately to prevent race conditions
// with createAdminIfNeeded() in database.ts
systemRestoreService.markRestoreStarted();
(async () => {
try {
const restoreFromBackup = systemRestoreService.shouldRestore();
if (restoreFromBackup) {
logger.info('🔄 RESTORE_FROM_BACKUP environment variable detected');
logger.info(`📦 Attempting to restore from: ${restoreFromBackup}`);
// Validate restore can proceed
const validation = await systemRestoreService.canRestore(restoreFromBackup);
if (!validation.can) {
logger.error(`❌ Cannot restore from backup: ${validation.reason}`);
logger.error('⚠️ Container will start normally without restore');
systemRestoreService.markRestoreComplete();
return;
}
logger.info('✅ Backup validation passed, starting restore...');
// Restore the system (this happens BEFORE services start)
const result = await systemRestoreService.restoreFromBackup(restoreFromBackup);
if (result.success) {
logger.info('✅ System restore completed successfully!');
logger.info(`📊 Restored ${result.tablesRestored} tables with ${result.rowsRestored} rows`);
if (result.migrationRequired) {
logger.info('⚠️ Schema migration was required and completed');
}
// Audit log to mark restore completion point (after migrations)
databaseService.auditLogAsync(
null, // System action during bootstrap
'system_restore_bootstrap_complete',
'system_backup',
JSON.stringify({
dirname: restoreFromBackup,
tablesRestored: result.tablesRestored,
rowsRestored: result.rowsRestored,
migrationRequired: result.migrationRequired || false,
}),
null // No IP address during startup
);
logger.info('🚀 Continuing with normal startup...');
} else {
logger.error('❌ System restore failed:', result.message);
if (result.errors) {
result.errors.forEach(err => logger.error(` - ${err}`));
}
logger.error('⚠️ Container will start normally with existing database');
}
}
} catch (error) {
logger.error('❌ Fatal error during bootstrap restore:', error);
logger.error('⚠️ Container will start normally with existing database');
} finally {
// CRITICAL: Always mark restore as complete, regardless of outcome
// This allows createAdminIfNeeded() to proceed
systemRestoreService.markRestoreComplete();
}
})();
// Initialize Meshtastic connection
setTimeout(async () => {
try {
// Wait for database initialization (critical for PostgreSQL/MySQL where repos are async)
await databaseService.waitForReady();
// Load saved traceroute interval from database before connecting
const savedInterval = await databaseService.settings.getSetting('tracerouteIntervalMinutes');
if (savedInterval !== null) {
const intervalMinutes = parseInt(savedInterval);
if (!isNaN(intervalMinutes) && intervalMinutes >= 0 && intervalMinutes <= 60) {
meshtasticManager.setTracerouteInterval(intervalMinutes);
logger.debug(
`✅ Loaded saved traceroute interval: ${intervalMinutes} minutes${intervalMinutes === 0 ? ' (disabled)' : ''}`
);
}
}
// Load auto key repair settings
const keyRepairEnabled = await databaseService.settings.getSetting('autoKeyManagementEnabled');
const keyRepairInterval = await databaseService.settings.getSetting('autoKeyManagementIntervalMinutes');
const keyRepairMaxExchanges = await databaseService.settings.getSetting('autoKeyManagementMaxExchanges');
const keyRepairAutoPurge = await databaseService.settings.getSetting('autoKeyManagementAutoPurge');
const keyRepairImmediatePurge = await databaseService.settings.getSetting('autoKeyManagementImmediatePurge');
meshtasticManager.setKeyRepairSettings({
enabled: keyRepairEnabled === 'true',
intervalMinutes: keyRepairInterval ? parseInt(keyRepairInterval) : 5,
maxExchanges: keyRepairMaxExchanges ? parseInt(keyRepairMaxExchanges) : 3,
autoPurge: keyRepairAutoPurge === 'true',
immediatePurge: keyRepairImmediatePurge === 'true'
});
logger.debug('✅ Loaded auto key repair settings');
// Load remote admin scanner interval
const remoteAdminScannerInterval = await databaseService.settings.getSetting('remoteAdminScannerIntervalMinutes');
if (remoteAdminScannerInterval !== null) {
const intervalMinutes = parseInt(remoteAdminScannerInterval);
if (!isNaN(intervalMinutes) && intervalMinutes >= 0 && intervalMinutes <= 60) {
meshtasticManager.setRemoteAdminScannerInterval(intervalMinutes);
logger.debug(
`✅ Loaded saved remote admin scanner interval: ${intervalMinutes} minutes${intervalMinutes === 0 ? ' (disabled)' : ''}`
);
}
}
// Load LocalStats collection interval
const localStatsInterval = await databaseService.settings.getSetting('localStatsIntervalMinutes');
if (localStatsInterval !== null) {
const intervalMinutes = parseInt(localStatsInterval);
if (!isNaN(intervalMinutes) && intervalMinutes >= 0 && intervalMinutes <= 60) {
meshtasticManager.setLocalStatsInterval(intervalMinutes);
logger.debug(
`✅ Loaded saved LocalStats interval: ${intervalMinutes} minutes${intervalMinutes === 0 ? ' (disabled)' : ''}`
);
}
}
// NOTE: We no longer mark existing nodes as welcomed on startup.
// This is now handled when autoWelcomeEnabled is first changed to 'true'
// via the settings endpoint. This prevents welcoming existing nodes when
// the feature is enabled after nodes are already in the database.
// Clear any runtime IP/port overrides from previous sessions
// These are temporary settings that should reset on container restart
await databaseService.settings.setSetting('meshtasticNodeIpOverride', '');
await databaseService.settings.setSetting('meshtasticTcpPortOverride', '');
await meshtasticManager.connect();
logger.debug('Meshtastic manager connected successfully');
// Initialize backup scheduler
backupSchedulerService.initialize(meshtasticManager);
logger.debug('Backup scheduler initialized');
// Initialize duplicate key scanner
duplicateKeySchedulerService.start();
logger.debug('Duplicate key scanner initialized');
// Initialize solar monitoring service
solarMonitoringService.initialize();
logger.debug('Solar monitoring service initialized');
// Initialize news service (fetches news from meshmonitor.org)
newsService.initialize();
logger.debug('News service initialized');
// Initialize database maintenance service
databaseMaintenanceService.initialize();
logger.debug('Database maintenance service initialized');
// Start inactive node notification service with validation
const inactiveThresholdHoursRaw = parseInt(await databaseService.settings.getSetting('inactiveNodeThresholdHours') || '24', 10);
const inactiveCheckIntervalMinutesRaw = parseInt(
await databaseService.settings.getSetting('inactiveNodeCheckIntervalMinutes') || '60',
10
);
const inactiveCooldownHoursRaw = parseInt(await databaseService.settings.getSetting('inactiveNodeCooldownHours') || '24', 10);
// Validate and use defaults if invalid values are found in database
const inactiveThresholdHours =
!isNaN(inactiveThresholdHoursRaw) && inactiveThresholdHoursRaw >= 1 && inactiveThresholdHoursRaw <= 720
? inactiveThresholdHoursRaw
: 24;
const inactiveCheckIntervalMinutes =
!isNaN(inactiveCheckIntervalMinutesRaw) &&
inactiveCheckIntervalMinutesRaw >= 1 &&
inactiveCheckIntervalMinutesRaw <= 1440
? inactiveCheckIntervalMinutesRaw
: 60;
const inactiveCooldownHours =
!isNaN(inactiveCooldownHoursRaw) && inactiveCooldownHoursRaw >= 1 && inactiveCooldownHoursRaw <= 720
? inactiveCooldownHoursRaw
: 24;
// Log warning if invalid values were found and corrected
if (
inactiveThresholdHours !== inactiveThresholdHoursRaw ||
inactiveCheckIntervalMinutes !== inactiveCheckIntervalMinutesRaw ||
inactiveCooldownHours !== inactiveCooldownHoursRaw
) {
logger.warn(
`⚠️ Invalid inactive node notification settings found in database, using defaults (threshold: ${inactiveThresholdHours}h, check: ${inactiveCheckIntervalMinutes}min, cooldown: ${inactiveCooldownHours}h)`
);
}
inactiveNodeNotificationService.start(inactiveThresholdHours, inactiveCheckIntervalMinutes, inactiveCooldownHours);
logger.info('✅ Inactive node notification service started');
// Start auto-delete-by-distance service if enabled
const autoDeleteByDistanceEnabled = await databaseService.settings.getSetting('autoDeleteByDistanceEnabled');
if (autoDeleteByDistanceEnabled === 'true') {
const intervalHours = parseInt(await databaseService.settings.getSetting('autoDeleteByDistanceIntervalHours') || '24', 10);
autoDeleteByDistanceService.start(intervalHours);
}
// Note: Virtual node server initialization has been moved to a callback
// that triggers when config capture completes (see registerConfigCaptureCompleteCallback above)
} catch (error) {
logger.error('Failed to connect to Meshtastic node on startup:', error);
// Virtual node server will still initialize on successful reconnection
// via the registered callback
}
}, 1000);
// Schedule hourly telemetry purge to keep database performant
// Keep telemetry for 7 days (168 hours) by default
const TELEMETRY_RETENTION_HOURS = 168; // 7 days
setInterval(async () => {
try {
// Get favorite telemetry storage days from settings (defaults to 7 if not set)
const favoriteDaysStr = await databaseService.settings.getSetting('favoriteTelemetryStorageDays');
const favoriteDays = favoriteDaysStr ? parseInt(favoriteDaysStr) : 7;
const purgedCount = await databaseService.purgeOldTelemetryAsync(TELEMETRY_RETENTION_HOURS, favoriteDays);
if (purgedCount > 0) {
logger.debug(`⏰ Hourly telemetry purge completed: removed ${purgedCount} records`);
}
} catch (error) {
logger.error('Error during telemetry purge:', error);
}
}, 60 * 60 * 1000); // Run every hour
// Run initial purge on startup
setTimeout(async () => {
try {
// Get favorite telemetry storage days from settings (defaults to 7 if not set)
const favoriteDaysStr = await databaseService.settings.getSetting('favoriteTelemetryStorageDays');
const favoriteDays = favoriteDaysStr ? parseInt(favoriteDaysStr) : 7;
await databaseService.purgeOldTelemetryAsync(TELEMETRY_RETENTION_HOURS, favoriteDays);
} catch (error) {
logger.error('Error during initial telemetry purge:', error);
}
}, 5000); // Wait 5 seconds after startup
// ==========================================
// Scheduled Auto-Upgrade Check
// ==========================================
// Check for updates every 4 hours server-side to enable unattended upgrades
// This allows auto-upgrade to work without requiring a frontend to be open
const AUTO_UPGRADE_CHECK_INTERVAL_MS = 4 * 60 * 60 * 1000; // 4 hours
async function checkForAutoUpgrade(): Promise<void> {
// Skip if version check is disabled
if (env.versionCheckDisabled) {
return;
}
// Skip if auto-upgrade is not enabled
if (!upgradeService.isEnabled()) {
return;
}
// Skip if autoUpgradeImmediate is not enabled
const autoUpgradeImmediate = await databaseService.settings.getSetting('autoUpgradeImmediate') === 'true';
if (!autoUpgradeImmediate) {
return;
}
try {
logger.debug('🔄 Running scheduled auto-upgrade check...');
// Fetch latest release from GitHub
const response = await fetch('https://api.github.com/repos/Yeraze/meshmonitor/releases/latest');
if (!response.ok) {
logger.warn(`GitHub API returned ${response.status} for scheduled version check`);
return;
}
const release = await response.json();
const currentVersion = packageJson.version;
const latestVersionRaw = release.tag_name;
// Strip 'v' prefix from version strings for comparison
const latestVersion = latestVersionRaw.replace(/^v/, '');
const current = currentVersion.replace(/^v/, '');
// Simple semantic version comparison
const isNewerVersion = compareVersions(latestVersion, current) > 0;
if (!isNewerVersion) {
logger.debug(`✓ Already on latest version (${currentVersion})`);
return;
}
// Check if Docker image exists for this version
const imageReady = await checkDockerImageExists(latestVersion, release.published_at);
if (!imageReady) {
logger.debug(`⏳ Update available (${latestVersion}) but Docker image not ready yet`);
return;
}
// Check if an upgrade is already in progress
const inProgress = await upgradeService.isUpgradeInProgress();
if (inProgress) {
logger.debug('ℹ️ Scheduled auto-upgrade skipped: upgrade already in progress');
return;
}
// Trigger the upgrade
logger.info(`🚀 Scheduled auto-upgrade: triggering upgrade to ${latestVersion}`);
const upgradeResult = await upgradeService.triggerUpgrade(
{ targetVersion: latestVersion, backup: true },
currentVersion,
'system-scheduled-auto-upgrade'
);
if (upgradeResult.success) {
logger.info(`✅ Scheduled auto-upgrade triggered successfully: ${upgradeResult.upgradeId}`);
databaseService.auditLogAsync(
null,
'auto_upgrade_triggered',
'system',
`Scheduled auto-upgrade initiated: ${currentVersion} → ${latestVersion}`,
null
);
} else {
if (upgradeResult.message === 'An upgrade is already in progress') {
logger.debug('ℹ️ Scheduled auto-upgrade skipped: upgrade started by another process');
} else {
logger.warn(`⚠️ Scheduled auto-upgrade failed to trigger: ${upgradeResult.message}`);
}
}
} catch (error) {
logger.error('❌ Error during scheduled auto-upgrade check:', error);
}
}
// Schedule periodic auto-upgrade check (every 4 hours)
setInterval(() => {
checkForAutoUpgrade().catch(error => {
logger.error('Error in scheduled auto-upgrade check:', error);
});
}, AUTO_UPGRADE_CHECK_INTERVAL_MS);
// Run initial auto-upgrade check after a delay to allow system to stabilize
setTimeout(() => {
checkForAutoUpgrade().catch(error => {
logger.error('Error in initial auto-upgrade check:', error);
});
}, 60 * 1000); // Wait 1 minute after startup
// Create router for API routes
const apiRouter = express.Router();
// Import route handlers
import authRoutes from './routes/authRoutes.js';
import userRoutes from './routes/userRoutes.js';
import auditRoutes from './routes/auditRoutes.js';
import securityRoutes from './routes/securityRoutes.js';
import packetRoutes from './routes/packetRoutes.js';
import solarRoutes from './routes/solarRoutes.js';
import upgradeRoutes from './routes/upgradeRoutes.js';
import messageRoutes from './routes/messageRoutes.js';
import linkPreviewRoutes from './routes/linkPreviewRoutes.js';
import scriptContentRoutes from './routes/scriptContentRoutes.js';
import apiTokenRoutes from './routes/apiTokenRoutes.js';
import mfaRoutes from './routes/mfaRoutes.js';
import channelDatabaseRoutes from './routes/channelDatabaseRoutes.js';
import newsRoutes from './routes/newsRoutes.js';
import tileServerRoutes from './routes/tileServerTest.js';
import v1Router from './routes/v1/index.js';
import meshcoreRoutes from './routes/meshcoreRoutes.js';
import embedProfileRoutes from './routes/embedProfileRoutes.js';
import { createEmbedCspMiddleware } from './middleware/embedMiddleware.js';
import embedPublicRoutes from './routes/embedPublicRoutes.js';
import firmwareUpdateRoutes from './routes/firmwareUpdateRoutes.js';
import { firmwareUpdateService } from './services/firmwareUpdateService.js';
// CSRF token endpoint (must be before CSRF protection middleware)
apiRouter.get('/csrf-token', csrfTokenEndpoint);
// Health check endpoint (for upgrade watchdog and monitoring)
apiRouter.get('/health', (_req, res) => {
res.json({
status: 'ok',
version: packageJson.version,
uptime: Date.now() - serverStartTime,
databaseType: databaseService.drizzleDbType,
firmwareOtaEnabled: process.env.IS_DESKTOP !== 'true',
});
});
// Server info endpoint (returns timezone and other server configuration)
apiRouter.get('/server-info', (_req, res) => {
res.json({
timezone: env.timezone,
timezoneProvided: env.timezoneProvided,
});
});
// Debug endpoint for IP detection (development only)
// Helps diagnose reverse proxy and rate limiting issues
if (!env.isProduction) {
apiRouter.get('/debug/ip', (req, res) => {
res.json({
'req.ip': req.ip,
'req.ips': req.ips,
'x-forwarded-for': req.headers['x-forwarded-for'],
'x-real-ip': req.headers['x-real-ip'],
'trust-proxy': app.get('trust proxy'),
note: 'The rate limiter uses req.ip to identify clients',
});
});
}
// Authentication routes
apiRouter.use('/auth', authRoutes);
// API Token management routes (requires auth)
apiRouter.use('/token', apiTokenRoutes);
// MFA management routes (requires auth)
apiRouter.use('/mfa', mfaRoutes);
// v1 API routes (requires API token)
apiRouter.use('/v1', v1Router);
// User management routes (admin only)
apiRouter.use('/users', userRoutes);
// Audit log routes (admin only)
apiRouter.use('/audit', auditRoutes);
// Channel database routes (admin only, session-based)
apiRouter.use('/channel-database', channelDatabaseRoutes);
// Security routes (requires security:read)
apiRouter.use('/security', securityRoutes);
// Packet log routes (requires channels:read AND messages:read)
apiRouter.use('/packets', optionalAuth(), packetRoutes);
// Solar monitoring routes
apiRouter.use('/solar', optionalAuth(), solarRoutes);
// News routes (public feed, authenticated status endpoints)
apiRouter.use('/news', newsRoutes);
// Upgrade routes (requires authentication)
apiRouter.use('/upgrade', upgradeRoutes);
// Message routes (requires appropriate write permissions)
apiRouter.use('/messages', optionalAuth(), messageRoutes);
// MeshCore routes (for MeshCore device monitoring)
// Authentication handled per-route in meshcoreRoutes.ts
// Enable with MESHCORE_ENABLED=true in .env
if (process.env.MESHCORE_ENABLED === 'true') {
apiRouter.use('/meshcore', meshcoreRoutes);
}
// Link preview routes
apiRouter.use('/', linkPreviewRoutes);
// Script content proxy routes (for User Scripts Gallery)
apiRouter.use('/', scriptContentRoutes);
// Tile server testing routes (for Custom Tileset Manager autodetect)
apiRouter.use('/tile-server', optionalAuth(), tileServerRoutes);
// Settings routes (GET/POST/DELETE /settings)
apiRouter.use('/settings', settingsRoutes);
// Embed profile admin routes (admin only)
apiRouter.use('/embed-profiles', embedProfileRoutes);
// Firmware OTA update routes (admin only)
apiRouter.use('/firmware', firmwareUpdateRoutes);
// Wire up side-effect callbacks for settingsRoutes
setSettingsCallbacks({
refreshTileHostnameCache,
setTracerouteInterval: (interval) => meshtasticManager.setTracerouteInterval(interval),
setRemoteAdminScannerInterval: (interval) => meshtasticManager.setRemoteAdminScannerInterval(interval),
setLocalStatsInterval: (interval) => meshtasticManager.setLocalStatsInterval(interval),
setKeyRepairSettings: (settings) => meshtasticManager.setKeyRepairSettings(settings),
restartInactiveNodeService: (threshold, check, cooldown) =>
inactiveNodeNotificationService.start(threshold, check, cooldown),
stopInactiveNodeService: () => inactiveNodeNotificationService.stop(),
restartAnnounceScheduler: () => meshtasticManager.restartAnnounceScheduler(),
restartTimerScheduler: () => meshtasticManager.restartTimerScheduler(),
restartGeofenceEngine: () => meshtasticManager.restartGeofenceEngine(),
handleAutoWelcomeEnabled: () => { databaseService.handleAutoWelcomeEnabledAsync().catch(() => {}); return 0; },
invalidateHtmlCache,
restartAutoDeleteByDistanceService: (intervalHours: number) =>
autoDeleteByDistanceService.start(intervalHours),
stopAutoDeleteByDistanceService: () => autoDeleteByDistanceService.stop(),
});
// API Routes
/**
* GET /api/nodes
* Returns all nodes in the mesh
*/
apiRouter.get('/nodes', optionalAuth(), async (req, res) => {
try {
const allNodes = await meshtasticManager.getAllNodesAsync();
const estimatedPositions = await databaseService.getAllNodesEstimatedPositionsAsync();
// Filter nodes based on channel read permissions
const filteredNodes = await filterNodesByChannelPermission(allNodes, (req as any).user);
const enhancedNodes = await Promise.all(filteredNodes.map(node => enhanceNodeForClient(node, (req as any).user, estimatedPositions)));
res.json(enhancedNodes);
} catch (error) {
logger.error('Error fetching nodes:', error);
res.status(500).json({ error: 'Failed to fetch nodes' });
}
});
apiRouter.get('/nodes/active', optionalAuth(), async (req, res) => {
try {
const days = parseInt(req.query.days as string) || 7;
const allDbNodes = await databaseService.nodes.getActiveNodes(days);
// Filter nodes based on channel read permissions
const dbNodes = await filterNodesByChannelPermission(allDbNodes, (req as any).user);
// Map raw DB nodes to DeviceInfo format then enhance
const maskedNodes = await Promise.all(dbNodes.map(async node => {
// Map basic fields
const deviceInfo: any = {
nodeNum: node.nodeNum,
user: { id: node.nodeId, longName: node.longName, shortName: node.shortName },
mobile: node.mobile,
positionOverrideEnabled: Boolean(node.positionOverrideEnabled),
latitudeOverride: node.latitudeOverride,
longitudeOverride: node.longitudeOverride,
altitudeOverride: node.altitudeOverride,
positionOverrideIsPrivate: Boolean(node.positionOverrideIsPrivate)
};
if (node.latitude && node.longitude) {
deviceInfo.position = { latitude: node.latitude, longitude: node.longitude, altitude: node.altitude };
}
return enhanceNodeForClient(deviceInfo, (req as any).user);
}));
res.json(maskedNodes);
} catch (error) {
logger.error('Error fetching active nodes:', error);
res.status(500).json({ error: 'Failed to fetch active nodes' });
}
});
// Get position history for a node (for mobile node visualization)
apiRouter.get('/nodes/:nodeId/position-history', optionalAuth(), async (req, res) => {
try {
const { nodeId } = req.params;
// Check channel-based access for this node
if (!await checkNodeChannelAccess(nodeId, req.user)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
// Allow hours parameter for future use, but default to fetching ALL position history
// This ensures we capture movement that may have happened long ago
// Validate hours: must be positive integer, max 8760 (1 year)
const rawHours = req.query.hours ? parseInt(req.query.hours as string) : null;
const hoursParam = rawHours !== null && !isNaN(rawHours) && rawHours > 0
? Math.min(rawHours, 8760)
: null;
const cutoffTime = hoursParam ? Date.now() - hoursParam * 60 * 60 * 1000 : 0;
// Check privacy for position history
const nodeNum = parseInt(nodeId.replace('!', ''), 16);
const node = await databaseService.nodes.getNode(nodeNum);
const isPrivate = node?.positionOverrideIsPrivate === true;
const canViewPrivate = !!req.user && await hasPermission(req.user, 'nodes_private', 'read');
if (isPrivate && !canViewPrivate) {
res.json([]);
return;
}
// Get only position-related telemetry (lat/lon/alt/speed/track) for the node - much more efficient!
const positionTelemetry = await databaseService.getPositionTelemetryByNodeAsync(nodeId, 1500, cutoffTime);
// Group by timestamp to get lat/lon pairs with optional speed/track
const positionMap = new Map<number, { lat?: number; lon?: number; alt?: number; groundSpeed?: number; groundTrack?: number }>();
positionTelemetry.forEach(t => {
if (!positionMap.has(t.timestamp)) {
positionMap.set(t.timestamp, {});
}
const pos = positionMap.get(t.timestamp)!;
if (t.telemetryType === 'latitude') {
pos.lat = t.value;
} else if (t.telemetryType === 'longitude') {
pos.lon = t.value;
} else if (t.telemetryType === 'altitude') {
pos.alt = t.value;
} else if (t.telemetryType === 'ground_speed') {
pos.groundSpeed = t.value;
} else if (t.telemetryType === 'ground_track') {
pos.groundTrack = t.value;
}
});
// Convert to array of positions, filter incomplete ones
const positions = Array.from(positionMap.entries())
.filter(([_timestamp, pos]) => pos.lat !== undefined && pos.lon !== undefined)
.map(([timestamp, pos]) => ({
timestamp,
latitude: pos.lat!,
longitude: pos.lon!,
altitude: pos.alt,
groundSpeed: pos.groundSpeed,
groundTrack: pos.groundTrack,
}))
.sort((a, b) => a.timestamp - b.timestamp);
res.json(positions);
} catch (error) {
logger.error('Error fetching position history:', error);
res.status(500).json({ error: 'Failed to fetch position history' });
}
});
// Alternative endpoint with limit parameter for fetching positions
apiRouter.get('/nodes/:nodeId/positions', optionalAuth(), async (req, res) => {
try {
const { nodeId } = req.params;
// Check channel-based access for this node
if (!await checkNodeChannelAccess(nodeId, req.user)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
const limit = req.query.limit ? parseInt(req.query.limit as string) : 2000;
// Get only position-related telemetry (lat/lon/alt) for the node