-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathwebExtensionWorker.ts
286 lines (248 loc) · 10.2 KB
/
webExtensionWorker.ts
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
import {AuthType} from "../../userInfo";
import {ClientInfo} from "../../clientInfo";
import {ClientType} from "../../clientType";
import {ClipperUrls} from "../../clipperUrls";
import {Constants} from "../../constants";
import {UrlUtils} from "../../urlUtils";
import {SmartValue} from "../../communicator/smartValue";
import * as Log from "../../logging/log";
import {ClipperData} from "../../storage/clipperData";
import {LocalStorage} from "../../storage/localStorage";
import {ChangeLog} from "../../versioning/changeLog";
import {AuthenticationHelper} from "../authenticationHelper";
import {ExtensionWorkerBase} from "../extensionWorkerBase";
import {InjectHelper} from "../injectHelper";
import {InjectUrls} from "./injectUrls";
import {WebExtension} from "./webExtension";
import {WebExtensionBackgroundMessageHandler} from "./webExtensionMessageHandler";
type TabRemoveInfo = chrome.tabs.TabRemoveInfo;
type WebResponseCacheDetails = chrome.webRequest.WebResponseCacheDetails;
type Window = chrome.windows.Window;
export class WebExtensionWorker extends ExtensionWorkerBase<W3CTab, number> {
private injectUrls: InjectUrls;
private noOpTrackerInvoked: boolean;
constructor(injectUrls: InjectUrls, tab: W3CTab, clientInfo: SmartValue<ClientInfo>, auth: AuthenticationHelper) {
let messageHandlerThunk = () => { return new WebExtensionBackgroundMessageHandler(tab.id); };
super(clientInfo, auth, new ClipperData(new LocalStorage()), messageHandlerThunk, messageHandlerThunk);
this.injectUrls = injectUrls;
this.tab = tab;
this.tabId = tab.id;
this.noOpTrackerInvoked = false;
let isPrivateWindow: Boolean = !!tab.incognito || !!tab.inPrivate;
this.consoleOutputEnabledFlagProcessed.then(() => {
this.logger.setContextProperty(Log.Context.Custom.InPrivateBrowsing, isPrivateWindow.toString());
this.invokeDebugLoggingIfEnabled();
});
}
/**
* Get the url associated with this worker's tab
*/
public getUrl(): string {
return this.tab.url;
}
/**
* Launches the sign in window, rejecting with an error object if something went wrong on the server during
* authentication. Otherwise, it resolves with true if the redirect endpoint was hit as a result of a successful
* sign in attempt, and false if it was not hit (e.g., user manually closed the popup)
*/
protected doSignInAction(authType: AuthType): Promise<boolean> {
let usidQueryParamValue = this.getUserSessionIdQueryParamValue();
let signInUrl = ClipperUrls.generateSignInUrl(this.clientInfo.get().clipperId, usidQueryParamValue, AuthType[authType]);
return this.launchWebExtensionPopupAndWaitForClose(signInUrl, Constants.Urls.Authentication.authRedirectUrl);
}
/**
* Signs the user out
*/
protected doSignOutAction(authType: AuthType) {
let usidQueryParamValue = this.getUserSessionIdQueryParamValue();
let signOutUrl = ClipperUrls.generateSignOutUrl(this.clientInfo.get().clipperId, usidQueryParamValue, AuthType[authType]);
fetch(signOutUrl);
}
/**
* Notify the UI to invoke the clipper. Resolve with true if it was thought to be successfully
* injected; otherwise resolves with false.
*/
protected invokeClipperBrowserSpecific(): Promise<boolean> {
return new Promise<boolean>((resolve) => {
WebExtension.browser.scripting.executeScript({
target: { tabId: this.tab.id },
func: () => {}
}, () => {
if (WebExtension.browser.runtime.lastError) {
Log.ErrorUtils.sendFailureLogRequest({
label: Log.Failure.Label.UnclippablePage,
properties: {
failureType: Log.Failure.Type.Expected,
failureInfo: { error: WebExtension.browser.runtime.lastError.message },
stackTrace: Log.Failure.getStackTrace()
},
clientInfo: this.clientInfo
});
// In Firefox, alert() is not callable from the service worker, so it looks like we have to no-op here
if (this.clientInfo.get().clipperType !== ClientType.FirefoxExtension) {
InjectHelper.alertUserOfUnclippablePage();
}
resolve(false);
} else {
if (this.clientInfo.get().clipperType === ClientType.FirefoxExtension) {
WebExtension.browser.management.uninstallSelf();
resolve(true);
} else {
WebExtension.browser.scripting.executeScript({
target: { tabId: this.tab.id },
files: [this.injectUrls.webClipperInjectUrl]
});
if (!this.noOpTrackerInvoked) {
this.setUpNoOpTrackers(this.tab.url);
this.noOpTrackerInvoked = true;
}
resolve(true);
}
}
});
});
}
/**
* Notify the UI to invoke the frontend script that handles logging to the conosle. Resolve with
* true if it was thought to be successfully injected; otherwise resolves with false.
*/
protected invokeDebugLoggingBrowserSpecific(): Promise<boolean> {
return new Promise<boolean>((resolve) => {
WebExtension.browser.scripting.executeScript({
target: { tabId: this.tab.id },
files: [this.injectUrls.debugLoggingInjectUrl]
}, () => {
if (WebExtension.browser.runtime.lastError) {
// We are probably on a page like about:blank, which is pretty normal
resolve(false);
} else {
resolve(true);
}
});
});
}
protected invokePageNavBrowserSpecific(): Promise<boolean> {
return new Promise<boolean>((resolve) => {
WebExtension.browser.scripting.executeScript({
target: { tabId: this.tab.id },
func: () => {}
}, () => {
// It's safest to not use lastError in the resolve due to special behavior in the Chrome API
if (WebExtension.browser.runtime.lastError) {
// We are probably on a page like about:blank, which is pretty normal
resolve(false);
} else {
WebExtension.browser.scripting.executeScript({
target: { tabId: this.tab.id },
files: [this.injectUrls.pageNavInjectUrl]
});
resolve(true);
}
});
});
}
/**
* Notify the UI to invoke the What's New tooltip. Resolve with true if it was thought to be successfully
* injected; otherwise resolves with false.
*/
protected invokeWhatsNewTooltipBrowserSpecific(newVersions: ChangeLog.Update[]): Promise<boolean> {
return this.invokePageNavBrowserSpecific();
}
protected invokeTooltipBrowserSpecific(): Promise<boolean> {
return this.invokePageNavBrowserSpecific();
}
protected isAllowedFileSchemeAccessBrowserSpecific(callback: (allowed: boolean) => void): void {
if (!WebExtension.browser.extension.isAllowedFileSchemeAccess) {
callback(true);
return;
}
WebExtension.browser.extension.isAllowedFileSchemeAccess((isAllowed) => {
if (!isAllowed && this.tab.url.indexOf("file:///") === 0) {
callback(false);
} else {
callback(true);
}
});
}
/**
* Gets the visible tab's screenshot as an image url
*/
protected takeTabScreenshot(): Promise<string> {
return new Promise<string>((resolve) => {
WebExtension.browser.tabs.query({ active: true, lastFocusedWindow: true }, () => {
WebExtension.browser.tabs.captureVisibleTab({ format: "png" }, (dataUrl: string) => {
resolve(dataUrl);
});
});
});
}
private launchWebExtensionPopupAndWaitForClose(url: string, autoCloseDestinationUrl: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
let popupWidth = 1000;
let popupHeight = 700;
WebExtension.browser.windows.getCurrent((currentWindow: Window) => {
let leftPosition: number = currentWindow.left + Math.round((currentWindow.width - popupWidth) / 2);
let topPosition: number = currentWindow.top + Math.round((currentWindow.height - popupHeight) / 2);
try {
/* As of 7/19/2016, Firefox does not yet supported the "focused" key for windows.create in the WebExtensions API */
/* See bug filed here: https://bugzilla.mozilla.org/show_bug.cgi?id=1213484 */
let windowOptions: chrome.windows.CreateData = {
height: popupHeight,
left: leftPosition,
top: topPosition,
type: "popup",
url: url,
width: popupWidth
};
if (this.clientInfo.get().clipperType !== ClientType.FirefoxExtension) {
windowOptions.focused = true;
}
WebExtension.browser.windows.create(windowOptions, (newWindow: Window) => {
let redirectOccurred = false;
let errorObject;
let correlationId: string;
let redirectListener = (details: WebResponseCacheDetails) => {
redirectOccurred = true;
// Find and get correlation id
if (details.responseHeaders) {
for (let i = 0; i < details.responseHeaders.length; i++) {
if (details.responseHeaders[i].name === Constants.HeaderValues.correlationId) {
correlationId = details.responseHeaders[i].value;
break;
}
}
}
let redirectUrl = details.url;
let error = UrlUtils.getQueryValue(redirectUrl, Constants.Urls.QueryParams.error);
let errorDescription = UrlUtils.getQueryValue(redirectUrl, Constants.Urls.QueryParams.errorDescription);
if (error || errorDescription) {
errorObject = { error: error, errorDescription: errorDescription, correlationId: correlationId };
}
WebExtension.browser.webRequest.onCompleted.removeListener(redirectListener);
WebExtension.browser.tabs.remove(details.tabId);
};
WebExtension.browser.webRequest.onCompleted.addListener(redirectListener, {
windowId: newWindow.id, urls: [autoCloseDestinationUrl + "*"]
}, ["responseHeaders"]);
let closeListener = (tabId: number, tabRemoveInfo: TabRemoveInfo) => {
if (tabRemoveInfo.windowId === newWindow.id) {
errorObject ? reject(errorObject) : resolve(redirectOccurred);
WebExtension.browser.tabs.onRemoved.removeListener(closeListener);
}
};
WebExtension.browser.tabs.onRemoved.addListener(closeListener);
});
} catch (e) {
// In the event that there was an exception thrown during the creation of the popup, fallback to using window.open with a monitor
this.logger.logFailure(Log.Failure.Label.WebExtensionWindowCreate, Log.Failure.Type.Unexpected, { error: e.message });
this.launchPopupAndWaitForClose(url).then((redirectOccurred) => {
// From chrome's background, we currently are unable to reliably determine if the redirect happened
resolve(true /* redirectOccurred */);
}, (errorObject) => {
reject(errorObject);
});
}
});
});
}
}