/
protection.js
554 lines (487 loc) · 18.5 KB
/
protection.js
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
/*
Licensed per https://github.com/privacy-tech-lab/gpc-optmeowt/blob/main/LICENSE.md
privacy-tech-lab, https://privacytechlab.org/
*/
/*
protection.js
================================================================================
protection.js (1) Implements our per-site functionality for the background listeners
(2) Handles cached values & message passing to popup & options page
*/
import { stores, storage } from "./../storage.js";
import { modes } from "../../data/modes.js";
import { defaultSettings } from "../../data/defaultSettings.js";
import { headers } from "../../data/headers.js";
import { enableListeners, disableListeners } from "./listeners-$BROWSER.js";
import { initIAB } from "../cookiesIAB.js";
import { initCookiesPerDomain } from "./cookiesOnInstall.js";
import { initCookiesOnInstall } from "./cookiesOnInstall.js";
import psl, { parse } from "psl";
// TODO: Remove this when done
import {
addDynamicRule,
deleteDynamicRule,
reloadDynamicRules,
} from "../../common/editRules.js";
import { updateRemovalScript } from "../../common/editDomainlist.js";
/******************************************************************************/
/******************************************************************************/
/********** # Initializers (cached values) **********/
/******************************************************************************/
/******************************************************************************/
var domainlist = {}; // Caches & mirrors domainlist in storage
var isDomainlisted = defaultSettings["IS_DOMAINLISTED"];
var tabs = {}; // Caches all tab infomration, i.e. requests, etc.
var wellknown = {}; // Caches wellknown info to be sent to popup
var signalPerTab = {}; // Caches if a signal is sent to render the popup icon
var activeTabID = 0; // Caches current active tab id
var sendSignal = true; // Caches if the signal can be sent to the curr domain
var domPrev3rdParties = {}; //stores all the 3rd parties by domain (resets when you quit chrome)
var isFirefox = ("$BROWSER" === "firefox");
var globalParsedDomain;
var isFirefox = "$BROWSER" === "firefox";
async function reloadVars() {
let storedDomainlisted = await storage.get(
stores.settings,
"IS_DOMAINLISTED"
);
if (storedDomainlisted) {
isDomainlisted = storedDomainlisted;
}
}
reloadVars();
/******************************************************************************/
/******************************************************************************/
/********** # Lisetener callbacks - Main functionality **********/
/******************************************************************************/
/******************************************************************************/
/*
* The four following functions are all related to the four main listeners in
* `background.js`. These four functions implement all the other helper
* functions below
*/
const listenerCallbacks = {
/**
* Handles all signal processessing prior to sending request headers
* @param {object} details - retrieved info passed into callback
* @returns {array} details.requestHeaders from addHeaders
*/
onBeforeSendHeaders: (details) => {
updateDomainlist(details);
},
/**
* @param {object} details - retrieved info passed into callback
*/
onHeadersReceived: (details) => {
logData(details);
},
/**
* @param {object} details - retrieved info passed into callback
*/
onBeforeNavigate: (details) => {
// Resets certain cached info
},
/**
* Adds DOM property
* @param {object} details - retrieved info passed into callback
*/
onCommitted: async (details) => {
updateDomainlist(details);
},
}; // closes listenerCallbacks object
/******************************************************************************/
/******************************************************************************/
/********** # Listener helper fxns - Main functionality **********/
/******************************************************************************/
/******************************************************************************/
/**
* Attaches headers from `headers.js` to details.requestHeaders
* @param {object} details - retrieved info passed into callback
* @returns {array} details.requestHeaders
*/
function addHeaders(details) {
for (let signal in headers) {
let s = headers[signal];
details.requestHeaders.push({ name: s.name, value: s.value });
}
return { requestHeaders: details.requestHeaders };
}
function getCurrentParsedDomain() {
return new Promise((resolve, reject) => {
try {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
let tab = tabs[0];
let url = new URL(tab.url);
let parsed = psl.parse(url.hostname);
let domain = parsed.domain;
globalParsedDomain = domain; // for global scope variable
resolve(domain);
});
} catch(e) {
reject();
}
})
}
/**
* Checks whether a particular domain should receive a DNS signal
* (1) Parse url to get domain for domainlist
* (2) Update domains by adding current domain to domainlist in storage.
* (3) Updates the 3rd party list for the currentDomain
* (4) Check to see if we should send signal.
*
* Currently, it only adds to domainlist store as NULL if it doesnt exist
* @param {Object} details - callback object according to Chrome API
*/
async function updateDomainlist(details) {
let url = new URL(details.url);
let parsedUrl = psl.parse(url.hostname);
let parsedDomain = parsedUrl.domain;
let currDomainValue = await storage.get(stores.domainlist, parsedDomain);
console.log(parsedDomain);
if (currDomainValue === undefined) {
storage.set(stores.domainlist, null, parsedDomain); // Sets to storage async
}
//get the current parsed domain--this is used to store 3rd parties (using globalParsedDomain variable)
let currentDomain = await getCurrentParsedDomain();
//initialize the objects
if (!(activeTabID in domPrev3rdParties)){
domPrev3rdParties[activeTabID] = {};
}
if (!(currentDomain in domPrev3rdParties[activeTabID]) ){
domPrev3rdParties[activeTabID][currentDomain] = {};
}
//as they come in, add the parsedDomain to the object with null value (just a placeholder)
domPrev3rdParties[activeTabID][currentDomain][parsedDomain] = null;
}
function updatePopupIcon(tabId) {
chrome.action.setIcon({
tabId: tabId,
path: "assets/face-icons/optmeow-face-circle-green-ring-128.png",
});
}
function logData(details) {
let url = new URL(details.url);
let parsed = psl.parse(url.hostname);
if (tabs[details.tabId] === undefined) {
tabs[details.tabId] = { DOMAIN: null, REQUEST_DOMAINS: {}, TIMESTAMP: 0 };
tabs[details.tabId].REQUEST_DOMAINS[parsed.domain] = {
URLS: {},
RESPONSE: details.responseHeaders,
TIMESTAMP: details.timeStamp,
};
tabs[details.tabId].REQUEST_DOMAINS[parsed.domain].URLS = {
URL: details.url,
RESPONSE: details.responseHeaders,
};
} else {
if (tabs[details.tabId].REQUEST_DOMAINS[parsed.domain] === undefined) {
tabs[details.tabId].REQUEST_DOMAINS[parsed.domain] = {
URLS: {},
RESPONSE: details.responseHeaders,
TIMESTAMP: details.timeStamp,
};
tabs[details.tabId].REQUEST_DOMAINS[parsed.domain].URLS[details.url] = {
RESPONSE: details.responseHeaders,
};
} else {
tabs[details.tabId].REQUEST_DOMAINS[parsed.domain].URLS[details.url] = {
RESPONSE: details.responseHeaders,
};
}
}
}
async function pullToDomainlistCache() {
let domain;
let domainlistKeys = await storage.getAllKeys(stores.domainlist);
let domainlistValues = await storage.getAll(stores.domainlist);
for (let key in domainlistKeys) {
domain = domainlistKeys[key];
domainlist[domain] = domainlistValues[key];
}
}
async function syncDomainlists() {
// (1) Reconstruct a domainlist indexedDB object from storage
// (2) Iterate through local domainlist
// --- If item in cache NOT in domainlistKeys/domainlistDB, add to storage
// via storage.set()
// (3) Iterate through all domain keys in indexedDB domainlist
// --- If key NOT in cached domainlist, add to cached domainlist
let domainlistKeys = await storage.getAllKeys(stores.domainlist);
let domainlistValues = await storage.getAll(stores.domainlist);
let domainlistDB = {};
let domain;
for (let key in domainlistKeys) {
domain = domainlistKeys[key];
domainlistDB[domain] = domainlistValues[key];
}
for (let domainKey in domainlist) {
if (!domainlistDB[domainKey]) {
await storage.set(stores.domainlist, domainlist[domainKey], domainKey);
}
}
for (let domainKey in domainlistDB) {
if (!domainlist[domainKey]) {
domainlist[domainKey] = domainlistDB[domainKey];
}
}
}
/**
* whether the curr site should get privacy signals
* (We need to try and make a synchronous version, esp. for DOM issue & related
* message passing with the contentscript which injects the DOM signal)
* @returns {bool} sendSignal
*/
async function sendPrivacySignal(domain) {
let sendSignal;
const extensionEnabled = await storage.get(stores.settings, "IS_ENABLED");
const extensionDomainlisted = await storage.get(
stores.settings,
"IS_DOMAINLISTED"
);
const domainDomainlisted = await storage.get(stores.domainlist, domain);
if (extensionEnabled) {
if (extensionDomainlisted) {
// Recall we must flip the value of the domainlisted domain
// due to how to how defined domainlisted values, corresponding to MV3
// declarativeNetRequest rule exceptions
// (i.e., null => no rule exists, valued => exception rule exists)
sendSignal = !domainDomainlisted ? true : false;
} else {
sendSignal = true;
}
} else {
sendSignal = false;
}
return sendSignal;
}
/******************************************************************************/
/******************************************************************************/
/********** # Message Passing - Popup helper fxns **********/
/******************************************************************************/
/******************************************************************************/
function handleSendMessageError() {
const error = chrome.runtime.lastError;
if (error) {
console.warn(error.message);
}
}
function dataToPopupHelper(){
//data gets sent back every time the popup is clicked
let requestsData = {};
if (tabs[activeTabID] !== undefined) {
requestsData = domPrev3rdParties[activeTabID][globalParsedDomain];
console.log("requests by tabID:", domPrev3rdParties);
}
return requestsData
}
// Info back to popup
function dataToPopup(wellknownData) {
let requestsData = dataToPopupHelper(); //get requests from the helper
console.log("req data",requestsData);
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
let popupData = {
requests: requestsData,
wellknown: wellknownData,
};
chrome.runtime.sendMessage(
{
msg: "POPUP_PROTECTION_DATA",
data: popupData,
},
handleSendMessageError
);
});
}
function dataToPopupRequests() {
let requestsData = dataToPopupHelper(); //get requests from the helper
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.runtime.sendMessage(
{
msg: "POPUP_PROTECTION_DATA_REQUESTS",
data: requestsData,
},
handleSendMessageError
);
});
}
/******************************************************************************/
/******************************************************************************/
/********** # Message passing **********/
/******************************************************************************/
/******************************************************************************/
/**
* Currently only handles syncing domainlists between storage and memory
* This runs when the popup disconnects from the background page
* @param {Port} port
*/
function onConnectHandler(port) {
if (port.name === "POPUP") {
port.onDisconnect.addListener(function () {
syncDomainlists();
});
}
}
/**
* This is currently only to handle adding the GPC DOM signal.
* I'm not sure how to fit it into an async call, it doesn't want to connect.
* It would be nice to merge the two onMessage handlers.
* TODO: This method still seems to have a timing issue. Doesn't always show DOM signal as thumbs up on reference site.
* @returns {Bool} true (lets us send asynchronous responses to senders)
*/
function onMessageHandlerSynchronous(message, sender, sendResponse) {
if (message.msg === "APPEND_GPC_PROP") {
let url = new URL(sender.origin);
let parsed = psl.parse(url.hostname);
let domain = parsed.domain;
const r = sendPrivacySignal(domain);
r.then((r) => {
const response = {
msg: "APPEND_GPC_PROP_RESPONSE",
sendGPC: r,
};
sendResponse(response);
});
}
return true;
}
/**
* Listeners for information from --POPUP-- or --OPTIONS-- page
* This is the main "hub" for message passing between the extension components
* https://developer.chrome.com/docs/extensions/mv3/messaging/
*/
async function onMessageHandlerAsync(message, sender, sendResponse) {
if (message.msg === "CHANGE_IS_DOMAINLISTED") {
let isDomainlisted = message.data.isDomainlisted;
storage.set(stores.settings, isDomainlisted, "IS_DOMAINLISTED");
}
if (message.msg === "SET_TO_DOMAINLIST") {
let { domain, key } = message.data;
domainlist[domain] = key; // Sets to cache
addDynamicRule(id, domain);
storage.set(stores.domainlist, key, domain); // Sets to long term storage
}
if (message.msg === "POPUP_PROTECTION_REQUESTS") {
dataToPopupRequests();
}
if (message.msg === "CONTENT_SCRIPT_WELLKNOWN") {
let url = new URL(sender.origin);
let parsed = psl.parse(url.hostname);
let domain = parsed.domain;
let tabID = sender.tab.id;
let wellknown = [];
let sendSignal = await storage.get(stores.domainlist, domain);
wellknown[tabID] = message.data;
let wellknownData = message.data;
if (wellknown[tabID] === null && sendSignal == null) {
initIAB();
updatePopupIcon(tabID);
} else if (wellknown[tabID]["gpc"] === true && sendSignal == null) {
initIAB();
chrome.action.setIcon({
tabId: tabID,
path: "assets/face-icons/optmeow-face-circle-green-128.png",
});
}
chrome.runtime.onMessage.addListener(function (message, _, __) {
if (message.msg === "POPUP_PROTECTION") {
dataToPopup(wellknownData);
}
});
}
if (message.msg === "CONTENT_SCRIPT_TAB") {
let url = new URL(sender.origin);
let parsed = psl.parse(url.hostname);
let domain = parsed.domain;
let tabID = sender.tab.id;
if (tabs[tabID] === undefined) {
tabs[tabID] = {
DOMAIN: domain,
REQUEST_DOMAINS: {},
TIMESTAMP: message.data,
};
} else if (tabs[tabID].DOMAIN !== domain) {
tabs[tabID].DOMAIN = domain;
let urls = tabs[tabID]["REQUEST_DOMAINS"];
for (let key in urls) {
if (urls[key]["TIMESTAMP"] >= message.data) {
tabs[tabID]["REQUEST_DOMAINS"][key] = urls[key];
} else {
delete tabs[tabID]["REQUEST_DOMAINS"][key];
}
}
tabs[tabID]["TIMESTAMP"] = message.data;
}
}
if (message.msg === "SET_OPTOUT_COOKEIS") {
// This is initialized when cookies are to be reset to a page after
// do not sell is turned back on (e.g., when its turned on from the popup).
// This is specifically for when cookies are removed when a user turns off
// do not sell for a particular site, and chooses to re-enable it
initCookiesPerDomain(message.data);
}
return true; // Async callbacks require this
}
function initMessagePassing() {
chrome.runtime.onConnect.addListener(onConnectHandler);
chrome.runtime.onMessage.addListener(onMessageHandlerAsync);
chrome.runtime.onMessage.addListener(onMessageHandlerSynchronous);
}
function closeMessagePassing() {
chrome.runtime.onConnect.removeListener(onConnectHandler);
chrome.runtime.onMessage.removeListener(onMessageHandlerAsync);
chrome.runtime.onMessage.removeListener(onMessageHandlerSynchronous);
}
/******************************************************************************/
/******************************************************************************/
/********** # Other initializers - run once per enable **********/
/******************************************************************************/
/******************************************************************************/
/**
* Listener for tab switch that updates the cached current tab variable
*/
function onActivatedProtectionMode(info) {
activeTabID = info.tabId;
}
// Handles misc. setup & setup listeners
function initSetup() {
pullToDomainlistCache();
// Runs on startup to initialize the cached current tab variable
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs.id) {
activeTabID = tabs.id;
}
});
chrome.tabs.onActivated.addListener(onActivatedProtectionMode);
}
function closeSetup() {
chrome.tabs.onActivated.removeListener(onActivatedProtectionMode);
}
/**
* Inteded to facilitate transitioning between analysis & protection modes
*/
function wipeLocalVars() {
domainlist = {}; // Caches & mirrors domainlist in storage
tabs = {}; // Caches all tab infomration, i.e. requests, etc.
wellknown = {}; // Caches wellknown info to be sent to popup
signalPerTab = {}; // Caches if a signal is sent to render the popup icon
activeTabID = 0; // Caches current active tab id
sendSignal = false; // Caches if the signal can be sent to the curr domain
}
/******************************************************************************/
/******************************************************************************/
/********** # Exportable init / halt functions **********/
/******************************************************************************/
/******************************************************************************/
export function init() {
reloadVars();
initCookiesOnInstall(); // NOTE: This replaces ALL do not sell cookies
enableListeners(listenerCallbacks);
initMessagePassing();
initSetup();
}
export function halt() {
disableListeners(listenerCallbacks);
closeMessagePassing();
closeSetup();
wipeLocalVars();
}