Repository navigation
Expand file tree
/
Copy pathnetmap.js
More file actions
3574 lines (3438 loc) · 198 KB
/
Copy pathnetmap.js
File metadata and controls
3574 lines (3438 loc) · 198 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
// Network Map tab: scan the LAN and show every machine in an interactive 3D map
// with your router in the middle. Everything here runs inside the app window;
// the actual scanning is done by scanner.js in the app's background process.
(function () {
'use strict';
const $ = (id) => document.getElementById(id);
const THREE = window.THREE;
const OrbitControls = window.OrbitControls;
const els = {
tabPanels: $('tabPanels'), tabMap: $('tabMap'), view: $('mapView'), wrap: $('mapWrap'),
iface: $('mapIface'), cidr: $('mapCidr'), router: $('mapRouter'), mode: $('mapMode'),
scan: $('mapScan'), stop: $('mapStop'), status: $('mapStatus'), progress: $('mapProgress'), bar: $('mapProgressBar'),
connect: $('mapConnect'), cable: $('mapCable'), top: $('mapTop'), reset: $('mapReset'), tidy: $('mapTidy'), identify: $('mapIdentify'), offline: $('mapOffline'), gCluster: $('mapGroupMove'), gCircles: $('mapGroupCircles'),
hint: $('mapHint'), legend: $('mapLegend'), tip: $('mapTip'), empty: $('mapEmpty'), side: $('mapSide'),
list: $('mapList'), listBtn: $('mapListBtn'), alerts: $('mapAlerts'), services: $('mapServices'), toasts: $('mapToasts'),
live: $('mapLive'), liveDot: $('mapLiveDot'), liveText: $('mapLiveText'), addSwitch: $('mapAddSwitch')
};
const OS_COLORS = { router: 0x06b6d4, windows: 0x3b82f6, linux: 0x22c55e, apple: 0xd1d5db, android: 0x84cc16, iot: 0xf97316, console: 0xf43f5e, printer: 0xf472b6, network: 0xa855f7, switch: 0xeab308, unknown: 0x6b7280 };
const OS_NAMES = {
router: 'Router', windows: 'Windows', linux: 'Linux / Unix', apple: 'Apple (macOS / iOS)', android: 'Android', iot: 'IoT / smart device', console: 'Game console', printer: 'Printer',
network: 'Router / network device', switch: 'Switch', unknown: 'Unknown'
};
// the kinds of machine a person can choose to hear about (routers, network devices and switches count as one kind)
const ALERT_KINDS = [['windows', 'Windows'], ['linux', 'Linux / Unix'], ['apple', 'Apple (macOS / iOS)'], ['android', 'Android'], ['iot', 'IoT / smart devices'], ['console', 'Game consoles'], ['printer', 'Printers'], ['network', 'Routers, switches and network devices'], ['unknown', 'Other / unknown']];
const alertKind = (id) => (id === 'router' || id === 'switch' ? 'network' : id);
const LIVE_CHOICES = [0, 15, 30, 60, 120, 300, 600, 1800];
const HTTPS_PORTS = new Set([443, 5001, 8006, 8443, 8920, 9443]);
const WEB_PORTS = new Set([1880, 3002, 4533, 5055, 5173, 5230, 5601, 5678, 6767, 7474, 8082, 8083, 8085, 8086, 8088, 8090, 8112, 8181, 8686, 8787, 8920, 9001, 9117, 9200, 9696, 10000, 28080, 80, 81, 443, 3000, 3001, 5000, 5001, 7878, 8000, 8006, 8008, 8080, 8081, 8096, 8123, 8200, 8384, 8443, 8888, 8989, 9000, 9090, 9091, 9443, 19999, 32400]);
// ---------- saved data ----------
let net = null;
function validIp(s) {
if (typeof s !== 'string' || !/^\d{1,3}(\.\d{1,3}){3}$/.test(s)) return false;
return s.split('.').every((p) => Number(p) <= 255);
}
function normMac(m) {
if (typeof m !== 'string') return null;
const h = m.toLowerCase().replace(/[^0-9a-f]/g, '');
if (h.length !== 12 || h === '000000000000' || h === 'ffffffffffff') return null;
return h.match(/../g).join(':');
}
const text = (v, max) => String(v === null || v === undefined ? '' : v).slice(0, max || 100);
const FLOOR_Y = -1.1; // the grid floor sits just under the machines
const num = (v, fallback) => (typeof v === 'number' && isFinite(v) ? Math.max(-300, Math.min(300, v)) : fallback);
function spiralPos(i) {
const angle = i * 2.39996;
const r = 11 + 3.2 * Math.sqrt(i);
return { x: Math.cos(angle) * r, y: 0, z: Math.sin(angle) * r };
}
function cleanExtras(d) {
const info = d.info && typeof d.info === 'object' ? d.info : {};
const names = {};
if (d.svcNames && typeof d.svcNames === 'object') {
Object.keys(d.svcNames).slice(0, 60).forEach((k) => { if (/^\d{1,5}$/.test(k) && Number(k) >= 1 && Number(k) <= 65535) names[k] = text(d.svcNames[k], 40); });
}
return {
vlan: text(d.vlan || '', 30),
info: {
brand: text(info.brand || '', 60),
model: text(info.model || '', 60),
ports: Number.isInteger(info.ports) && info.ports >= 0 && info.ports <= 1024 ? info.ports : null,
notes: text(info.notes || '', 400),
webUrl: typeof info.webUrl === 'string' && /^https?:\/\/[^\s<>"']{1,200}$/.test(info.webUrl) ? info.webUrl : ''
},
services: (Array.isArray(d.services) ? d.services : []).slice(0, 30).filter((s) => s && typeof s === 'object').map((s) => ({
id: text(s.id || '', 20).replace(/[^a-zA-Z0-9]/g, ''),
name: text(s.name || '', 40),
port: Number.isInteger(s.port) && s.port >= 1 && s.port <= 65535 ? s.port : null,
kind: s.kind === 'vpn' ? 'vpn' : 'service'
})),
svcNames: names,
svcHidden: (Array.isArray(d.svcHidden) ? d.svcHidden : []).slice(0, 100).filter((p) => Number.isInteger(p) && p >= 1 && p <= 65535),
autoVpn: (Array.isArray(d.autoVpn) ? d.autoVpn : []).slice(0, 6).map((v) => text(v, 40))
};
}
function cleanDevice(key, d) {
const out = {
key: key,
ip: validIp(d.ip) ? d.ip : (key.startsWith('ip:') && validIp(key.slice(3)) ? key.slice(3) : ''),
mac: /^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/.test(d.mac || '') ? d.mac : (/^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/.test(key) ? key : null),
vendor: d.vendor ? text(d.vendor, 60) : null,
hostname: d.hostname ? text(d.hostname, 80) : null,
label: text(d.label || '', 60),
group: text(d.group || '', 30),
connSeen: d.connSeen === 'wireless' || d.connSeen === 'wired' ? d.connSeen : null,
attach: d.attach && typeof d.attach === 'object' ? { via: text(d.attach.via || '', 100), speed: speedNum(d.attach.speed), speedRx: speedNum(d.attach.speedRx), signal: Number.isFinite(d.attach.signal) ? Math.round(d.attach.signal) : null, by: text(d.attach.by || '', 40), port: text(d.attach.port || '', 30), parentKey: typeof d.attach.parentKey === 'string' ? text(d.attach.parentKey, 80) : '' } : null,
portTable: Array.isArray(d.portTable) ? d.portTable.slice(0, 128).filter((p) => p && typeof p === 'object' && p.name).map((p) => ({ name: text(p.name, 30), up: p.up === true, speed: speedNum(p.speed) })) : [],
portTableAt: Number.isFinite(d.portTableAt) ? d.portTableAt : null,
speedSet: speedNum(d.speedSet),
shares: Array.isArray(d.shares) ? d.shares.slice(0, 60).filter((s) => s && typeof s === 'object' && s.name).map((s) => ({ name: text(s.name, 120), type: text(s.type || 'Disk', 10), comment: text(s.comment || '', 120), proto: ['SMB', 'NFS'].includes(s.proto) ? s.proto : 'SMB' })) : [],
sharesAt: Number.isFinite(d.sharesAt) ? d.sharesAt : null,
dns: d.dns && typeof d.dns === 'object' && d.dns.server === true ? { server: true, recursive: d.dns.recursive === true, refused: d.dns.refused === true, software: text(d.dns.software || '', 60) } : null,
dnsAt: Number.isFinite(d.dnsAt) ? d.dnsAt : null,
uplinkSpeed: speedNum(d.uplinkSpeed),
uplinkPort: d.uplinkPort ? text(d.uplinkPort, 30) : null,
osOverride: OS_NAMES[d.osOverride] && d.osOverride !== 'router' ? d.osOverride : null,
os: d.os && typeof d.os === 'object'
? { id: OS_NAMES[d.os.id] ? d.os.id : 'unknown', label: text(d.os.label, 40), confidence: text(d.os.confidence, 10), reasons: Array.isArray(d.os.reasons) ? d.os.reasons.slice(0, 12).map((r) => text(r, 120)) : [] }
: { id: 'unknown', label: 'Unknown', confidence: 'low', reasons: [] },
ports: Array.isArray(d.ports) ? d.ports.slice(0, 200).filter((p) => p && Number.isInteger(p.port)).map((p) => ({
port: p.port, service: p.service ? text(p.service, 40) : null, banner: p.banner ? text(p.banner, 100) : null, title: p.title ? text(p.title, 80) : null
})) : [],
ttl: Number.isInteger(d.ttl) ? d.ttl : null,
self: !!d.self,
linkSpeed: d.linkSpeed && typeof d.linkSpeed === 'object' && speedNum(d.linkSpeed.mbps) ? { mbps: speedNum(d.linkSpeed.mbps), wireless: d.linkSpeed.wireless === true } : null,
online: d.online !== false,
manual: key.startsWith('manual:'),
misses: 0,
lastSeen: typeof d.lastSeen === 'number' ? d.lastSeen : null,
firstSeen: Number.isFinite(d.firstSeen) && d.firstSeen > 0 ? d.firstSeen : null,
onlineSince: Number.isFinite(d.onlineSince) && d.onlineSince > 0 ? d.onlineSince : null,
upInfo: d.upInfo && typeof d.upInfo === 'object' && Number.isFinite(d.upInfo.sec) && d.upInfo.sec >= 0 && d.upInfo.sec <= 3153600000 && Number.isFinite(d.upInfo.at) && d.upInfo.at > 0 ? { sec: Math.floor(d.upInfo.sec), at: d.upInfo.at, kind: d.upInfo.kind === 'connected' ? 'connected' : 'device' } : null,
isRouter: key === 'router',
pos: { x: 0, y: 0, z: 0 }
};
if (d.pos) out.pos = { x: num(d.pos.x, 0), y: 0, z: num(d.pos.z, 0) }; // every machine sits on the same flat level
return Object.assign(out, cleanExtras(d));
}
// ---------- LAN speedtest ----------
// Asks the saved routers / access points / managed switches for their latest reports, then says what each machine's link rate is.
// It reads the rate the two ends agreed on; it does not send test traffic, so a machine nobody reports on shows "not reported".
async function runLanSpeedtest(list) {
const devs = list.filter((d) => d && !d.isRouter);
if (!devs.length) return 'Pick a machine first.';
const hub = window.hubConnections;
if (!hub || !hub.refreshNow) return 'Router and switch connections are not available here.';
let r;
try { r = await hub.refreshNow(); } catch (e) { r = null; }
if (!r || r.none) return 'No router, access point or switch connections are set up yet. Add one under Router & switch links, then run the test again.';
const lines = devs.slice(0, 8).map((d) => {
const cur = net.devices[d.key] || d;
const at = cur.attach && typeof cur.attach === 'object' ? cur.attach : null;
const s = cur.self && cur.linkSpeed ? speedLabel(cur.linkSpeed.mbps, null, cur.linkSpeed.wireless) : at ? speedLabel(at.speed, at.speedRx, at.wireless) : '';
return title(cur) + ': ' + (s ? s + (at && at.by ? ' (reported by ' + at.by + ')' : '') : 'not reported by your router or switch');
});
if (devs.length > 8) lines.push('...and ' + (devs.length - 8) + ' more.');
return lines.join('\n');
}
// ---------- Wake-on-LAN ----------
const waking = new Map(); // device key -> when the signal was sent
async function wakeDevices(list) {
const withMac = list.filter((d) => d && d.mac && !d.isRouter);
if (!withMac.length) { setStatus('That machine has no hardware (MAC) address, so it cannot be woken.', true); return 'No hardware address.'; }
if (!window.netApi || !window.netApi.wake) { setStatus('Wake-on-LAN only works inside the Dashboard Hub app.', true); return 'Not available here.'; }
let res;
// a server with a management chip (iLO / iDRAC) linked to it is switched on through that as well: it works even when Wake-on-LAN does not
const viaBmc = [];
for (const d of withMac) {
const es = window.hubBmcFor && window.bmcApi ? window.hubBmcFor(d.mac) : [];
if (es.length) { try { const r = await window.bmcApi.power(es[0].id, 'on'); if (r && r.ok) viaBmc.push(d); } catch (e) { /* the normal wake-up still goes out */ } }
}
try { res = await window.netApi.wake(withMac.map((d) => d.mac)); } catch (e) { res = { ok: false, error: 'The wake-up signal could not be sent.' }; }
if ((!res || !res.ok) && viaBmc.length) res = { ok: true };
if (!res || !res.ok) { const m = (res && res.error) || 'The wake-up signal could not be sent.'; setStatus(m, true); return m; }
const names = withMac.map((d) => title(d));
const msg = 'Wake-up signal sent to ' + (names.length === 1 ? names[0] : names.length + ' machines') + (viaBmc.length ? ' (and a power-on through its server management chip)' : '') + '. Machines that are set up for Wake-on-LAN start within a few seconds.';
setStatus(msg);
withMac.filter((d) => d.online === false).forEach((d) => waking.set(d.key, { t: Date.now(), told: false }));
[6000, 20000, 45000, 75000, 120000, 180000, 300000].forEach((ms) => setTimeout(() => { if (!scanKind && waking.size) startScan({ background: true }); }, ms)); // slow boots take minutes
return msg;
}
setInterval(() => {
waking.forEach((w, key) => {
const d = net.devices[key];
if (!d) { waking.delete(key); return; }
const age = Date.now() - w.t;
if (d.online !== false && age > 3000) { waking.delete(key); setStatus(title(d) + ' is awake.'); renderSide(); return; } // seen online by a scan or a router check
if (age > 180000 && !w.told) { w.told = true; setStatus(title(d) + ' has not shown up yet. Slow computers can take a few minutes, so Dashboard Hub keeps watching. If it never wakes, check that Wake-on-LAN is on in its BIOS and network card settings.', true); }
if (age > 900000) waking.delete(key);
});
}, 3000);
// ---------- file sharing (SMB, NFS, Apple, FTP, WebDAV...) ----------
const SHARE_PORTS = { 445: 'SMB', 139: 'SMB', 2049: 'NFS', 548: 'AFP', 21: 'FTP', 873: 'rsync', 5005: 'WebDAV', 5006: 'WebDAV', 3260: 'iSCSI' };
function shareKinds(d) {
const out = [];
(d.ports || []).forEach((p) => { const k = SHARE_PORTS[p.port]; if (k && !out.includes(k)) out.push(k); });
return out;
}
// link speed: whole number of Mbps, shown as Mbps or Gbps
function speedNum(v) { const n = Number(v); return Number.isFinite(n) && n >= 1 && n <= 200000 ? Math.round(n * 10) / 10 : null; }
function speedFmt(n) { return n >= 1000 ? (Math.round(n / 100) / 10) + ' Gbps' : n + ' Mbps'; }
function speedLabel(tx, rx, wireless) {
const a = speedNum(tx), b = speedNum(rx);
if (!a && !b) return '';
if (a && b && a !== b) return '\u2193 ' + speedFmt(a) + ' \u00b7 \u2191 ' + speedFmt(b);
return speedFmt(a || b);
}
function ensureNetwork(override) {
const src = override && typeof override === 'object' ? override : (state.network && typeof state.network === 'object' ? state.network : {});
const n = {
router: validIp(src.router) ? src.router : '192.168.0.1',
routerUser: !!src.routerUser,
cidr: typeof src.cidr === 'string' ? src.cidr.slice(0, 20) : '',
mode: src.mode === 'thorough' ? 'thorough' : 'quick',
showOffline: src.showOffline === true,
groupCluster: src.groupCluster !== false,
groupCircles: src.groupCircles !== false,
autoSeconds: LIVE_CHOICES.includes(Number(src.autoSeconds)) ? Number(src.autoSeconds) : 60,
scannedOnce: !!src.scannedOnce,
presenceAt: Number.isFinite(src.presenceAt) && src.presenceAt > 0 ? src.presenceAt : 0,
alerts: ['off', 'app', 'desktop'].includes(src.alerts) ? src.alerts : 'app',
// which kinds of machine to alert about: null means all of them
alertTypes: Array.isArray(src.alertTypes) ? ALERT_KINDS.map((k) => k[0]).filter((k) => src.alertTypes.includes(k)) : null,
showServices: src.showServices === true,
removedReturn: true,
// older versions kept removed machines away for good; now they come back when found again
ignored: src.removedReturn === true && Array.isArray(src.ignored) ? src.ignored.filter((k) => typeof k === 'string' && k.length < 40).slice(0, 500) : [],
devices: {},
links: []
};
const devs = src.devices && typeof src.devices === 'object' ? src.devices : {};
Object.keys(devs).slice(0, 2000).forEach((key) => {
if (devs[key] && typeof devs[key] === 'object') n.devices[key] = cleanDevice(key, devs[key]);
});
if (!n.devices.router) {
n.devices.router = cleanDevice('router', { ip: n.router, os: { id: 'network', label: OS_NAMES.network, confidence: 'high', reasons: ['this is your router'] }, online: true });
}
n.devices.router.ip = n.router;
n.devices.router.pos = { x: 0, y: 0, z: 0 };
// "online for X days" only counts time the app was watching: if it was closed for a while, the count starts again
Object.values(n.devices).forEach((d) => {
const ref = d.lastSeen || n.presenceAt || 0;
if (d.onlineSince && ref && Date.now() - ref > PRESENCE_GAP_MS) d.onlineSince = null;
});
if (Array.isArray(src.links)) {
const seen = new Set();
src.links.slice(0, 5000).forEach((l) => {
if (!l || !n.devices[l.a] || !n.devices[l.b] || l.a === l.b) return;
const id = linkId(l.a, l.b);
if (seen.has(id)) return;
seen.add(id);
n.links.push({ a: l.a, b: l.b, auto: !!l.auto, cable: l.cable === true && !l.auto, wireless: l.cable === true && !l.auto ? false : l.wireless === true ? true : l.wireless === false ? false : null });
});
}
state.network = n;
net = n;
}
const PRESENCE_GAP_MS = 2 * 3600 * 1000;
// Keeps "first seen" and "online since" up to date. Runs on every save, so the count follows scans and router checks.
function trackPresence() {
if (!net) return;
const now = Date.now();
Object.values(net.devices).forEach((d) => {
if (d.manual && !d.ip && !d.lastSeen) return;
if (d.online === false) { d.onlineSince = null; d.upInfo = null; return; }
if (!d.onlineSince) d.onlineSince = now;
if (!d.firstSeen) d.firstSeen = d.lastSeen || now;
});
net.presenceAt = now;
}
// The device's own report (seconds), moved forward by the time since we heard it. Null once it is offline.
function reportedUp(d) {
if (!d.upInfo || d.online === false) return null;
return d.upInfo.sec + Math.max(0, Math.round((Date.now() - d.upInfo.at) / 1000));
}
function fmtDuration(sec) {
sec = Math.max(0, Math.floor(sec));
const days = Math.floor(sec / 86400), h = Math.floor((sec % 86400) / 3600), m = Math.floor((sec % 3600) / 60);
if (days >= 1) return days + (days === 1 ? ' day' : ' days') + (h ? ' ' + h + ' h' : '');
if (h >= 1) return h + ' h' + (m ? ' ' + m + ' min' : '');
if (m >= 1) return m + ' min';
return 'under a minute';
}
function save() { try { trackPresence(); saveState(); if (window.hubProfilesCapture) window.hubProfilesCapture(); window.dispatchEvent(new Event('hub-map-changed')); } catch (e) { /* ignore */ } }
const linkId = (a, b) => (a < b ? a + '~' + b : b + '~' + a);
const devices = () => Object.values(net.devices);
const effectiveOs = (d) => (d.isRouter ? 'router' : (d.osOverride || (d.os && d.os.id) || 'unknown'));
function title(d) {
if (d.label) return d.label;
if (d.isRouter) return 'Router';
if (d.hostname) return d.hostname;
const web = (d.ports || []).find((p) => p.title);
if (web) return web.title;
if (d.vendor && !/^Private/.test(d.vendor)) return d.vendor;
return d.ip || 'Unknown device';
}
function ipSort(a, b) {
const pa = (a.ip || '0.0.0.0').split('.').map(Number), pb = (b.ip || '0.0.0.0').split('.').map(Number);
for (let i = 0; i < 4; i++) if (pa[i] !== pb[i]) return pa[i] - pb[i];
return 0;
}
// ---------- merging scan results ----------
let seenKeys = new Set();
const wifiClaims = new Map(); // machine key -> Map(parent key -> { first, last }): who said "this machine is on my Wi-Fi", and since when
let newCount = 0;
let scanVlan = ''; // set while scanning a VLAN network, so the machines found get that VLAN label
let alertBase = false; // alerts only start after the first full scan
let alertQueue = [];
function rekey(oldKey, newKey) {
const dev = net.devices[oldKey];
if (!dev || oldKey === newKey) return;
const other = net.devices[newKey];
if (other) { // the same machine already has a record: keep that one and merge custom attributes
if (dev.label && !other.label) other.label = dev.label;
if (dev.label && other.label === '') other.label = dev.label;
if (dev.group && !other.group) other.group = dev.group;
if (dev.osOverride && !other.osOverride) other.osOverride = dev.osOverride;
if (dev.vlan && !other.vlan) other.vlan = dev.vlan;
if (dev.attach) other.attach = Object.assign({}, dev.attach, other.attach || {});
if (dev.info) other.info = Object.assign({}, dev.info, other.info || {});
if (dev.svcNames) other.svcNames = Object.assign({}, dev.svcNames, other.svcNames || {});
if (dev.services && dev.services.length) {
const existing = new Set((other.services || []).map((s) => s.id));
other.services = (other.services || []).concat(dev.services.filter((s) => !existing.has(s.id)));
}
net.links.forEach((l) => {
if (l.a === oldKey) l.a = newKey;
if (l.b === oldKey) l.b = newKey;
});
const seenLinkIds = new Set();
net.links = net.links.filter((l) => {
if (l.a === l.b) return false;
const id = linkId(l.a, l.b);
if (seenLinkIds.has(id)) return false;
seenLinkIds.add(id);
return true;
});
if (selected && selected.type === 'node' && selected.key === oldKey) selected.key = newKey;
if (pending === oldKey) pending = newKey;
delete net.devices[oldKey];
removeNode(oldKey);
seenKeys.delete(oldKey);
return;
}
const n = nodes.get(oldKey);
if (n) {
nodes.set(newKey, n);
nodes.delete(oldKey);
if (n.mesh && n.mesh.userData) n.mesh.userData.key = newKey;
}
net.devices[newKey] = dev;
delete net.devices[oldKey];
dev.key = newKey;
net.links.forEach((l) => { if (l.a === oldKey) l.a = newKey; if (l.b === oldKey) l.b = newKey; });
devices().forEach((d) => { if (d.attach && d.attach.parentKey === oldKey) d.attach.parentKey = newKey; });
if (selected && selected.type === 'node' && selected.key === oldKey) selected.key = newKey;
if (pending === oldKey) pending = newKey;
seenKeys.delete(oldKey);
}
function mergeHost(h) {
if (!h) return null;
const mac = normMac(h.mac);
const hasIp = validIp(h.ip);
if (!hasIp && !mac) return null;
// machines you chose to ignore stay hidden (a plain "Remove from map" does not do this)
if (hasIp && h.ip !== net.router && ((mac && net.ignored.includes(mac)) || net.ignored.includes('ip:' + h.ip))) return null;
let dev = null;
if (hasIp && h.ip === net.router) dev = net.devices.router;
if (!dev && mac) dev = devices().find((d) => !d.isRouter && d.mac && d.mac.toLowerCase() === mac) || null;
if (!dev && hasIp) dev = net.devices['ip:' + h.ip] || null;
if (!dev && hasIp) dev = devices().find((d) => !d.isRouter && d.manual && d.ip === h.ip) || null; // a switch you added by hand
if (!dev && !mac && hasIp) dev = devices().find((d) => !d.isRouter && d.ip === h.ip && !seenKeys.has(d.key)) || null;
let created = false;
if (!dev) {
const key = mac || (hasIp ? 'ip:' + h.ip : newId());
dev = cleanDevice(key, { ip: hasIp ? h.ip : '', pos: spiralPos(devices().length) });
net.devices[key] = dev;
const hasLink = net.links.some((l) => l.a === key || l.b === key);
if (!hasLink) {
net.links.push({ a: 'router', b: key, auto: true });
}
created = true;
newCount++;
alertEvent('new', dev);
}
if (!created && hasIp && dev.ip && dev.ip !== h.ip && dev.online !== false) histEvent('ip', dev); // same machine, new address
if (hasIp) dev.ip = h.ip;
if (mac) {
dev.mac = mac;
if (!dev.isRouter && !dev.manual && dev.key !== mac) { rekey(dev.key, mac); dev = net.devices[mac] || dev; }
}
if (h.vendor) dev.vendor = text(h.vendor, 60);
// an early or "still there" report must not wipe what a full scan found earlier
const full = !h.scanning && !h.portsSkipped;
if (full) {
if (h.hostname) dev.hostname = text(h.hostname, 80);
dev.ports = cleanDevice(dev.key, { ports: h.ports }).ports;
}
if (created || full) {
const wasSwitch = effectiveOs(dev) === 'switch';
dev.os = cleanDevice(dev.key, { os: h.os }).os;
if (!wasSwitch && !dev.osOverride && dev.os.id === 'switch' && !dev.info.brand) dev.info.brand = brandHint(dev); // first time a scan recognises a switch: fill in the maker if it is known
dev.ttl = Number.isInteger(h.ttl) ? h.ttl : dev.ttl;
}
if (!created && dev.online === false) {
alertEvent('back', dev);
// detected again: a machine whose line was deleted while it was offline gets its line back now (a router check may then place it better)
if (!dev.isRouter && !net.links.some((l) => l.a === dev.key || l.b === dev.key)) net.links.push({ a: 'router', b: dev.key, auto: true });
}
if (scanVlan && !dev.vlan) dev.vlan = scanVlan;
if (full && h.self && Array.isArray(h.vpn)) dev.autoVpn = h.vpn.slice(0, 6).map((v) => text(v, 40));
dev.self = !!h.self;
dev.lastSeen = Date.now();
dev.online = true;
dev.misses = 0;
seenKeys.add(dev.key);
return dev;
}
// ---------- 3D scene ----------
let renderer = null, scene = null, camera = null, controls = null, raycaster = null, canvas = null;
let webglFailed = false, softwareGl = false, glLost = false, glLostTimer = null;
// light or dark: the chosen colours (Settings) first, otherwise whatever the computer uses
function hubIsLight() { const t = document.documentElement.getAttribute('data-theme'); if (t === 'light' || t === 'dark' || t === 'tron') return t === 'light'; return !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches); }
const isTron = () => document.documentElement.getAttribute('data-theme') === 'tron';
const edgeColor = () => (hubIsLight() ? 0x1f2937 : (isTron() ? 0x6ff3ff : 0xffffff));
function refreshEdges() { nodes.forEach((n) => { if (n.edges && n.edges.material) n.edges.material.color.setHex(edgeColor()); }); }
const nodes = new Map(); // device key -> { group, mesh, edges, sprite, sig }
const linkObjs = new Map(); // link id -> { group, vis, pick, a, b }
let nodeGeo, routerGeo, switchGeo, linkGeo, svcGeo;
let animateNew = false; // new/lost machines pop in and out (switched on once the map has been drawn)
const typeFilter = new Set(); // kinds ticked in the colour key (none ticked = show everything)
let selected = null; // { type:'node', key } or { type:'link', id }
let pending = null; // first machine picked while drawing a line
let connectMode = false;
let running = false;
let syncQueued = false;
let fitted = false;
function initThree() {
if (renderer || webglFailed) return !webglFailed;
if (!THREE || !OrbitControls) { webglFailed = true; return false; }
try {
// smooth edges first; some graphics drivers refuse that, so try again without it before giving up
try { renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); }
catch (e1) { renderer = new THREE.WebGLRenderer({ antialias: false, alpha: true }); }
} catch (e) {
webglFailed = true;
els.empty.textContent = 'The 3D map could not start because this computer\'s graphics are not available.';
els.empty.classList.remove('hidden');
return false;
}
// software drawing (no real graphics card) is slow and heats the processor: keep that case light
try {
const gl = renderer.getContext(), dbg = gl.getExtension('WEBGL_debug_renderer_info');
softwareGl = !!dbg && /swiftshader|llvmpipe|softpipe|software|basic render/i.test(String(gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)));
} catch (e) { softwareGl = false; }
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, softwareGl ? 1 : 2));
canvas = renderer.domElement;
// the graphics driver can reset (a driver update, sleep, a crash it recovers from): pause while the picture is gone, then carry on
canvas.addEventListener('webglcontextlost', (e) => {
e.preventDefault();
glLost = true;
clearTimeout(glLostTimer);
glLostTimer = setTimeout(() => { if (glLost) { els.empty.textContent = 'The graphics driver reset and has not come back yet. The map will return by itself; if it does not, close and reopen Dashboard Hub, or switch the graphics card off in Settings.'; els.empty.classList.remove('hidden'); } }, 6000);
});
canvas.addEventListener('webglcontextrestored', () => {
glLost = false; clearTimeout(glLostTimer);
updateEmptyMessage();
queueSync(); wakeLoop();
});
canvas.tabIndex = 0;
els.wrap.insertBefore(canvas, els.wrap.firstChild);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(55, 1, 0.1, 1200);
camera.position.set(0, 30, 42);
raycaster = new THREE.Raycaster();
scene.add(new THREE.AmbientLight(0xffffff, 0.75));
const sun = new THREE.DirectionalLight(0xffffff, 1.3);
sun.position.set(20, 40, 30);
scene.add(sun);
const fill = new THREE.DirectionalLight(0x88aaff, 0.5);
fill.position.set(-30, 10, -20);
scene.add(fill);
let grid = null;
const lightMq = window.matchMedia ? window.matchMedia('(prefers-color-scheme: light)') : null;
const isLightTheme = () => hubIsLight();
const buildGrid = () => { // the floor grid and selection outlines follow light / dark mode
if (grid) { scene.remove(grid); grid.geometry.dispose(); grid.material.dispose(); }
grid = isLightTheme() ? new THREE.GridHelper(160, 32, 0x9aa5b8, 0xcdd3de) : (isTron() ? new THREE.GridHelper(160, 32, 0x6ff3ff, 0x0f6d7c) : new THREE.GridHelper(160, 32, 0x2c3340, 0x1c2330));
grid.position.y = FLOOR_Y;
scene.add(grid);
};
buildGrid();
const retheme = () => { buildGrid(); refreshEdges(); };
if (lightMq && lightMq.addEventListener) lightMq.addEventListener('change', retheme);
window.addEventListener('hub-theme', retheme);
nodeGeo = new THREE.BoxGeometry(3.2, 2, 2);
routerGeo = new THREE.BoxGeometry(5.6, 1.7, 3.6);
switchGeo = new THREE.BoxGeometry(5.6, 0.9, 2.6);
linkGeo = new THREE.CylinderGeometry(1, 1, 1, 8);
svcGeo = new THREE.BoxGeometry(1.5, 1.1, 1.5);
// add my handlers first (capture) so a drag on a machine moves it instead of rotating the camera
canvas.addEventListener('pointerdown', onDown, true);
canvas.addEventListener('pointermove', onMove);
['pointermove', 'pointerdown', 'wheel', 'keydown'].forEach((ev) => canvas.addEventListener(ev, wakeLoop, { passive: true }));
canvas.addEventListener('pointerup', onUp);
canvas.addEventListener('pointercancel', onUp);
canvas.addEventListener('pointerleave', () => { els.tip.classList.add('hidden'); });
canvas.addEventListener('contextmenu', (e) => e.preventDefault());
controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.maxDistance = 400;
controls.minDistance = 4;
if (window.ResizeObserver) new ResizeObserver(resize).observe(els.wrap);
window.addEventListener('resize', resize);
resize();
return true;
}
let lastW = 0, lastH = 0, lastDpr = 0;
function resize() {
wakeLoop();
if (!renderer) return;
const w = Math.max(1, els.wrap.clientWidth), h = Math.max(1, els.wrap.clientHeight);
// resizing the picture is expensive (the graphics card has to make a new one): do it only when the size really changed
if (w === lastW && h === lastH && (window.devicePixelRatio || 1) === lastDpr) return;
lastW = w; lastH = h; lastDpr = window.devicePixelRatio || 1;
// never ask for more than about a 4K picture, however big the window or sharp the screen
const pr = Math.max(0.5, Math.min(window.devicePixelRatio || 1, softwareGl ? 1 : 2, Math.sqrt(8500000 / (w * h))));
if (Math.abs(renderer.getPixelRatio() - pr) > 0.01) renderer.setPixelRatio(pr);
renderer.setSize(w, h);
camera.aspect = w / h;
camera.updateProjectionMatrix();
}
function easeOutBack(k) { const c1 = 1.70158, c3 = c1 + 1; return 1 + c3 * Math.pow(k - 1, 3) + c1 * Math.pow(k - 1, 2); }
// machines pop in when they join and shrink away when they leave
function stepAnimations() {
const t = performance.now();
let active = false;
nodes.forEach((n) => {
if (!n.anim) return;
active = true;
const k = Math.min(1, (t - n.anim.t0) / (n.anim.type === 'in' ? 550 : 350));
n.scale = n.anim.type === 'in' ? easeOutBack(k) : n.anim.from * (1 - k * k);
if (k >= 1) { n.anim = null; n.scale = n.shown ? 1 : 0; n.group.visible = n.shown; }
n.group.scale.setScalar(Math.max(0.001, n.scale));
});
if (active) { net.links.forEach((l) => { const o = linkObjs.get(linkId(l.a, l.b)); if (o) placeLink(o, l); }); syncServices(); }
}
// Saves battery and fan noise: when nothing has moved for a couple of seconds the 3D view redraws about 15 times a second
// instead of 60, and goes back to full speed the moment you touch the map or something changes.
var reducedMotion = !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches); // people who ask their computer for less motion get steady lines
var pulseWanted = true;
try { pulseWanted = localStorage.getItem('hubLinkPulse') !== 'off'; } catch (e) { /* no saved choice: blinking stays on */ }
var pulseOn = pulseWanted && !reducedMotion;
(function () {
const chk = document.getElementById('pulseCheck');
if (!chk) return;
chk.checked = pulseWanted;
chk.addEventListener('change', () => {
pulseWanted = chk.checked; pulseOn = pulseWanted && !reducedMotion;
try { localStorage.setItem('hubLinkPulse', pulseWanted ? 'on' : 'off'); } catch (e) { /* choice lasts until the app closes */ }
if (!pulseOn) linkObjs.forEach((o) => { o.vis.material.opacity = 1; });
wakeLoop();
});
})();
var lastMove = performance.now(), lastCam = '', lastDraw = 0, loopGen = 0, idleTimer = null;
// Anything that touches the map wakes it up at once (also when it was sleeping between slow redraws).
function wakeLoop() {
lastMove = performance.now();
if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; if (running) next(0); }
}
// Schedules the next pass: now (on the next screen refresh) or after a pause. A pass belongs to one "generation", so a stop
// followed by a quick start can never leave two loops running at the same time.
function next(ms) {
const g = loopGen;
if (ms > 0) idleTimer = setTimeout(() => { idleTimer = null; if (running && g === loopGen) requestAnimationFrame(() => loop(g)); }, ms);
else requestAnimationFrame(() => loop(g));
}
function loop(g) {
if (!running || g !== loopGen) return;
// nobody can see the picture (window hidden in the tray, minimised, or the graphics were reset): draw nothing, look again in a second
if (window.hubWindowHidden || document.hidden || glLost) { next(1000); return; }
const now = performance.now();
stepAnimations();
controls.update();
if (keepMapInView()) controls.update();
const cam = camera.position.x.toFixed(2) + camera.position.y.toFixed(2) + camera.position.z.toFixed(2) + controls.target.x.toFixed(2) + controls.target.y.toFixed(2) + controls.target.z.toFixed(2);
let busy = cam !== lastCam; lastCam = cam;
nodes.forEach((x) => { if (x.anim) busy = true; });
if (busy) lastMove = now;
let anyPulse = false;
if (pulseOn) linkObjs.forEach((o) => { if (o.pulse) anyPulse = true; });
if (now - lastMove > 2000) {
// Resting: redraw only as often as the blinking needs (about 15 times a second, 10 after a minute of rest, 5 after five minutes), or once every half
// second when nothing moves at all. This is by time, so a 144 Hz or 240 Hz screen does not draw more often than a 60 Hz one.
const rest = now - lastMove;
const wait = anyPulse ? (rest > 300000 ? 200 : rest > 60000 ? 100 : 66) : (softwareGl ? 1000 : 500);
const since = now - lastDraw;
if (since < wait) { next(Math.max(4, wait - since - 6)); return; }
}
if (anyPulse) { const t = now / 1000; linkObjs.forEach((o) => { if (o.pulse) { const sv = 0.7 * Math.sin(t * 2.4 + o.phase) + 0.3 * Math.sin(t * 5.1 + o.phase * 1.7); o.vis.material.opacity = 0.7 + 0.3 * sv; } }); }
renderer.render(scene, camera);
lastDraw = now;
next(0);
}
function startLoop() { if (renderer && !running) { running = true; loopGen++; next(0); } }
function stopLoop() { running = false; loopGen++; if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } }
// the app window was hidden or shown (the main program tells the page): wake up right away when it comes back
window.addEventListener('hub-visibility', wakeLoop);
document.addEventListener('visibilitychange', wakeLoop);
// label sprite
function labelTexture(lines, dim) {
const c = document.createElement('canvas');
c.width = 512; c.height = 176;
const g = c.getContext('2d');
g.fillStyle = 'rgba(11,13,17,0.78)';
const r = 22;
g.beginPath();
g.moveTo(r, 4); g.lineTo(c.width - r, 4); g.quadraticCurveTo(c.width - 4, 4, c.width - 4, r);
g.lineTo(c.width - 4, c.height - r); g.quadraticCurveTo(c.width - 4, c.height - 4, c.width - r, c.height - 4);
g.lineTo(r, c.height - 4); g.quadraticCurveTo(4, c.height - 4, 4, c.height - r);
g.lineTo(4, r); g.quadraticCurveTo(4, 4, r, 4); g.closePath(); g.fill();
g.textAlign = 'center'; g.textBaseline = 'middle';
const fit = (s, font, max) => {
g.font = font;
let t = s;
while (g.measureText(t).width > max && t.length > 3) t = t.slice(0, -2);
return t === s ? s : t.replace(/\s+$/, '') + '…';
};
g.fillStyle = dim ? '#8a93a5' : '#ffffff';
g.fillText(fit(lines[0], 'bold 54px "Segoe UI", system-ui, sans-serif', 480), 256, 48);
g.fillStyle = dim ? '#6f788a' : '#8db8ff';
g.fillText(fit(lines[1], '44px Consolas, "DejaVu Sans Mono", monospace', 480), 256, 98);
g.fillStyle = '#8a93a5';
g.fillText(fit(lines[2], '32px "Segoe UI", system-ui, sans-serif', 480), 256, 143);
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
tex.anisotropy = 4;
return tex;
}
function nodeVisible(d) {
if (d.isRouter) return true;
if (typeFilter.size && !(keepKeys && keepKeys.has(d.key))) return false; // the colour key: only the ticked kinds (and the switches on the way to them)
if (typeFilter.size && pathKeys && pathKeys.has(d.key)) return true; // network gear and switches on the way stay, even if offline or not ticked
if (d.manual && !d.ip) return true; // a switch you drew has no address to check
return d.online !== false || net.showOffline;
}
function geoFor(d) {
if (d.isRouter) return routerGeo;
return effectiveOs(d) === 'switch' ? switchGeo : nodeGeo;
}
function ensureNode(d) {
let n = nodes.get(d.key);
const geo = geoFor(d);
if (!n) {
const mat = new THREE.MeshStandardMaterial({ color: 0x888888, emissive: 0x000000, roughness: 0.45, metalness: 0.15, transparent: true });
const mesh = new THREE.Mesh(geo, mat);
mesh.userData.key = d.key;
const edges = new THREE.LineSegments(new THREE.EdgesGeometry(geo), new THREE.LineBasicMaterial({ color: edgeColor() }));
edges.scale.setScalar(1.14);
edges.visible = false;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ transparent: true, depthTest: false }));
sprite.renderOrder = 10;
const group = new THREE.Group();
group.add(mesh, edges, sprite);
scene.add(group);
n = { group: group, mesh: mesh, edges: edges, sprite: sprite, sig: '', geo: geo, shown: null, scale: 1, anim: null };
nodes.set(d.key, n);
}
if (n.geo !== geo) { // its type changed (for example to Switch)
n.geo = geo;
n.mesh.geometry = geo;
n.edges.geometry.dispose();
n.edges.geometry = new THREE.EdgesGeometry(geo);
n.sig = '';
}
// appearing and disappearing
const want = nodeVisible(d);
if (n.shown === null) {
n.shown = want;
if (want && animateNew && running && !d.isRouter) { n.scale = 0.001; n.anim = { type: 'in', t0: performance.now() }; }
else n.scale = want ? 1 : 0;
} else if (want !== n.shown) {
n.shown = want;
if (running) n.anim = { type: want ? 'in' : 'out', t0: performance.now(), from: n.scale || 1 };
else { n.anim = null; n.scale = want ? 1 : 0; }
}
n.group.visible = n.shown || !!n.anim;
n.group.scale.setScalar(Math.max(0.001, n.scale));
// position and look
n.group.position.set(d.pos.x, d.pos.y, d.pos.z);
const os = effectiveOs(d);
const color = OS_COLORS[os] || OS_COLORS.unknown;
n.mesh.material.color.setHex(color);
n.mesh.material.emissive.setHex(color);
n.mesh.material.emissiveIntensity = d.online === false ? 0.05 : 0.3;
n.mesh.material.opacity = d.online === false ? 0.35 : 1;
const isSel = selected && selected.type === 'node' && selected.key === d.key;
const isPending = pending === d.key;
n.edges.visible = !!(isSel || isPending);
n.edges.material.color.setHex(isPending ? 0xf59e0b : edgeColor());
const lines = [
title(d),
(d.ip || '') + (shareKinds(d).length ? ' \u25A4 files: ' + shareKinds(d).slice(0, 3).join('/') : ''),
(d.online === false ? 'offline · ' : '') + (d.self ? 'this computer · ' : '') + OS_NAMES[os] + (os === 'switch' && (d.info.brand || d.info.ports) ? ' · ' + [d.info.brand, d.info.ports ? d.info.ports + '-port' : ''].filter(Boolean).join(' ') : (d.ports && d.ports.length ? ' · ' + d.ports.length + (d.ports.length === 1 ? ' port' : ' ports') : ''))
];
const sig = lines.join('|') + '|' + (d.online === false);
if (sig !== n.sig) {
n.sig = sig;
if (n.sprite.material.map) n.sprite.material.map.dispose();
n.sprite.material.map = labelTexture(lines, d.online === false);
n.sprite.material.needsUpdate = true;
n.sprite.scale.set(10.5, 10.5 * 176 / 512, 1);
n.sprite.position.set(0, geo.parameters.height / 2 + 0.4 + 1.8, 0);
}
return n;
}
function removeNode(key) {
const n = nodes.get(key);
if (!n) return;
scene.remove(n.group);
if (n.sprite.material.map) n.sprite.material.map.dispose();
n.sprite.material.dispose();
n.mesh.material.dispose();
n.edges.geometry.dispose();
n.edges.material.dispose();
nodes.delete(key);
}
// A line is dotted when it is wireless. You can set it per line; "automatic" prioritizes authoritative AP / router reports or wireless device profiles.
function isWireless(l) {
if (l.cable === true && !l.auto) return false; // a cable you drew is always a cable
if (l.wireless === true) return true;
if (l.wireless === false) return false;
const ends = [l.a, l.b].map((k) => net.devices[k]).filter((d) => d && !d.isRouter);
const wlSeen = ends.some((d) => d.connSeen === 'wireless' || (d.attach && (d.attach.wireless || /wi-?fi/i.test(d.attach.via || ''))));
if (wlSeen) return true;
const wiredSeen = ends.some((d) => d.connSeen === 'wired' || (d.attach && (/cable|ethernet|port/i.test(d.attach.via || ''))));
if (wiredSeen) return false;
return ends.some((d) => ['iot', 'android'].includes(effectiveOs(d)));
}
let dashCanvas = null;
function dashTexture(len) {
if (!dashCanvas) {
dashCanvas = document.createElement('canvas');
dashCanvas.width = 4; dashCanvas.height = 32;
const c = dashCanvas.getContext('2d');
c.fillStyle = '#000'; c.fillRect(0, 0, 4, 32);
c.fillStyle = '#fff'; c.fillRect(0, 0, 4, 18); // dash 18/32, gap 14/32
}
const t = new THREE.CanvasTexture(dashCanvas);
t.wrapS = t.wrapT = THREE.RepeatWrapping;
t.repeat.set(1, Math.max(1, Math.round(len / 1.4)));
return t;
}
function applyDash(o, wl, len) {
const m = o.vis.material;
if (!wl) {
if (m.alphaMap) { m.alphaMap.dispose(); m.alphaMap = null; m.alphaTest = 0; m.needsUpdate = true; }
m.transparent = true;
o.dashLen = 0;
return;
}
const want = Math.max(1, Math.round(len / 1.4));
if (!m.alphaMap || o.dashLen !== want) {
if (m.alphaMap) m.alphaMap.dispose();
m.alphaMap = dashTexture(len);
m.transparent = true;
m.alphaTest = 0.15; // low, so the dashes stay visible while the line fades
m.needsUpdate = true;
o.dashLen = want;
}
}
function linkColor(l) {
const isSel = selected && selected.type === 'link' && selected.id === linkId(l.a, l.b);
if (isSel) return 0xf59e0b;
if (l.cable === true && !l.auto) return 0xec4899; // a physical cable you drew: pink (found-by-the-app lines stay green)
return 0x2dd4bf;
}
function placeLink(o, l) {
const A = net.devices[l.a], B = net.devices[l.b];
const a = new THREE.Vector3(A.pos.x, A.pos.y, A.pos.z), b = new THREE.Vector3(B.pos.x, B.pos.y, B.pos.z);
const dir = b.clone().sub(a);
const len = Math.max(0.001, dir.length());
const mid = a.clone().add(b).multiplyScalar(0.5);
o.group.position.copy(mid);
o.group.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir.normalize());
o.vis.scale.set(0.09, len, 0.09);
o.pick.scale.set(0.5, len, 0.5);
const na = nodes.get(l.a), nb = nodes.get(l.b);
const present = (n) => !n || n.shown || !!n.anim;
o.group.visible = present(na) && present(nb);
const sc = Math.max(0, Math.min(na ? na.scale : 1, nb ? nb.scale : 1));
o.vis.material.color.setHex(linkColor(l));
o.pulse = linkColor(l) === 0x2dd4bf && A.online !== false && B.online !== false; // only lines to machines that are online blink // the green (found-by-the-app) lines blink gently; picked or hand-drawn ones stay steady
if (!o.pulse) o.vis.material.opacity = 1;
if (o.phase === undefined) { let h = 0; const id = linkId(l.a, l.b); for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) % 9973; o.phase = (h / 9973) * 6.283; }
const isSel = selected && selected.type === 'link' && selected.id === linkId(l.a, l.b);
const wl = isWireless(l);
applyDash(o, wl, len);
o.vis.scale.x = o.vis.scale.z = (isSel ? 0.16 : (l.cable === true && !l.auto ? 0.14 : 0.09)) * Math.max(0.001, sc) * (wl ? 1.25 : 1);
}
// ---------- device groups: a soft circle around each named group, and the group can move as one ----------
const groupObjs = new Map(); // group name -> { mesh, ring, sprite, label }
let groupDiscGeo = null;
const RING_W = 0.14; // every group ring is this thick in map units, whatever the circle's size
function groupColor(name) {
let h = 0;
for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) % 360;
return new THREE.Color().setHSL(h / 360, 0.65, 0.6);
}
function groupMembers(name) {
return devices().filter((d) => !d.isRouter && d.group === name && nodeVisible(d));
}
function groupLabelTexture(name) {
const font = 'bold 56px "Segoe UI", system-ui, sans-serif';
const m = document.createElement('canvas').getContext('2d');
m.font = font;
let t = name;
while (m.measureText(t).width > 700 && t.length > 3) t = t.slice(0, -2);
const w = Math.ceil(m.measureText(t).width) + 48, h = 96;
const c = document.createElement('canvas'); c.width = w; c.height = h;
const g = c.getContext('2d');
g.fillStyle = 'rgba(8,12,20,0.78)';
g.beginPath();
if (g.roundRect) g.roundRect(2, 8, w - 4, h - 16, 24); else g.rect(2, 8, w - 4, h - 16);
g.fill();
g.font = font; g.textAlign = 'center'; g.textBaseline = 'middle';
g.fillStyle = '#ffffff'; g.fillText(t, w / 2, h / 2 + 2);
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
tex.userData = { aspect: w / h };
return tex;
}
function removeGroupObj(name) {
const o = groupObjs.get(name);
if (!o) return;
scene.remove(o.mesh, o.ring, o.sprite);
o.mesh.material.dispose(); o.ring.material.dispose(); o.ring.geometry.dispose();
if (o.sprite.material.map) o.sprite.material.map.dispose();
o.sprite.material.dispose();
groupObjs.delete(name);
}
function syncGroups() {
if (!renderer || !net) return;
const want = new Map();
if (net.groupCircles !== false) {
devices().forEach((d) => {
if (d.isRouter || !d.group || !nodeVisible(d)) return;
if (!want.has(d.group)) want.set(d.group, []);
want.get(d.group).push(d);
});
}
Array.from(groupObjs.keys()).forEach((k) => { if (!want.has(k) || want.get(k).length < 2) removeGroupObj(k); });
want.forEach((list, name) => {
if (list.length < 2) return;
let cx = 0, cz = 0;
list.forEach((d) => { cx += d.pos.x; cz += d.pos.z; });
cx /= list.length; cz /= list.length;
let r = 0;
list.forEach((d) => { r = Math.max(r, Math.hypot(d.pos.x - cx, d.pos.z - cz)); });
r = Math.min(Math.max(r + 1.6, 2.2), 400);
let o = groupObjs.get(name);
if (!o) {
if (!groupDiscGeo) { groupDiscGeo = new THREE.CircleGeometry(1, 96); }
const col = groupColor(name);
const mesh = new THREE.Mesh(groupDiscGeo, new THREE.MeshBasicMaterial({ color: col, transparent: true, opacity: 0.24, depthWrite: false, side: THREE.DoubleSide }));
const ring = new THREE.Mesh(new THREE.RingGeometry(0.9, 1, 96), new THREE.MeshBasicMaterial({ color: col, transparent: true, opacity: 1, depthWrite: false, side: THREE.DoubleSide }));
mesh.rotation.x = ring.rotation.x = -Math.PI / 2;
mesh.renderOrder = 1; ring.renderOrder = 1;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: groupLabelTexture(name), transparent: true, depthWrite: false, depthTest: false }));
sprite.renderOrder = 6;
scene.add(mesh, ring, sprite);
o = { mesh: mesh, ring: ring, sprite: sprite };
groupObjs.set(name, o);
}
const y = FLOOR_Y + 0.04;
o.mesh.position.set(cx, y, cz); o.ring.position.set(cx, y + 0.01, cz);
o.mesh.scale.setScalar(r); o.ring.scale.setScalar(r);
if (o.ringR === undefined || Math.abs(o.ringR - r) > 0.005) { // rebuild the ring so its thickness stays RING_W
o.ring.geometry.dispose();
o.ring.geometry = new THREE.RingGeometry(Math.max(0.5, 1 - RING_W / r), 1, 96);
o.ringR = r;
}
const lh = Math.min(Math.max(r * 0.3, 1.6), 3.6), asp = (o.sprite.material.map && o.sprite.material.map.userData && o.sprite.material.map.userData.aspect) || 5;
o.sprite.scale.set(lh * asp, lh, 1);
o.sprite.position.set(cx, y + 1.2, cz + r + lh * 0.6);
});
}
function clusterMates(dev) {
if (!net || net.groupCluster === false || !dev || dev.isRouter || !dev.group) return [];
return groupMembers(dev.group).filter((d) => d.key !== dev.key);
}
function syncScene() {
syncQueued = false;
if (!renderer) return;
computeKeep();
const keys = new Set();
devices().forEach((d) => { keys.add(d.key); ensureNode(d); });
Array.from(nodes.keys()).forEach((k) => { if (!keys.has(k)) removeNode(k); });
const ids = new Set();
net.links.forEach((l) => {
const id = linkId(l.a, l.b);
ids.add(id);
let o = linkObjs.get(id);
if (!o) {
const vis = new THREE.Mesh(linkGeo, new THREE.MeshBasicMaterial({ color: 0x2dd4bf, transparent: true }));
const pickMat = new THREE.MeshBasicMaterial({ visible: false });
const pick = new THREE.Mesh(linkGeo, pickMat);
pick.userData.linkId = id;
const group = new THREE.Group();
group.add(vis, pick);
scene.add(group);
o = { group: group, vis: vis, pick: pick };
linkObjs.set(id, o);
}
placeLink(o, l);
});
Array.from(linkObjs.keys()).forEach((id) => {
if (!ids.has(id)) {
const o = linkObjs.get(id);
scene.remove(o.group);
if (o.vis.material.alphaMap) o.vis.material.alphaMap.dispose();
o.vis.material.dispose();
o.pick.material.dispose();
linkObjs.delete(id);
}
});
syncServices();
syncGroups();
animateNew = true;
updateEmptyMessage();
renderList();
}
function queueSync() {
wakeLoop();
if (syncQueued) return;
syncQueued = true;
requestAnimationFrame(syncScene);
}
function updateEmptyMessage() {
const onlyRouter = devices().length <= 1;
if (webglFailed) return;
if (onlyRouter && scanKind !== 'manual') {
els.empty.textContent = net.scannedOnce
? 'No other machines were found. Check the Network setting above and scan again.'
: 'Press "Scan network" to find the machines on your network. They will appear here around your router.';
els.empty.classList.remove('hidden');
} else {
els.empty.classList.add('hidden');
}
}
function maxRadius() {
let m = 10;
devices().forEach((d) => { if (nodeVisible(d)) m = Math.max(m, Math.hypot(d.pos.x, d.pos.z)); });
return m;
}
// The map can be pushed around and zoomed out, but never out of sight: the point the camera looks at stays
// inside the area the machines cover (plus a margin), and zooming out stops a sensible distance away.
function keepMapInView() {
if (!controls || !camera) return false;
let minX = 0, maxX = 0, minZ = 0, maxZ = 0;
devices().forEach((d) => { if (!nodeVisible(d) || !d.pos) return; if (d.pos.x < minX) minX = d.pos.x; if (d.pos.x > maxX) maxX = d.pos.x; if (d.pos.z < minZ) minZ = d.pos.z; if (d.pos.z > maxZ) maxZ = d.pos.z; });
const pad = 12 + 0.1 * Math.max(maxX - minX, maxZ - minZ);
const r = maxRadius();
controls.maxDistance = Math.min(400, Math.max(70, r * 3.2 + 50));
const t = controls.target;
const cx = Math.min(maxX + pad, Math.max(minX - pad, t.x)), cz = Math.min(maxZ + pad, Math.max(minZ - pad, t.z));
const cy = Math.min(8, Math.max(-8, t.y));
if (cx === t.x && cz === t.z && cy === t.y) return false;
camera.position.x += cx - t.x; camera.position.y += cy - t.y; camera.position.z += cz - t.z; // slide the camera with it so nothing jumps
t.set(cx, cy, cz);
return true;
}
function fitView(top) {
if (!renderer) return;
const r = maxRadius();
controls.target.set(0, 0, 0);
if (top) camera.position.set(0, r * 2.0 + 18, 0.01);
else camera.position.set(0, r * 0.85 + 14, r * 1.25 + 20);