-
Notifications
You must be signed in to change notification settings - Fork 22
/
internal.ts
314 lines (284 loc) · 9.57 KB
/
internal.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
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
/*
* Copyright (C) 2021 Pixie Brix, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {
HandlerOptions,
isNotification,
RemoteProcedureCallRequest,
SerializableResponse,
toErrorResponse,
} from "@/messaging/protocol";
import { browser, Runtime, WebNavigation } from "webextension-polyfill-ts";
import { allowBackgroundSender } from "@/background/protocol";
import {
BackgroundEventType,
HandlerEntry,
MESSAGE_PREFIX,
Meta,
PORT_NAME,
PromiseHandler,
TabId,
Target,
} from "@/background/devtools/contract";
import { reportError } from "@/telemetry/logging";
import { isBackgroundPage } from "webext-detect-page";
import { v4 as uuidv4 } from "uuid";
import { callBackground } from "@/background/devtools/external";
import { testTabPermissions, injectContentScript } from "@/background/util";
import * as nativeEditorProtocol from "@/nativeEditor";
import { reactivate } from "@/background/navigation";
const TOP_LEVEL_FRAME_ID = 0;
let numOpenConnections = 0;
type Nonce = string;
const backgroundHandlers = new Map<Nonce, HandlerEntry>();
const connections = new Map<TabId, Runtime.Port>();
const permissionsListeners = new Map<TabId, PromiseHandler[]>();
/**
* Listener that runs on the background page.
*/
function backgroundMessageListener(
request: RemoteProcedureCallRequest<Meta>,
port: Runtime.Port
) {
const { type, payload, meta } = request;
const { handler, options } = backgroundHandlers.get(type) ?? {};
if (!allowBackgroundSender(port.sender)) {
console.debug(
`Ignoring devtools message to background page from unknown sender`,
port.sender
);
return;
} else if (handler) {
const notification = isNotification(options);
console.debug(`Handling devtools request ${type} (nonce: ${meta?.nonce})`);
const handlerPromise = new Promise((resolve) => {
resolve(
handler(
{ tabId: meta.tabId, frameId: meta.frameId ?? 0 },
port
)(...payload)
);
});
let responded = false;
if (notification) {
handlerPromise.catch((error) => {
console.warn(
`An error occurred when handling notification ${type} (nonce: ${meta?.nonce}): ${error}`,
error
);
});
return;
}
handlerPromise.then(
(value) => {
if (!responded) {
port.postMessage({
type: `${type}_FULFILLED`,
meta: { nonce: meta?.nonce },
payload: value,
});
}
responded = true;
},
(error) => {
if (!responded) {
port.postMessage({
type: `${type}_REJECTED`,
meta: { nonce: meta?.nonce },
payload: toErrorResponse(type, error),
});
}
responded = true;
}
);
port.onDisconnect.addListener((port) => {
if (!responded) {
try {
port.postMessage({
type: `${type}_REJECTED`,
meta: { nonce: meta?.nonce },
payload: toErrorResponse(type, new Error("Port disconnected")),
});
} catch {
console.debug(
`Dropping message ${type}_REJECTED because port is disconnected`
);
}
}
responded = true;
});
} else {
console.warn(`No handler defined for message ${type}`, { request });
}
}
/**
* Lift a method to be run on the background page
* @param type a unique name for the background action
* @param method the method to lift
* @param options background action handler options
*/
export function liftBackground<R extends SerializableResponse>(
type: string,
method: (target: Target, port: Runtime.Port) => () => R | Promise<R>,
options?: HandlerOptions
): (port: Runtime.Port) => Promise<R>;
export function liftBackground<T, R extends SerializableResponse>(
type: string,
method: (target: Target, port: Runtime.Port) => (a0: T) => R | Promise<R>,
options?: HandlerOptions
): (port: Runtime.Port, a0: T) => Promise<R>;
export function liftBackground<R extends SerializableResponse>(
type: string,
method: (
target: Target,
port: Runtime.Port
) => (...args: unknown[]) => R | Promise<R>,
options?: HandlerOptions
): (port: Runtime.Port, ...args: unknown[]) => Promise<R> {
const fullType = `${MESSAGE_PREFIX}${type}`;
if (isBackgroundPage()) {
if (backgroundHandlers.has(fullType)) {
console.warn(`Handler already registered for ${fullType}`);
} else {
// console.debug(`Installed background page handler for ${type}`);
backgroundHandlers.set(fullType, { handler: method, options });
}
}
return async (port: Runtime.Port, ...args: unknown[]): Promise<R> => {
if (isBackgroundPage()) {
throw new Error(
"This method should not be called from the background page"
);
} else if (!port) {
throw new Error("Devtools port is required");
}
return callBackground(port, fullType, args, options) as Promise<R>;
};
}
async function resetTab(tabId: number): Promise<void> {
try {
await nativeEditorProtocol.clear(
{ tabId, frameId: TOP_LEVEL_FRAME_ID },
{}
);
} catch (error) {
console.warn(`Error clearing dynamic elements for tab: %d`, tabId, {
error,
});
reportError(error);
}
console.info(`Removed dynamic elements for tab: %d`, tabId);
// Re-activate the content script so any saved extensions are added to the page as "permanent" extensions
await reactivate();
console.info(`Re-activated extensions for tab: %d`, tabId);
}
function deleteStaleConnections(port: Runtime.Port) {
// Theoretically each port should only correspond to a single tab, but iterate over all tabIds just to be safe
for (const tabId of connections.keys()) {
if (connections.get(tabId) === port) {
connections.delete(tabId);
void resetTab(tabId);
if (permissionsListeners.has(tabId)) {
const listeners = permissionsListeners.get(tabId);
permissionsListeners.delete(tabId);
for (const [, reject] of listeners) {
reject(new Error(`Cleaning up stale connection`));
}
}
}
}
}
function connectDevtools(port: Runtime.Port): void {
if (!isBackgroundPage()) {
throw new Error(
"connectDevtools can only be called from the background page"
);
} else if (allowBackgroundSender(port.sender) && port.name === PORT_NAME) {
// sender.tab won't be available if we don't have permissions for it yet
console.debug(
`Adding devtools listeners for port ${port.name} for tab: ${
port.sender.tab?.id ?? "[[no permissions for tab]]"
}`
);
// add/cleanup listener
numOpenConnections++;
port.onMessage.addListener(backgroundMessageListener);
port.onDisconnect.addListener(() => {
port.onMessage.removeListener(backgroundMessageListener);
deleteStaleConnections(port);
numOpenConnections--;
console.debug(
`Devtools port disconnected for tab: ${port.sender?.tab}; # open ports: ${numOpenConnections})`
);
});
} else {
console.debug(
`Ignoring connection request from unknown sender/port ${port.sender.id}`
);
}
}
export function registerPort(tabId: TabId, port: Runtime.Port): void {
// can't register the port in connectDevtools because we might know the tab at that point
if (connections.has(tabId) && connections.get(tabId) !== port) {
console.warn(`Devtools connection already exists for tab: ${tabId}`);
}
connections.set(tabId, port);
}
/**
* Listener to inject contentScript on tabs that user has granted temporary access to and that the devtools
* are open. If the user has granted permanent access, the content script will be injected based on the
* dynamic content script permissions via `webext-dynamic-content-scripts`
*/
async function injectTemporaryAccess({
tabId,
frameId,
}: WebNavigation.OnDOMContentLoadedDetailsType): Promise<void> {
if (connections.has(tabId)) {
const hasPermissions = await testTabPermissions({ tabId, frameId });
if (hasPermissions) {
await injectContentScript({ tabId, frameId });
} else {
console.debug(
`Skipping injectDevtoolsContentScript because no activeTab permissions for tab: ${tabId}`
);
}
}
}
export function emitDevtools(
type: BackgroundEventType,
details: { tabId: TabId; frameId: number }
): void {
if (details.frameId === 0 && connections.has(details.tabId)) {
console.debug(`emitDevtools: ${type}`, details);
const port = connections.get(details.tabId);
port.postMessage({
type,
meta: { tabId: details.tabId, frameId: details.frameId, nonce: uuidv4() },
payload: details,
});
}
}
if (isBackgroundPage()) {
console.debug("Adding devtools connection listener");
browser.runtime.onConnect.addListener(connectDevtools);
browser.webNavigation.onHistoryStateUpdated.addListener((details) => {
emitDevtools("HistoryStateUpdate", details);
});
browser.webNavigation.onDOMContentLoaded.addListener((details) => {
void injectTemporaryAccess(details);
emitDevtools("DOMContentLoaded", details);
});
}