-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
321 lines (275 loc) · 7.96 KB
/
index.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
315
316
317
318
319
320
321
import chromeP from 'webext-polyfill-kinda';
import {patternToRegex} from 'webext-patterns';
import type {ContentScript, ExtensionFileOrCode, RunAt} from './types.js';
const gotScripting = Boolean(globalThis.chrome?.scripting);
interface AllFramesTarget {
tabId: number;
frameId: number | undefined;
allFrames: boolean;
}
interface Target {
tabId: number;
frameId: number;
}
interface InjectionOptions {
ignoreTargetErrors?: boolean;
}
function castTarget(target: number | Target): Target {
return typeof target === 'object' ? target : {
tabId: target,
frameId: 0,
};
}
function castAllFramesTarget(target: number | Target): AllFramesTarget {
if (typeof target === 'object') {
return {...target, allFrames: false};
}
return {
tabId: target,
frameId: undefined,
allFrames: true,
};
}
function castArray<A = unknown>(possibleArray: A | A[]): A[] {
if (Array.isArray(possibleArray)) {
return possibleArray;
}
return [possibleArray];
}
type MaybeArray<X> = X | X[];
const nativeFunction = /^function \w+\(\) {[\n\s]+\[native code][\n\s]+}/;
export async function executeFunction<Fn extends (...args: any[]) => unknown>(
target: number | Target,
function_: Fn,
...args: unknown[]
): Promise<ReturnType<Fn>> {
if (nativeFunction.test(String(function_))) {
throw new TypeError('Native functions need to be wrapped first, like `executeFunction(1, () => alert(1))`');
}
const {frameId, tabId} = castTarget(target);
if (gotScripting) {
const [injection] = await chrome.scripting.executeScript({
target: {
tabId,
frameIds: [frameId],
},
func: function_,
args,
});
return injection?.result as ReturnType<Fn>;
}
const [result] = await chromeP.tabs.executeScript(tabId, {
code: `(${function_.toString()})(...${JSON.stringify(args)})`,
matchAboutBlank: true, // Needed for `srcdoc` frames; doesn't hurt normal pages
frameId,
}) as [ReturnType<Fn>];
return result;
}
function arrayOrUndefined<X>(value?: X): [X] | undefined {
return value === undefined ? undefined : [value];
}
interface InjectionDetails {
tabId: number;
frameId?: number;
matchAboutBlank?: boolean;
allFrames?: boolean;
runAt?: RunAt;
files: string [] | ExtensionFileOrCode[];
}
// eslint-disable-next-line @typescript-eslint/naming-convention -- It follows the native naming
export async function insertCSS(
{
tabId,
frameId,
files,
allFrames,
matchAboutBlank,
runAt,
}: InjectionDetails,
{ignoreTargetErrors}: InjectionOptions = {},
): Promise<void> {
const everyInsertion = Promise.all(files.map(async content => {
if (typeof content === 'string') {
content = {file: content};
}
if (gotScripting) {
return chrome.scripting.insertCSS({
target: {
tabId,
frameIds: arrayOrUndefined(frameId),
allFrames: frameId === undefined ? allFrames : undefined,
},
files: 'file' in content ? [content.file] : undefined,
css: 'code' in content ? content.code : undefined,
});
}
return chromeP.tabs.insertCSS(tabId, {
...content,
matchAboutBlank,
allFrames,
frameId,
runAt: runAt ?? 'document_start', // CSS should prefer `document_start` when unspecified
});
}));
if (ignoreTargetErrors) {
await catchTargetInjectionErrors(everyInsertion);
} else {
await everyInsertion;
}
}
function assertNoCode(files: Array<{
code: string;
} | {
file: string;
}>): asserts files is Array<{file: string}> {
if (files.some(content => 'code' in content)) {
throw new Error('chrome.scripting does not support injecting strings of `code`');
}
}
export async function executeScript(
{
tabId,
frameId,
files,
allFrames,
matchAboutBlank,
runAt,
}: InjectionDetails,
{ignoreTargetErrors}: InjectionOptions = {},
): Promise<void> {
const normalizedFiles = files.map(file => typeof file === 'string' ? {file} : file);
if (gotScripting) {
assertNoCode(normalizedFiles);
const injection = chrome.scripting.executeScript({
target: {
tabId,
frameIds: arrayOrUndefined(frameId),
allFrames: frameId === undefined ? allFrames : undefined,
},
files: normalizedFiles.map(({file}) => file),
});
if (ignoreTargetErrors) {
await catchTargetInjectionErrors(injection);
} else {
await injection;
}
// Don't return `injection`; the "return value" of a file is generally not useful
return;
}
// Don't use .map(), `code` injections can't be "parallel"
const executions: Array<Promise<unknown>> = [];
for (const content of normalizedFiles) {
// Files are executed in order, but `code` isn’t, so it must await the last script before injecting more
if ('code' in content) {
// eslint-disable-next-line no-await-in-loop -- On purpose, see above
await executions.at(-1);
}
executions.push(chromeP.tabs.executeScript(tabId, {
...content,
matchAboutBlank,
allFrames,
frameId,
runAt,
}));
}
if (ignoreTargetErrors) {
await catchTargetInjectionErrors(Promise.all(executions));
} else {
await Promise.all(executions);
}
}
export async function getTabsByUrl(matches: string[], excludeMatches?: string[]): Promise<number[]> {
if (matches.length === 0) {
return [];
}
const exclude = excludeMatches ? patternToRegex(...excludeMatches) : undefined;
const tabs = await chromeP.tabs.query({url: matches});
return tabs
.filter(tab => tab.id && tab.url && (exclude ? !exclude.test(tab.url) : true))
.map(tab => tab.id!);
}
export async function injectContentScript(
where: MaybeArray<number | Target>,
scripts: MaybeArray<ContentScript>,
options: InjectionOptions = {},
): Promise<void> {
const targets = castArray(where);
await Promise.all(
targets.map(
async target => injectContentScriptInSpecificTarget(castAllFramesTarget(target), scripts, options),
),
);
}
async function injectContentScriptInSpecificTarget(
{frameId, tabId, allFrames}: AllFramesTarget,
scripts: MaybeArray<ContentScript>,
options: InjectionOptions = {},
): Promise<void> {
const injections = castArray(scripts).flatMap(script => [
insertCSS({
tabId,
frameId,
allFrames,
files: script.css ?? [],
matchAboutBlank: script.matchAboutBlank ?? script.match_about_blank,
runAt: script.runAt ?? script.run_at as RunAt,
}, options),
executeScript({
tabId,
frameId,
allFrames,
files: script.js ?? [],
matchAboutBlank: script.matchAboutBlank ?? script.match_about_blank,
runAt: script.runAt ?? script.run_at as RunAt,
}, options),
]);
await Promise.all(injections);
}
// Sourced from:
// https://source.chromium.org/chromium/chromium/src/+/main:extensions/common/extension_urls.cc;drc=6b42116fe3b3d93a77750bdcc07948e98a728405;l=29
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts
const blockedPrefixes = [
'chrome.google.com/webstore', // Host *and* pathname
'chromewebstore.google.com',
'accounts-static.cdn.mozilla.net',
'accounts.firefox.com',
'addons.cdn.mozilla.net',
'addons.mozilla.org',
'api.accounts.firefox.com',
'content.cdn.mozilla.net',
'discovery.addons.mozilla.org',
'input.mozilla.org',
'install.mozilla.org',
'oauth.accounts.firefox.com',
'profile.accounts.firefox.com',
'support.mozilla.org',
'sync.services.mozilla.com',
'testpilot.firefox.com',
];
export function isScriptableUrl(url: string | undefined): boolean {
if (!url?.startsWith('http')) {
return false;
}
const cleanUrl = url.replace(/^https?:\/\//, '');
return blockedPrefixes.every(blocked => !cleanUrl.startsWith(blocked));
}
const targetErrors = /^No frame with id \d+ in tab \d+.$|^No tab with id: \d+.$|^The tab was closed.$|^The frame was removed.$/;
async function catchTargetInjectionErrors(promise: Promise<unknown>): Promise<void> {
try {
await promise;
} catch (error) {
// @ts-expect-error Optional chaining is good enough
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
if (!targetErrors.test(error?.message)) {
throw error;
}
}
}
export async function canAccessTab(
target: number | Target,
): Promise<boolean> {
return executeFunction(castTarget(target), () => true).then(
() => true,
() => false,
);
}