-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinit-webext.js
310 lines (279 loc) · 8.1 KB
/
init-webext.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
/* global Util, chrome, Config, UI, Broker, Snowflake, WS */
/* eslint no-unused-vars: 0 */
/*
UI
*/
/**
* Decide whether we need to request or revoke the 'background' permission, and
* set the `runInBackground` storage value appropriately.
* @param {boolean | undefined} enabledSetting
* @param {boolean | undefined} runInBackgroundSetting
*/
function maybeChangeBackgroundPermission(enabledSetting, runInBackgroundSetting) {
const needBackgroundPermission =
runInBackgroundSetting
// When the extension is disabled, we need the permission to be revoked because
// otherwise it'll keep the browser process running for no reason.
&& enabledSetting;
// Yes, this is called even if the permission is already in the state we need
// it to be in (granted/removed).
new Promise(r => {
chrome.permissions[needBackgroundPermission ? "request" : "remove"](
{ permissions: ['background'] },
r
);
})
.then(success => {
// Currently the resolve value is `true` even when the permission was alrady granted
// before it was requested (already removed before it was revoked). TODO Need to make
// sure it's the desired behavior and if it needs to change.
// https://developer.chrome.com/docs/extensions/reference/permissions/#method-remove
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/permissions/remove#return_value
// https://github.com/mdn/content/pull/17516
if (success) {
chrome.storage.local.set({ runInBackground: runInBackgroundSetting });
}
});
}
// If you want to gonna change this to `false`, double-check everything as some code
// may still be assuming it to be `true`.
const DEFAULT_ENABLED = true;
class WebExtUI extends UI {
constructor() {
super();
this.onConnect = this.onConnect.bind(this);
this.onMessage = this.onMessage.bind(this);
this.onDisconnect = this.onDisconnect.bind(this);
chrome.runtime.onConnect.addListener(this.onConnect);
}
checkNAT() {
Util.checkNATType(config.datachannelTimeout).then((type) => {
console.log("Setting NAT type: " + type);
this.natType = type;
}).catch((e) => {
console.log(e);
});
}
initNATType() {
this.natType = "unknown";
this.checkNAT();
setInterval(() => {this.checkNAT();}, config.natCheckInterval);
}
tryProbe() {
WS.probeWebsocket(config.defaultRelayAddr)
.then(
() => {
this.missingFeature = false;
this.setEnabled(true);
},
() => {
log('Could not connect to bridge.');
this.missingFeature = 'popupBridgeUnreachable';
this.setEnabled(false);
}
);
}
initToggle() {
// First, check if we have our status stored
(new Promise((resolve) => {
chrome.storage.local.get(["snowflake-enabled"], resolve);
}))
.then((result) => {
let enabled = this.enabled;
if (result['snowflake-enabled'] !== undefined) {
enabled = result['snowflake-enabled'];
} else {
log("Toggle state not yet saved");
}
// If it isn't enabled, stop
if (!enabled) {
this.setEnabled(enabled);
return;
}
// Otherwise, do feature checks
if (!Util.hasWebRTC()) {
this.missingFeature = 'popupWebRTCOff';
this.setEnabled(false);
return;
}
this.tryProbe();
});
}
postActive() {
this.setIcon();
if (!this.port) { return; }
this.port.postMessage({
clients: this.clients,
total: this.stats.reduce((t, c) => t + c, 0),
enabled: this.enabled,
missingFeature: this.missingFeature,
});
}
onConnect(port) {
this.port = port;
port.onDisconnect.addListener(this.onDisconnect);
port.onMessage.addListener(this.onMessage);
this.postActive();
}
onMessage(m) {
if (m.retry) {
// FIXME: Can set a retrying state here
this.tryProbe();
} else if (m.enabled != undefined) {
(new Promise((resolve) => {
chrome.storage.local.set({ "snowflake-enabled": m.enabled }, resolve);
}))
.then(() => {
log("Stored toggle state");
this.initToggle();
});
if (
typeof SUPPORTS_WEBEXT_OPTIONAL_BACKGROUND_PERMISSION !== 'undefined'
// eslint-disable-next-line no-undef
&& SUPPORTS_WEBEXT_OPTIONAL_BACKGROUND_PERMISSION
) {
new Promise(r => chrome.storage.local.get({ runInBackground: false }, r))
.then(storage => {
maybeChangeBackgroundPermission(m.enabled, storage.runInBackground);
});
}
} else if (m.runInBackground != undefined) {
if (
typeof SUPPORTS_WEBEXT_OPTIONAL_BACKGROUND_PERMISSION !== 'undefined'
// eslint-disable-next-line no-undef
&& SUPPORTS_WEBEXT_OPTIONAL_BACKGROUND_PERMISSION
) {
new Promise(r => chrome.storage.local.get({ "snowflake-enabled": DEFAULT_ENABLED }, r))
.then(storage => {
maybeChangeBackgroundPermission(storage["snowflake-enabled"], m.runInBackground);
});
}
} else {
log("Unrecognized message");
}
}
onDisconnect() {
this.port = null;
}
/**
* @param {boolean} enabled
*/
setEnabled(enabled) {
this.enabled = enabled;
this.postActive();
update();
}
setIcon() {
let path = null;
let badgeText = '';
if (!this.enabled) {
path = {
48: "assets/toolbar-off-48.png",
96: "assets/toolbar-off-96.png"
};
} else {
if (this.active) {
path = {
48: "assets/toolbar-running-48.png",
96: "assets/toolbar-running-96.png"
};
} else {
path = {
48: "assets/toolbar-on-48.png",
96: "assets/toolbar-on-96.png"
};
}
const totalClients = this.stats.reduce((t, c) => t + c, 0);
if (totalClients > 0) {
if (config.maxNumClients > 1 && this.clients > 0) {
// Like `19+3`
badgeText = `${totalClients - this.clients}+${this.clients}`;
} else {
badgeText = `${totalClients}`;
}
}
}
chrome.browserAction.setIcon({
path: path,
});
// Color is taken from Tor Browser (tor-styles.css, `purple-30`,
// with lightness changed to 81%).
chrome.browserAction.setBadgeBackgroundColor({ color: '#d79eff' });
chrome.browserAction.setBadgeText({ text: badgeText });
}
}
WebExtUI.prototype.port = null;
WebExtUI.prototype.enabled = DEFAULT_ENABLED;
/*
Entry point.
*/
/** @typedef {WebExtUI} UIOfThisContext */
var
/** @type {boolean} */
debug,
/** @type {Snowflake | null} */
snowflake,
/** @type {Config | null} */
config,
/** @type {Broker | null} */
broker,
/** @type {UIOfThisContext | null} */
ui,
/** @type {(msg: unknown) => void} */
log,
/** @type {(msg: unknown) => void} */
dbg,
/** @type {() => void} */
init,
/** @type {() => void} */
update,
/** @type {boolean} */
silenceNotifications;
(function () {
silenceNotifications = false;
debug = false;
snowflake = null;
config = null;
broker = null;
ui = null;
// Log to both console and UI if applicable.
// Requires that the snowflake and UI objects are hooked up in order to
// log to console.
log = function(msg) {
console.log('Snowflake: ' + msg);
if (snowflake != null) {
snowflake.ui.log(msg);
}
};
dbg = function(msg) {
if (debug) {
log(msg);
}
};
init = function() {
config = new Config("webext");
ui = new WebExtUI();
broker = new Broker(config);
snowflake = new Snowflake(config, ui, broker);
log('== snowflake proxy ==');
ui.initToggle();
ui.initNATType();
};
update = function() {
if (!ui.enabled) {
// Do not activate the proxy if any number of conditions are true.
snowflake.disable();
log('Currently not active.');
return;
}
// Otherwise, begin setting up WebRTC and acting as a proxy.
dbg('Contacting Broker at ' + broker.url);
log('Starting snowflake');
snowflake.beginServingClients();
};
window.onunload = function() {
if (snowflake !== null) { snowflake.disable(); }
return null;
};
window.onload = init;
}());