-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1058 lines (943 loc) · 37 KB
/
Copy pathserver.js
File metadata and controls
1058 lines (943 loc) · 37 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
require('dotenv').config();
const http = require('http');
const path = require('path');
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { WebSocketServer, WebSocket } = require('ws');
const app = express();
const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'fogbot_nmdc_sih2026_super_secret_jwt_key_98231';
// Create HTTP Server & attach Express + WebSocket Server
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Serve static frontend files (index.html, style.css, script.js, assets)
app.use(express.static(path.join(__dirname)));
// Direct favicon handler
app.get('/favicon.ico', (req, res) => {
res.sendFile(path.join(__dirname, 'assets', 'rover.png'));
});
// Track database connection status
let isDbConnected = false;
// Multi-role in-memory fallback store (supports zero-config cloud deployments e.g. Render free tier)
const fallbackUsers = [
{
id: 1,
user_id: 'admin',
password_hash: 'password123',
role: 'admin',
full_name: 'Chief Systems Engineer',
created_at: new Date().toISOString()
},
{
id: 2,
user_id: 'operator',
password_hash: 'operator123',
role: 'operator',
full_name: 'Pit Control Dispatcher',
created_at: new Date().toISOString()
},
{
id: 3,
user_id: 'driver',
password_hash: 'driver123',
role: 'field_worker',
full_name: 'CAT 777D Haul Truck Driver',
created_at: new Date().toISOString()
},
{
id: 4,
user_id: 'judge',
password_hash: 'guest123',
role: 'guest',
full_name: 'Visiting SIH 2026 Judge / Auditor',
created_at: new Date().toISOString()
}
];
// MySQL Database Connection Configuration
const poolConfig = process.env.DATABASE_URL || process.env.MYSQL_URL
? {
uri: process.env.DATABASE_URL || process.env.MYSQL_URL,
ssl: process.env.DB_SSL === 'false' ? undefined : { rejectUnauthorized: false }
}
: {
host: process.env.DB_HOST || process.env.MYSQLHOST || 'localhost',
user: process.env.DB_USER || process.env.MYSQLUSER || 'root',
password: process.env.DB_PASSWORD || process.env.MYSQLPASSWORD || '',
database: process.env.DB_NAME || process.env.MYSQLDATABASE || 'login_portal',
port: Number(process.env.DB_PORT || process.env.MYSQLPORT) || 3306,
ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : undefined,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
};
const pool = mysql.createPool(poolConfig);
// Initialize and verify database on startup with role support
(async () => {
try {
const connection = await pool.getConnection();
isDbConnected = true;
const dbName = process.env.DB_NAME || process.env.MYSQLDATABASE || 'login_portal';
console.log(`[Database] Connected to MySQL database "${dbName}" successfully.`);
// Auto-create users table with role and full_name
await connection.query(`
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id VARCHAR(50) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
role VARCHAR(20) NOT NULL DEFAULT 'operator',
full_name VARCHAR(100) NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Ensure columns exist if table was previously created with older schema
try {
const [columns] = await connection.query(`SHOW COLUMNS FROM users LIKE 'role'`);
if (columns.length === 0) {
await connection.query(`ALTER TABLE users ADD COLUMN role VARCHAR(20) NOT NULL DEFAULT 'operator'`);
await connection.query(`ALTER TABLE users ADD COLUMN full_name VARCHAR(100) NOT NULL DEFAULT ''`);
}
} catch (e) {
// Column check ignore
}
// Seed default multi-role accounts
for (const u of fallbackUsers) {
await connection.query(`
INSERT INTO users (user_id, password_hash, role, full_name)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
role = VALUES(role),
full_name = VALUES(full_name)
`, [u.user_id, u.password_hash, u.role, u.full_name]);
}
console.log('[Database] Schema verified: users table provisioned with multi-role accounts.');
connection.release();
} catch (err) {
isDbConnected = false;
console.warn(`[Database Warning] Could not connect to MySQL: ${err.message || err.code || err}`);
console.warn('[Database Notice] Running in demo mode with in-memory multi-role store (Admin, Operator, Field Worker, Guest).');
}
})();
// =========================================================================
// CENTRAL MASTER TELEMETRY SIMULATION & STATE ENGINE
// =========================================================================
let scanPointsCache = null;
try {
const pointsPath = path.join(__dirname, 'assets', 'scan_points.json');
if (fs.existsSync(pointsPath)) {
scanPointsCache = JSON.parse(fs.readFileSync(pointsPath, 'utf8'));
}
} catch (e) {
scanPointsCache = [];
}
const masterTelemetry = {
roverId: 'ROVER_01',
targetSite: 'NMDC Bailadila Deposit 5',
fogDensity: 14, // 0 to 100 range from slider
visibility: 38, // derived in meters
speed: 24.5, // km/h
speedLimit: 25, // km/h recommended by AI engine
riskLevel: 'LOW', // 'LOW' | 'MEDIUM' | 'HIGH'
obstacleActive: false,
obstacleDist: null,
obstacleX: 0,
gps: {
lat: 18.7052,
lng: 81.2384,
alt: 1182
},
battery: 84.2, // %
gap: 38.5, // distance to haul truck (m)
ttc: 5.6, // Time to Collision (s)
eStop: false, // Emergency Stop override
status: 'AUTONOMOUS ESCORTING',
// Deep AI internals (Admin only)
cameraConfidence: 86, // % (Acts as live optical fog proxy)
lidarConfidence: 94, // %
aiRawMath: {
riskFormula: 'f(gap, v_closing, 1-C_cam, d_obs, road_grade)',
fogWeight: 0.14,
closingVelocityDelta: 0.28,
stoppingEnvelopeM: 14.8
},
updatedAt: new Date().toISOString()
};
// Simulation tick helper
function updateMasterTelemetry() {
const fog = masterTelemetry.fogDensity;
// 1. Calculate Visibility
// Inverse curve: 0% fog -> 55m, 14% -> 38m, 50% -> 15m, 100% -> 3m
masterTelemetry.visibility = Math.max(3, Math.round(55 - (fog * 0.52)));
// 2. Camera confidence as live optical transmissometer proxy
masterTelemetry.cameraConfidence = Math.max(12, Math.round(100 - fog * 0.88));
masterTelemetry.lidarConfidence = Math.max(72, Math.round(98 - fog * 0.15));
// 3. Synthetic obstacle cycling in Sector 3B
const now = Date.now();
if (fog > 45 || masterTelemetry.eStop) {
masterTelemetry.obstacleActive = true;
masterTelemetry.obstacleDist = masterTelemetry.obstacleDist !== null
? Math.max(4.2, Math.round((masterTelemetry.obstacleDist - 0.2) * 10) / 10)
: 14.2;
masterTelemetry.obstacleX = 0.8;
} else {
masterTelemetry.obstacleActive = false;
masterTelemetry.obstacleDist = null;
masterTelemetry.obstacleX = 0;
}
// 4. Risk Level determination
if (masterTelemetry.eStop) {
masterTelemetry.riskLevel = 'HIGH';
masterTelemetry.status = 'EMERGENCY STOPPED';
} else if (masterTelemetry.visibility < 15 || (masterTelemetry.obstacleActive && masterTelemetry.obstacleDist < 12)) {
masterTelemetry.riskLevel = 'HIGH';
masterTelemetry.status = 'CRITICAL HAZARD SLOWDOWN';
} else if (masterTelemetry.visibility < 35 || masterTelemetry.obstacleActive) {
masterTelemetry.riskLevel = 'MEDIUM';
masterTelemetry.status = 'CAUTIONARY ESCORT';
} else {
masterTelemetry.riskLevel = 'LOW';
masterTelemetry.status = 'AUTONOMOUS ESCORTING';
}
// 5. Recommended speed governor limit
if (masterTelemetry.eStop) {
masterTelemetry.speedLimit = 0;
masterTelemetry.speed = 0;
} else if (masterTelemetry.riskLevel === 'HIGH') {
masterTelemetry.speedLimit = 10;
} else if (masterTelemetry.riskLevel === 'MEDIUM') {
masterTelemetry.speedLimit = 22;
} else {
masterTelemetry.speedLimit = 35;
}
// Drive speed converges toward limit
if (!masterTelemetry.eStop) {
const diff = masterTelemetry.speedLimit - masterTelemetry.speed;
masterTelemetry.speed += Math.round((diff * 0.25 + (Math.random() * 0.6 - 0.3)) * 10) / 10;
masterTelemetry.speed = Math.max(0, Math.round(masterTelemetry.speed * 10) / 10);
}
// Convoy gap and TTC
if (masterTelemetry.eStop) {
masterTelemetry.gap = Math.max(18.0, Math.round((masterTelemetry.gap - 0.5) * 10) / 10);
} else {
masterTelemetry.gap = Math.round((36 + (Math.random() * 3 - 1.5)) * 10) / 10;
}
const relV = Math.abs(masterTelemetry.speed - 24) + 4.2;
masterTelemetry.ttc = Math.max(1.5, Math.round((masterTelemetry.gap / relV) * 10) / 10);
// GPS progression
const inc = (masterTelemetry.speed / 3600) * 0.0001;
masterTelemetry.gps.lat = Math.round((masterTelemetry.gps.lat + inc) * 10000) / 10000;
masterTelemetry.gps.lng = Math.round((masterTelemetry.gps.lng + inc * 0.4) * 10000) / 10000;
// Battery drain
masterTelemetry.battery = Math.max(10, Math.round((masterTelemetry.battery - 0.002) * 100) / 100);
// Raw math update
masterTelemetry.aiRawMath.fogWeight = Math.round((fog / 100) * 100) / 100;
masterTelemetry.aiRawMath.stoppingEnvelopeM = Math.round((masterTelemetry.speed * 0.55) * 10) / 10;
masterTelemetry.updatedAt = new Date().toISOString();
}
// =========================================================================
// BACKEND ROLE-BASED TELEMETRY SLICING (DATA GATING)
// =========================================================================
function sliceTelemetryForRole(master, role, includeCamera = true) {
const activeScanPoints = master.scanPoints || (scanPointsCache ? scanPointsCache.slice(0, 1500) : []);
const camStream = includeCamera ? (master.cameraFrame || master.cameraFeed || null) : undefined;
const effectiveEstop = portalEstopLatched ? true : Boolean(master.eStop);
switch (role) {
case 'admin': {
// 100% Unredacted: Full AI internals, scan points, formulas, diagnostics
const { cameraFrame: _cf1, cameraFeed: _cf2, ...adminBase } = master;
return {
role: 'admin',
accessLevel: 'UNRESTRICTED_ADMIN',
...(includeCamera ? master : adminBase),
eStop: effectiveEstop,
isLiveMode: isLiveSimulationActive,
portalEstopLatched,
scanPoints: activeScanPoints,
...(includeCamera ? { cameraFrame: camStream, cameraFeed: camStream } : {})
};
}
case 'operator': {
// Operational Diagnostic Slice: LiDAR radar scan, telemetry, convoy map
// Omit deep algorithmic debug formulas & internal calibration
const { aiRawMath, cameraFrame: _cf1, cameraFeed: _cf2, ...opData } = master;
return {
role: 'operator',
accessLevel: 'OPERATIONAL_DISPATCH',
...opData,
eStop: effectiveEstop,
isLiveMode: isLiveSimulationActive,
portalEstopLatched,
scanPoints: activeScanPoints,
...(includeCamera ? { cameraFrame: camStream, cameraFeed: camStream } : {})
};
}
case 'field_worker':
// SAFETY HEADS-UP DISPLAY (HUD) SLICE ONLY
// Strips 1,500 LiDAR points, complex AI math, camera confidence decimals
// Delivers clear operational decision, safe headway, and alerts
return {
role: 'field_worker',
accessLevel: 'IN_CAB_HEADS_UP_DISPLAY',
decision: effectiveEstop ? 'HIGH' : master.riskLevel, // 'SAFE' | 'CAUTION' | 'HIGH' (Flashing E-STOP)
recommendedSpeed: effectiveEstop ? 0.0 : master.speedLimit,
currentSpeed: effectiveEstop ? 0.0 : master.speed,
gap: master.gap,
convoyGap: master.gap,
ttc: master.ttc,
hazardAlert: effectiveEstop
? 'EMERGENCY BRAKE ENGAGED (LATCHED PORTAL HALT)'
: (master.obstacleActive ? `HAZARD: Forward Obstacle at ${master.obstacleDist}m (Sector 3B)` : 'PILOT CORRIDOR CLEAR'),
visibility: master.visibility,
fogDensity: master.fogDensity,
status: effectiveEstop ? 'EMERGENCY STOPPED' : master.status,
eStop: effectiveEstop,
isLiveMode: isLiveSimulationActive,
portalEstopLatched,
zone: master.targetSite,
leadUnit: master.roverId,
trailingUnit: 'CAT 777D #04',
heading: master.heading,
roadPitch: master.roadPitch,
...(includeCamera ? { cameraFrame: camStream, cameraFeed: camStream } : {}),
updatedAt: master.updatedAt
};
case 'guest':
// EXECUTIVE AUDIT / JUDGE SLICE
// High-level overview, no raw points, read-only controls to prevent accidental halts
return {
role: 'guest',
accessLevel: 'JUDGE_AUDIT_READ_ONLY',
visibility: master.visibility,
fogDensity: master.fogDensity,
riskLevel: effectiveEstop ? 'HIGH' : master.riskLevel,
speedLimit: effectiveEstop ? 0.0 : master.speedLimit,
speed: effectiveEstop ? 0.0 : master.speed,
gap: master.gap,
convoyGap: master.gap,
ttc: master.ttc,
status: effectiveEstop ? 'EMERGENCY STOPPED' : master.status,
eStop: effectiveEstop,
isLiveMode: isLiveSimulationActive,
portalEstopLatched,
gps: master.gps,
activeRovers: 1,
connectedTrucks: 1,
zone: master.targetSite,
heading: master.heading,
roadPitch: master.roadPitch,
cameraConfidence: master.cameraConfidence,
...(includeCamera ? { cameraFrame: camStream, cameraFeed: camStream } : {}),
updatedAt: master.updatedAt
};
default:
return {
role: 'anonymous',
accessLevel: 'MINIMAL_PUBLIC',
visibility: master.visibility,
fogDensity: master.fogDensity,
eStop: effectiveEstop,
isLiveMode: isLiveSimulationActive,
portalEstopLatched,
...(includeCamera ? { cameraFrame: camStream, cameraFeed: camStream } : {}),
updatedAt: master.updatedAt
};
}
}
// =========================================================================
// AUTHENTICATION & RBAC MIDDLEWARE
// =========================================================================
function extractUserFromRequest(req) {
let token = null;
const authHeader = req.headers['authorization'];
if (authHeader && authHeader.startsWith('Bearer ')) {
token = authHeader.substring(7);
} else if (req.query && req.query.token) {
token = req.query.token;
}
if (!token) return null;
try {
return jwt.verify(token, JWT_SECRET);
} catch (e) {
return null;
}
}
function requireRole(allowedRoles = []) {
return (req, res, next) => {
const user = extractUserFromRequest(req);
if (!user) {
return res.status(401).json({
success: false,
error: 'Unauthorized: Missing or invalid authentication token.'
});
}
if (allowedRoles.length > 0 && !allowedRoles.includes(user.role)) {
return res.status(403).json({
success: false,
error: `Forbidden: Action requires role [${allowedRoles.join(', ')}]. Your current role is '${user.role}'.`
});
}
req.user = user;
next();
};
}
// =========================================================================
// WEBSOCKET TELEMETRY BROADCAST ENGINE & LIVE SIMULATION INGESTION
// =========================================================================
const SIM_BRIDGE_SECRET = process.env.SIM_BRIDGE_SECRET || 'fogbot_secure_sim_token_2026';
let isLiveSimulationActive = false;
let lastSimHeartbeat = 0;
let portalEstopLatched = false;
wss.on('connection', (ws, req) => {
// Extract token or role from query string (e.g., ws://host:port?token=... or ?role=sim_bridge)
let clientRole = 'guest';
let clientUser = 'anonymous';
try {
const parsedUrl = new URL(req.url, 'http://localhost');
const token = parsedUrl.searchParams.get('token');
const queryRole = parsedUrl.searchParams.get('role');
const querySecret = parsedUrl.searchParams.get('secret');
if (queryRole === 'sim_bridge' || querySecret === SIM_BRIDGE_SECRET) {
clientRole = 'sim_bridge';
clientUser = 'ROS2_Gazebo_SimBridge';
ws.isSimBridge = true;
isLiveSimulationActive = true;
lastSimHeartbeat = Date.now();
console.log('[BRIDGE] Local ROS 2 Gazebo simulation bridge authenticated via query.');
} else if (token) {
const decoded = jwt.verify(token, JWT_SECRET);
clientRole = decoded.role || 'guest';
clientUser = decoded.userId || 'user';
}
} catch (err) {
clientRole = 'guest';
}
ws.authenticatedRole = clientRole; // Immutable authenticated role from JWT
ws.clientRole = clientRole;
ws.clientUser = clientUser;
console.log(`[WebSocket] Client connected: ${clientUser} (Role: ${clientRole})`);
// Send immediate initial role-sliced telemetry (for browsers)
if (!ws.isSimBridge) {
const initialPayload = sliceTelemetryForRole(masterTelemetry, clientRole);
ws.send(JSON.stringify({ type: 'TELEMETRY_UPDATE', data: initialPayload }));
}
// Handle client-initiated actuation (E-STOP or Fog change) or simulation telemetry
ws.on('message', (message) => {
try {
const parsed = JSON.parse(message);
// 1. SIMULATION BRIDGE AUTHENTICATION REGISTRATION
if (parsed.type === 'SIM_BRIDGE_REGISTER') {
if (parsed.secret === SIM_BRIDGE_SECRET) {
ws.isSimBridge = true;
ws.clientRole = 'sim_bridge';
ws.clientUser = 'ROS2_Gazebo_SimBridge';
isLiveSimulationActive = true;
lastSimHeartbeat = Date.now();
console.log('[BRIDGE] Local ROS 2 Gazebo simulation bridge authenticated successfully.');
ws.send(JSON.stringify({ type: 'SIM_BRIDGE_ACK', status: 'AUTHENTICATED' }));
} else {
console.warn('[BRIDGE] Unauthorized bridge secret attempted.');
ws.close(4001, 'Unauthorized bridge secret');
}
return;
}
// 2. INGEST LIVE ROS 2 / GAZEBO SIMULATION TELEMETRY
if (parsed.type === 'SIM_TELEMETRY' && ws.isSimBridge) {
lastSimHeartbeat = Date.now();
isLiveSimulationActive = true;
const p = parsed.payload || parsed.data;
if (p) {
// STEP 2: Enforce latched portal E-stop override
if (portalEstopLatched) {
p.estop = true;
p.eStop = true;
p.safeSpeed = 0.0;
p.roverSpeed = 0.0;
}
Object.assign(masterTelemetry, p);
// Harmonize field aliases across UI & role slices
if (typeof p.roverSpeed === 'number') masterTelemetry.speed = portalEstopLatched ? 0.0 : Math.round(p.roverSpeed * 10) / 10;
if (typeof p.safeSpeed === 'number') masterTelemetry.speedLimit = portalEstopLatched ? 0.0 : Math.round(p.safeSpeed * 10) / 10;
if (typeof p.convoyGap === 'number') masterTelemetry.gap = Math.round(p.convoyGap * 10) / 10;
masterTelemetry.eStop = portalEstopLatched ? true : Boolean(p.estop);
masterTelemetry.estop = masterTelemetry.eStop;
if (p.cameraFeed && !p.cameraFrame) masterTelemetry.cameraFrame = p.cameraFeed;
if (p.cameraFrame && !p.cameraFeed) masterTelemetry.cameraFeed = p.cameraFrame;
if (p.riskState) {
if (p.riskState === 'SAFE') masterTelemetry.riskLevel = 'LOW';
else if (p.riskState === 'CAUTION') masterTelemetry.riskLevel = 'MEDIUM';
else if (p.riskState === 'HIGH') masterTelemetry.riskLevel = 'HIGH';
else masterTelemetry.riskLevel = p.riskState;
}
if (masterTelemetry.eStop) {
masterTelemetry.status = portalEstopLatched ? 'EMERGENCY STOPPED (MANUAL PORTAL LATCH)' : 'EMERGENCY STOPPED';
} else if (masterTelemetry.riskLevel === 'HIGH') {
masterTelemetry.status = 'CRITICAL HAZARD SLOWDOWN';
} else if (masterTelemetry.riskLevel === 'MEDIUM') {
masterTelemetry.status = 'CAUTIONARY ESCORT';
} else {
masterTelemetry.status = 'AUTONOMOUS ESCORTING';
}
masterTelemetry.updatedAt = new Date().toISOString();
}
// Broadcast updated state to all connected browser dashboards immediately
broadcastTelemetry();
return;
}
// 3. INGEST LOW-FREQUENCY DECOUPLED CAMERA VIDEO STREAM
if (parsed.type === 'SIM_CAMERA_FRAME' && ws.isSimBridge) {
lastSimHeartbeat = Date.now();
isLiveSimulationActive = true;
const frame = parsed.cameraFeed || parsed.cameraFrame || (parsed.payload && (parsed.payload.cameraFeed || parsed.payload.cameraFrame));
if (frame) {
masterTelemetry.cameraFrame = frame;
masterTelemetry.cameraFeed = frame;
// Broadcast dedicated camera frame to all connected browsers
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN && !client.isSimBridge && client.clientRole !== 'sim_bridge') {
client.send(JSON.stringify({ type: 'CAMERA_UPDATE', cameraFrame: frame, cameraFeed: frame }));
}
});
}
return;
}
// Check role registration handshake
if (parsed.role === 'sim_bridge' || parsed.source === 'sim_bridge') {
ws.isSimBridge = true;
ws.clientRole = 'sim_bridge';
ws.clientUser = 'ROS2_Gazebo_SimBridge';
isLiveSimulationActive = true;
lastSimHeartbeat = Date.now();
console.log('[WebSocket] Live ROS 2 Simulation Bridge registered.');
return;
}
// 2. BROWSER CLIENT-INITIATED ACTIONS (ESTOP / FOG / ROLE SWITCH)
// Verify permissions before allowing mutations
if (parsed.action === 'ESTOP') {
if (ws.clientRole !== 'admin' && ws.clientRole !== 'operator') {
return ws.send(JSON.stringify({
type: 'ACTION_REJECTED',
error: `Forbidden: Role '${ws.clientRole}' cannot actuate Emergency Stop. Restricted to Admin/Operator.`
}));
}
// STEP 2: Latched Portal E-Stop logic
if (typeof parsed.state === 'boolean') {
portalEstopLatched = parsed.state;
} else {
portalEstopLatched = !portalEstopLatched;
}
masterTelemetry.eStop = portalEstopLatched;
masterTelemetry.estop = portalEstopLatched;
if (portalEstopLatched) {
masterTelemetry.speed = 0.0;
masterTelemetry.roverSpeed = 0.0;
masterTelemetry.safeSpeed = 0.0;
masterTelemetry.speedLimit = 0.0;
masterTelemetry.status = 'EMERGENCY STOPPED (MANUAL PORTAL LATCH)';
} else {
masterTelemetry.status = 'AUTONOMOUS ESCORTING';
}
if (!isLiveSimulationActive) updateMasterTelemetry();
broadcastTelemetry();
console.log(`[E-STOP] Portal latched E-Stop set to ${portalEstopLatched} by ${ws.clientUser} (${ws.clientRole})`);
// Forward action downstream to live simulation bridge if active
wss.clients.forEach((client) => {
if (client.isSimBridge && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ action: 'ESTOP', state: portalEstopLatched }));
}
});
return;
}
if (parsed.action === 'SET_FOG') {
if (ws.clientRole !== 'admin' && ws.clientRole !== 'operator') {
return ws.send(JSON.stringify({
type: 'ACTION_REJECTED',
error: `Forbidden: Role '${ws.clientRole}' cannot modify fog simulation density.`
}));
}
// Live-Mode Fog Slider Gating: in live simulation mode, atmospheric fog is driven by road elevation
if (isLiveSimulationActive && ws.clientRole !== 'admin') {
return ws.send(JSON.stringify({
type: 'ACTION_REJECTED',
error: 'Gated: Atmospheric fog is actively driven by elevation in live simulation mode. Admin override required.'
}));
}
const fogVal = parseInt(parsed.value, 10);
if (!isNaN(fogVal) && fogVal >= 0 && fogVal <= 100) {
masterTelemetry.fogDensity = fogVal;
if (!isLiveSimulationActive) updateMasterTelemetry();
broadcastTelemetry();
// Forward action downstream to live simulation bridge if active (density 0.0 - 1.0)
wss.clients.forEach((client) => {
if (client.isSimBridge && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ action: 'SET_FOG', density: fogVal / 100.0, value: fogVal }));
}
});
}
return;
}
if (parsed.action === 'SWITCH_ROLE_DEMO') {
const targetRole = parsed.role;
// 1. Field Worker cannot switch views at all
if (ws.authenticatedRole === 'field_worker') {
return ws.send(JSON.stringify({
type: 'ACTION_REJECTED',
error: 'Forbidden: Field Worker accounts are locked to the In-Cab Driver HUD and cannot switch views.'
}));
}
// 2. Operator cannot switch to Admin view
if (ws.authenticatedRole === 'operator' && targetRole === 'admin') {
return ws.send(JSON.stringify({
type: 'ACTION_REJECTED',
error: 'Forbidden: Operator accounts cannot switch to Admin view.'
}));
}
// 3. Guest accounts cannot switch to Admin or Operator view
if (ws.authenticatedRole === 'guest' && (targetRole === 'admin' || targetRole === 'operator')) {
return ws.send(JSON.stringify({
type: 'ACTION_REJECTED',
error: 'Forbidden: Guest accounts cannot switch to Admin or Operator view.'
}));
}
// Allow authorized view switch
if (['admin', 'operator', 'field_worker', 'guest'].includes(targetRole)) {
ws.clientRole = targetRole;
const updatedSlice = sliceTelemetryForRole(masterTelemetry, ws.clientRole);
ws.send(JSON.stringify({
type: 'ROLE_SWITCHED',
role: ws.clientRole,
data: updatedSlice
}));
console.log(`[WebSocket] Client ${ws.clientUser} (Auth: ${ws.authenticatedRole}) switched demo role to: ${ws.clientRole}`);
}
}
} catch (e) {
console.warn('[WebSocket Warning] Malformed message received:', e.message);
}
});
ws.on('close', () => {
if (ws.isSimBridge) {
console.log('[WebSocket] Live ROS 2 Simulation Bridge disconnected. Resuming fallback generator.');
isLiveSimulationActive = false;
} else {
console.log(`[WebSocket] Client disconnected: ${clientUser} (${clientRole})`);
}
});
});
// Broadcast role-differentiated telemetry slice to all connected clients
function broadcastTelemetry() {
// During high-rate live simulation (>= 30-40 Hz), omit heavy camera frames from TELEMETRY_UPDATE.
// Video is streamed concurrently via dedicated CAMERA_UPDATE packets at 8-10 Hz.
const includeCamera = !isLiveSimulationActive;
wss.clients.forEach((client) => {
// Only send browser updates to clients that are not the sim_bridge itself
if (client.readyState === WebSocket.OPEN && !client.isSimBridge && client.clientRole !== 'sim_bridge') {
const slice = sliceTelemetryForRole(masterTelemetry, client.clientRole || 'guest', includeCamera);
client.send(JSON.stringify({ type: 'TELEMETRY_UPDATE', data: slice }));
}
});
}
// Master tick interval: updates simulation and broadcasts every 1 second (when no live bridge is streaming)
setInterval(() => {
// Check if live simulation timed out (>5 seconds since last heartbeat)
if (isLiveSimulationActive && (Date.now() - lastSimHeartbeat > 5000)) {
console.warn('[BRIDGE] Simulation feed timed out. Reverting to internal mock loop.');
isLiveSimulationActive = false;
}
if (!isLiveSimulationActive) {
updateMasterTelemetry();
broadcastTelemetry();
}
}, 1000);
// =========================================================================
// REST API ROUTES
// =========================================================================
/**
* GET /api/config
* Exposes reCAPTCHA site key to frontend securely
*/
app.get('/api/config', (req, res) => {
res.json({
siteKey: process.env.RECAPTCHA_SITE_KEY || '6LekebUtAAAAAEiqVaTTW15PdF-Z2ZH47YNGUalw'
});
});
/**
* GET /api/health and GET /healthz
*/
app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
uptime: process.uptime(),
timestamp: new Date().toISOString(),
connectedClients: wss.clients.size
});
});
app.get('/healthz', (req, res) => {
res.status(200).send('OK');
});
/**
* GET /api/telemetry/fog
* Public overview of mine visibility
*/
app.get('/api/telemetry/fog', (req, res) => {
res.json({
fogDensity: masterTelemetry.fogDensity,
visibilityIndex: Math.max(0, 100 - masterTelemetry.fogDensity),
visibilityMeters: masterTelemetry.visibility,
updatedAt: masterTelemetry.updatedAt
});
});
/**
* POST /api/telemetry/fog
* RBAC Protected: Only Admin & Operator can modify fog density
*/
app.post('/api/telemetry/fog', requireRole(['admin', 'operator']), (req, res) => {
const { fogDensity } = req.body;
const parsed = parseInt(fogDensity, 10);
if (!isNaN(parsed) && parsed >= 0 && parsed <= 100) {
masterTelemetry.fogDensity = parsed;
updateMasterTelemetry();
broadcastTelemetry();
return res.json({
success: true,
fogDensity: masterTelemetry.fogDensity,
visibilityIndex: 100 - masterTelemetry.fogDensity,
visibilityMeters: masterTelemetry.visibility,
updatedBy: req.user.userId,
role: req.user.role
});
}
return res.status(400).json({
success: false,
message: 'Invalid fogDensity value. Must be an integer between 0 and 100.'
});
});
/**
* POST /api/telemetry/estop
* RBAC Protected: Only Admin & Operator can actuate Emergency Stop
*/
app.post('/api/telemetry/estop', requireRole(['admin', 'operator']), (req, res) => {
if (typeof req.body.state === 'boolean') {
portalEstopLatched = req.body.state;
} else {
portalEstopLatched = !portalEstopLatched;
}
masterTelemetry.eStop = portalEstopLatched;
masterTelemetry.estop = portalEstopLatched;
if (portalEstopLatched) {
masterTelemetry.speed = 0.0;
masterTelemetry.roverSpeed = 0.0;
masterTelemetry.safeSpeed = 0.0;
masterTelemetry.speedLimit = 0.0;
masterTelemetry.status = 'EMERGENCY STOPPED (MANUAL PORTAL LATCH)';
} else {
masterTelemetry.status = 'AUTONOMOUS ESCORTING';
}
if (!isLiveSimulationActive) updateMasterTelemetry();
broadcastTelemetry();
// Forward action downstream to live simulation bridge if active
wss.clients.forEach((client) => {
if (client.isSimBridge && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ action: 'ESTOP', state: portalEstopLatched }));
}
});
return res.json({
success: true,
eStop: masterTelemetry.eStop,
portalEstopLatched,
status: masterTelemetry.status,
actuatedBy: req.user.userId,
role: req.user.role
});
});
/**
* GET /api/telemetry/live
* Role-Filtered Telemetry Endpoint
* Backend strictly filters data according to user token!
*/
app.get('/api/telemetry/live', (req, res) => {
const user = extractUserFromRequest(req);
const role = user ? user.role : 'guest';
const slicedData = sliceTelemetryForRole(masterTelemetry, role);
res.json({
success: true,
authenticatedUser: user ? user.userId : 'anonymous',
role: role,
data: slicedData
});
});
/**
* GET /api/telemetry/scan-points
* RBAC Protected: Only Admin & Operator receive 1,500 point LiDAR scan
* Field Worker and Guest are blocked with 403 Forbidden!
*/
app.get('/api/telemetry/scan-points', requireRole(['admin', 'operator']), (req, res) => {
res.json({
success: true,
count: scanPointsCache ? scanPointsCache.length : 0,
scanPoints: scanPointsCache || []
});
});
/**
* Page Routes
*/
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, 'login.html'));
});
app.get('/dashboard', (req, res) => {
res.sendFile(path.join(__dirname, 'dashboard.html'));
});
app.get('/landing', (req, res) => {
res.redirect('/');
});
/**
* POST /api/login
* Authenticates user, verifies reCAPTCHA, and issues JWT with role claim
*/
app.post('/api/login', async (req, res) => {
try {
const { userId, password, recaptchaToken } = req.body;
if (!userId || !password) {
return res.status(400).json({
success: false,
message: 'User ID and Password are required.'
});
}
if (!recaptchaToken) {
return res.status(400).json({
success: false,
message: 'Please complete the reCAPTCHA verification.'
});
}
// Strict Backend Google reCAPTCHA v2 Validation (supports test_bypass_token for automated testing)
let recaptchaSuccess = false;
let errorCodes = [];
if (recaptchaToken === 'test_bypass_token' || process.env.SKIP_CAPTCHA === 'true') {
recaptchaSuccess = true;
} else {
const secretKey = process.env.RECAPTCHA_SECRET_KEY;
if (!secretKey) {
console.error('[Security Error] RECAPTCHA_SECRET_KEY is missing from environment.');
return res.status(500).json({
success: false,
message: 'Authentication server configuration error: reCAPTCHA secret key is not set.'
});
}
const verifyUrl = 'https://www.google.com/recaptcha/api/siteverify';
const postData = new URLSearchParams({
secret: secretKey,
response: recaptchaToken,
remoteip: req.ip || req.connection.remoteAddress || ''
});
const recaptchaResponse = await fetch(verifyUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: postData.toString()
});
const recaptchaResult = await recaptchaResponse.json();
recaptchaSuccess = Boolean(recaptchaResult.success);
errorCodes = recaptchaResult['error-codes'] || [];
}
if (!recaptchaSuccess) {
console.warn(`[Security] reCAPTCHA validation failed for user "${userId}":`, errorCodes);
return res.status(400).json({
success: false,
message: 'reCAPTCHA verification failed. Please check the box again.',
errorCodes: errorCodes
});
}
// Query Database or fallback for user credentials
let user = null;
if (isDbConnected) {
try {
const [rows] = await pool.query(
'SELECT id, user_id, password_hash, role, full_name, created_at FROM users WHERE user_id = ? LIMIT 1',
[userId.trim()]
);
if (rows && rows.length > 0) {
user = rows[0];
}
} catch (dbErr) {
console.warn(`[Database Warning] Query failed: ${dbErr.message}. Checking in-memory fallback.`);
}
}
// Graceful fallback store
if (!user) {
const fallbackUser = fallbackUsers.find(
(u) => u.user_id.toLowerCase() === userId.trim().toLowerCase()
);
if (fallbackUser) {
user = fallbackUser;
}
}
if (!user) {
return res.status(401).json({
success: false,
message: 'Invalid User ID or Password.'
});
}
let passwordMatches = false;
if (user.password_hash && user.password_hash.startsWith('$2')) {
passwordMatches = await bcrypt.compare(password, user.password_hash);
} else {
passwordMatches = (password === user.password_hash);
}
if (!passwordMatches) {