-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent_script.js
More file actions
177 lines (145 loc) · 5.96 KB
/
Copy pathcontent_script.js
File metadata and controls
177 lines (145 loc) · 5.96 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
// content_script.js — Orchestrates detection pipeline and bridges to popup/background
// Phase 2: adds AI analysis layer on page load + manual rescan trigger.
(async () => {
const { sensitivity = 'balanced', enabled = true } =
await chrome.storage.sync.get(['sensitivity', 'enabled']);
if (!enabled) return;
const SEVERITY_WEIGHT = { critical: 4, high: 3, medium: 2, info: 1 };
const SENSITIVITY_THRESHOLDS = {
cautious: { minWeight: 3 },
balanced: { minWeight: 2 },
strict: { minWeight: 1 },
};
const threshold = SENSITIVITY_THRESHOLDS[sensitivity] || SENSITIVITY_THRESHOLDS.balanced;
// ─── HELPERS ───────────────────────────────────────────────────────────────
function filterByThreshold(findings) {
return findings.filter(f => SEVERITY_WEIGHT[f.severity] >= threshold.minWeight);
}
function dedup(findings) {
const seen = new Set();
// Key on patternId + trimmed text content — catches parent/child elements
// containing identical text that the rule matched multiple times
return findings.filter(f => {
const text = (f.element?.textContent || '').trim().substring(0, 80);
const key = `${f.patternId}::${text}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
function toSummaryFinding(f) {
return {
patternId: f.patternId,
label: f.label,
plainLabel: f.plainLabel || f.label,
severity: f.severity,
explanation: f.explanation,
action: f.action || '',
category: f.category,
source: f.source || 'dom',
};
}
function buildSummary(findings) {
return {
url: window.location.href,
title: document.title,
total: findings.length,
bySeverity: {
critical: findings.filter(f => f.severity === 'critical').length,
high: findings.filter(f => f.severity === 'high').length,
medium: findings.filter(f => f.severity === 'medium').length,
info: findings.filter(f => f.severity === 'info').length,
},
findings: findings.map(toSummaryFinding),
scannedAt: Date.now(),
aiComplete: false, // flips to true once AI layer finishes
};
}
// ─── PHASE 1: DOM RULES (instant) ─────────────────────────────────────────
DPOverlay.init();
let allFindings = [];
function runDOMRules() {
let findings = [];
for (const rule of window.DPRules.RULES) {
try { findings.push(...rule.run()); }
catch (err) { console.warn(`[DarkPatternDetector] Rule "${rule.id}" failed:`, err); }
}
return dedup(filterByThreshold(findings));
}
allFindings = runDOMRules();
DPOverlay.render(allFindings);
let summary = buildSummary(allFindings);
chrome.runtime.sendMessage({ type: 'SCAN_COMPLETE', summary });
// ─── PHASE 2: AI ANALYSIS (async, on page load) ────────────────────────────
async function runAIAnalysis() {
try {
const aiFindings = await window.DPAIAnalyzer.analyse();
if (!aiFindings || aiFindings.length === 0) return;
// Merge — don't add AI finding if DOM already caught same element+pattern
const genuinelyNew = aiFindings.filter(ai =>
!allFindings.find(dom =>
dom.element === ai.element && dom.category === ai.category
)
);
if (genuinelyNew.length === 0) return;
const filtered = filterByThreshold(genuinelyNew);
allFindings.push(...filtered);
DPOverlay.render(allFindings);
// Update summary and notify popup
summary = buildSummary(allFindings);
summary.aiComplete = true;
chrome.runtime.sendMessage({ type: 'SCAN_COMPLETE', summary });
} catch (err) {
console.warn('[DarkPatternDetector] AI analysis error:', err);
}
}
// Fire AI analysis automatically on page load
runAIAnalysis();
// ─── MUTATION OBSERVER (DOM rules only on new nodes) ──────────────────────
const observerDebounce = {};
const observer = new MutationObserver((mutations) => {
clearTimeout(observerDebounce.t);
observerDebounce.t = setTimeout(() => {
const hasNewNodes = mutations.some(m =>
[...m.addedNodes].some(n => n.nodeType === Node.ELEMENT_NODE)
);
if (!hasNewNodes) return;
const freshDOM = runDOMRules();
const newFindings = freshDOM.filter(f =>
!allFindings.find(ex => ex.element === f.element && ex.patternId === f.patternId)
);
if (newFindings.length > 0) {
allFindings.push(...newFindings);
DPOverlay.render(allFindings);
chrome.runtime.sendMessage({
type: 'NEW_FINDINGS',
count: newFindings.length,
findings: newFindings.map(toSummaryFinding),
});
}
}, 800);
});
observer.observe(document.body, { childList: true, subtree: true });
// ─── MESSAGE LISTENER ─────────────────────────────────────────────────────
chrome.runtime.onMessage.addListener((msg, _sender, respond) => {
if (msg.type === 'GET_FINDINGS') {
respond({ summary });
return true;
}
if (msg.type === 'RESCAN') {
observer.disconnect();
DPOverlay.clearAll();
allFindings = [];
// Re-run DOM rules immediately
allFindings = runDOMRules();
DPOverlay.render(allFindings);
summary = buildSummary(allFindings);
chrome.runtime.sendMessage({ type: 'SCAN_COMPLETE', summary });
// Re-trigger AI analysis (user explicitly asked for it)
runAIAnalysis();
respond({ ok: true, count: allFindings.length });
observer.observe(document.body, { childList: true, subtree: true });
return true;
}
});
})();