-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice_worker.js
More file actions
261 lines (210 loc) · 9.78 KB
/
service_worker.js
File metadata and controls
261 lines (210 loc) · 9.78 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
// Privacy Shield Service Worker (Manifest V3)
// Implements aggressive tracker blocking and third-party cookie enforcement
// Import blocklist manager
importScripts('blocklist.js');
// Track blocked requests per tab
const blockedStats = new Map(); // tabId -> { count, domains: Set() }
// Get or create stats for a tab
function getTabStats(tabId) {
if (!blockedStats.has(tabId)) {
blockedStats.set(tabId, { count: 0, domains: new Set() });
}
return blockedStats.get(tabId);
}
// Clean up stats when tab is closed
chrome.tabs.onRemoved.addListener((tabId) => {
blockedStats.delete(tabId);
});
// Reset stats when navigation occurs
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.status === 'loading') {
blockedStats.delete(tabId);
}
});
// Essential trackers to block immediately (fallback)
const ESSENTIAL_TRACKERS = [
'google-analytics.com',
'googletagmanager.com',
'googlesyndication.com',
'doubleclick.net',
'googleadservices.com',
'facebook.com/tr',
'facebook.net',
'scorecardresearch.com',
'adservice.google',
'analytics.google.com'
];
// Create immediate blocking rules from essential trackers
function createEssentialRules(allowlist = []) {
return ESSENTIAL_TRACKERS.map((domain, index) => ({
id: index + 1,
priority: 1,
action: { type: 'block' },
condition: {
urlFilter: `*://*.${domain}/*`,
resourceTypes: ['script', 'xmlhttprequest', 'image', 'sub_frame', 'ping', 'other'],
excludedInitiatorDomains: allowlist.length > 0 ? allowlist : undefined
}
}));
}
chrome.runtime.onInstalled.addListener(async (details) => {
console.log('Privacy Shield: Extension installed/updated');
try {
// Load allowlist from storage
const { allowlist = [] } = await chrome.storage.local.get(['allowlist']);
console.log(`Privacy Shield: Loaded ${allowlist.length} allowlisted sites`);
// STEP 1: Apply essential blocking rules IMMEDIATELY
const essentialRules = createEssentialRules(allowlist);
console.log('Privacy Shield: Applying essential tracker blocking rules...');
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: await chrome.declarativeNetRequest.getDynamicRules().then(rules => rules.map(r => r.id)),
addRules: essentialRules
});
console.log(`Privacy Shield: ${essentialRules.length} essential trackers blocked immediately`);
// Verify rules were applied
const appliedRules = await chrome.declarativeNetRequest.getDynamicRules();
console.log(`Privacy Shield: ${appliedRules.length} rules currently active`);
console.log('Privacy Shield: Sample rule:', appliedRules[0]);
// STEP 2: Fetch comprehensive blocklist in background
console.log('Privacy Shield: Fetching comprehensive blocklist...');
try {
const domains = await initializeBlocklist();
console.log(`Privacy Shield: Loaded ${domains.length} tracker domains from blocklist`);
// Convert to rules with allowlist
const blocklistRules = domainsToRules(domains, allowlist);
console.log(`Privacy Shield: Created ${blocklistRules.length} blocklist rules`);
// IMPORTANT: Keep essential rules + add blocklist rules
// Essential rules have wildcards like *.doubleclick.net which catch all subdomains
// Blocklist has specific domains that might not be caught by wildcards
// Adjust rule IDs to avoid conflicts
const maxEssentialId = essentialRules.length;
const adjustedBlocklistRules = blocklistRules.map(rule => ({
...rule,
id: rule.id + maxEssentialId
}));
// Keep first 4990 blocklist rules (5000 total - 10 essential = 4990)
const limitedBlocklistRules = adjustedBlocklistRules.slice(0, 4990);
// Combine essential + blocklist
const allRules = [...essentialRules, ...limitedBlocklistRules];
// Update with combined rules (remove all first)
const existingRuleIds = (await chrome.declarativeNetRequest.getDynamicRules()).map(rule => rule.id);
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: existingRuleIds,
addRules: allRules
});
console.log('Privacy Shield: Comprehensive tracker blocking rules applied');
console.log(`Privacy Shield: ${allRules.length} total rules (${essentialRules.length} essential + ${limitedBlocklistRules.length} from blocklist)`);
// Verify DoubleClick wildcard is active
const finalRules = await chrome.declarativeNetRequest.getDynamicRules();
const dclickRule = finalRules.find(r => r.condition.urlFilter && r.condition.urlFilter.includes('*.doubleclick.net'));
console.log('Privacy Shield: DoubleClick wildcard rule active:', dclickRule ? '✅ YES' : '❌ NO');
// Store activation status with comprehensive blocklist
await chrome.storage.local.set({
privacyShieldActive: true,
activationTimestamp: Date.now(),
blockedTrackers: allRules.length,
totalDomains: domains.length + ESSENTIAL_TRACKERS.length
});
} catch (blocklistError) {
console.error('Privacy Shield: Error loading comprehensive blocklist:', blocklistError);
console.log('Privacy Shield: Continuing with essential trackers only');
// Store partial activation status
await chrome.storage.local.set({
privacyShieldActive: true,
activationTimestamp: Date.now(),
blockedTrackers: essentialRules.length,
totalDomains: ESSENTIAL_TRACKERS.length,
lastError: blocklistError.message
});
}
console.log('Privacy Shield: Fully activated and ready');
} catch (error) {
console.error('Privacy Shield: Critical error during initialization:', error);
// Store error state
await chrome.storage.local.set({
privacyShieldActive: false,
lastError: error.message
});
}
});
// Track blocked requests for statistics (only available in dev mode)
if (chrome.declarativeNetRequest.onRuleMatchedDebug) {
chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((details) => {
console.log('Privacy Shield: Blocked request to', details.request.url);
// Track per-tab statistics
if (details.request.tabId && details.request.tabId >= 0) {
const stats = getTabStats(details.request.tabId);
stats.count++;
// Extract domain from URL
try {
const url = new URL(details.request.url);
stats.domains.add(url.hostname);
} catch (e) {
// Invalid URL, skip
}
}
});
} else {
console.log('Privacy Shield: onRuleMatchedDebug not available (normal in production)');
}
// Add alarm to periodically update the blocklist (once per day)
chrome.alarms.create('updateBlocklist', { periodInMinutes: 1440 });
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'updateBlocklist') {
console.log('Privacy Shield: Updating blocklist...');
try {
const domains = await initializeBlocklist();
const rules = domainsToRules(domains);
const existingRuleIds = (await chrome.declarativeNetRequest.getDynamicRules()).map(rule => rule.id);
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: existingRuleIds,
addRules: rules
});
await chrome.storage.local.set({
blockedTrackers: rules.length,
totalDomains: domains.length,
lastUpdate: Date.now()
});
console.log(`Privacy Shield: Blocklist updated - ${domains.length} domains`);
} catch (error) {
console.error('Privacy Shield: Error updating blocklist:', error);
}
}
});
// Listen for allowlist updates from popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'updateAllowlist') {
console.log('Privacy Shield: Updating allowlist...', message.allowlist);
// Reload all rules with new allowlist
(async () => {
try {
const { blockedDomains = [] } = await chrome.storage.local.get(['blockedDomains']);
let rules;
if (blockedDomains.length > 0) {
rules = domainsToRules(blockedDomains, message.allowlist);
} else {
rules = createEssentialRules(message.allowlist);
}
const existingRuleIds = (await chrome.declarativeNetRequest.getDynamicRules()).map(rule => rule.id);
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: existingRuleIds,
addRules: rules
});
console.log(`Privacy Shield: Rules updated with ${message.allowlist.length} allowlisted sites`);
} catch (error) {
console.error('Privacy Shield: Error updating allowlist:', error);
}
})();
return true;
}
// Get stats for current tab
if (message.action === 'getTabStats') {
const stats = blockedStats.get(message.tabId);
sendResponse({
count: stats ? stats.count : 0,
domains: stats ? Array.from(stats.domains) : []
});
return true;
}
});
console.log('Privacy Shield: Service worker loaded');