-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackground.js
executable file
·377 lines (312 loc) · 10.7 KB
/
background.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
// Initialize the namespace.
stannum = window.stannum || {};
/**
* The URL of the Stannum extension.
* @type {string}
*/
stannum.EXTENSION_URL = chrome.extension.getURL('');
/**
* Specifies if Chrome is to be in offline mode.
* @type {boolean}
*/
stannum.offlineMode = false;
/**
* Specifies if all outgoing requests should be over HTTPS.
* @type {boolean}
*/
stannum.alwaysHttpsMode = false;
/**
* Specifies if all outgoing HTTP requests should be upgraded to HTTPS.
* @type {boolean}
*/
stannum.upgradeHttpMode = false;
/**
* Initialize Stannum.
*/
stannum.init = function() {
// Install the web request filter as the first order of initialization
chrome.webRequest.onBeforeRequest.addListener(
stannum.handlers.requestFilter,
{urls: ["<all_urls>"]},
["blocking"]
);
stannum.lockDownContentSettings();
stannum.lockDownPrivacySettings();
chrome.extension.onRequest.addListener(msgListener);
// TODO(radi): Rename once config.js is refactored.
initConfig();
stannum.initTabs();
};
/**
* Enables/disables the offline mode in Chrome.
* @return {boolean} True if offline mode is enabled.
*/
stannum.toggleOffline = function() {
stannum.offlineMode = !stannum.offlineMode;
chrome.webRequest.handlerBehaviorChanged();
return stannum.offlineMode;
};
/**
* Enables/disables the always HTTPS mode in Chrome.
* @return {boolean} True if always HTTPS mode is enabled.
*/
stannum.toggleAlwaysHttpsMode = function() {
stannum.alwaysHttpsMode = !stannum.alwaysHttpsMode;
chrome.webRequest.handlerBehaviorChanged();
return stannum.alwaysHttpsMode;
};
/**
* Enables/disables the upgrade HTTP to HTTPS mode in Chrome.
* @return {boolean} True if upgrade HTTP to HTTPS mode is enabled.
*/
stannum.toggleUpgradeHttpMode = function() {
stannum.upgradeHttpMode = !stannum.upgradeHttpMode;
chrome.webRequest.handlerBehaviorChanged();
return stannum.upgradeHttpMode;
};
/**
* Lock down the content settings.
*/
stannum.lockDownContentSettings = function() {
var defaultArgs = {
primaryPattern: '<all_urls>',
setting: 'block',
scope: 'regular'
};
stannum.setSetting_(
chrome.contentSettings.javascript, defaultArgs, 'JavaScript');
stannum.setSetting_(chrome.contentSettings.cookies, function() {
var args = JSON.parse(JSON.stringify(defaultArgs));
args.secondaryPattern = '<all_urls>';
args.setting = 'session_only';
return args;
}(), 'Cookie persistence');
stannum.setSetting_(chrome.contentSettings.plugins, defaultArgs, 'Plugins');
stannum.setSetting_(chrome.contentSettings.popups, defaultArgs, 'Popups');
stannum.setSetting_(
chrome.contentSettings.notifications, defaultArgs, 'Notifications');
};
/**
* Lock down the privacy settings.
*/
stannum.lockDownPrivacySettings = function() {
var args = {value: false};
var settingsMap = {
'Auto-fill': chrome.privacy.services.autofillEnabled,
'Alternate error pages': chrome.privacy.services.alternateErrorPagesEnabled,
'Safe-browsing': chrome.privacy.services.safeBrowsingEnabled,
'Search suggest': chrome.privacy.services.searchSuggestEnabled,
'Spelling': chrome.privacy.services.spellingServiceEnabled,
'Translation service': chrome.privacy.services.translationServiceEnabled,
'Network prediction': chrome.privacy.network.networkPredictionEnabled,
'Third-party cookies': chrome.privacy.websites.thirdPartyCookiesAllowed,
'Hyperlink auditing': chrome.privacy.websites.hyperlinkAuditingEnabled
};
for (settingName in settingsMap) {
stannum.setPrivacySetting_(settingsMap[settingName], args, settingName);
}
};
/**
* Set a given setting.
* @param {!Object} setting The setting to lock down.
* @param {!Object} settingArgs The required arguments to lock down the setting.
* @param {string} settingName The name of the setting.
* @param {function(...)=} opt_callback An optional callback to invoke once the
* setting is set.
* @private
*/
stannum.setSetting_ = function(setting, settingArgs, settingName, opt_callback) {
setting.set(settingArgs, function() {
if (chrome.extension.lastError) {
console.error('Failed to set ' + settingName.toLowerCase() + '!',
chrome.extension.lastError);
} else {
console.log(settingName + ' has been set successfully.');
if (opt_callback) {
opt_callback();
}
}
});
};
/**
* Set a given privacy setting.
* @param {!Object} setting The setting to lock down.
* @param {!Object} settingArgs The required arguments to lock down the setting.
* @param {string} settingName The name of the setting.
* @private
*/
stannum.setPrivacySetting_ = function(setting, settingArgs, settingName) {
setting.get({}, function(details) {
if (details.levelOfControl == 'controllable_by_this_extension' ||
details.levelOfControl == 'controlled_by_this_extension') {
stannum.setSetting_(setting, settingArgs, settingName);
} else {
console.warn('Access denied to set ' + settingName.toLowerCase()
+ ': ' + details.levelOfControl);
}
});
};
/**
* Sets the settings for loading a particular resource.
* @param {string} origin The origin from which the resource is loaded.
* @param {string} setting The setting to apply to the given resource.
* @param {boolean} temp Inidicator whether the setting should be temporary
* or not.
* @param {function(...)=} opt_callback An optional callback to invoke once the
* setting is applied to the given resource.
*/
stannum.setResourceSetting = function(origin, setting, temp, opt_callback) {
var pattern = origin + '/*';
stannum.setSetting_(chrome.contentSettings.javascript, {
primaryPattern: pattern,
setting: setting
}, 'JavaScript', function() {
if (!temp) {
// TODO(radi): Refactor.
configData.addScriptOrigin(pattern, setting);
}
if(opt_callback) {
opt_callback(setting);
}
});
};
/**
* Gets the settings for loading a particular resource.
* @param {string} origin The origin from which the resource is loaded.
* @param {!function(...)} callback The callback to invoke once the settings are
* retrieved.
*/
stannum.getResourceSetting = function(origin, callback) {
if (!callback) {
throw new Error('Missing callback to stannum.getResourceSetting');
}
chrome.contentSettings.javascript.get({
primaryUrl: origin + '/*'
}, function(details) {
if (chrome.extension.lastError) {
console.error('Failed to get value for ' + origin + '!\nError details: ',
chrome.extension.lastError);
} else {
callback(origin, details.setting);
}
});
};
/**
* Enables JavaScript for a given origin.
* @param {string} origin The origin for which to enable JavaScript.
*/
stannum.enableJavaScript = function(origin) {
stannum.setSetting_(chrome.contentSettings.javascript, {
primaryPattern: origin + '/*',
setting: 'allow',
scope: 'regular'
}, 'JavaScript', function() {
// TODO(radi): Refactor.
configData.addScriptOrigin(pattern, 'allow');
});
};
/**
* Event handlers for handling network and navigation events.
* @type {!Object}
*/
stannum.handlers = {};
/**
* Enforce user preferences with respect to which traffic is allowed.
* @param {!Object} details HTTP request details.
*/
stannum.handlers.requestFilter = function(details) {
var url = details.url;
var requestLog = 'request [' + details.tabId + '][' + details.frameId + '][' +
details.parentFrameId + '][' + details.type + ']: ' + url;
// Allow all requests destined to our own extension.
if (url.indexOf(stannum.EXTENSION_URL) == 0) {
return;
}
// If we are in offline mode, block all requests.
if (stannum.offlineMode) {
console.log('Blocking offline ' + requestLog);
return {cancel: true};
}
// Transform HTTP to HTTPS.
if (stannum.upgradeHttpMode && /^http:\/\//i.test(url)) {
var newUrl = 'https:' + url.substring(5);
console.log('Upgraded ' + url + ' to ' + newUrl);
return { redirectUrl: newUrl };
}
// Block non-https traffic.
if (stannum.alwaysHttpsMode) {
if (/^(chrome|https):\/\//.test(details.url)) {
console.log('Allowing ' + requestLog);
} else {
console.log('Blocking non-HTTPS ' + requestLog);
return {cancel: true};
}
}
var tab = stannum.tabsHolder.tabs[details.tabId];
if (tab) {
if (details.type === 'main_frame') {
tab.reset();
} else if (details.type === 'script') {
tab.add('scripts', url);
}
}
console.log('Allowing ' + requestLog);
};
stannum.init();
console.log("Stannum initialized");
// Temporary hack so that refactoring does not break Stannum's functionality.
var dispatchTable = new Array();
dispatchTable['getOrigins'] = function getOrigins(request, sendResponse) {
var t = stannum.tabsHolder.tabs[request.tabId];
var scripts = {};
for (var i = 0; i < t.scripts.length; ++i) {
var origin = getOriginFromUrl(t.scripts[i]);
var config = t.scripts[origin + '/*'];
if (config === undefined) {
scripts[origin] = {'setting': 'block'};
} else {
scripts[origin] = {'setting': config.setting};
}
}
chrome.tabs.get(request.tabId, function(tab) {
var tabOrigin = getOriginFromUrl(tab.url);
stannum.getResourceSetting(tabOrigin, function(origin, value) {
scripts[origin] = {'setting': value};
var r = {'scripts': scripts};
sendResponse(r);
});
});
}
dispatchTable['allowResource'] = function(request, sendResponse) {
var origin = request.origin;
console.log('Allowing resource from: ' + origin);
stannum.setResourceSetting(origin, 'allow', false, function(setting) {
sendResponse({'origin': origin, 'setting': setting}); });
}
dispatchTable['allowResourceTemp'] = function(request, sendResponse) {
var origin = request.origin;
console.log('Allowing temporarily resource from: ' + origin);
if (stannum.tabsHolder.tabs[request.tabId] !== undefined) {
stannum.tabsHolder.tabs[request.tabId].tempSciptExceptions.push(origin);
}
stannum.setResourceSetting(origin, 'allow', true, function(setting) {
sendResponse({'origin': origin, 'setting': setting}); });
}
dispatchTable['blockResource'] = function(request, sendResponse) {
var origin = request.origin;
console.log('Blocking resource from: ' + origin);
stannum.setResourceSetting(origin, 'block', function(setting) {
sendResponse({'origin': origin, 'setting': setting}); });
}
dispatchTable['ping'] = function(request, sendResponse) {
console.log("ping: " + request.data);
}
function msgListener(request, sender, sendResponse) {
console.log(sender.tab ?
"msg |" + request.msg + "| from content script:" + sender.tab.url :
"msg from the extension");
var f = dispatchTable[request.msg];
if (f !== undefined) {
f(request, sendResponse);
}
}