forked from vektort13/MITMVpn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard_live.php
More file actions
946 lines (873 loc) · 66.5 KB
/
Copy pathdashboard_live.php
File metadata and controls
946 lines (873 loc) · 66.5 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
<?php
declare(strict_types=1);
$requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$studentView = strpos($requestPath, '/student') === 0;
?>
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>VPN Deanonymization Lab</title>
<style>
:root {
--bg: #eef2f7;
--panel: #ffffff;
--soft: #f6f9fc;
--ink: #15212e;
--muted: #5d6d80;
--line: #dce4ee;
--blue: #1f66d1;
--green: #12805c;
--red: #d6391f;
--amber: #b7791f;
--cyan: #0b7c93;
--violet: #6b46c1;
--soft-blue: #eaf2ff;
--soft-green: #e8f7f0;
--soft-red: #fff0ed;
--soft-amber: #fff6e3;
--soft-cyan: #e2f6fb;
--soft-violet: #f1ecfd;
--shadow: 0 10px 30px rgba(20, 40, 70, .06);
--radius: 14px;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
font-size: 15px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
header {
background: linear-gradient(120deg, #0b1622 0%, #14283c 100%);
color: #fff;
padding: 22px 30px;
border-bottom: 3px solid var(--blue);
}
header .wrap { max-width: 1380px; margin: 0 auto; display: flex; justify-content: space-between; align-items: center; gap: 16px; flex-wrap: wrap; }
header h1 { margin: 0; font-size: 25px; font-weight: 800; letter-spacing: -.3px; }
header p { margin: 5px 0 0; color: #b6c6d8; font-size: 13.5px; max-width: 720px; }
main { max-width: 1380px; margin: 0 auto; padding: 20px; }
.toolbar {
display: flex; justify-content: space-between; align-items: center; gap: 12px;
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
padding: 11px 14px; margin-bottom: 16px; box-shadow: var(--shadow);
}
.toolbar .left { display: flex; align-items: center; gap: 10px; }
.toolbar-actions { display: flex; gap: 8px; flex-wrap: wrap; }
button.btn {
appearance: none; border: 1px solid #cdd9e6; background: #fff; color: var(--ink);
border-radius: 9px; padding: 8px 12px; font: inherit; font-size: 13px; font-weight: 650;
cursor: pointer; line-height: 1; transition: all .15s ease;
}
button.btn:hover { border-color: var(--blue); color: var(--blue); }
button.btn.danger { border-color: #f4c4bb; color: var(--red); background: var(--soft-red); }
button.btn.danger:hover { border-color: var(--red); }
button.btn:disabled { opacity: .55; cursor: wait; }
button.btn.small { padding: 6px 9px; font-size: 12px; }
button.btn.redirect-on { border-color: #bbe5d3; color: var(--green); background: var(--soft-green); }
button.btn.redirect-off { border-color: #d7e0ea; color: var(--muted); background: #fff; }
.lang-select {
border: 1px solid #cdd9e6; border-radius: 9px; padding: 7px 10px;
background: #fff; color: var(--ink); font: inherit; font-size: 13px; font-weight: 650;
}
.metrics { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; }
.metric { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 13px 15px; box-shadow: var(--shadow); }
.metric .label { color: var(--muted); font-size: 12px; margin-bottom: 5px; }
.metric .value { font-size: 23px; font-weight: 800; letter-spacing: -.3px; overflow-wrap: anywhere; }
.tabs { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 16px; }
.tab {
display: flex; align-items: center; gap: 10px; cursor: pointer;
background: var(--panel); border: 1.5px solid var(--line); border-radius: var(--radius);
padding: 11px 15px; box-shadow: var(--shadow); transition: all .15s ease; min-width: 200px;
}
.tab:hover { border-color: #b9c9dc; }
.tab.active { border-color: var(--blue); box-shadow: 0 0 0 3px rgba(31,102,209,.12); }
.tab .dot { width: 10px; height: 10px; border-radius: 50%; background: #c2ccd8; flex: none; }
.tab.online .dot { background: var(--green); box-shadow: 0 0 0 4px rgba(18,128,92,.16); }
.tab .tab-name { font-weight: 750; }
.tab .tab-sub { font-size: 12px; color: var(--muted); }
.tab .tab-score { margin-left: auto; font-weight: 800; font-size: 16px; }
/* dossier */
.dossier { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; margin-bottom: 18px; }
.dossier-head { display: flex; align-items: center; gap: 22px; padding: 22px 24px; border-bottom: 1px solid var(--line); background: linear-gradient(180deg, var(--soft) 0%, #fff 100%); flex-wrap: wrap; }
.ring { position: relative; width: 132px; height: 132px; border-radius: 50%; flex: none; display: grid; place-items: center; }
.ring::after { content: ""; position: absolute; inset: 13px; border-radius: 50%; background: var(--panel); }
.ring .ring-inner { position: relative; z-index: 1; text-align: center; }
.ring .ring-score { font-size: 34px; font-weight: 850; line-height: 1; letter-spacing: -1px; }
.ring .ring-cap { font-size: 11px; color: var(--muted); margin-top: 3px; }
.dossier-id { flex: 1; min-width: 280px; }
.dossier-id .who { font-size: 22px; font-weight: 820; letter-spacing: -.3px; }
.dossier-id .lvl { display: inline-flex; align-items: center; gap: 7px; margin: 6px 0 9px; font-weight: 750; font-size: 13px; padding: 4px 11px; border-radius: 999px; }
.dossier-id .summary { color: #33475b; font-size: 14.5px; }
.lvl.fully { color: var(--red); background: var(--soft-red); border: 1px solid #f4c4bb; }
.lvl.high { color: var(--amber); background: var(--soft-amber); border: 1px solid #f0d8a0; }
.lvl.medium { color: var(--cyan); background: var(--soft-cyan); border: 1px solid #bce6ef; }
.lvl.low { color: var(--muted); background: var(--soft); border: 1px solid var(--line); }
.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 14px; padding: 20px 24px; }
.tile { border: 1px solid var(--line); border-radius: 12px; padding: 13px 15px; background: var(--soft); }
.tile .t-label { display: flex; align-items: center; gap: 7px; color: var(--muted); font-size: 12px; font-weight: 650; text-transform: uppercase; letter-spacing: .03em; margin-bottom: 8px; }
.tile .t-main { font-size: 16px; font-weight: 750; overflow-wrap: anywhere; }
.tile .t-sub { font-size: 12.5px; color: var(--muted); margin-top: 3px; overflow-wrap: anywhere; }
.tile.span2 { grid-column: span 2; }
.chips { display: flex; flex-wrap: wrap; gap: 7px; }
.chip { display: inline-flex; align-items: center; gap: 6px; background: var(--soft-blue); border: 1px solid #c9ddff; color: #16459d; border-radius: 8px; padding: 4px 9px; font-size: 12.5px; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
button.chip { appearance: none; cursor: pointer; font: inherit; text-align: left; }
button.chip:hover { border-color: var(--blue); color: var(--blue); }
.chip.acct { background: var(--soft-violet); border-color: #d9caf6; color: var(--violet); font-weight: 650; }
.chip.soft { background: var(--soft-green); border-color: #bbe5d3; color: var(--green); }
.chip .badge { font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .04em; background: rgba(0,0,0,.06); border-radius: 5px; padding: 1px 5px; }
.chip .badge.idle { background: #fde2c4; color: #8a4b00; }
.fav { width: 16px; height: 16px; border-radius: 4px; flex: none; background: #fff; }
/* details */
details { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); margin-top: 14px; overflow: hidden; }
details > summary { cursor: pointer; list-style: none; padding: 14px 18px; font-weight: 750; font-size: 16px; display: flex; align-items: center; justify-content: space-between; gap: 12px; background: var(--soft); }
details > summary::-webkit-details-marker { display: none; }
details > summary .cnt { font-size: 13px; color: var(--muted); font-weight: 600; }
details[open] > summary { border-bottom: 1px solid var(--line); }
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; min-width: 760px; }
th, td { padding: 10px 13px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; }
th { color: #46566b; background: #fbfcfe; font-size: 11.5px; text-transform: uppercase; letter-spacing: .03em; }
tr:last-child td { border-bottom: 0; }
code { background: #f1f5f9; border: 1px solid #e3eaf2; border-radius: 6px; padding: 2px 6px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12.5px; overflow-wrap: anywhere; }
.pill { display: inline-flex; align-items: center; border-radius: 999px; padding: 3px 9px; font-weight: 700; font-size: 11.5px; white-space: nowrap; }
.online { color: var(--green); background: var(--soft-green); border: 1px solid #b8e3d0; }
.offline { color: var(--red); background: var(--soft-red); border: 1px solid #f4c4bb; }
.sev-high { color: var(--red); background: var(--soft-red); border: 1px solid #f4c4bb; }
.sev-medium { color: var(--amber); background: var(--soft-amber); border: 1px solid #f0d8a0; }
.sev-low { color: var(--cyan); background: var(--soft-cyan); border: 1px solid #bce6ef; }
.signal { color: var(--cyan); background: var(--soft-cyan); border: 1px solid #bce6ef; border-radius: 6px; padding: 2px 7px; font-size: 11.5px; font-weight: 700; white-space: nowrap; }
.muted { color: var(--muted); }
.empty { padding: 22px; color: var(--muted); }
.nowrap { white-space: nowrap; }
.site-cell { display: flex; align-items: center; gap: 8px; }
.redirect-cell { min-width: 220px; }
.redirect-target { margin-top: 5px; color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
.modal-backdrop {
position: fixed; inset: 0; display: none; place-items: center; z-index: 50;
background: rgba(5, 12, 20, .58); padding: 18px;
}
.modal-backdrop.open { display: grid; }
.modal {
width: min(520px, 100%); background: var(--panel); color: var(--ink);
border: 1px solid var(--line); border-radius: var(--radius); box-shadow: 0 24px 80px rgba(0,0,0,.28);
overflow: hidden;
}
.modal-head { padding: 15px 17px; border-bottom: 1px solid var(--line); background: var(--soft); }
.modal-head h3 { margin: 0; font-size: 17px; }
.modal-body { padding: 17px; display: grid; gap: 12px; }
.field { display: grid; gap: 6px; }
.field label { font-size: 12px; color: var(--muted); font-weight: 700; text-transform: uppercase; letter-spacing: .03em; }
.field input {
width: 100%; border: 1px solid #cdd9e6; border-radius: 9px; padding: 10px 11px;
background: #fff; color: var(--ink); font: inherit;
}
.modal-actions { display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; padding: 0 17px 17px; }
.modal-actions .group { display: flex; gap: 8px; flex-wrap: wrap; }
.category-sites { display: grid; gap: 8px; max-height: 420px; overflow: auto; }
.category-site-row {
display: grid; grid-template-columns: minmax(180px, 1fr) auto; gap: 12px; align-items: start;
border: 1px solid var(--line); border-radius: 10px; padding: 9px 10px; background: var(--soft);
}
.category-site-row .meta { color: var(--muted); font-size: 12px; margin-top: 4px; }
body.demo .field input { background: #091620; border-color: #28506b; color: var(--ink); }
body.demo .lang-select { background: #0c1824; border-color: #28506b; color: var(--ink); }
body:not(.student-view) [data-student-only],
body.student-view [data-admin-only] { display: none !important; }
.console-stream { display: grid; gap: 6px; max-height: 340px; overflow: auto; padding: 12px 14px; background: #08111a; color: #d9f7ff; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12.5px; }
.console-line { display: grid; grid-template-columns: 80px 140px 90px minmax(220px, 1fr); gap: 10px; align-items: baseline; border-bottom: 1px solid rgba(141,196,220,.14); padding-bottom: 6px; }
.console-line:last-child { border-bottom: 0; }
.console-time { color: #9fb7c9; } .console-client { color: #a6f3c5; } .console-kind { color: #77d7ff; text-transform: uppercase; } .console-detail { color: #93aabc; }
/* demo (dark) mode */
body.demo {
--bg: #060e16; --panel: #0f1c29; --soft: #0d1a27; --ink: #e8f6ff; --muted: #8da6ba;
--line: #213b51; --blue: #3fa9ff; --green: #2bd58f; --red: #ff6f6f; --amber: #ffce6a; --cyan: #4fdde2; --violet: #b794ff;
--soft-blue: #0f2c46; --soft-green: #0c3328; --soft-red: #34181a; --soft-amber: #332915; --soft-cyan: #0e3338; --soft-violet: #221a3a;
--shadow: 0 0 0 1px rgba(79,221,226,.06), 0 18px 50px rgba(0,0,0,.35);
}
body.demo header { background: #03080d; border-bottom-color: var(--green); }
body.demo code { color: #c8f7dc; background: #091620; border-color: #213b51; }
body.demo th { color: #a9c6da; background: #0c1825; }
body.demo button.btn { background: #0c1824; border-color: #28506b; color: var(--ink); }
@media (max-width: 1100px) { .metrics { grid-template-columns: repeat(3, 1fr); } }
@media (max-width: 760px) { .metrics { grid-template-columns: repeat(2, 1fr); } header h1 { font-size: 21px; } .dossier-head { gap: 16px; } .tile.span2 { grid-column: span 1; } }
@media (max-width: 480px) { .metrics { grid-template-columns: 1fr; } }
</style>
</head>
<body class="<?= $studentView ? 'student-view' : '' ?>">
<header>
<div class="wrap">
<div>
<h1 data-i18n="title">VPN Deanonymization Lab</h1>
<p data-i18n="subtitle">Что видит оператор VPN, когда клиент просто импортировал один конфиг и подключился — без расшифровки HTTPS и без действий на устройстве.</p>
</div>
<div class="toolbar-actions">
<select class="lang-select" data-lang-switch aria-label="Language">
<option value="ru">Русский</option>
<option value="en">English</option>
<option value="vi">Tiếng Việt</option>
<option value="zh">中文</option>
</select>
<button class="btn" type="button" data-toggle-demo data-admin-only data-i18n="demoMode">Презентационный режим</button>
</div>
</div>
</header>
<main>
<div class="toolbar">
<div class="left">
<span class="pill online" style="background:var(--soft-blue);color:var(--blue);border-color:#c9ddff">LIVE · PASSIVE</span>
<span class="pill sev-low" data-student-only data-i18n="readOnlyMode">Только просмотр</span>
<span class="muted" id="status">обновление каждые 3 сек</span>
</div>
<div class="toolbar-actions" data-admin-only>
<button class="btn small" type="button" data-export data-i18n="exportJson">Экспорт JSON клиента</button>
<button class="btn small" type="button" data-report data-i18n="htmlReport">HTML-отчёт</button>
<button class="btn small" type="button" data-flush-dns data-i18n="flushDns">Сброс DNS-кэша</button>
<button class="btn small danger" type="button" data-clear data-i18n="clearLogs">Очистить логи</button>
</div>
</div>
<div class="metrics" id="metrics"></div>
<div class="tabs" id="tabs"></div>
<div id="dossier"></div>
<details open>
<summary data-section-title="sites">🌐 Сайты и домены <span class="cnt" id="c-sites"></span></summary>
<div class="table-wrap"><table id="t-sites"></table></div>
</details>
<details>
<summary data-section-title="apps">🧩 Обнаруженное ПО <span class="cnt" id="c-apps"></span></summary>
<div class="table-wrap"><table id="t-apps"></table></div>
</details>
<details>
<summary data-section-title="risks">⚠️ Риски (Tor / proxy / VPN / remote-admin) <span class="cnt" id="c-risks"></span></summary>
<div class="table-wrap"><table id="t-risks"></table></div>
</details>
<details>
<summary data-section-title="tls">🔑 TLS / QUIC fingerprints (JA3) <span class="cnt" id="c-tls"></span></summary>
<div class="table-wrap"><table id="t-tls"></table></div>
</details>
<details>
<summary data-section-title="signals">🛰️ Сигналы классификатора <span class="cnt" id="c-signals"></span></summary>
<div class="table-wrap"><table id="t-signals"></table></div>
</details>
<details>
<summary data-section-title="timeline">🧭 Timeline активности <span class="cnt" id="c-timeline"></span></summary>
<div class="table-wrap"><table id="t-timeline"></table></div>
</details>
<details>
<summary data-section-title="console">🖥️ Live-консоль событий</summary>
<div id="console" class="console-stream"></div>
</details>
</main>
<div class="modal-backdrop" id="redirect-modal" aria-hidden="true" data-admin-only>
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="redirect-title">
<div class="modal-head">
<h3 id="redirect-title" data-i18n="dnsRedirectLab">DNS Redirect Lab</h3>
</div>
<div class="modal-body">
<div class="field">
<label data-i18n="sourceDomain">Исходный домен</label>
<input id="redirect-domain" type="text" readonly>
</div>
<div class="field">
<label data-i18n="redirectTarget">Куда направить</label>
<input id="redirect-target" type="text" placeholder="example.org или 10.8.0.1" autocomplete="off">
</div>
<div class="muted" data-i18n="dnsOnlyNote">DNS-only: для HTTPS браузер обычно покажет ошибку сертификата, если целевой сервер не обслуживает исходный hostname.</div>
</div>
<div class="modal-actions">
<div class="group">
<button class="btn redirect-on" type="button" data-redirect-save data-i18n="redirectOn">Redirect On</button>
<button class="btn danger" type="button" data-redirect-delete data-i18n="redirectOff">Redirect Off</button>
</div>
<div class="group">
<button class="btn" type="button" data-redirect-close data-i18n="close">Закрыть</button>
</div>
</div>
</div>
</div>
<div class="modal-backdrop" id="category-modal" aria-hidden="true">
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="category-title">
<div class="modal-head">
<h3 id="category-title">Sites in category</h3>
</div>
<div class="modal-body">
<div id="category-sites" class="category-sites"></div>
</div>
<div class="modal-actions">
<div></div>
<div class="group">
<button class="btn" type="button" data-category-close data-i18n="close">Закрыть</button>
</div>
</div>
</div>
</div>
<script>
const readOnly = <?= $studentView ? 'true' : 'false' ?>;
const apiUrl = readOnly ? '/student/api.php' : '/api.php';
const faviconUrl = readOnly ? '/student/favicon.php' : '/favicon.php';
const logsUrl = '/logs.php';
let selected = localStorage.getItem('lab-selected') || '';
let redirectState = { redirects: {} };
let redirectModalDomain = '';
let lang = localStorage.getItem('lab-lang') || 'ru';
const LANG_META = { ru: 'ru', en: 'en', vi: 'vi', zh: 'zh-CN' };
const I18N = {
ru: {
title: 'VPN Deanonymization Lab',
subtitle: 'Что видит оператор VPN, когда клиент просто импортировал один конфиг и подключился — без расшифровки HTTPS и без действий на устройстве.',
demoMode: 'Презентационный режим', normalMode: 'Обычный режим',
statusPolling: 'обновление каждые 3 сек', statusUpdated: 'обновлено {time}', statusError: 'ошибка: {message}',
exportJson: 'Экспорт JSON клиента', htmlReport: 'HTML-отчёт', flushDns: 'Сброс DNS-кэша', clearLogs: 'Очистить логи', readOnlyMode: 'Только просмотр',
clientsOnline: 'Клиентов онлайн', maxScore: 'Макс. deanon-score', accountsFound: 'Аккаунтов выявлено', appsFound: 'ПО опознано', domains: 'Доменов',
deanonScore: 'deanon-score', trafficIn: 'вход', trafficOut: 'выход',
online: 'online', offline: 'offline', chooseClient: 'Выберите клиента.', noData: 'нет данных', waitingTcp: 'ожидает TCP-сигналов',
noSession: 'нет сессии', geoUnavailable: 'гео недоступно', previousSession: 'прошлая сессия',
realIngress: '📍 Реальный вход (до VPN)', operatingSystem: '💻 Операционная система', browserTls: '🌐 Браузер / TLS-клиент',
session: '⏱️ Сессия', traffic: '📦 Трафик', accountsDevices: '👤 Аккаунты и устройства',
softwareIdle: '🧩 ПО (фон = выдало себя без действий)', interestsCategories: '🏷️ Интересы / категории', recentSites: '🔎 Недавние сайты',
idle: 'фон', domainsCount: '{n} доменов', appLinksCount: '{n} связок',
sectionSites: '🌐 Сайты и домены', sectionApps: '🧩 Обнаруженное ПО', sectionRisks: '⚠️ Риски (Tor / proxy / VPN / remote-admin)',
sectionTls: '🔑 TLS / QUIC fingerprints (JA3)', sectionSignals: '🛰️ Сигналы классификатора', sectionTimeline: '🧭 Timeline активности', sectionConsole: '🖥️ Live-консоль событий',
time: 'Время', client: 'Клиент', site: 'Сайт', redirect: 'Редирект', dwell: 'Длит.', source: 'Источник', count: '×', software: 'ПО',
app: 'ПО', category: 'Категория', confidence: 'Уверенность', how: 'Как', signals: 'Сигналы', backgroundTelemetry: 'фоновая телеметрия', afterAction: 'после действия',
level: 'Уровень', event: 'Событие', detail: 'Деталь', server: 'SNI / сервер', tlsClient: 'Клиент', uniqueness: 'Уникальность', tls: 'TLS',
shared: 'общий', uniqueLab: 'уникален в lab', clientsHits: '{clients} клиентов · {hits} событий',
sitesEmpty: 'Домены появятся после DNS / TLS SNI / QUIC / HTTP событий.', appsEmpty: 'Признаки ПО появятся после сетевой активности.',
risksEmpty: 'Рисков не обнаружено.', tlsEmpty: 'TLS/QUIC metadata появятся после HTTPS/QUIC-соединений.',
signalsEmpty: 'Сигналы появятся после сетевой активности.', timelineEmpty: 'Timeline появится после активности.', consoleEmpty: 'События появятся после подключения и активности клиентов.',
sourceDomain: 'Исходный домен', redirectTarget: 'Куда направить', dnsRedirectLab: 'DNS Redirect Lab', redirectOn: 'Редирект вкл.', redirectOff: 'Редирект выкл.', dnsOnlyNote: 'DNS-only: для HTTPS браузер обычно покажет ошибку сертификата, если целевой сервер не обслуживает исходный hostname.',
close: 'Закрыть', mobile: 'моб.', confirmClear: 'Очистить журналы DNS, Suricata, p0f, сессий и текущую сводку?',
clearing: 'очищаю...', cleared: 'логи очищены', clearError: 'ошибка очистки: {message}',
applyingRedirect: 'применяю DNS redirect...', redirectEnabled: 'DNS redirect включен, dnsmasq перезапущен', redirectDisabled: 'DNS redirect выключен, dnsmasq перезапущен', redirectError: 'ошибка redirect: {message}',
disablingRedirect: 'выключаю DNS redirect...', flushingDns: 'сбрасываю DNS-кэш сервера...', dnsFlushed: 'DNS-кэш сервера сброшен; клиентский кэш может жить отдельно', dnsFlushError: 'ошибка DNS flush: {message}',
sitesInCategory: 'Сайты категории', noSitesInCategory: 'В этой категории пока нет сайтов.', lastSeen: 'последний раз', sources: 'источники',
level_fully: 'полная деанонимизация', level_high: 'высокая', level_medium: 'средняя', level_low: 'низкая',
summarySignalsLow: 'сигналов пока недостаточно — нужен трафик клиента', summaryIngress: 'реальный вход: {value}', summaryAccounts: 'аккаунт-сигналы: {value}', summaryIdleApps: '{n} прилож. выдали себя в фоне'
},
en: {
title: 'VPN Deanonymization Lab',
subtitle: 'What a VPN operator can see after a client imports one config and connects — without HTTPS decryption or actions on the device.',
demoMode: 'Presentation mode', normalMode: 'Normal mode',
statusPolling: 'refreshing every 3 sec', statusUpdated: 'updated {time}', statusError: 'error: {message}',
exportJson: 'Export client JSON', htmlReport: 'HTML report', flushDns: 'Flush DNS cache', clearLogs: 'Clear logs', readOnlyMode: 'Read-only',
clientsOnline: 'Clients online', maxScore: 'Max deanon score', accountsFound: 'Account signals', appsFound: 'Apps identified', domains: 'Domains',
deanonScore: 'deanon score', trafficIn: 'in', trafficOut: 'out',
online: 'online', offline: 'offline', chooseClient: 'Select a client.', noData: 'no data', waitingTcp: 'waiting for TCP signals',
noSession: 'no session', geoUnavailable: 'geo unavailable', previousSession: 'previous session',
realIngress: '📍 Real ingress before VPN', operatingSystem: '💻 Operating system', browserTls: '🌐 Browser / TLS client',
session: '⏱️ Session', traffic: '📦 Traffic', accountsDevices: '👤 Accounts and devices',
softwareIdle: '🧩 Software (background signals)', interestsCategories: '🏷️ Interests / categories', recentSites: '🔎 Recent sites',
idle: 'idle', domainsCount: '{n} domains', appLinksCount: '{n} links',
sectionSites: '🌐 Sites and domains', sectionApps: '🧩 Detected software', sectionRisks: '⚠️ Risks (Tor / proxy / VPN / remote admin)',
sectionTls: '🔑 TLS / QUIC fingerprints (JA3)', sectionSignals: '🛰️ Classifier signals', sectionTimeline: '🧭 Activity timeline', sectionConsole: '🖥️ Live event console',
time: 'Time', client: 'Client', site: 'Site', redirect: 'Redirect', dwell: 'Dwell', source: 'Source', count: '×', software: 'Software',
app: 'App', category: 'Category', confidence: 'Confidence', how: 'How', signals: 'Signals', backgroundTelemetry: 'background telemetry', afterAction: 'after action',
level: 'Level', event: 'Event', detail: 'Detail', server: 'SNI / server', tlsClient: 'Client', uniqueness: 'Uniqueness', tls: 'TLS',
shared: 'shared', uniqueLab: 'unique lab', clientsHits: '{clients} clients · {hits} hits',
sitesEmpty: 'Domains will appear after DNS / TLS SNI / QUIC / HTTP events.', appsEmpty: 'Software signals will appear after network activity.',
risksEmpty: 'No risks detected.', tlsEmpty: 'TLS/QUIC metadata will appear after HTTPS/QUIC connections.',
signalsEmpty: 'Signals will appear after network activity.', timelineEmpty: 'Timeline will appear after activity.', consoleEmpty: 'Events will appear after clients connect and browse.',
sourceDomain: 'Source domain', redirectTarget: 'Redirect target', dnsRedirectLab: 'DNS Redirect Lab', redirectOn: 'Redirect On', redirectOff: 'Redirect Off', dnsOnlyNote: 'DNS-only: for HTTPS, browsers usually show a certificate error unless the target server serves the original hostname.',
close: 'Close', mobile: 'mobile', confirmClear: 'Clear DNS, Suricata, p0f, session logs and the current summary?',
clearing: 'clearing...', cleared: 'logs cleared', clearError: 'clear error: {message}',
applyingRedirect: 'applying DNS redirect...', redirectEnabled: 'DNS redirect enabled, dnsmasq restarted', redirectDisabled: 'DNS redirect disabled, dnsmasq restarted', redirectError: 'redirect error: {message}',
disablingRedirect: 'disabling DNS redirect...', flushingDns: 'flushing server DNS cache...', dnsFlushed: 'Server DNS cache flushed; client-side cache may still live separately', dnsFlushError: 'DNS flush error: {message}',
sitesInCategory: 'Sites in category', noSitesInCategory: 'No sites in this category yet.', lastSeen: 'last seen', sources: 'sources',
level_fully: 'full deanonymization', level_high: 'high', level_medium: 'medium', level_low: 'low',
summarySignalsLow: 'not enough signals yet — client traffic is needed', summaryIngress: 'real ingress: {value}', summaryAccounts: 'account signals: {value}', summaryIdleApps: '{n} apps leaked background signals'
},
vi: {
title: 'Phòng lab Deanonymization VPN',
subtitle: 'Những gì nhà vận hành VPN có thể thấy khi client chỉ nhập một cấu hình và kết nối — không giải mã HTTPS và không thao tác trên thiết bị.',
demoMode: 'Chế độ trình chiếu', normalMode: 'Chế độ thường',
statusPolling: 'cập nhật mỗi 3 giây', statusUpdated: 'đã cập nhật {time}', statusError: 'lỗi: {message}',
exportJson: 'Xuất JSON client', htmlReport: 'Báo cáo HTML', flushDns: 'Xóa cache DNS', clearLogs: 'Xóa log', readOnlyMode: 'Chỉ xem',
clientsOnline: 'Client online', maxScore: 'Điểm deanon cao nhất', accountsFound: 'Tín hiệu tài khoản', appsFound: 'Ứng dụng nhận diện', domains: 'Tên miền',
deanonScore: 'điểm deanon', trafficIn: 'vào', trafficOut: 'ra',
online: 'online', offline: 'offline', chooseClient: 'Chọn client.', noData: 'chưa có dữ liệu', waitingTcp: 'đang chờ tín hiệu TCP',
noSession: 'không có phiên', geoUnavailable: 'không có geo', previousSession: 'phiên trước',
realIngress: '📍 IP vào thật trước VPN', operatingSystem: '💻 Hệ điều hành', browserTls: '🌐 Trình duyệt / TLS client',
session: '⏱️ Phiên', traffic: '📦 Lưu lượng', accountsDevices: '👤 Tài khoản và thiết bị',
softwareIdle: '🧩 Phần mềm (tín hiệu nền)', interestsCategories: '🏷️ Sở thích / danh mục', recentSites: '🔎 Website gần đây',
idle: 'nền', domainsCount: '{n} tên miền', appLinksCount: '{n} liên kết',
sectionSites: '🌐 Website và tên miền', sectionApps: '🧩 Phần mềm phát hiện', sectionRisks: '⚠️ Rủi ro (Tor / proxy / VPN / remote admin)',
sectionTls: '🔑 Dấu vân tay TLS / QUIC (JA3)', sectionSignals: '🛰️ Tín hiệu phân loại', sectionTimeline: '🧭 Dòng thời gian hoạt động', sectionConsole: '🖥️ Console sự kiện live',
time: 'Thời gian', client: 'Client', site: 'Website', redirect: 'Redirect', dwell: 'Thời lượng', source: 'Nguồn', count: '×', software: 'Phần mềm',
app: 'Ứng dụng', category: 'Danh mục', confidence: 'Độ tin cậy', how: 'Cách phát hiện', signals: 'Tín hiệu', backgroundTelemetry: 'telemetry nền', afterAction: 'sau thao tác',
level: 'Mức', event: 'Sự kiện', detail: 'Chi tiết', server: 'SNI / server', tlsClient: 'Client', uniqueness: 'Độ duy nhất', tls: 'TLS',
shared: 'dùng chung', uniqueLab: 'duy nhất trong lab', clientsHits: '{clients} client · {hits} lần',
sitesEmpty: 'Tên miền sẽ xuất hiện sau sự kiện DNS / TLS SNI / QUIC / HTTP.', appsEmpty: 'Tín hiệu phần mềm sẽ xuất hiện sau hoạt động mạng.',
risksEmpty: 'Chưa phát hiện rủi ro.', tlsEmpty: 'Metadata TLS/QUIC sẽ xuất hiện sau kết nối HTTPS/QUIC.',
signalsEmpty: 'Tín hiệu sẽ xuất hiện sau hoạt động mạng.', timelineEmpty: 'Timeline sẽ xuất hiện sau khi có hoạt động.', consoleEmpty: 'Sự kiện sẽ xuất hiện sau khi client kết nối và truy cập.',
sourceDomain: 'Tên miền gốc', redirectTarget: 'Đích redirect', dnsRedirectLab: 'Lab DNS Redirect', redirectOn: 'Bật redirect', redirectOff: 'Tắt redirect', dnsOnlyNote: 'Chỉ DNS: với HTTPS, trình duyệt thường báo lỗi chứng chỉ nếu server đích không phục vụ hostname gốc.',
close: 'Đóng', mobile: 'di động', confirmClear: 'Xóa log DNS, Suricata, p0f, phiên và summary hiện tại?',
clearing: 'đang xóa...', cleared: 'đã xóa log', clearError: 'lỗi xóa: {message}',
applyingRedirect: 'đang áp dụng DNS redirect...', redirectEnabled: 'Đã bật DNS redirect, dnsmasq đã khởi động lại', redirectDisabled: 'Đã tắt DNS redirect, dnsmasq đã khởi động lại', redirectError: 'lỗi redirect: {message}',
disablingRedirect: 'đang tắt DNS redirect...', flushingDns: 'đang xóa cache DNS server...', dnsFlushed: 'Đã xóa cache DNS server; cache phía client có thể vẫn còn', dnsFlushError: 'lỗi xóa DNS: {message}',
sitesInCategory: 'Website trong danh mục', noSitesInCategory: 'Chưa có website trong danh mục này.', lastSeen: 'lần cuối', sources: 'nguồn',
level_fully: 'deanonymization đầy đủ', level_high: 'cao', level_medium: 'trung bình', level_low: 'thấp',
summarySignalsLow: 'chưa đủ tín hiệu — cần lưu lượng của client', summaryIngress: 'IP vào thật: {value}', summaryAccounts: 'tín hiệu tài khoản: {value}', summaryIdleApps: '{n} ứng dụng lộ tín hiệu nền'
},
zh: {
title: 'VPN 去匿名化实验室',
subtitle: '客户端仅导入一个配置并连接后,VPN 运营者能看到什么——不解密 HTTPS,也不操作客户端设备。',
demoMode: '演示模式', normalMode: '普通模式',
statusPolling: '每 3 秒刷新', statusUpdated: '已更新 {time}', statusError: '错误:{message}',
exportJson: '导出客户端 JSON', htmlReport: 'HTML 报告', flushDns: '清除 DNS 缓存', clearLogs: '清空日志', readOnlyMode: '只读',
clientsOnline: '在线客户端', maxScore: '最高去匿名分数', accountsFound: '账号信号', appsFound: '已识别软件', domains: '域名',
deanonScore: '去匿名分数', trafficIn: '入', trafficOut: '出',
online: '在线', offline: '离线', chooseClient: '请选择客户端。', noData: '无数据', waitingTcp: '等待 TCP 信号',
noSession: '无会话', geoUnavailable: '地理信息不可用', previousSession: '上一次会话',
realIngress: '📍 VPN 前真实入口', operatingSystem: '💻 操作系统', browserTls: '🌐 浏览器 / TLS 客户端',
session: '⏱️ 会话', traffic: '📦 流量', accountsDevices: '👤 账号与设备',
softwareIdle: '🧩 软件(后台信号)', interestsCategories: '🏷️ 兴趣 / 分类', recentSites: '🔎 最近网站',
idle: '后台', domainsCount: '{n} 个域名', appLinksCount: '{n} 个关联',
sectionSites: '🌐 网站和域名', sectionApps: '🧩 检测到的软件', sectionRisks: '⚠️ 风险(Tor / 代理 / VPN / 远程管理)',
sectionTls: '🔑 TLS / QUIC 指纹(JA3)', sectionSignals: '🛰️ 分类器信号', sectionTimeline: '🧭 活动时间线', sectionConsole: '🖥️ 实时事件控制台',
time: '时间', client: '客户端', site: '网站', redirect: '重定向', dwell: '停留', source: '来源', count: '×', software: '软件',
app: '应用', category: '分类', confidence: '置信度', how: '方式', signals: '信号', backgroundTelemetry: '后台遥测', afterAction: '操作后',
level: '级别', event: '事件', detail: '详情', server: 'SNI / 服务器', tlsClient: '客户端', uniqueness: '唯一性', tls: 'TLS',
shared: '共享', uniqueLab: '实验室唯一', clientsHits: '{clients} 个客户端 · {hits} 次',
sitesEmpty: 'DNS / TLS SNI / QUIC / HTTP 事件出现后会显示域名。', appsEmpty: '网络活动出现后会显示软件信号。',
risksEmpty: '未发现风险。', tlsEmpty: 'HTTPS/QUIC 连接后会显示 TLS/QUIC 元数据。',
signalsEmpty: '网络活动出现后会显示信号。', timelineEmpty: '有活动后会显示时间线。', consoleEmpty: '客户端连接并访问后会显示事件。',
sourceDomain: '源域名', redirectTarget: '重定向目标', dnsRedirectLab: 'DNS 重定向实验', redirectOn: '开启重定向', redirectOff: '关闭重定向', dnsOnlyNote: '仅 DNS:对于 HTTPS,如果目标服务器不服务原始 hostname,浏览器通常会显示证书错误。',
close: '关闭', mobile: '移动网络', confirmClear: '清空 DNS、Suricata、p0f、会话日志和当前摘要?',
clearing: '正在清空...', cleared: '日志已清空', clearError: '清空错误:{message}',
applyingRedirect: '正在应用 DNS 重定向...', redirectEnabled: 'DNS 重定向已启用,dnsmasq 已重启', redirectDisabled: 'DNS 重定向已关闭,dnsmasq 已重启', redirectError: '重定向错误:{message}',
disablingRedirect: '正在关闭 DNS 重定向...', flushingDns: '正在清除服务器 DNS 缓存...', dnsFlushed: '服务器 DNS 缓存已清除;客户端缓存可能仍然存在', dnsFlushError: 'DNS 清除错误:{message}',
sitesInCategory: '分类中的网站', noSitesInCategory: '此分类暂无网站。', lastSeen: '最后出现', sources: '来源',
level_fully: '完全去匿名化', level_high: '高', level_medium: '中', level_low: '低',
summarySignalsLow: '信号不足——需要客户端流量', summaryIngress: '真实入口:{value}', summaryAccounts: '账号信号:{value}', summaryIdleApps: '{n} 个应用泄露后台信号'
}
};
const CATEGORY_LABELS = {
'privacy/proxy': { ru: 'Приватность / proxy', en: 'Privacy / proxy', vi: 'Riêng tư / proxy', zh: '隐私 / 代理' },
'messenger': { ru: 'Мессенджеры', en: 'Messengers', vi: 'Nhắn tin', zh: '即时通讯' },
'video/voice': { ru: 'Видео / звонки', en: 'Video / voice', vi: 'Video / thoại', zh: '视频 / 语音' },
'media': { ru: 'Медиа', en: 'Media', vi: 'Giải trí', zh: '媒体' },
'social': { ru: 'Соцсети', en: 'Social', vi: 'Mạng xã hội', zh: '社交' },
'developer': { ru: 'Разработка', en: 'Developer', vi: 'Lập trình', zh: '开发' },
'security/wallet': { ru: 'Безопасность / wallet', en: 'Security / wallet', vi: 'Bảo mật / ví', zh: '安全 / 钱包' },
'cloud': { ru: 'Облако', en: 'Cloud', vi: 'Đám mây', zh: '云服务' },
'browser/os': { ru: 'Браузер / ОС', en: 'Browser / OS', vi: 'Trình duyệt / HĐH', zh: '浏览器 / 系统' },
'gaming': { ru: 'Игры', en: 'Gaming', vi: 'Game', zh: '游戏' },
'remote-admin': { ru: 'Удаленное управление', en: 'Remote admin', vi: 'Quản trị từ xa', zh: '远程管理' },
'ads/trackers': { ru: 'Реклама / трекеры', en: 'Ads / trackers', vi: 'Quảng cáo / theo dõi', zh: '广告 / 跟踪器' },
'uncategorized': { ru: 'Без категории', en: 'Uncategorized', vi: 'Chưa phân loại', zh: '未分类' }
};
function t(key, vars = {}) {
const dict = I18N[lang] || I18N.ru;
let text = dict[key] ?? I18N.en[key] ?? I18N.ru[key] ?? key;
for (const [name, value] of Object.entries(vars)) {
text = text.replaceAll(`{${name}}`, String(value));
}
return text;
}
function esc(value) {
return String(value ?? '').replace(/[&<>"']/g, c => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[c]));
}
const code = v => `<code>${esc(v)}</code>`;
const fav = d => `<img class="fav" src="${faviconUrl}?domain=${encodeURIComponent(d || '')}" alt="">`;
function levelLabel(level, fallback = '') {
return t(`level_${level || 'low'}`) || fallback || level || '';
}
function categoryLabel(category) {
const value = category || 'uncategorized';
return (CATEGORY_LABELS[value] && (CATEGORY_LABELS[value][lang] || CATEGORY_LABELS[value].en)) || value;
}
function localizedSummary(id) {
const signals = id?.signals || {};
const parts = [];
if (signals.location) parts.push(t('summaryIngress', { value: signals.location }));
if (signals.isp) parts.push(signals.isp);
if (signals.os) parts.push(signals.os);
if (signals.browser) parts.push(signals.browser);
if (signals.tls_client && signals.tls_client !== signals.browser) parts.push(signals.tls_client);
if (Array.isArray(signals.accounts) && signals.accounts.length) parts.push(t('summaryAccounts', { value: signals.accounts.slice(0, 4).join(', ') }));
if (signals.idle_software_count) parts.push(t('summaryIdleApps', { n: signals.idle_software_count }));
return parts.length ? parts.join(' · ') : t('summarySignalsLow');
}
function sectionTitle(key) {
return t(`section${key[0].toUpperCase()}${key.slice(1)}`);
}
function applyStaticI18n() {
document.documentElement.lang = LANG_META[lang] || lang;
document.title = t('title');
document.querySelectorAll('[data-i18n]').forEach(el => { el.textContent = t(el.dataset.i18n); });
const selector = document.querySelector('[data-lang-switch]');
if (selector) selector.value = lang;
const demoButton = document.querySelector('[data-toggle-demo]');
if (demoButton) demoButton.textContent = document.body.classList.contains('demo') ? t('normalMode') : t('demoMode');
document.querySelectorAll('[data-section-title]').forEach(summary => {
const count = summary.querySelector('.cnt');
const countId = count ? count.id : '';
summary.innerHTML = `${sectionTitle(summary.dataset.sectionTitle)}${countId ? ` <span class="cnt" id="${countId}">${count.textContent || ''}</span>` : ''}`;
});
if (!lastData) document.getElementById('status').textContent = t('statusPolling');
}
function duration(s) {
s = Number(s || 0); if (s <= 0) return lang === 'zh' ? '0 秒' : lang === 'vi' ? '0 giây' : lang === 'en' ? '0 sec' : '0 сек';
const d = Math.floor(s/86400); s%=86400; const h = Math.floor(s/3600); s%=3600; const m = Math.floor(s/60); s%=60;
const units = {
ru: [' д', ' ч', ' мин', ' сек'],
en: [' d', ' h', ' min', ' sec'],
vi: [' ngày', ' giờ', ' phút', ' giây'],
zh: [' 天', ' 小时', ' 分', ' 秒'],
}[lang] || [' d', ' h', ' min', ' sec'];
const p = []; if (d) p.push(d+units[0]); if (h) p.push(h+units[1]); if (m) p.push(m+units[2]); if (!p.length) p.push(s+units[3]);
return p.slice(0,3).join(' ');
}
function bytes(v) { let n = Number(v||0); const u=['B','KB','MB','GB','TB']; let i=0; while (n>=1024 && i<u.length-1){n/=1024;i++;} return `${i?n.toFixed(1):Math.round(n)} ${u[i]}`; }
function chips(items, cls='') { if (!items || !items.length) return '<span class="muted">—</span>'; return `<div class="chips">${items.join('')}</div>`; }
const clientsOf = data => Object.entries(data.clients || {}).map(([client, row]) => ({ client, ...row }));
function renderMetrics(data, cl) {
const active = cl.filter(c => c.active).length;
const maxScore = Math.max(0, ...cl.map(c => (c.identity || {}).score || 0));
const accounts = new Set(cl.flatMap(c => (c.accounts || []).map(a => a.service))).size;
const domains = cl.reduce((s, c) => s + (c.domains || []).length, 0);
const apps = new Set(cl.flatMap(c => (c.apps || []).map(a => a.app))).size;
const rows = [
[t('clientsOnline'), `${active} / ${cl.length}`],
[t('maxScore'), maxScore],
[t('accountsFound'), accounts],
[t('appsFound'), apps],
[t('domains'), domains],
];
document.getElementById('metrics').innerHTML = rows.map(([l, v]) =>
`<div class="metric"><div class="label">${esc(l)}</div><div class="value">${esc(v)}</div></div>`).join('');
}
function renderTabs(cl) {
if (cl.length && !cl.some(c => c.client === selected)) selected = cl[0].client;
document.getElementById('tabs').innerHTML = cl.map(c => {
const sc = (c.identity || {}).score || 0;
return `<div class="tab ${c.active ? 'online' : ''} ${c.client === selected ? 'active' : ''}" data-tab="${esc(c.client)}">
<span class="dot"></span>
<span><span class="tab-name">${esc(c.label || c.client)}</span><br><span class="tab-sub">${esc(c.client)} · ${c.active ? t('online') : t('offline')}</span></span>
<span class="tab-score" style="color:${sc>=85?'var(--red)':sc>=60?'var(--amber)':'var(--muted)'}">${sc}</span>
</div>`;
}).join('');
}
function tile(label, main, sub) {
return `<div class="tile"><div class="t-label">${label}</div><div class="t-main">${main || '<span class="muted">—</span>'}</div>${sub ? `<div class="t-sub">${sub}</div>` : ''}</div>`;
}
function hintText(hint) {
if (!hint || !hint.label) return '';
return `${hint.label} · ${hint.confidence || 0}%`;
}
function renderDossier(row) {
const el = document.getElementById('dossier');
if (!row) { el.innerHTML = `<div class="dossier"><div class="empty">${esc(t('chooseClient'))}</div></div>`; return; }
const id = row.identity || { score: 0, level: 'low', level_label: 'низкая', summary: 'нет данных', signals: {} };
const geo = row.real_geo && row.real_geo.status === 'success' ? row.real_geo : null;
const ringColor = id.score >= 85 ? 'var(--red)' : id.score >= 60 ? 'var(--amber)' : id.score >= 35 ? 'var(--cyan)' : 'var(--muted)';
const accounts = (row.accounts || []).map(a => `<span class="chip acct" title="${esc(a.inference)} · ${esc(a.evidence)}">👤 ${esc(a.service)}</span>`);
const software = (row.apps || []).slice(0, 16).map(a =>
`<span class="chip soft" title="${esc(a.category || '')} · ${esc(a.score)}%">${esc(a.app)}${a.auto ? ` <span class="badge idle">${esc(t('idle'))}</span>` : ''}</span>`);
const interests = (row.category_stats || []).slice(0, 8).map(c =>
`<button class="chip" type="button" data-category-chip data-category-client="${esc(row.client)}" data-category="${esc(c.category || 'uncategorized')}">${esc(categoryLabel(c.category))} · ${esc(c.events || 0)}</button>`);
const sites = (row.domains || []).slice(0, 14).map(d => `<span class="chip">${fav(d.domain)} ${esc(d.domain)}</span>`);
const osRow = row.os || {};
const os = (osRow.guess && !String(osRow.guess).includes('???')) ? esc(osRow.guess) : `<span class="muted">${esc(t('waitingTcp'))}</span>`;
const osSub = osRow.last_seen
? `${esc(osRow.method || 'p0f')} · ${esc(osRow.confidence || 0)}% · ${esc(osRow.last_seen)}${osRow.dist ? '<br>dist: ' + esc(osRow.dist) : ''}${osRow.raw_sig ? '<br>' + code(osRow.raw_sig) : ''}`
: '';
const tlsSummary = row.tls_client_summary || {};
const tlsHint = tlsSummary.dominant_hint || null;
const browser = id.signals && id.signals.browser ? esc(id.signals.browser) : (tlsHint ? esc(tlsHint.label) : '<span class="muted">—</span>');
const browserSub = tlsHint
? `${esc(tlsHint.reason || '')}<br>${esc(tlsSummary.unique_ja3 || 0)} JA3 · ${esc(tlsSummary.unique_to_client || 0)} ${esc(t('uniqueLab'))}`
: (row.real_ip ? code(row.real_ip) + (row.real_ip_source === 'last-session' ? ` <span class="muted">(${esc(t('previousSession'))})</span>` : '') : '');
const session = row.active ? `${duration(row.duration_seconds)}` : `<span class="muted">${esc(t('offline'))}</span>`;
const traffic = `${bytes(row.bytes_received)} ${esc(t('trafficIn'))} · ${bytes(row.bytes_sent)} ${esc(t('trafficOut'))}`;
const geoMain = geo ? `${esc([geo.city, geo.country].filter(Boolean).join(', '))}` : (row.real_ip ? `<span class="muted">${esc(t('geoUnavailable'))}</span>` : `<span class="muted">${esc(t('noSession'))}</span>`);
const geoSub = geo ? `${esc(geo.isp || geo.org || '')}${geo.as ? ' · ' + esc(geo.as) : ''}${geo.reverse ? '<br>rDNS: ' + esc(geo.reverse) : ''}${geo.mobile ? ' · 📱 ' + esc(t('mobile')) : ''}${geo.proxy ? ' · ⚠ proxy/VPN' : ''}` : (row.real_ip ? esc(row.real_ip) : '');
el.innerHTML = `<div class="dossier">
<div class="dossier-head">
<div class="ring" style="background:conic-gradient(${ringColor} ${id.score}%, var(--line) 0)">
<div class="ring-inner"><div class="ring-score" style="color:${ringColor}">${id.score}</div><div class="ring-cap">${esc(t('deanonScore'))}</div></div>
</div>
<div class="dossier-id">
<div class="who">${esc(row.label || row.client)} ${row.active ? `<span class="pill online">${esc(t('online').toUpperCase())}</span>` : `<span class="pill offline">${esc(t('offline').toUpperCase())}</span>`}</div>
<div class="lvl ${id.level}">🎯 ${esc(levelLabel(id.level, id.level_label))}</div>
<div class="summary">${esc(localizedSummary(id))}</div>
</div>
</div>
<div class="tiles">
${tile(t('realIngress'), geoMain, geoSub)}
${tile(t('operatingSystem'), os, osSub)}
${tile(t('browserTls'), browser, browserSub)}
${tile(t('session'), session, row.connected_since ? esc(row.connected_since) : '')}
${tile(t('traffic'), traffic, '')}
<div class="tile span2"><div class="t-label">${esc(t('accountsDevices'))}</div>${chips(accounts)}</div>
<div class="tile span2"><div class="t-label">${esc(t('softwareIdle'))}</div>${chips(software)}</div>
<div class="tile span2"><div class="t-label">${esc(t('interestsCategories'))}</div>${chips(interests)}</div>
<div class="tile span2"><div class="t-label">${esc(t('recentSites'))}</div>${chips(sites)}</div>
</div>
</div>`;
}
function table(id, head, rows, empty) {
const el = document.getElementById(id);
el.innerHTML = rows.length ? `<thead>${head}</thead><tbody>${rows.join('')}</tbody>`
: `<thead>${head}</thead><tbody><tr><td colspan="12" class="empty">${esc(empty)}</td></tr></tbody>`;
}
function redirects() {
return redirectState.redirects || {};
}
function renderDetails(data, cl) {
const domainRows = cl.flatMap(r => (r.domains || []).map(d => ({ client: r.client, ...d })))
.sort((a, b) => String(b.last_seen || '').localeCompare(String(a.last_seen || '')));
document.getElementById('c-sites').textContent = t('domainsCount', { n: domainRows.length });
table('t-sites',
readOnly
? `<tr><th>${esc(t('time'))}</th><th>${esc(t('client'))}</th><th>${esc(t('site'))}</th><th>${esc(t('dwell'))}</th><th>${esc(t('source'))}</th><th>${esc(t('count'))}</th><th>${esc(t('software'))}</th></tr>`
: `<tr><th>${esc(t('time'))}</th><th>${esc(t('client'))}</th><th>${esc(t('site'))}</th><th>${esc(t('redirect'))}</th><th>${esc(t('dwell'))}</th><th>${esc(t('source'))}</th><th>${esc(t('count'))}</th><th>${esc(t('software'))}</th></tr>`,
domainRows.slice(0, 250).map(d => {
const redir = redirects()[d.domain];
const redirectCell = `<div class="redirect-cell">
<button class="btn small ${redir ? 'redirect-on' : 'redirect-off'}" type="button" data-redirect-domain="${esc(d.domain)}">${esc(t(redir ? 'redirectOn' : 'redirectOff'))}</button>
${redir ? `<div class="redirect-target">${code(redir.target_ip || '')}<br>${esc(redir.target || '')}</div>` : ''}
</div>`;
return readOnly ? `<tr>
<td class="nowrap">${esc(d.last_seen || '')}</td><td>${code(d.client)}</td>
<td><div class="site-cell">${fav(d.domain)}${code(d.domain)}</div></td>
<td>${duration(d.dwell_seconds || 0)}</td>
<td>${Object.keys(d.sources || {}).map(esc).join(', ')}</td>
<td>${esc(d.count || 0)}</td>
<td>${(d.matched_apps || []).map(esc).join(', ')}</td></tr>` : `<tr>
<td class="nowrap">${esc(d.last_seen || '')}</td><td>${code(d.client)}</td>
<td><div class="site-cell">${fav(d.domain)}${code(d.domain)}</div></td>
<td>${redirectCell}</td>
<td>${duration(d.dwell_seconds || 0)}</td>
<td>${Object.keys(d.sources || {}).map(esc).join(', ')}</td>
<td>${esc(d.count || 0)}</td>
<td>${(d.matched_apps || []).map(esc).join(', ')}</td></tr>`;
}),
t('sitesEmpty'));
const appRows = cl.flatMap(r => (r.apps || []).map(a => ({ client: r.client, label: r.label || r.client, app: a })))
.sort((a, b) => (b.app.score || 0) - (a.app.score || 0));
document.getElementById('c-apps').textContent = t('appLinksCount', { n: appRows.length });
table('t-apps',
`<tr><th>${esc(t('client'))}</th><th>${esc(t('app'))}</th><th>${esc(t('category'))}</th><th>${esc(t('confidence'))}</th><th>${esc(t('how'))}</th><th>${esc(t('signals'))}</th></tr>`,
appRows.slice(0, 200).map(({ client, app }) => `<tr>
<td>${code(client)}</td><td><strong>${esc(app.app)}</strong></td><td>${esc(app.category || '')}</td>
<td><span class="pill ${app.level === 'high' ? 'online' : app.level === 'medium' ? 'sev-medium' : 'sev-low'}">${esc(levelLabel(app.level, app.level_label))} · ${esc(app.score || 0)}%</span></td>
<td>${app.auto ? `<span class="pill sev-medium">${esc(t('backgroundTelemetry'))}</span>` : `<span class="muted">${esc(t('afterAction'))}</span>`}</td>
<td>${Object.entries(app.signals || {}).map(([k, v]) => `${esc(k)} × ${esc(v)}`).join(', ')}</td></tr>`),
t('appsEmpty'));
const risks = cl.flatMap(r => (r.risk_alerts || []).map(x => ({ client: r.client, ...x })));
document.getElementById('c-risks').textContent = `${risks.length}`;
table('t-risks',
`<tr><th>${esc(t('time'))}</th><th>${esc(t('client'))}</th><th>${esc(t('level'))}</th><th>${esc(t('event'))}</th><th>${esc(t('detail'))}</th></tr>`,
risks.slice(0, 120).map(r => `<tr><td class="nowrap">${esc(r.ts || '')}</td><td>${code(r.client)}</td>
<td><span class="pill ${r.level === 'high' ? 'sev-high' : r.level === 'medium' ? 'sev-medium' : 'sev-low'}">${esc(r.level)}</span></td>
<td><strong>${esc(r.title || '')}</strong></td><td>${esc(r.detail || '')}</td></tr>`),
t('risksEmpty'));
const fps = cl.flatMap(r => (r.tls_fingerprints || []).map(f => ({ client: r.client, ...f })));
document.getElementById('c-tls').textContent = `${fps.length}`;
table('t-tls',
`<tr><th>${esc(t('time'))}</th><th>${esc(t('client'))}</th><th>${esc(t('server'))}</th><th>${esc(t('tlsClient'))}</th><th>${esc(t('uniqueness'))}</th><th>${esc(t('tls'))}</th><th>JA3</th><th>JA3S</th></tr>`,
fps.slice(0, 100).map(f => `<tr><td class="nowrap">${esc(f.ts || '')}</td><td>${code(f.client)}</td>
<td>${code(f.server || '')}</td>
<td><strong>${esc((f.client_hint || {}).label || 'unknown')}</strong><br><span class="muted">${esc((f.client_hint || {}).reason || '')}</span></td>
<td>${f.ja3_unique_lab ? `<span class="pill sev-medium">${esc(t('uniqueLab'))}</span>` : `<span class="pill sev-low">${esc(t('shared'))}</span>`}<br><span class="muted">${esc(t('clientsHits', { clients: f.ja3_seen_clients || 0, hits: f.ja3_seen_total || 0 }))}</span></td>
<td>${esc(f.version || '')}<br><span class="muted">${esc(f.alpn || '')}</span></td>
<td>${code(f.ja3_hash || f.ja3 || '')}</td><td>${code(f.ja3s_hash || f.ja3s || '')}</td></tr>`),
t('tlsEmpty'));
const sig = data.recent_events || [];
document.getElementById('c-signals').textContent = `${sig.length}`;
table('t-signals',
`<tr><th>${esc(t('time'))}</th><th>${esc(t('client'))}</th><th>${esc(t('app'))}</th><th>${esc(t('signals'))}</th><th>${esc(t('detail'))}</th><th>%</th></tr>`,
sig.slice(0, 160).map(e => `<tr><td class="nowrap">${esc(e.ts)}</td><td>${code(e.client)}</td><td>${esc(e.app)}</td>
<td><span class="signal">${esc(e.signal)}</span></td><td>${code(e.value)}<br><span class="muted">${esc(e.detail || '')}</span></td>
<td>${esc(e.confidence)}%</td></tr>`),
t('signalsEmpty'));
const tl = cl.flatMap(r => (r.timeline || []).map(t => ({ client: r.client, ...t }))).sort((a, b) => (b.epoch || 0) - (a.epoch || 0));
document.getElementById('c-timeline').textContent = `${tl.length}`;
table('t-timeline',
`<tr><th>${esc(t('time'))}</th><th>${esc(t('client'))}</th><th>${esc(t('category'))}</th><th>${esc(t('event'))}</th><th>${esc(t('detail'))}</th></tr>`,
tl.slice(0, 200).map(t => `<tr><td class="nowrap">${esc(t.ts || '')}</td><td>${code(t.client)}</td>
<td><span class="signal">${esc(t.kind || '')}</span></td><td><strong>${esc(t.title || '')}</strong></td><td>${esc(t.detail || '')}</td></tr>`),
t('timelineEmpty'));
const cons = document.getElementById('console');
cons.innerHTML = tl.slice(0, 80).map(t => {
const tm = String(t.ts || '').replace('T', ' ').slice(11, 19) || '--:--:--';
return `<div class="console-line"><span class="console-time">${esc(tm)}</span><span class="console-client">${esc(t.client)}</span>
<span class="console-kind">${esc(t.kind || 'event')}</span><span><span>${esc(t.title || '')}</span>${t.detail ? `<br><span class="console-detail">${esc(t.detail)}</span>` : ''}</span></div>`;
}).join('') || `<span class="console-detail">${esc(t('consoleEmpty'))}</span>`;
}
let lastData = null;
function render(data) {
lastData = data;
const cl = clientsOf(data);
renderMetrics(data, cl);
renderTabs(cl);
renderDossier(cl.find(c => c.client === selected) || cl[0]);
renderDetails(data, cl);
}
async function poll() {
try {
const [r, redirectsResponse] = await Promise.all([
fetch(`${apiUrl}?t=${Date.now()}`, { cache: 'no-store' }),
readOnly ? Promise.resolve(null) : fetch(`${logsUrl}?action=redirects&t=${Date.now()}`, { cache: 'no-store', credentials: 'same-origin' }),
]);
if (!r.ok) throw new Error('HTTP ' + r.status);
if (!readOnly && redirectsResponse && redirectsResponse.ok) {
redirectState = await redirectsResponse.json();
} else if (readOnly) {
redirectState = { redirects: {} };
}
render(await r.json());
document.getElementById('status').textContent = t('statusUpdated', { time: new Date().toLocaleTimeString() });
} catch (e) {
document.getElementById('status').textContent = t('statusError', { message: e.message });
}
}
function setDemo(on) {
document.body.classList.toggle('demo', on);
localStorage.setItem('lab-demo', on ? '1' : '0');
const b = document.querySelector('[data-toggle-demo]');
if (b) b.textContent = on ? t('normalMode') : t('demoMode');
}
async function clearLogs(btn) {
if (!confirm(t('confirmClear'))) return;
btn.disabled = true; document.getElementById('status').textContent = t('clearing');
try {
const r = await fetch(`${logsUrl}?action=clear`, { method: 'POST', cache: 'no-store', credentials: 'same-origin' });
const p = await r.json().catch(() => ({}));
if (!r.ok || !p.ok) throw new Error(p.error || 'HTTP ' + r.status);
document.getElementById('status').textContent = t('cleared'); await poll();
} catch (e) { document.getElementById('status').textContent = t('clearError', { message: e.message }); }
finally { btn.disabled = false; }
}
function openCategoryModal(client, category) {
if (!lastData) return;
const row = clientsOf(lastData).find(c => c.client === client);
const domains = ((row && row.domains) || [])
.filter(d => (d.category || 'uncategorized') === category)
.sort((a, b) => String(b.last_seen || '').localeCompare(String(a.last_seen || '')));
document.getElementById('category-title').textContent = `${t('sitesInCategory')}: ${categoryLabel(category)}`;
document.getElementById('category-sites').innerHTML = domains.length
? domains.map(d => `<div class="category-site-row">
<div>
<div class="site-cell">${fav(d.domain)}${code(d.domain)}</div>
<div class="meta">${esc(t('lastSeen'))}: ${esc(d.last_seen || '')}<br>${esc(t('sources'))}: ${Object.keys(d.sources || {}).map(esc).join(', ')}</div>
</div>
<div class="nowrap">${duration(d.dwell_seconds || 0)}</div>
</div>`).join('')
: `<div class="empty">${esc(t('noSitesInCategory'))}</div>`;
document.getElementById('category-modal').classList.add('open');
document.getElementById('category-modal').setAttribute('aria-hidden', 'false');
}
function closeCategoryModal() {
document.getElementById('category-modal').classList.remove('open');
document.getElementById('category-modal').setAttribute('aria-hidden', 'true');
}
function openRedirectModal(domain) {
redirectModalDomain = domain;
const existing = redirects()[domain] || {};
document.getElementById('redirect-domain').value = domain;
document.getElementById('redirect-target').value = existing.target || existing.target_ip || '';
document.getElementById('redirect-modal').classList.add('open');
document.getElementById('redirect-modal').setAttribute('aria-hidden', 'false');
setTimeout(() => document.getElementById('redirect-target').focus(), 30);
}
function closeRedirectModal() {
document.getElementById('redirect-modal').classList.remove('open');
document.getElementById('redirect-modal').setAttribute('aria-hidden', 'true');
redirectModalDomain = '';
}
async function redirectOp(payload) {
const r = await fetch(`${logsUrl}?action=redirects`, {
method: 'POST',
cache: 'no-store',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
const p = await r.json().catch(() => ({}));
if (!r.ok || !p.ok) throw new Error(p.error || 'HTTP ' + r.status);
redirectState = p;
return p;
}
async function saveRedirect() {
const domain = redirectModalDomain;
const target = document.getElementById('redirect-target').value.trim();
if (!domain || !target) return;
document.getElementById('status').textContent = t('applyingRedirect');
try {
await redirectOp({ op: 'set', domain, target });
closeRedirectModal();
await poll();
document.getElementById('status').textContent = t('redirectEnabled');
} catch (e) {
document.getElementById('status').textContent = t('redirectError', { message: e.message });
}
}
async function deleteRedirect(domain = redirectModalDomain) {
if (!domain) return;
document.getElementById('status').textContent = t('disablingRedirect');
try {
await redirectOp({ op: 'delete', domain });
closeRedirectModal();
await poll();
document.getElementById('status').textContent = t('redirectDisabled');
} catch (e) {
document.getElementById('status').textContent = t('redirectError', { message: e.message });
}
}
async function flushDns(btn) {
btn.disabled = true;
document.getElementById('status').textContent = t('flushingDns');
try {
await redirectOp({ op: 'flush' });
await poll();
document.getElementById('status').textContent = t('dnsFlushed');
} catch (e) {
document.getElementById('status').textContent = t('dnsFlushError', { message: e.message });
} finally {
btn.disabled = false;
}
}
document.addEventListener('click', e => {
const tab = e.target.closest('[data-tab]');
if (tab) { selected = tab.dataset.tab; localStorage.setItem('lab-selected', selected); if (lastData) render(lastData); return; }
const categoryChip = e.target.closest('[data-category-chip]');
if (categoryChip) { openCategoryModal(categoryChip.dataset.categoryClient, categoryChip.dataset.category); return; }
if (e.target.closest('[data-category-close]')) { closeCategoryModal(); return; }
if (e.target.id === 'category-modal') { closeCategoryModal(); return; }
if (readOnly) return;
if (e.target.closest('[data-toggle-demo]')) { setDemo(!document.body.classList.contains('demo')); return; }
if (e.target.closest('[data-export]')) { if (selected) location.href = `${logsUrl}?action=export&client=${encodeURIComponent(selected)}`; return; }
if (e.target.closest('[data-report]')) { if (selected) location.href = `${logsUrl}?action=report&client=${encodeURIComponent(selected)}`; return; }
const redirectButton = e.target.closest('[data-redirect-domain]');
if (redirectButton) { openRedirectModal(redirectButton.dataset.redirectDomain); return; }
if (e.target.closest('[data-redirect-save]')) { saveRedirect(); return; }
if (e.target.closest('[data-redirect-delete]')) { deleteRedirect(); return; }
if (e.target.closest('[data-redirect-close]')) { closeRedirectModal(); return; }
if (e.target.id === 'redirect-modal') { closeRedirectModal(); return; }
const flush = e.target.closest('[data-flush-dns]');
if (flush) { flushDns(flush); return; }
const clr = e.target.closest('[data-clear]');
if (clr) clearLogs(clr);
});
document.addEventListener('change', e => {
const selector = e.target.closest('[data-lang-switch]');
if (!selector) return;
lang = selector.value in I18N ? selector.value : 'ru';
localStorage.setItem('lab-lang', lang);
applyStaticI18n();
if (lastData) render(lastData);
});
if (!readOnly) setDemo(localStorage.getItem('lab-demo') === '1');
applyStaticI18n();
poll();
setInterval(poll, 3000);
</script>
</body>
</html>