-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpopup.js
More file actions
1537 lines (1358 loc) · 64.2 KB
/
Copy pathpopup.js
File metadata and controls
1537 lines (1358 loc) · 64.2 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
// ── 安全转义(防止 innerHTML 注入)─────────────────────────────────────────────
function esc(str) {
return String(str ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// ── 用户设置(popup 本地副本)──────────────────────────────────────────────────
const DEFAULT_SETTINGS = {
mod_trackers: true, mod_fingerprinting: true,
mod_aiSafety: true, mod_contentSafety: true,
mod_spendGuard: true, mod_cookieConsent: true,
spendSensitivity: "normal",
aiAnnotateInPage: true,
};
let currentSettings = { ...DEFAULT_SETTINGS };
// ── 初始化静态 UI 文字 ─────────────────────────────────────────────────────────
document.getElementById("verdictTitle").textContent = t.scanning;
document.getElementById("verdictSub").textContent = t.loadingData;
document.getElementById("ttlTrackers").textContent = t.tabTrackers;
document.getElementById("ttlApis").textContent = t.tabBrowserAPIs;
document.getElementById("ttlAi").textContent = t.tabAiSafety;
document.getElementById("ttlContent").textContent = t.tabContentSafety;
document.getElementById("ttlSpend").textContent = t.tabSpendGuard;
document.getElementById("ttlCookie").textContent = t.tabCookieConsent;
document.getElementById("emptyTrackersTitle").textContent = t.noTrackersTitle;
document.getElementById("emptyTrackersSub").textContent = t.noTrackersSub;
document.getElementById("emptyApisTitle").textContent = t.noApisTitle;
document.getElementById("emptyApisSub").textContent = t.noApisSub;
document.getElementById("compEndLeft").textContent = t.privacyFriendly;
document.getElementById("compEndRight").textContent = t.mostInvasive;
document.getElementById("statLabelTrackers").textContent = t.trackers;
document.getElementById("statLabelRequests").textContent = t.requests;
document.getElementById("statLabelApis").textContent = t.apiCalls;
document.getElementById("emptyContentTitle").textContent = t.csEmptyTitle;
document.getElementById("emptyContentSub").textContent = t.csEmptySub;
document.getElementById("emptySpendTitle").textContent = t.subEmptyScanningTitle;
document.getElementById("emptySpendSub").textContent = t.subEmptyScanningSub;
// session bar 静态文字
document.getElementById("sessionLabel").textContent = t.sessionLabel || "SESSION";
// 反馈入口静态文字
(function initFeedbackLink() {
const btn = document.getElementById("feedbackBtn");
if (!btn) return;
btn.textContent = "🐞 " + (t.feedbackLink || "Report");
btn.title = t.feedbackTitle || "Report a missed or wrong detection";
})();
// 根据当前页面 URL 生成预填的 GitHub issue 链接
function updateFeedbackLink(url) {
const btn = document.getElementById("feedbackBtn");
if (!btn) return;
const repo = "https://github.com/koni20/iris-extension/issues/new";
let pageUrl = url || "";
// 仅保留 http(s) 页面地址,避免把扩展内部页或空值填进去
if (!/^https?:\/\//i.test(pageUrl)) pageUrl = "";
const ver = (typeof chrome !== "undefined" && chrome.runtime?.getManifest)
? chrome.runtime.getManifest().version : "";
const title = `[Report] ${pageUrl ? new URL(pageUrl).hostname.replace(/^www\./, "") : "issue"}`;
const body = [
"<!-- 感谢反馈 / Thanks for the report -->",
"",
`Page URL: ${pageUrl || "(N/A)"}`,
`Iris version: ${ver}`,
"",
"Type / 类型 (留下其一 / keep one):",
"- [ ] Missed something / 漏检",
"- [ ] False positive / 误报",
"",
"Module / 模块 (Trackers / Fingerprinting / AI Safety / Content Safety / Spend Guard / Cookie / GEO):",
"",
"Details / 详细描述:",
"",
].join("\n");
btn.href = `${repo}?title=${encodeURIComponent(title)}&body=${encodeURIComponent(body)}`;
}
// ── Section Cards 折叠导航 ────────────────────────────────────────────────────
function initCards() {
document.querySelectorAll(".sc-hdr").forEach((hdr) => {
hdr.addEventListener("click", () => {
const body = hdr.nextElementSibling;
const isOpen = body.classList.contains("open");
body.classList.toggle("open", !isOpen);
hdr.classList.toggle("open", !isOpen);
});
});
// 「更多 / 高级」折叠区
const moreToggle = document.getElementById("moreToggle");
const moreMount = document.getElementById("moreMount");
const moreTtl = document.getElementById("moreTtl");
if (moreTtl) moreTtl.textContent = t.moreSection || "More";
if (moreToggle && moreMount) {
moreToggle.addEventListener("click", () => {
const collapsed = moreMount.classList.toggle("more-collapsed");
moreToggle.classList.toggle("open", !collapsed);
});
}
}
initCards();
// ── 按页面类型前置招牌卡,其余收进「更多」 ────────────────────────────────────
const CARD_ORDER = ["cardTrackers", "cardApis", "cardAi", "cardContent", "cardSpend", "cardCookie"];
function setCardOpen(card, open) {
const hdr = card.querySelector(".sc-hdr");
const body = card.querySelector(".sc-body");
if (hdr) hdr.classList.toggle("open", open);
if (body) body.classList.toggle("open", open);
}
function arrangeCards(isAiPage) {
const heroMount = document.getElementById("heroMount");
const moreMount = document.getElementById("moreMount");
if (!heroMount || !moreMount) return;
const heroId = isAiPage ? "cardAi" : "cardTrackers";
const hero = document.getElementById(heroId);
if (hero) {
heroMount.appendChild(hero);
setCardOpen(hero, true);
}
for (const id of CARD_ORDER) {
if (id === heroId) continue;
const card = document.getElementById(id);
if (!card) continue;
moreMount.appendChild(card);
setCardOpen(card, false);
}
}
// ── 设置面板 ──────────────────────────────────────────────────────────────────
function initSettingsPanel() {
// 静态文字
document.getElementById("spTitle").textContent = t.settingsTitle || "Settings";
document.getElementById("spLabelModules").textContent = t.settingsModules || "Modules";
document.getElementById("spLabelSensitivity").textContent = t.settingsSensitivity || "Spend Guard";
document.getElementById("spMod_trackers").textContent = t.tabTrackers;
document.getElementById("spMod_fingerprinting").textContent = t.tabBrowserAPIs;
document.getElementById("spMod_aiSafety").textContent = t.tabAiSafety;
document.getElementById("spMod_contentSafety").textContent = t.tabContentSafety;
document.getElementById("spMod_spendGuard").textContent = t.tabSpendGuard;
document.getElementById("spMod_cookieConsent").textContent = t.tabCookieConsent;
document.getElementById("spAiAnnotate").textContent = t.aiAnnotateToggle || "In-page source check";
document.getElementById("spSensTitle").textContent = t.settingsSensTitle || "Detection Sensitivity";
document.getElementById("sensNormal").textContent = t.settingsSensNormal || "Normal";
document.getElementById("sensStrict").textContent = t.settingsSensStrict || "Strict";
document.getElementById("spNote").textContent = t.settingsSavedNote || "Changes saved automatically.";
// 齿轮按钮
document.getElementById("gearBtn").addEventListener("click", () => {
showPanel(_currentPanel === "settings" ? null : "settings");
});
document.getElementById("settingsClose").addEventListener("click", () => toggleSettings(false));
// 模块开关:change 时立即保存
["trackers","fingerprinting","aiSafety","contentSafety","spendGuard","cookieConsent"].forEach((mod) => {
document.getElementById("tog_" + mod).addEventListener("change", (e) => {
currentSettings["mod_" + mod] = e.target.checked;
saveSettings();
});
});
// AI 页面内标注开关
document.getElementById("tog_aiAnnotate").addEventListener("change", (e) => {
currentSettings.aiAnnotateInPage = e.target.checked;
saveSettings();
});
// 灵敏度 pill
["sensNormal","sensStrict"].forEach((id) => {
document.getElementById(id).addEventListener("click", (e) => {
const val = e.currentTarget.dataset.val;
currentSettings.spendSensitivity = val;
applySensitivityUI(val);
saveSettings();
});
});
}
// ── 面板切换(settings / history / null)────────────────────────────────────
let _currentPanel = null;
function showPanel(panel) {
_currentPanel = panel;
const showSections = panel === null;
document.getElementById("settingsPanel").classList.toggle("hidden", panel !== "settings");
document.getElementById("historyPanel").classList.toggle("hidden", panel !== "history");
document.getElementById("sections").classList.toggle("hidden", !showSections);
document.getElementById("gearBtn").classList.toggle("active", panel === "settings");
document.getElementById("historyBtn").classList.toggle("active", panel === "history");
}
function toggleSettings(open) {
showPanel(open ? "settings" : null);
}
function toggleHistory(open) {
showPanel(open ? "history" : null);
if (open) {
chrome.runtime.sendMessage({ type: "GET_HISTORY" }, (entries) => {
renderHistory(entries || []);
});
}
}
function applySettingsToUI() {
["trackers","fingerprinting","aiSafety","contentSafety","spendGuard","cookieConsent"].forEach((mod) => {
const el = document.getElementById("tog_" + mod);
if (el) el.checked = !!currentSettings["mod_" + mod];
});
const annEl = document.getElementById("tog_aiAnnotate");
if (annEl) annEl.checked = currentSettings.aiAnnotateInPage !== false;
applySensitivityUI(currentSettings.spendSensitivity || "normal");
}
function applySensitivityUI(val) {
document.getElementById("sensNormal").classList.toggle("active", val === "normal");
document.getElementById("sensStrict").classList.toggle("active", val === "strict");
const descKey = val === "strict" ? "settingsSensStrictDesc" : "settingsSensNormalDesc";
document.getElementById("spSensDesc").textContent = t[descKey] || "";
}
function saveSettings() {
chrome.runtime.sendMessage({ type: "SAVE_SETTINGS", settings: currentSettings });
}
// ── Session 汇总栏渲染 ────────────────────────────────────────────────────────
function renderSession(session) {
if (!session) return;
document.getElementById("sessTrackers").textContent = session.trackers || 0;
document.getElementById("sessAiCalls").textContent = session.aiCalls || 0;
document.getElementById("sessLowTrust").textContent = session.lowTrustCitations || 0;
const ltEl = document.getElementById("sessLt");
if (ltEl) ltEl.classList.toggle("has-alert", (session.lowTrustCitations || 0) > 0);
}
// ── 更新 section card 头部状态和角标 ──────────────────────────────────────────
function updateCard(key, { dot = "", badge = "", badgeColor = "", findings = false, findingLevel = "" } = {}) {
const dotEl = document.getElementById("dot" + key);
const bdgEl = document.getElementById("bdg" + key);
const cardEl = document.getElementById("card" + key);
if (dotEl) dotEl.className = "sc-dot" + (dot ? " " + dot : "");
if (bdgEl) {
if (badge) {
bdgEl.textContent = badge;
bdgEl.className = "sc-bdg" + (badgeColor ? " bdg-" + badgeColor : "");
} else {
bdgEl.classList.add("hidden");
}
}
if (cardEl) {
cardEl.classList.toggle("lvl-red", findingLevel === "red");
cardEl.classList.toggle("lvl-amber", findingLevel === "amber");
}
}
// ── 获取并渲染数据 ─────────────────────────────────────────────────────────────
function fetchAndRender() {
chrome.runtime.sendMessage({ type: "GET_DATA" }, (data) => {
if (chrome.runtime.lastError || !data) return;
render(data);
});
}
// ── 重置为"扫描中"状态 ────────────────────────────────────────────────────────
function resetToScanning() {
document.getElementById("verdictSection").className = "verdict-section";
document.getElementById("verdictIcon").textContent = "🔍";
document.getElementById("verdictTitle").textContent = t.scanning;
document.getElementById("verdictTitle").className = "verdict-title accent";
document.getElementById("verdictSub").textContent = t.loadingData;
document.getElementById("statTrackers").textContent = "—";
document.getElementById("statRequests").textContent = "—";
document.getElementById("statApis").textContent = "—";
document.getElementById("comparisonSection").style.display = "none";
document.getElementById("trackerList").innerHTML = "";
document.getElementById("apiList").innerHTML = "";
document.getElementById("emptyTrackers").style.display = "flex";
document.getElementById("emptyApis").style.display = "flex";
document.getElementById("logoDot").className = "logo-dot";
document.getElementById("siteBadge").textContent = "—";
document.getElementById("phishingBanner").classList.add("hidden");
document.getElementById("contentSafetyList").innerHTML = "";
lastContentSafetyJson = "";
lastAiSourcesJson = "";
lastSpendJson = "";
lastCookieJson = "";
lastSessionReplayJson = "";
lastConfirmshamingJson = "";
lastAntiGeoJson = "";
const agMount = document.getElementById("antiGeoMount");
if (agMount) agMount.innerHTML = "";
const asm = document.getElementById("aiSourcesMount");
if (asm) asm.innerHTML = "";
const csSummary = document.getElementById("csSummary");
if (csSummary) { csSummary.className = "cs-summary cs-rating-green"; csSummary.innerHTML = ""; }
const spendSummary = document.getElementById("spendSummary");
if (spendSummary) { spendSummary.className = "cs-summary cs-rating-neutral"; spendSummary.innerHTML = ""; }
document.getElementById("spendList").innerHTML = "";
document.getElementById("emptySpend").classList.add("hidden");
const cookieSummary = document.getElementById("cookieSummary");
if (cookieSummary) { cookieSummary.className = "cs-summary cs-rating-neutral"; cookieSummary.innerHTML = ""; }
document.getElementById("cookieList").innerHTML = "";
const csMount = document.getElementById("confirmshamingMount");
if (csMount) csMount.innerHTML = "";
// 重置所有 card 角标
["Trackers","Apis","Ai","Content","Spend","Cookie"].forEach((k) => {
updateCard(k, { dot: "", badge: "" });
});
}
// ── 监听来自 background 的 Tab 变化通知 ──────────────────────────────────────
chrome.runtime.onMessage.addListener((message) => {
if (message.type === "TAB_CHANGED") {
resetToScanning();
setTimeout(fetchAndRender, 300);
}
if (message.type === "TAB_LOADING") {
resetToScanning();
}
});
// ── 轮询刷新(每 2 秒,让数据实时更新)──────────────────────────────────────
let lastTrackerCount = -1;
let lastApiCount = -1;
let lastContentSafetyJson = "";
let lastAiSourcesJson = "";
let lastSpendJson = "";
let lastCookieJson = "";
let lastSessionReplayJson = "";
let lastConfirmshamingJson = "";
let lastAntiGeoJson = "";
function pollData() {
chrome.runtime.sendMessage({ type: "GET_DATA" }, (data) => {
if (chrome.runtime.lastError || !data) return;
const csJson = JSON.stringify(data.contentSafety || {});
const asJson = JSON.stringify(data.aiSearchSources || null);
const spendJson = JSON.stringify(data.subscriptionGuard || null);
const cookieJson = JSON.stringify(data.cookieConsent || null);
const srJson = JSON.stringify(data.sessionReplay || []);
const cfJson = JSON.stringify(data.confirmshaming || null);
const agJson = JSON.stringify(data.antiGeo || null);
const changed =
data.trackers.length !== lastTrackerCount ||
data.apiCalls.length !== lastApiCount ||
csJson !== lastContentSafetyJson ||
asJson !== lastAiSourcesJson ||
spendJson !== lastSpendJson ||
cookieJson !== lastCookieJson ||
srJson !== lastSessionReplayJson ||
cfJson !== lastConfirmshamingJson ||
agJson !== lastAntiGeoJson;
if (changed) {
lastTrackerCount = data.trackers.length;
lastApiCount = data.apiCalls.length;
lastContentSafetyJson = csJson;
lastAiSourcesJson = asJson;
lastSpendJson = spendJson;
lastCookieJson = cookieJson;
lastSessionReplayJson = srJson;
lastConfirmshamingJson = cfJson;
lastAntiGeoJson = agJson;
render(data);
}
});
}
// ── 启动:先加载设置,再初始化面板和数据 ─────────────────────────────────────
initSettingsPanel();
initHistoryPanel();
initRateBanner();
// ── 评分入口:低频出现、可永久关闭、纯本地(不发任何请求、不收集数据)──────────
function initRateBanner() {
const banner = document.getElementById("rateBanner");
if (!banner || !(typeof chrome !== "undefined" && chrome.storage?.local)) return;
const OPENS_MIN = 5; // 至少打开 popup 5 次
const DAYS_MIN = 3; // 且距首次使用 ≥3 天
const DAY = 24 * 60 * 60 * 1000;
chrome.storage.local.get("irisRate", (stored) => {
const st = stored.irisRate || {};
// 已评分或已永久关闭:不再打扰
if (st.status === "rated" || st.status === "dismissed") return;
const now = Date.now();
const next = {
firstSeen: st.firstSeen || now,
opens: (st.opens || 0) + 1,
status: st.status,
};
chrome.storage.local.set({ irisRate: next });
const eligible = next.opens >= OPENS_MIN && (now - next.firstSeen) >= DAYS_MIN * DAY;
if (!eligible) return;
const rateText = document.getElementById("rateText");
const rateBtn = document.getElementById("rateBtn");
const rateDismiss = document.getElementById("rateDismiss");
if (rateText) rateText.textContent = t.ratePrompt || "Enjoying Iris? A quick rating really helps.";
if (rateBtn) rateBtn.textContent = t.rateAction || "Rate it";
if (rateDismiss) rateDismiss.title = t.rateDismiss || "Don't show again";
const remember = (status) => chrome.storage.local.set({ irisRate: { ...next, status } });
if (rateBtn) rateBtn.addEventListener("click", () => { remember("rated"); banner.classList.add("hidden"); });
if (rateDismiss) rateDismiss.addEventListener("click", () => { remember("dismissed"); banner.classList.add("hidden"); });
banner.classList.remove("hidden");
});
}
chrome.storage.local.get("irisSettings", (stored) => {
if (stored.irisSettings) Object.assign(currentSettings, stored.irisSettings);
applySettingsToUI();
fetchAndRender();
});
// 持续轮询,实时更新
const pollInterval = setInterval(pollData, 2000);
// Popup 关闭时清理定时器
window.addEventListener("unload", () => clearInterval(pollInterval));
function renderPhishing(phishing) {
const banner = document.getElementById("phishingBanner");
if (!phishing) {
banner.classList.add("hidden");
return;
}
banner.classList.remove("hidden");
document.getElementById("phishingTitle").textContent =
t.phishingTitle
? t.phishingTitle(phishing.brand)
: `⚠️ Possible fake ${phishing.brand} website`;
document.getElementById("phishingSub").textContent =
t.phishingSub
? t.phishingSub(phishing.spoofedDomain)
: `"${phishing.spoofedDomain}" is not the official domain. You may be on a phishing site designed to steal your account or conversation data.`;
document.getElementById("phishingLegit").textContent =
(t.phishingLegitPrefix || "✅ Official: ") + phishing.legitimateDomains.join(" / ");
}
function renderDBMeta(dbMeta, csMeta) {
if (!dbMeta) return;
const dot = document.getElementById("dbDot");
const status = document.getElementById("dbStatus");
const parts = [];
if (dbMeta.updatedAt) {
const days = Math.floor((Date.now() - dbMeta.updatedAt) / 86400000);
const dateStr = new Date(dbMeta.updatedAt).toLocaleDateString();
const countStr = dbMeta.dynamicCount ? `+${dbMeta.dynamicCount.toLocaleString()} domains` : "";
dot.className = "db-dot cache";
parts.push(
`disconnect.me ${countStr} · ${t.dbUpdated ? t.dbUpdated(days) : days === 0 ? "updated today" : `updated ${days}d ago`} (${dateStr})`
);
} else {
dot.className = "db-dot local";
parts.push(t.dbBuiltIn || "built-in database · fetching latest…");
}
if (csMeta && csMeta.updatedAt) {
const csd = Math.floor((Date.now() - csMeta.updatedAt) / 86400000);
let csPart = "";
if (csMeta.dynamicCount) {
if (csMeta.breakdown) {
const b = csMeta.breakdown;
csPart = `${csMeta.dynamicCount.toLocaleString()} domains (A${b.adult}+G${b.gambling}+S${b.scam}) · `;
} else {
csPart = `${csMeta.dynamicCount.toLocaleString()} domains · `;
}
}
parts.push(`content ${csPart}${t.dbUpdated(csd)}`);
}
status.textContent = parts.join(" · ");
}
function renderContentSafety(cs) {
const summary = document.getElementById("csSummary");
const list = document.getElementById("contentSafetyList");
const empty = document.getElementById("emptyContent");
const lang = (navigator.language || "en").toLowerCase().split("-")[0];
const useZh = lang === "zh";
const rating = cs.rating || "green";
summary.className = "cs-summary cs-rating-" + rating;
const titleKey = "csRating_" + rating + "Title";
const subKey = "csRating_" + rating + "Sub";
summary.innerHTML = `
<div class="cs-rating-icon">${rating === "green" ? "🟢" : rating === "yellow" ? "🟡" : "🔴"}</div>
<div class="cs-rating-body">
<div class="cs-rating-title">${t[titleKey] || ""}</div>
<div class="cs-rating-sub">${t[subKey] || ""}</div>
</div>
`;
const hasRows =
(cs.domainMatches && cs.domainMatches.length > 0) ||
(cs.keywords && cs.keywords.length > 0) ||
(cs.manipulation && cs.manipulation.length > 0);
list.innerHTML = "";
if (!hasRows && rating === "green") {
empty.classList.remove("hidden");
return;
}
empty.classList.add("hidden");
for (const d of cs.domainMatches || []) {
const div = document.createElement("div");
div.className = "cs-item cs-item-domain";
const catLabel = (t.csCategories && t.csCategories[d.category]) || d.category;
div.innerHTML = `
<div class="cs-item-tag">${esc(catLabel)}</div>
<div class="cs-item-domain">${esc(d.domain)}</div>
<div class="cs-item-plain">${esc(useZh ? d.plain_zh : d.plain_en)}</div>
`;
list.appendChild(div);
}
for (const k of cs.keywords || []) {
const div = document.createElement("div");
div.className = "cs-item cs-item-kw cs-level-" + k.level;
const lvlKey = "csLevel_" + k.level;
div.innerHTML = `
<div class="cs-item-tag">${esc(t[lvlKey] || k.level)}</div>
<div class="cs-item-plain">${esc(typeof t.csKeywordMatch === "function" ? t.csKeywordMatch(k.match) : k.match)}</div>
`;
list.appendChild(div);
}
for (const m of cs.manipulation || []) {
const div = document.createElement("div");
div.className = "cs-item cs-item-manip";
const hintKey = "csManip_" + m.hint;
const msg = t[hintKey] || m.hint;
div.innerHTML = `
<div class="cs-item-tag">${esc(t.csManipType)}</div>
<div class="cs-item-plain">${esc(msg)}</div>
`;
list.appendChild(div);
}
// 更新 card 角标
if (rating === "red") {
updateCard("Content", { dot: "red", badge: t.csRating_redTitle || "Flagged", badgeColor: "red", findingLevel: "red" });
} else if (rating === "yellow") {
updateCard("Content", { dot: "amber", badge: t.csRating_yellowTitle || "Caution", badgeColor: "amber", findingLevel: "amber" });
} else {
updateCard("Content", { dot: "green", badge: t.clean || "Clean", badgeColor: "green" });
}
}
function renderSpendGuard(subscriptionGuard) {
const summary = document.getElementById("spendSummary");
const list = document.getElementById("spendList");
const empty = document.getElementById("emptySpend");
if (!summary || !list || !empty) return;
const disc = `<div class="ai-sources-disclaimer" style="margin-top:8px;">${t.subDisclaimer || ""}</div>`;
if (subscriptionGuard == null) {
summary.className = "cs-summary cs-rating-neutral";
summary.innerHTML = `
<div class="cs-rating-icon">🔍</div>
<div class="cs-rating-body">
<div class="cs-rating-title">${t.subEmptyScanningTitle || ""}</div>
<div class="cs-rating-sub">${t.subEmptyScanningSub || ""}</div>
</div>
`;
list.innerHTML = "";
empty.classList.add("hidden");
updateCard("Spend", { dot: "", badge: "—" });
return;
}
const rating = subscriptionGuard.rating || "neutral";
const hits = subscriptionGuard.hits || [];
if (rating === "neutral") {
summary.className = "cs-summary cs-rating-neutral";
summary.innerHTML = `
<div class="cs-rating-icon">➖</div>
<div class="cs-rating-body">
<div class="cs-rating-title">${t.subSummary_neutralTitle || ""}</div>
<div class="cs-rating-sub">${t.subSummary_neutralSub || ""}</div>
${disc}
</div>
`;
list.innerHTML = "";
empty.classList.add("hidden");
updateCard("Spend", { dot: "green", badge: t.clean || "Clean", badgeColor: "green" });
return;
}
if (rating === "green") {
summary.className = "cs-summary cs-rating-green";
summary.innerHTML = `
<div class="cs-rating-icon">🟢</div>
<div class="cs-rating-body">
<div class="cs-rating-title">${t.subSummary_greenTitle || ""}</div>
<div class="cs-rating-sub">${t.subSummary_greenSub || ""}</div>
${disc}
</div>
`;
list.innerHTML = "";
empty.classList.add("hidden");
updateCard("Spend", { dot: "green", badge: t.clean || "Clean", badgeColor: "green" });
return;
}
summary.className = "cs-summary cs-rating-yellow";
summary.innerHTML = `
<div class="cs-rating-icon">🟡</div>
<div class="cs-rating-body">
<div class="cs-rating-title">${t.subSummary_yellowTitle || ""}</div>
<div class="cs-rating-sub">${t.subSummary_yellowSub || ""}</div>
${disc}
</div>
`;
list.innerHTML = "";
for (const h of hits) {
const div = document.createElement("div");
div.className = "cs-item cs-item-manip";
const msg = (h && h.id && t[h.id]) || (h && h.id) || "";
div.innerHTML = `
<div class="cs-item-tag">${esc(t.subSigTag || "Pattern")}</div>
<div class="cs-item-plain">${esc(msg)}</div>
`;
list.appendChild(div);
}
empty.classList.add("hidden");
// 更新 card 角标
updateCard("Spend", { dot: "amber", badge: String(hits.length), badgeColor: "amber", findingLevel: "amber" });
}
function render({
trackers,
totalRequests,
apiCalls,
aiCalls = [],
phishing = null,
dbMeta = null,
csMeta = null,
contentSafety = null,
aiSearchSources = null,
subscriptionGuard = null,
cookieConsent = null,
confirmshaming = null,
sessionReplay = [],
antiGeo = null,
url,
session = null,
}) {
renderPhishing(phishing);
renderDBMeta(dbMeta, csMeta);
renderSession(session);
// 各模块按设置决定是否渲染
if (currentSettings.mod_contentSafety) {
renderContentSafety(contentSafety || { rating: "green", domainMatches: [], keywords: [], manipulation: [] });
} else {
renderModuleDisabled("Content");
}
if (currentSettings.mod_spendGuard) {
renderSpendGuard(subscriptionGuard);
} else {
renderModuleDisabled("Spend");
}
if (currentSettings.mod_cookieConsent) {
renderCookieConsent(cookieConsent, confirmshaming);
} else {
renderModuleDisabled("Cookie");
}
let hostname = "—";
try { hostname = new URL(url).hostname.replace(/^www\./, ""); } catch {}
document.getElementById("siteBadge").textContent = hostname;
updateFeedbackLink(url);
const effectiveTrackers = currentSettings.mod_trackers ? trackers : [];
const effectiveApis = currentSettings.mod_fingerprinting ? apiCalls : [];
document.getElementById("statTrackers").textContent = effectiveTrackers.length;
document.getElementById("statRequests").textContent = totalRequests;
document.getElementById("statApis").textContent = effectiveApis.length;
const risk = getRiskLevel({ trackers: effectiveTrackers, apiCalls: effectiveApis });
renderVerdict(risk, effectiveTrackers, effectiveApis);
if (effectiveTrackers.length > 0) renderComparison(effectiveTrackers.length);
if (currentSettings.mod_trackers) {
renderTrackers(trackers, sessionReplay);
} else {
renderModuleDisabled("Trackers");
}
if (currentSettings.mod_fingerprinting) {
renderApis(apiCalls);
} else {
renderModuleDisabled("Apis");
}
if (currentSettings.mod_aiSafety) {
renderAiCalls(aiCalls, aiSearchSources);
renderAntiGeo(antiGeo); // 在 renderAiCalls 之后执行,角标有 GEO 信号时覆盖
} else {
renderModuleDisabled("Ai");
}
// 上下文聚焦:AI 回答页前置引用透镜,普通页前置追踪器,其余收进「更多」
const isAiPage =
!!aiSearchSources ||
(typeof matchAIWebsite === "function" && !!matchAIWebsite(url));
arrangeCards(isAiPage);
}
// ── 模块已禁用时的卡片状态 ────────────────────────────────────────────────────
function renderModuleDisabled(key) {
updateCard(key, { dot: "", badge: t.moduleDisabledBadge || "Off", badgeColor: "" });
}
// ── 风险等级判断 ────────────────────────────────────────────────────────────────
function getRiskLevel({ trackers, apiCalls }) {
// 第一梯队:无论其他情况,直接判定为高风险
const criticalApis = ["geolocation", "media-access"];
const criticalCategories = ["Session Recording", "Data Broker"];
const hasCriticalApi = apiCalls.some(a => criticalApis.includes(a.api));
const hasCriticalTracker = trackers.some(tr => criticalCategories.includes(tr.category));
if (hasCriticalApi || hasCriticalTracker || trackers.length > 15) return "high";
// 第二梯队:指纹采集相关
const fingerprintApis = ["canvas-fingerprint", "webgl-fingerprint", "audio-fingerprint"];
const hasFingerprintApi = apiCalls.some(a => fingerprintApis.includes(a.api));
const hasFingerprintTracker = trackers.some(tr => tr.category === "Fingerprinting");
// 指纹 + 较多追踪器 → 组合威胁,升级为高风险
if ((hasFingerprintApi || hasFingerprintTracker) && trackers.length >= 5) return "high";
// 指纹单独出现,或追踪器数量偏多 → 中风险
if (hasFingerprintApi || hasFingerprintTracker || trackers.length > 3) return "medium";
// 第三梯队:WebRTC 或少量追踪器
if (apiCalls.some(a => a.api === "webrtc-leak") || trackers.length > 0 || apiCalls.length > 0) return "low";
return "safe";
}
// ── 渲染 Verdict ─────────────────────────────────────────────────────────────
function renderVerdict(risk, trackers, apiCalls) {
const section = document.getElementById("verdictSection");
const icon = document.getElementById("verdictIcon");
const title = document.getElementById("verdictTitle");
const sub = document.getElementById("verdictSub");
const dot = document.getElementById("logoDot");
section.className = "verdict-section risk-" + risk;
const configs = {
high: { icon: "⚠️", titleText: t.highExposure, titleClass: "red", dotClass: "red", sub: buildSub(trackers, apiCalls) },
medium: { icon: "🔶", titleText: t.mediumTracking, titleClass: "amber", dotClass: "amber", sub: buildSub(trackers, apiCalls) },
low: { icon: "🔵", titleText: t.lightTracking, titleClass: "accent", dotClass: "", sub: buildSub(trackers, apiCalls) },
safe: { icon: "✅", titleText: t.noTracking, titleClass: "green", dotClass: "green", sub: t.noIssues }
};
const cfg = configs[risk];
icon.textContent = cfg.icon;
title.textContent = cfg.titleText;
title.className = "verdict-title " + cfg.titleClass;
sub.textContent = cfg.sub;
dot.className = "logo-dot " + cfg.dotClass;
}
function buildSub(trackers, apiCalls) {
const parts = [];
if (trackers.length > 0) {
const companies = [...new Set(trackers.map(tr => tr.company))];
const shown = companies.slice(0, 2).join(", ");
const more = companies.length > 2 ? ` +${companies.length - 2}` : "";
parts.push(t.dataSentTo(trackers.length, shown + more));
}
// API 调用:按 api 字段判断风险,label 字段显示友好名称
const HIGH_RISK_APIS = ["canvas-fingerprint", "webgl-fingerprint", "audio-fingerprint", "geolocation", "media-access"];
const highApis = apiCalls.filter(a => HIGH_RISK_APIS.includes(a.api) || a.risk === "high");
const otherApis = apiCalls.filter(a => !HIGH_RISK_APIS.includes(a.api) && a.risk !== "high");
const apiName = (a) => a.label || {
"canvas-fingerprint": "Canvas Fingerprinting",
"webgl-fingerprint": "WebGL Fingerprinting",
"audio-fingerprint": "Audio Fingerprinting",
"geolocation": "Location Access",
"media-access": "Camera / Microphone",
"webrtc-leak": "WebRTC IP Exposure",
"clipboard-read": "Clipboard Access",
"battery-fingerprint": "Battery Fingerprinting"
}[a.api] || a.api;
if (highApis.length > 0) {
parts.push(t.detected(highApis.map(apiName).join(", ")));
} else if (otherApis.length > 0) {
parts.push(t.detected(otherApis.map(apiName).join(", ")));
}
return parts.join(" · ") || t.noIssues;
}
// ── 渲染比较条 ──────────────────────────────────────────────────────────────────
function renderComparison(trackerCount) {
const section = document.getElementById("comparisonSection");
const fill = document.getElementById("compFill");
const label = document.getElementById("compLabel");
const pct = getPercentile(trackerCount);
section.style.display = "block";
label.innerHTML = t.compLabel(pct);
setTimeout(() => { fill.style.width = pct + "%"; }, 100);
}
// ── 渲染追踪器列表 ──────────────────────────────────────────────────────────────
function renderTrackers(trackers, sessionReplay = []) {
const list = document.getElementById("trackerList");
const empty = document.getElementById("emptyTrackers");
list.innerHTML = "";
const hasReplay = sessionReplay.length > 0;
const hasTrackers = trackers.length > 0;
if (!hasReplay && !hasTrackers) {
empty.style.display = "flex";
updateCard("Trackers", { dot: "green", badge: t.clean || "Clean", badgeColor: "green" });
return;
}
empty.style.display = "none";
// ── Session Replay 警告区(置顶)──────────────────────────────────────────
if (hasReplay) {
const srBlock = document.createElement("div");
srBlock.className = "sr-block";
srBlock.innerHTML = `
<div class="sr-header">
<span class="sr-icon">🎥</span>
<div class="sr-titles">
<div class="sr-title">${esc(t.sessionReplayTitle || "Session Recording")}</div>
<div class="sr-subtitle">${esc(t.sessionReplaySubtitle || "This site is recording your session")}</div>
</div>
</div>
<div class="sr-warning">${esc(t.sessionReplayWarning || "Your mouse movements, clicks, scrolls, and form inputs may be captured by a third party.")}</div>
<div class="sr-services" id="srServices"></div>`;
list.appendChild(srBlock);
const svcContainer = srBlock.querySelector("#srServices");
sessionReplay.forEach((sr) => {
const svcEl = document.createElement("div");
svcEl.className = "sr-service-item";
const plain = (navigator.language || "").startsWith("zh") ? sr.plain_zh : sr.plain_en;
svcEl.innerHTML = `
<div class="sr-service-row">
<span class="tracker-tag tag-Session-Recording">${esc(t.sessionReplayTitle || "Session Recording")}</span>
<span class="tracker-domain">${esc(sr.domain)}</span>
</div>
<div class="tracker-company">${esc(sr.name)}</div>
<div class="tracker-plain">${esc(plain || sr.plain_en)}</div>`;
svcContainer.appendChild(svcEl);
});
}
// ── 普通追踪器列表 ─────────────────────────────────────────────────────────
if (hasTrackers) {
const hint = document.createElement("div");
hint.className = "expand-hint";
hint.textContent = t.expandHint;
list.appendChild(hint);
trackers.forEach((tracker, i) => {
const item = document.createElement("div");
item.className = "tracker-item";
item.style.animationDelay = `${i * 40}ms`;
const tagClass = "tag-" + tracker.category.replace(/[\s/]+/g, "-");
const categoryLabel = t.categories[tracker.category] || tracker.category;
item.innerHTML = `
<div class="tracker-row">
<span class="tracker-tag ${esc(tagClass)}">${esc(categoryLabel)}</span>
<span class="tracker-domain">${esc(tracker.domain)}</span>
<span class="tracker-chevron">▼</span>
</div>
<div class="tracker-company">${esc(tracker.company)}</div>
<div class="tracker-plain">${esc(tracker.plain)}</div>
`;
item.addEventListener("click", () => item.classList.toggle("expanded"));
list.appendChild(item);
});
}
// ── 角标(Session Replay 优先触发红色)──────────────────────────────────
const hasCritical = hasReplay || trackers.some((tr) =>
["Session Recording", "Data Broker", "Fingerprinting"].includes(tr.category)
);
const totalCount = trackers.length;
const lvl = (hasCritical || totalCount > 5) ? "red" : "amber";
const badgeText = hasReplay
? `${totalCount} + 🎥`
: String(totalCount);
updateCard("Trackers", { dot: lvl, badge: badgeText, badgeColor: lvl, findingLevel: lvl });
}
function formatAiSourceReason(r) {
if (r.kind === "contentSafety") return (t.csCategories && t.csCategories[r.category]) || r.category;
if (r.kind === "tracker") return (t.categories && t.categories[r.category]) || r.category;
if (r.kind === "citationList" && r.key && t[r.key]) return t[r.key];
return "";
}
function renderAiSearchSources(aiSearchSources) {
const mount = document.getElementById("aiSourcesMount");
if (!mount) return;
mount.innerHTML = "";
if (!aiSearchSources || !Array.isArray(aiSearchSources.sources)) {
return;
}
const { sources, rating, counts } = aiSearchSources;
const wrap = document.createElement("div");
wrap.className = "ai-sources-wrap";
const sum = document.createElement("div");
sum.className = "ai-sources-summary cs-rating-" + (rating === "red" ? "red" : rating === "yellow" ? "yellow" : "green");
const icon = rating === "red" ? "🔴" : rating === "yellow" ? "🟡" : "🟢";
const summaryLine =
typeof t.aiSourcesSummary === "function"
? t.aiSourcesSummary(counts)
: `${counts.total} sources`;
sum.innerHTML = `
<div class="cs-rating-icon">${icon}</div>
<div class="cs-rating-body">
<div class="cs-rating-title">${t.aiSourcesHeading || "Citation sources"}</div>
<div class="cs-rating-sub">${summaryLine}</div>
<div class="ai-sources-disclaimer">${t.aiSourcesDisclaimer || ""}</div>
</div>
`;
wrap.appendChild(sum);
if (sources.length === 0) {
const emptyRow = document.createElement("div");
emptyRow.className = "ai-sources-empty";
emptyRow.textContent = t.aiSourcesEmpty || "No external links yet.";
wrap.appendChild(emptyRow);
mount.appendChild(wrap);
return;
}
const tierLabel = (tier) =>
({
low: t.aiSourceTier_low || "Low trust",
caution: t.aiSourceTier_caution || "Review",
ok: t.aiSourceTier_ok || "OK",
})[tier] || tier;
const catLabel = (cat) => (t.aiSourceCat && t.aiSourceCat[cat]) || cat;
const CAT_ICON = { official: "🏛", news: "📰", ugc: "💬", lowtrust: "🔴", other: "🔗" };
const CAT_ORDER = ["official", "news", "ugc", "lowtrust", "other"];
// 与页面内体检口径一致:按 category 统计构成
const comp = { official: 0, news: 0, ugc: 0, lowtrust: 0, other: 0 };
sources.forEach((s) => {
const c = comp[s.category] != null ? s.category : "other";
comp[c]++;
});
const compTotal = sources.length;
// 与页面内体检口径一致的大白话可信度结论 + 行动建议
const V = t.aiVerdict || {};