-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathdashboard.js
More file actions
3422 lines (3181 loc) · 135 KB
/
dashboard.js
File metadata and controls
3422 lines (3181 loc) · 135 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
let keys = [];
let selectedKey;
let chart;
let currentTab = "activity";
let headerSettings = null;
let ratelimitSettings = null;
let corsSettings = null;
let filteringSettings = null;
let hasGeoSource = false;
let demoMode = false;
const keysList = document.getElementById("keysList");
const searchInput = document.getElementById("searchInput");
const welcomeScreen = document.getElementById("welcomeScreen");
const keyDetail = document.getElementById("keyDetail");
const escapeHtml = (s) =>
String(s)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
const api = async (method, path, body) => {
try {
const auth = JSON.parse(localStorage.getItem("cap_auth"));
if (!auth && !demoMode) throw new Error("Not authenticated");
const opts = { method, headers: {} };
if (auth) {
opts.headers.Authorization = `Bearer ${btoa(JSON.stringify({ token: auth.token, hash: auth.hash }))}`;
}
if (body) {
opts.headers["Content-Type"] = "application/json";
opts.body = JSON.stringify(body);
}
return await (await fetch(`/server${path}`, opts)).json();
} catch (e) {
console.error("standalone:", e);
return { error: e.message };
}
};
const formatCompact = (n) => {
if (n >= 1e6) return (n / 1e6).toFixed(n >= 10e6 ? 0 : 1).replace(/\.0$/, "") + "M";
if (n >= 1e3) return Math.round(n / 1e3) + "k";
return String(n);
};
const formatRelative = (date) => {
const diff = new Date(date) - Date.now();
const past = diff < 0;
const d = Math.abs(diff);
const ms = {
year: 365 * 24 * 60 * 60 * 1000,
month: 30 * 24 * 60 * 60 * 1000,
week: 7 * 24 * 60 * 60 * 1000,
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
};
for (const [u, v] of Object.entries(ms)) {
if (d >= v) {
const val = Math.floor(d / v);
return past ? `${val} ${u}${val > 1 ? "s" : ""} ago` : `in ${val} ${u}${val > 1 ? "s" : ""}`;
}
}
return past ? "just now" : "in a moment";
};
const formatDate = (ts) => {
if (!ts) return "\u2014";
return new Date(ts).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
};
const formatLatency = (ms) => {
if (ms === 0) return "\u2014";
return `${Math.max(ms / 1000, 0.1)
.toFixed(1)
.replace(/\.0$/, "")}s`;
};
const trendHtml = (current, previous) => {
if (previous === null || previous === undefined) return "";
if (previous === 0 && current === 0) return "";
let pct;
if (previous === 0) pct = 100;
else pct = Math.round(((current - previous) / previous) * 100);
const dir = pct > 0 ? "up" : pct < 0 ? "down" : "neutral";
const svg = dir === "up"
? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M17 7H7M17 7v10"/></svg>'
: dir === "down"
? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 7L17 17M17 17H7M17 17V7"/></svg>'
: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/></svg>';
return `<span class="stat-trend ${dir}">${svg} ${Math.abs(pct)}%</span>`;
};
const getDateRange = (chartData) => {
if (!chartData?.data?.length) return "";
const first = new Date(chartData.data[0].bucket * 1000);
const last = new Date(chartData.data[chartData.data.length - 1].bucket * 1000);
const fmt = (d) =>
d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
return `${fmt(first)} <span>\u2014</span> ${fmt(last)}`;
};
const randKey = () => {
const left =
"admiring adoring affectionate agitated amazing angry awesome beautiful blissful bold boring brave busy charming clever compassionate competent condescending confident cool cranky crazy dazzling determined distracted dreamy eager ecstatic elastic elated elegant eloquent epic exciting fervent festive flamboyant focused friendly frosty funny gallant gifted goofy gracious great happy hardcore heuristic hopeful hungry infallible inspiring intelligent interesting jolly jovial keen kind laughing loving lucid magical modest musing mystifying naughty nervous nice nifty nostalgic objective optimistic peaceful pedantic pensive practical priceless quirky quizzical recursing relaxed reverent romantic sad serene sharp silly sleepy stoic strange stupefied suspicious sweet tender thirsty trusting unruffled upbeat vibrant vigilant vigorous wizardly wonderful xenodochial youthful zealous zen".split(
" ",
);
const right =
"agnesi albattani allen almeida antonelli archimedes ardinghelli aryabhata austin babbage banach banzai bardeen bartik bassi beaver bell benz bhabha bhaskara black blackburn blackwell bohr booth borg bose bouman boyd brahmagupta brattain brown buck burnell cannon carson cartwright carver cerf chandrasekhar chaplygin chatelet chatterjee chaum chebyshev clarke cohen colden cori cray curie curran darwin davinci dewdney dhawan diffie dijkstra dirac driscoll dubinsky easley edison einstein elbakyan elgamal elion ellis engelbart euclid euler faraday feistel fermat fermi feynman franklin gagarin galileo galois ganguly gates gauss germain goldberg goldstine goldwasser golick goodall gould greider grothendieck haibt hamilton haslett hawking heisenberg hellman hermann herschel hertz heyrovsky hodgkin hofstadter hoover hopper hugle hypatia ishizaka jackson jang jemison jennings jepsen johnson joliot jones kalam kapitsa kare keldysh keller kepler khayyam khorana kilby kirch knuth kowalevski lalande lamarr lamport leakey leavitt lederberg lehmann lewin lichterman liskov lovelace lumiere mahavira margulis matsumoto maxwell mayer mccarthy mcclintock mclaren mclean mcnulty meitner mendel mendeleev meninsky merkle mestorf mirzakhani montalcini moore morse moser murdock napier nash neumann newton nightingale nobel noether northcutt noyce panini pare pascal pasteur payne perlman pike poincare poitras proskuriakova ptolemy raman ramanujan rhodes ride ritchie robinson roentgen rosalind rubin saha sammet sanderson satoshi shamir shannon shaw shirley shockley shtern sinoussi snyder solomon spence stonebraker sutherland swanson swartz swirles taussig tesla tharp thompson torvalds tu turing varahamihira vaughan villani visvesvaraya volhard wescoff wilbur wiles williams williamson wilson wing wozniak wright wu yalow yonath zhukovsky".split(
" ",
);
return `${left[Math.floor(Math.random() * left.length)]}-${right[Math.floor(Math.random() * right.length)]}`;
};
async function init() {
try {
const aboutRes = await fetch("/server/about");
const aboutData = await aboutRes.json();
if (aboutData.demo) demoMode = true;
} catch {}
if (!demoMode && !localStorage.getItem("cap_auth")) {
document.cookie = "cap_authed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
return;
}
if (demoMode) hasGeoSource = true;
api("GET", "/settings/headers").then((res) => {
headerSettings = res?.error ? null : res;
hasGeoSource = !!(
headerSettings?.countryHeader ||
(ipdbStatus?.mode && ipdbStatus.mode !== "")
);
});
api("GET", "/settings/ratelimit").then((res) => {
ratelimitSettings = res?.error ? null : res;
});
api("GET", "/settings/cors").then((res) => {
corsSettings = res?.error ? null : res;
});
api("GET", "/settings/filtering").then((res) => {
filteringSettings = res?.error ? null : res;
});
api("GET", "/settings/ipdb").then((res) => {
ipdbStatus = res;
hasGeoSource = !!(
headerSettings?.countryHeader ||
(ipdbStatus?.mode && ipdbStatus.mode !== "")
);
});
loadKeys();
}
async function loadKeys() {
keys = await api("GET", "/keys");
if (keys.error?.includes?.("Unauthorized")) {
localStorage.removeItem("cap_auth");
document.cookie = "cap_authed=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
location.reload();
return;
}
if (keys?.error) {
keysList.innerHTML = '<div class="keys-empty"><p>Error loading keys</p></div>';
return;
}
renderKeysList();
}
function renderKeysList(filter = "") {
const filtered = keys.filter((k) => k.name.toLowerCase().includes(filter.toLowerCase()));
if (filtered.length === 0) {
keysList.innerHTML = `
<div class="keys-empty">
<p>${filter ? "No matching keys" : "No keys yet!"}</p>
</div>`;
return;
}
keysList.innerHTML = filtered
.map(
(key) => `
<div class="key-item ${selectedKey?.siteKey === key.siteKey ? "active" : ""}" data-key="${key.siteKey}">
<div class="key-item-name">${escapeHtml(key.name)}</div>
<div class="key-item-stats ${key.difference?.direction === "up" ? "trend-up" : key.difference?.direction === "down" ? "trend-down" : "trend-neutral"}">
${
key.difference?.direction === "down"
? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 7L17 17M17 17H7M17 17V7"/></svg>'
: key.difference?.direction === "up"
? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 17L17 7M17 7H7M17 7v10"/></svg>'
: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/></svg>'
}
${formatCompact(key.solvesLast24h || 0)} recent solves
</div>
</div>`,
)
.join("");
keysList.querySelectorAll(".key-item").forEach((el) => {
el.addEventListener("click", () => {
keysList.querySelectorAll(".key-item").forEach((e) => e.classList.remove("active"));
el.classList.add("active");
selectKey(el.dataset.key);
});
});
}
const spinnerSvg =
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-loader-2"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 3a9 9 0 1 0 9 9" /></svg>';
async function selectKey(siteKey) {
welcomeScreen.style.display = "none";
keyDetail.style.display = "flex";
if (keyDetail.children.length === 0) {
keyDetail.innerHTML = '<div class="key-detail-loading">' + spinnerSvg + "</div>";
} else {
keyDetail.querySelectorAll(".stat-value").forEach((el) => el.classList.add("shimmer-text"));
keyDetail.querySelectorAll(".stat-label").forEach((el) => el.classList.add("shimmer-text"));
const cl = document.getElementById("chartLoading");
if (cl) cl.classList.add("visible");
["locationBody", "networksBody", "platformBody", "osBody"].forEach((id) => {
const el = document.getElementById(id);
if (el) el.innerHTML = '<div class="insight-loading">' + spinnerSvg + "</div>";
});
}
const data = await api("GET", `/keys/${siteKey}`);
if (data.error) {
showModal(
"Error",
`<div class="modal-body"><p>Failed to load key: ${escapeHtml(data.error)}</p></div>`,
);
return;
}
selectedKey = data.key;
selectedKey.stats = data.stats;
selectedKey.prevStats = data.prevStats;
selectedKey.chartData = data.chartData;
currentTab = "activity";
renderKeyDetail();
keysList.querySelectorAll(".key-item").forEach((el) => {
el.classList.toggle("active", el.dataset.key === siteKey);
});
}
function renderKeyDetail() {
welcomeScreen.style.display = "none";
keyDetail.style.display = "flex";
const key = selectedKey;
const s = key.stats;
keyDetail.innerHTML = `
<div class="detail-header">
<div class="detail-tabs">
<div class="detail-tabs-indicator"></div>
<button class="detail-tab ${currentTab === "activity" ? "active" : ""}" data-tab="activity">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
Activity
</button>
<button class="detail-tab ${currentTab === "configuration" ? "active" : ""}" data-tab="configuration">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37 1 .608 2.296.07 2.572-1.065"/><circle cx="12" cy="12" r="3"/></svg>
Configuration
</button>
</div>
<button class="copy-site-key-btn" id="copyKeyBtn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
Copy site key
</button>
</div>
<div class="tab-content ${currentTab === "activity" ? "active" : ""}" id="activityTab">
<div class="activity-layout">
<div class="activity-main">
<div class="filters-row">
<select class="time-select" id="timeSelect">
<option value="today" ${key.chartData?.duration === "today" ? "selected" : ""}>Today</option>
<option value="yesterday" ${key.chartData?.duration === "yesterday" ? "selected" : ""}>Yesterday</option>
<option value="last7days" ${key.chartData?.duration === "last7days" ? "selected" : ""}>Last 7 days</option>
<option value="last28days" ${key.chartData?.duration === "last28days" ? "selected" : ""}>Last 30 days</option>
<option value="last91days" ${key.chartData?.duration === "last91days" ? "selected" : ""}>Last 3 months</option>
<option value="alltime" ${key.chartData?.duration === "alltime" ? "selected" : ""}>All time</option>
</select>
<span class="date-range" id="dateRange">${getDateRange(key.chartData)}</span>
<button class="refresh-btn" id="refreshBtn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0118.8-4.3M22 12.5a10 10 0 01-18.8 4.2"/></svg>
</button>
</div>
<div class="stats-row">
<div class="stat-item">
<div class="stat-bar blue"></div>
<div class="stat-label">Challenges</div>
<div class="stat-value" id="statChallenges">${formatCompact(s.challenges || 0)}</div>
<div id="trendChallenges">${trendHtml(s.challenges, key.prevStats?.challenges)}</div>
</div>
<div class="stat-item">
<div class="stat-bar green"></div>
<div class="stat-label">Verified</div>
<div class="stat-value" id="statVerified">${formatCompact(s.verified || 0)}</div>
<div id="trendVerified">${trendHtml(s.verified, key.prevStats?.verified)}</div>
</div>
<div class="stat-item">
<div class="stat-bar red"></div>
<div class="stat-label">Failed</div>
<div class="stat-value" id="statFailed">${formatCompact(Math.max(0, (s.challenges || 0) - (s.verified || 0)))}</div>
<div id="trendFailed">${trendHtml(Math.max(0, (s.challenges || 0) - (s.verified || 0)), key.prevStats ? Math.max(0, (key.prevStats.challenges || 0) - (key.prevStats.verified || 0)) : null)}</div>
</div>
<div class="stat-item">
<div class="stat-bar purple"></div>
<div class="stat-label">Avg. duration</div>
<div class="stat-value" id="statLatency">${formatLatency(s.avgLatency || 0)}</div>
</div>
</div>
<div class="chart-container">
<canvas id="chart"></canvas>
<div class="chart-loading" id="chartLoading">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-loader-2"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 3a9 9 0 1 0 9 9" /></svg>
</div>
</div>
<div class="insights-grid" id="insightsGrid">
<div class="insight-panel" id="locationPanel">
<div class="insight-panel-header">
<h3 class="insight-panel-title">Location</h3>
<div class="insight-view-toggle" id="locationViewToggle">
<button class="insight-toggle-btn ${!locationMapMode ? "active" : ""}" data-view="list" title="List view">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>
</button>
<button class="insight-toggle-btn ${locationMapMode ? "active" : ""}" data-view="map" title="Map view">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
</button>
</div>
</div>
<div class="insight-panel-body" id="locationBody">
<div class="insight-loading"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-loader-2"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 3a9 9 0 1 0 9 9" /></svg></div>
</div>
</div>
<div class="insight-panel" id="networksPanel">
<div class="insight-panel-header">
<h3 class="insight-panel-title">Networks</h3>
<button class="insight-search-btn" id="networksSearchBtn" title="Search networks">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
</button>
</div>
<div class="insight-search-bar" id="networksSearchBar" style="display:none">
<input type="text" id="networksSearchInput" placeholder="Filter networks\u2026">
</div>
<div class="insight-panel-body" id="networksBody">
<div class="insight-loading"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-loader-2"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 3a9 9 0 1 0 9 9" /></svg></div>
</div>
</div>
<div class="insight-panel" id="platformPanel">
<div class="insight-panel-header">
<h3 class="insight-panel-title">Platform</h3>
</div>
<div class="insight-panel-body" id="platformBody">
<div class="insight-loading">${spinnerSvg}</div>
</div>
</div>
<div class="insight-panel" id="osPanel">
<div class="insight-panel-header">
<h3 class="insight-panel-title">OS</h3>
</div>
<div class="insight-panel-body" id="osBody">
<div class="insight-loading">${spinnerSvg}</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-content ${currentTab === "configuration" ? "active" : ""}" id="configurationTab">
<div class="config-panel">
<h3 class="config-section-title">Main</h3>
<div class="config-card">
<div class="edit-field">
<label>Name</label>
<input type="text" id="cfgName" value="${escapeHtml(key.name)}">
</div>
<div class="edit-row">
<div class="edit-field">
<label>Difficulty</label>
<input type="number" id="cfgDifficulty" value="${key.config.difficulty}" min="1" max="8">
</div>
<div class="edit-field">
<label>Challenge count</label>
<input type="number" id="cfgChallengeCount" value="${key.config.challengeCount}" min="1" max="500">
</div>
</div>
<h3 class="config-section-title" style="margin-top:16px">Instrumentation</h3>
<div class="switch-field">
<label class="switch">
<input type="checkbox" id="cfgInstrumentation" ${key.config.instrumentation ? "checked" : ""}>
<span class="switch-track"></span>
</label>
<label for="cfgInstrumentation" class="switch-label">Enable instrumentation challenges</label>
</div>
<div class="switch-field" id="blockAutomatedBrowsersField" style="display:${key.config.instrumentation ? "flex" : "none"}">
<label class="switch">
<input type="checkbox" id="cfgBlockAutomatedBrowsers" ${key.config.blockAutomatedBrowsers ? "checked" : ""}>
<span class="switch-track"></span>
</label>
<label for="cfgBlockAutomatedBrowsers" class="switch-label">
Attempt to block headless browsers
<span class="hint">This may cause issues with testing or agent browsers and is not entirely foolproof.</span>
</label>
</div>
<div class="config-row" id="obfuscationLevelField" style="display:${key.config.instrumentation ? "flex" : "none"}">
<div class="range-field" style="flex:1">
<label>Obfuscation level <span class="range-value" id="obfuscationLevelHint">${key.config.obfuscationLevel ?? 5}</span></label>
<span class="range-hint">Higher obfuscation may result in higher CPU usage.</span>
<input type="range" id="cfgObfuscationLevel" min="1" max="10" value="${key.config.obfuscationLevel ?? 5}">
</div>
</div>
<h3 class="config-section-title" style="margin-top:16px">Adaptive challenge count</h3>
<div class="switch-field">
<label class="switch">
<input type="checkbox" id="cfgAdaptiveEnabled" ${key.config.adaptiveChallengeCount?.enabled ? "checked" : ""}>
<span class="switch-track"></span>
</label>
<label for="cfgAdaptiveEnabled" class="switch-label">
Enable adaptive challenge count
<span class="hint">Increase the number of challenges based on request frequency globally or per IP address.</span>
</label>
</div>
<div id="adaptiveConfigFields" style="display:${key.config.adaptiveChallengeCount?.enabled ? "block" : "none"}">
<div class="edit-row">
<div class="edit-field">
<label>Time window (ms)</label>
<input type="number" id="cfgAdaptiveWindow" value="${key.config.adaptiveChallengeCount?.windowMs ?? 60000}" min="60000" max="3600000" step="1000">
</div>
</div>
<h4 class="config-subsection-title" style="margin-top:16px">Global tiers</h4>
<p class="headers-description" style="margin:-4px 0 8px">Increase challenge count when total requests across all IPs exceed the threshold. Useful against distributed attacks.</p>
<div id="adaptiveGlobalTiersList">
${(key.config.adaptiveChallengeCount?.globalTiers || []).map((tier, i) => `
<div class="edit-row adaptive-tier-row" data-tier-index="${i}">
<div class="edit-field">
<label>Min total requests</label>
<input type="number" class="adaptive-tier-min" value="${tier.minRequests}" min="1" max="10000000">
</div>
<div class="edit-field">
<label>Challenge count</label>
<input type="number" class="adaptive-tier-count" value="${tier.challengeCount}" min="1" max="500">
</div>
<button class="origin-remove-btn adaptive-tier-remove" title="Remove tier"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:14px;height:14px"><path d="M18 6L6 18M6 6l12 12"/></svg></button>
</div>`).join("")}
</div>
<button class="add-btn" id="addAdaptiveGlobalTierBtn" style="margin-top:8px">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" style="width:14px;height:14px;margin-right:4px"><path d="M12 5v14M5 12h14"/></svg>
Add global tier
</button>
<h4 class="config-subsection-title" style="margin-top:12px">Per-IP tiers</h4>
<p class="headers-description" style="margin:-4px 0 8px">Increase challenge count when a single IP exceeds the request threshold within the time window.</p>
<div id="adaptiveTiersList">
${(key.config.adaptiveChallengeCount?.tiers || []).map((tier, i) => `
<div class="edit-row adaptive-tier-row" data-tier-index="${i}">
<div class="edit-field">
<label>Min requests</label>
<input type="number" class="adaptive-tier-min" value="${tier.minRequests}" min="1" max="100000">
</div>
<div class="edit-field">
<label>Challenge count</label>
<input type="number" class="adaptive-tier-count" value="${tier.challengeCount}" min="1" max="500">
</div>
<button class="origin-remove-btn adaptive-tier-remove" title="Remove tier"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:14px;height:14px"><path d="M18 6L6 18M6 6l12 12"/></svg></button>
</div>`).join("")}
</div>
<button class="add-btn" id="addAdaptiveTierBtn" style="margin-top:8px">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" style="width:14px;height:14px;margin-right:4px"><path d="M12 5v14M5 12h14"/></svg>
Add per-IP tier
</button>
</div>
<div class="config-save-row">
<button class="save-btn" id="saveMainConfigBtn" disabled>Save</button>
</div>
</div>
<h3 class="config-section-title">Security</h3>
<div class="config-card">
<h4 class="config-subsection-title">Rate limiting</h4>
<p class="headers-description" style="margin:-4px 0 8px">Override the global rate limit for this key. Leave empty to use the global defaults${ratelimitSettings ? ` (${ratelimitSettings.max} reqs / ${ratelimitSettings.duration / 1000}s)` : ""}.</p>
<div class="edit-row">
<div class="edit-field">
<label>Max requests</label>
<input type="number" id="cfgRatelimitMax" value="${key.config.ratelimitMax ?? ""}" min="1" max="10000" placeholder="${ratelimitSettings?.max ?? 30}">
</div>
<div class="edit-field">
<label>Window (ms)</label>
<input type="number" id="cfgRatelimitDuration" value="${key.config.ratelimitDuration ?? ""}" min="1000" max="3600000" step="1000" placeholder="${ratelimitSettings?.duration ?? 5000}">
</div>
</div>
<hr class="settings-divider">
<h4 class="config-subsection-title">CORS</h4>
<div class="switch-field">
<label class="switch">
<input type="checkbox" id="cfgCorsEnabled" ${key.config.corsOrigins?.length ? "checked" : ""}>
<span class="switch-track"></span>
</label>
<label for="cfgCorsEnabled" class="switch-label">Restrict allowed origins</label>
</div>
<div id="keyCorsPanel" style="display:${key.config.corsOrigins?.length ? "block" : "none"}">
<p class="headers-description" style="margin:0 0 8px">Only these origins will be able to request challenges for this key.</p>
<div id="keyCorsOriginsList" class="origin-list">
${(key.config.corsOrigins || []).map((o) => `<div class="origin-entry"><input type="text" class="key-cors-origin-input" value="${escapeHtml(o)}" placeholder="Add an origin\u2026"><button class="origin-remove-btn" title="Remove">×</button></div>`).join("")}
</div>
</div>
<hr class="settings-divider">
<h4 class="config-subsection-title">Request filtering</h4>
<p class="headers-description" style="margin:-4px 0 8px">Override the global filtering for this key. Leave unchecked to use global defaults.</p>
<div class="switch-field">
<label class="switch">
<input type="checkbox" id="cfgBlockNonBrowserUA" ${key.config.blockNonBrowserUA ? "checked" : ""}>
<span class="switch-track"></span>
</label>
<label for="cfgBlockNonBrowserUA" class="switch-label">
Block non-browser user agents
<span class="hint">Blocks requests from bots, scripts, and other non-browser clients (e.g. python-requests, curl).</span>
</label>
</div>
<div class="switch-field">
<label class="switch">
<input type="checkbox" id="cfgRequiredHeadersEnabled" ${key.config.requiredHeaders?.length ? "checked" : ""}>
<span class="switch-track"></span>
</label>
<label for="cfgRequiredHeadersEnabled" class="switch-label">
Require browser headers
<span class="hint">Block requests missing common browser headers.</span>
</label>
</div>
<div id="keyRequiredHeadersPanel" style="display:${key.config.requiredHeaders?.length ? "block" : "none"}">
<div class="header-checks">
${["accept-encoding", "accept-language", "cache-control", "referer", "sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform"].map((h) => `<label class="header-check-label"><input type="checkbox" class="key-required-header-check" value="${h}" ${(key.config.requiredHeaders || []).includes(h) ? "checked" : ""}> <code>${escapeHtml(h)}</code></label>`).join("")}
</div>
</div>
<div class="config-save-row">
<button class="save-btn" id="saveSecurityConfigBtn" disabled>Save</button>
</div>
</div>
<div class="config-section-header">
<h3 class="config-section-title">Block rules</h3>
<button class="add-block-rule-btn" id="addBlockRuleBtn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
Add rule
</button>
</div>
<div class="config-card">
<div id="blockedIpsList" class="blocked-ips-list">
<div class="blocked-ips-loading"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-loader-2"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 3a9 9 0 1 0 9 9" /></svg></div>
</div>
</div>
<div class="danger-zone">
<h3 class="config-section-title danger">Danger zone</h3>
<div class="danger-actions-col">
<button class="danger-action-btn" id="rotateSecretBtn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0118.8-4.3M22 12.5a10 10 0 01-18.8 4.2"/></svg>
Reset site secret
</button>
<button class="danger-action-btn red" id="deleteKeyBtn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
Delete key
</button>
</div>
</div>
</div>
</div>
`;
const tabsContainer = keyDetail.querySelector(".detail-tabs");
const tabIndicator = tabsContainer.querySelector(".detail-tabs-indicator");
const tabs = tabsContainer.querySelectorAll(".detail-tab");
function updateTabIndicator(animate = true) {
const activeTab = tabsContainer.querySelector(".detail-tab.active");
if (!activeTab || !tabIndicator) return;
if (!animate) tabIndicator.style.transition = "none";
tabIndicator.style.width = activeTab.offsetWidth + "px";
tabIndicator.style.transform = `translateX(${activeTab.offsetLeft - 3}px)`;
if (!animate)
requestAnimationFrame(() => {
tabIndicator.style.transition = "";
});
}
updateTabIndicator(false);
tabs.forEach((tab) => {
tab.addEventListener("click", () => {
currentTab = tab.dataset.tab;
tabs.forEach((t) => t.classList.toggle("active", t.dataset.tab === currentTab));
updateTabIndicator();
keyDetail.querySelectorAll(".tab-content").forEach((c) => {
if (c.id === currentTab + "Tab") {
c.classList.add("active");
} else {
c.classList.remove("active");
}
});
if (currentTab === "configuration") loadBlockedIps();
});
});
document.getElementById("copyKeyBtn").addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(key.siteKey);
const btn = document.getElementById("copyKeyBtn");
btn.innerHTML =
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg> Copied!';
setTimeout(() => {
btn.innerHTML =
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg> Copy site key';
}, 2000);
} catch {
showModal(
"Site Key",
`<div class="modal-body"><div class="modal-field"><label>Site Key</label><input type="text" value="${key.siteKey}" readonly onclick="this.select()"></div></div>`,
);
}
});
document
.getElementById("timeSelect")
.addEventListener("change", (e) => loadChartData(e.target.value));
document.getElementById("refreshBtn").addEventListener("click", () => {
const sel = document.getElementById("timeSelect");
if (sel) loadChartData(sel.value);
});
renderChart(key.chartData);
loadGeoStats();
if (currentTab === "configuration") loadBlockedIps();
function stripOriginVal(val) {
val = val.trim();
if (!val) return "";
try {
val = new URL(val.includes("://") ? val : "https://" + val).host;
} catch {}
return val.replace(/\/+$/, "");
}
function getKeyCorsEntries() {
return [...document.querySelectorAll("#keyCorsOriginsList .key-cors-origin-input")]
.map((i) => stripOriginVal(i.value))
.filter(Boolean);
}
function corsArraysEqual(a, b) {
if (!a && !b) return true;
if (!a || !b) return false;
if (a.length !== b.length) return false;
return a.every((v, i) => v === b[i]);
}
function getKeyRequiredHeaders() {
return [
...document.querySelectorAll("#keyRequiredHeadersPanel .key-required-header-check:checked"),
].map((c) => c.value);
}
function getAdaptiveConfig() {
const enabled = document.getElementById("cfgAdaptiveEnabled").checked;
const windowMs = parseInt(document.getElementById("cfgAdaptiveWindow").value, 10);
const tierRows = [...document.querySelectorAll("#adaptiveTiersList .adaptive-tier-row")];
const tiers = tierRows.map((row) => ({
minRequests: parseInt(row.querySelector(".adaptive-tier-min").value, 10) || 1,
challengeCount: parseInt(row.querySelector(".adaptive-tier-count").value, 10) || 80,
}));
const globalTierRows = [...document.querySelectorAll("#adaptiveGlobalTiersList .adaptive-tier-row")];
const globalTiers = globalTierRows.map((row) => ({
minRequests: parseInt(row.querySelector(".adaptive-tier-min").value, 10) || 1,
challengeCount: parseInt(row.querySelector(".adaptive-tier-count").value, 10) || 80,
}));
return { enabled, windowMs, tiers, globalTiers };
}
function tiersEqual(a, b) {
if ((a?.length || 0) !== (b?.length || 0)) return false;
for (let i = 0; i < (a?.length || 0); i++) {
if (a[i].minRequests !== b[i].minRequests) return false;
if (a[i].challengeCount !== b[i].challengeCount) return false;
}
return true;
}
function adaptiveConfigEquals(a, b) {
if (!a && !b) return true;
if (!a || !b) return false;
if (a.enabled !== b.enabled) return false;
if (a.windowMs !== b.windowMs) return false;
if (!tiersEqual(a.tiers, b.tiers)) return false;
if (!tiersEqual(a.globalTiers, b.globalTiers)) return false;
return true;
}
function checkMainDirty() {
const name = document.getElementById("cfgName").value.trim();
const difficulty = parseInt(document.getElementById("cfgDifficulty").value, 10);
const challengeCount = parseInt(document.getElementById("cfgChallengeCount").value, 10);
const instrumentation = document.getElementById("cfgInstrumentation").checked;
const obfuscationLevel = parseInt(document.getElementById("cfgObfuscationLevel").value, 10);
const blockAutomatedBrowsers = document.getElementById("cfgBlockAutomatedBrowsers").checked;
const adaptiveCurrent = getAdaptiveConfig();
const adaptiveOriginal = key.config.adaptiveChallengeCount || { enabled: false, windowMs: 60000, tiers: [], globalTiers: [] };
const dirty =
name !== key.name ||
difficulty !== key.config.difficulty ||
challengeCount !== key.config.challengeCount ||
instrumentation !== key.config.instrumentation ||
obfuscationLevel !== (key.config.obfuscationLevel ?? 5) ||
blockAutomatedBrowsers !== key.config.blockAutomatedBrowsers ||
!adaptiveConfigEquals(adaptiveCurrent, adaptiveOriginal);
document.getElementById("saveMainConfigBtn").disabled = !dirty;
}
function checkSecurityDirty() {
const rlMaxVal = document.getElementById("cfgRatelimitMax").value;
const rlDurVal = document.getElementById("cfgRatelimitDuration").value;
const ratelimitMax = rlMaxVal === "" ? null : parseInt(rlMaxVal, 10);
const ratelimitDuration = rlDurVal === "" ? null : parseInt(rlDurVal, 10);
const corsEnabled = document.getElementById("cfgCorsEnabled").checked;
const keyCorsOrigins = corsEnabled ? getKeyCorsEntries() : [];
const keyCorsOriginsVal = keyCorsOrigins.length ? keyCorsOrigins : null;
const blockNonBrowserUA = document.getElementById("cfgBlockNonBrowserUA").checked;
const reqHeadersEnabled = document.getElementById("cfgRequiredHeadersEnabled").checked;
const requiredHeaders = reqHeadersEnabled ? getKeyRequiredHeaders() : [];
const requiredHeadersVal = requiredHeaders.length ? requiredHeaders : null;
const dirty =
ratelimitMax !== (key.config.ratelimitMax ?? null) ||
ratelimitDuration !== (key.config.ratelimitDuration ?? null) ||
!corsArraysEqual(keyCorsOriginsVal, key.config.corsOrigins ?? null) ||
blockNonBrowserUA !== (key.config.blockNonBrowserUA ?? false) ||
!corsArraysEqual(requiredHeadersVal, key.config.requiredHeaders ?? null);
document.getElementById("saveSecurityConfigBtn").disabled = !dirty;
}
function checkDirty() {
checkMainDirty();
checkSecurityDirty();
}
for (const id of ["cfgName", "cfgDifficulty", "cfgChallengeCount"]) {
document.getElementById(id)?.addEventListener("input", checkMainDirty);
}
for (const id of ["cfgRatelimitMax", "cfgRatelimitDuration"]) {
document.getElementById(id)?.addEventListener("input", checkSecurityDirty);
}
document.getElementById("cfgAdaptiveEnabled")?.addEventListener("change", function () {
document.getElementById("adaptiveConfigFields").style.display = this.checked ? "block" : "none";
checkMainDirty();
});
document.getElementById("cfgAdaptiveWindow")?.addEventListener("input", checkMainDirty);
function addAdaptiveTierRow(minRequests = "", challengeCount = "") {
const list = document.getElementById("adaptiveTiersList");
const idx = list.querySelectorAll(".adaptive-tier-row").length;
const div = document.createElement("div");
div.className = "edit-row adaptive-tier-row";
div.dataset.tierIndex = idx;
div.innerHTML = `
<div class="edit-field">
<label>Min requests</label>
<input type="number" class="adaptive-tier-min" value="${minRequests}" min="1" max="100000" placeholder="e.g. 5">
</div>
<div class="edit-field">
<label>Challenge count</label>
<input type="number" class="adaptive-tier-count" value="${challengeCount}" min="1" max="500" placeholder="e.g. 150">
</div>
<button class="origin-remove-btn adaptive-tier-remove" title="Remove tier"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:14px;height:14px"><path d="M18 6L6 18M6 6l12 12"/></svg></button>`;
div.querySelector(".adaptive-tier-remove").addEventListener("click", () => {
div.remove();
checkMainDirty();
});
div.querySelector(".adaptive-tier-min").addEventListener("input", checkMainDirty);
div.querySelector(".adaptive-tier-count").addEventListener("input", checkMainDirty);
list.appendChild(div);
checkMainDirty();
}
document.getElementById("addAdaptiveTierBtn")?.addEventListener("click", () => addAdaptiveTierRow());
document.querySelectorAll("#adaptiveTiersList .adaptive-tier-remove").forEach((btn) => {
btn.addEventListener("click", () => {
btn.closest(".adaptive-tier-row").remove();
checkMainDirty();
});
});
document.querySelectorAll("#adaptiveTiersList .adaptive-tier-min, #adaptiveTiersList .adaptive-tier-count").forEach((input) => {
input.addEventListener("input", checkMainDirty);
});
function addAdaptiveGlobalTierRow(minRequests = "", challengeCount = "") {
const list = document.getElementById("adaptiveGlobalTiersList");
const idx = list.querySelectorAll(".adaptive-tier-row").length;
const div = document.createElement("div");
div.className = "edit-row adaptive-tier-row";
div.dataset.tierIndex = idx;
div.innerHTML = `
<div class="edit-field">
<label>Min total requests</label>
<input type="number" class="adaptive-tier-min" value="${minRequests}" min="1" max="10000000" placeholder="e.g. 100">
</div>
<div class="edit-field">
<label>Challenge count</label>
<input type="number" class="adaptive-tier-count" value="${challengeCount}" min="1" max="500" placeholder="e.g. 200">
</div>
<button class="origin-remove-btn adaptive-tier-remove" title="Remove tier"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:14px;height:14px"><path d="M18 6L6 18M6 6l12 12"/></svg></button>`;
div.querySelector(".adaptive-tier-remove").addEventListener("click", () => {
div.remove();
checkMainDirty();
});
div.querySelector(".adaptive-tier-min").addEventListener("input", checkMainDirty);
div.querySelector(".adaptive-tier-count").addEventListener("input", checkMainDirty);
list.appendChild(div);
checkMainDirty();
}
document.getElementById("addAdaptiveGlobalTierBtn")?.addEventListener("click", () => addAdaptiveGlobalTierRow());
document.querySelectorAll("#adaptiveGlobalTiersList .adaptive-tier-remove").forEach((btn) => {
btn.addEventListener("click", () => {
btn.closest(".adaptive-tier-row").remove();
checkMainDirty();
});
});
document.querySelectorAll("#adaptiveGlobalTiersList .adaptive-tier-min, #adaptiveGlobalTiersList .adaptive-tier-count").forEach((input) => {
input.addEventListener("input", checkMainDirty);
});
function ensureKeyCorsEmptyRow() {
const entries = [...document.querySelectorAll("#keyCorsOriginsList .origin-entry")];
const empties = entries.filter((e) => !e.querySelector(".key-cors-origin-input").value.trim());
if (empties.length === 0) {
addKeyCorsRow();
return;
}
while (empties.length > 1) {
empties.pop().remove();
}
}
function addKeyCorsRow(value = "") {
const div = document.createElement("div");
div.className = "origin-entry";
div.innerHTML = `<input type="text" class="key-cors-origin-input" value="${escapeHtml(value)}" placeholder="Add an origin\u2026"><button class="origin-remove-btn" title="Remove">×</button>`;
const input = div.querySelector(".key-cors-origin-input");
div.querySelector(".origin-remove-btn").addEventListener("click", () => {
div.remove();
ensureKeyCorsEmptyRow();
checkSecurityDirty();
});
input.addEventListener("input", () => {
ensureKeyCorsEmptyRow();
checkSecurityDirty();
});
input.addEventListener("blur", () => {
const stripped = stripOriginVal(input.value);
if (stripped !== input.value.trim()) input.value = stripped;
});
document.getElementById("keyCorsOriginsList").appendChild(div);
return input;
}
document.querySelectorAll("#keyCorsOriginsList .origin-remove-btn").forEach((btn) => {
btn.addEventListener("click", () => {
btn.parentElement.remove();
ensureKeyCorsEmptyRow();
checkSecurityDirty();
});
});
document.querySelectorAll("#keyCorsOriginsList .key-cors-origin-input").forEach((input) => {
input.addEventListener("input", () => {
ensureKeyCorsEmptyRow();
checkSecurityDirty();
});
input.addEventListener("blur", () => {
const stripped = stripOriginVal(input.value);
if (stripped !== input.value.trim()) input.value = stripped;
});
});
ensureKeyCorsEmptyRow();
document.getElementById("cfgCorsEnabled")?.addEventListener("change", (e) => {
const panel = document.getElementById("keyCorsPanel");
panel.style.display = e.target.checked ? "block" : "none";
if (e.target.checked) ensureKeyCorsEmptyRow();
checkSecurityDirty();
});
document.getElementById("cfgBlockNonBrowserUA")?.addEventListener("change", checkSecurityDirty);
document.getElementById("cfgRequiredHeadersEnabled")?.addEventListener("change", (e) => {
document.getElementById("keyRequiredHeadersPanel").style.display = e.target.checked
? "block"
: "none";
checkSecurityDirty();
});
document.querySelectorAll(".key-required-header-check").forEach((cb) => {
cb.addEventListener("change", checkSecurityDirty);
});
document.getElementById("cfgInstrumentation")?.addEventListener("change", (e) => {
const show = e.target.checked ? "flex" : "none";
document.getElementById("obfuscationLevelField").style.display = show;
document.getElementById("blockAutomatedBrowsersField").style.display = show;
if (!e.target.checked) {
document.getElementById("cfgBlockAutomatedBrowsers").checked = false;
const sl = document.getElementById("cfgObfuscationLevel");
sl.value = 5;
updateRangeFill(sl);
document.getElementById("obfuscationLevelHint").textContent = "5";
} else {
const sl = document.getElementById("cfgObfuscationLevel");
if (sl) updateRangeFill(sl);
}
checkMainDirty();
});
function updateRangeFill(el) {
const min = +el.min || 0,
max = +el.max || 10;
const pct = ((el.value - min) / (max - min)) * 100;
el.style.background = `linear-gradient(to right, var(--blue) ${pct}%, var(--border) ${pct}%)`;
}
const obfSlider = document.getElementById("cfgObfuscationLevel");
if (obfSlider) {
updateRangeFill(obfSlider);
obfSlider.addEventListener("input", (e) => {
document.getElementById("obfuscationLevelHint").textContent = e.target.value;
updateRangeFill(e.target);
checkMainDirty();
});
}
document.getElementById("cfgBlockAutomatedBrowsers")?.addEventListener("change", checkMainDirty);
document.getElementById("saveMainConfigBtn")?.addEventListener("click", saveMainConfig);
document.getElementById("saveSecurityConfigBtn")?.addEventListener("click", saveSecurityConfig);
document.getElementById("rotateSecretBtn")?.addEventListener("click", rotateSecret);
document.getElementById("deleteKeyBtn")?.addEventListener("click", deleteKey);
document.getElementById("addBlockRuleBtn")?.addEventListener("click", openAddBlockRuleModal);
}
async function loadChartData(duration) {
const refreshBtn = document.getElementById("refreshBtn");
refreshBtn?.classList.add("spinning");
document.getElementById("chartLoading")?.classList.add("visible");
const data = await api("GET", `/keys/${selectedKey.siteKey}?chartDuration=${duration}`);
refreshBtn?.classList.remove("spinning");
document.getElementById("chartLoading")?.classList.remove("visible");
if (data.chartData) {
selectedKey.stats = data.stats;
selectedKey.prevStats = data.prevStats;
selectedKey.chartData = data.chartData;
const s = data.stats;
const ps = data.prevStats;
const el = (id) => document.getElementById(id);
if (el("statChallenges")) el("statChallenges").textContent = formatCompact(s.challenges || 0);
if (el("statVerified")) el("statVerified").textContent = formatCompact(s.verified || 0);
if (el("statFailed"))
el("statFailed").textContent = formatCompact(
Math.max(0, (s.challenges || 0) - (s.verified || 0)),
);
if (el("statLatency")) el("statLatency").textContent = formatLatency(s.avgLatency || 0);
if (el("trendChallenges")) el("trendChallenges").innerHTML = trendHtml(s.challenges, ps?.challenges);
if (el("trendVerified")) el("trendVerified").innerHTML = trendHtml(s.verified, ps?.verified);
if (el("trendFailed")) el("trendFailed").innerHTML = trendHtml(Math.max(0, (s.challenges || 0) - (s.verified || 0)), ps ? Math.max(0, (ps.challenges || 0) - (ps.verified || 0)) : null);
if (el("dateRange")) el("dateRange").innerHTML = getDateRange(data.chartData);
renderChart(data.chartData);