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
|
/*
* NoScript Commons Library
* Reusable building blocks for cross-browser security/privacy WebExtensions.
* Copyright (C) 2020-2024 Giorgio Maone <https://maone.net>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*
* 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/>.
*/
// depends on /nscl/common/sha256.js
// depends on /nscl/common/uuid.js
"use strict";
var DocStartInjection = (() => {
const MSG_ID = "__DocStartInjection__";
const repeating = !("contentScripts" in browser);
const mv3Callbacks = repeating && !browser.tabs.executeScript; // mv3 on Chrome
let scriptBuilders = new Set();
let getId = ({requestId, tabId, frameId, url}) => requestId || `${tabId}:${frameId}:${url}`;
let pending = new Map();
function onMessage(msg, sender) {
let payload = msg[MSG_ID];
if (!payload) return;
let {id, tabId, frameId, url} = payload;
let ret = false;
if (tabId === sender.tab.id && frameId === sender.frameId && url === sender.url) {
end(payload, true);
ret = true;
}
return Promise.resolve(ret);
}
async function begin(request) {
let scripts = new Set();
let {tabId, frameId, url} = request;
if (tabId < 0 || !/^(?:(?:https?|ftp|data|blob|file):|about:blank$)/.test(url)) return;
await Promise.allSettled([...scriptBuilders].map(async buildScript => {
let script;
try {
script = await buildScript({tabId, frameId, url});
if (!script) return;
if (mv3Callbacks) {
if (typeof script !== "object") {
throw new Error('On MV3 only {data: jsonObject, callback: "globalFunctionName", assign: "globalScopeVarName"} injection can work!')
}
const {data, callback, assign} = script;
scripts.add({
data,
callback,
assign,
});
return;
}
// mv2
scripts.add(`try {
${typeof script === "function" ? `(${script})();` : script}
} catch (e) {
console.error("Error in DocStartInjection script", e);
}`
);
} catch (e) {
error(`Error calling DocStartInjection scriptBuilder: buildScript ${buildScript} - script: ${script}`, e);
}
}));
if (scripts.size === 0) {
debug(`DocStartInjection: no script to inject in ${url}`);
return;
}
let id = getId(request);
if (repeating) {
let injectionId = `injection:${uuid()}:${await sha256(Math.random().toString(16))}`;
let args = mv3Callbacks ?
// mv3 browser.scripting.executeScript()
{
func: (url, injectionId, scripts) => {
if (document.readyState === "complete" ||
window[injectionId] ||
document.URL !== url
) return window[injectionId];
window[injectionId] = true;
for (s of scripts) {
const {callback, assign, data} = s;
try {
if (assign && !(assign in globalThis)) {
globalThis[assign] = data;
}
if (callback) {
let cb = globalThis[callback];
if (typeof cb == "function") {
cb.call(globalThis, data);
} else {
console.warn(`callback globalThis.${callback} is not a function (${cb}).`);
}
}
} catch (e) {
console.error(`Error in DocStartInjection script ${JSON.stringify(s)}`, e);
}
}
return document.readyState === "loading";
},
args: [url, injectionId, [...scripts]],
target: {tabId, frameIds: [frameId]},
injectImmediately: true,
} :
// mv2 browser.tabs.executeScript()
{
code: `(() => {
let injectionId = ${JSON.stringify(injectionId)};
if (document.readyState === "complete" ||
window[injectionId] ||
document.URL !== ${JSON.stringify(url)}
) return window[injectionId];
window[injectionId] = true;
${[...scripts].join("\n")}
return document.readyState === "loading";
})();`,
runAt: "document_start",
frameId,
};
pending.set(id, args);
await run(request, true);
} else {
let matches = [url];
try {
let urlObj = new URL(url);
if (urlObj.port) {
urlObj.port = "";
matches[0] = urlObj.toString();
}
} catch (e) {}
let ackMsg = JSON.stringify({
[MSG_ID]: {id, tabId, frameId, url}
});
scripts.add(`if (document.readyState !== "complete") browser.runtime.sendMessage(${ackMsg});`);
let options = {
js: [...scripts].map(code => ({code})),
runAt: "document_start",
matchAboutBlank: true,
matches,
allFrames: true,
};
let current = pending.get(id);
if (current) {
current.unregister();
}
pending.set(id, await browser.contentScripts.register(options));
}
}
async function run(request, repeat = false) {
const id = getId(request);
const args = pending.get(id);
if (!args) return;
let {url, tabId} = request;
let attempts = 0;
let success = false;
const execute = mv3Callbacks ?
async () => {
const ret = await browser.scripting.executeScript(args);
return ret[0].result;
}
: async() => {
const ret = await browser.tabs.executeScript(tabId, args);
return ret[0];
};
for (; pending.has(id);) {
attempts++;
try {
if (attempts % 1000 === 0) {
let tab = await browser.tabs.get(request.tabId);
if (tab.url !== url) {
console.error(`Tab mismatch: ${tab.url} <> ${url} (download-triggered?)`);
break;
}
console.error(`DocStartInjection at ${url} ${attempts} failed attempts so far...`);
}
if (execute()) {
success = true;
break;
}
} catch (e) {
if (/No tab\b/.test(e.message)) {
break;
}
if (!/\baccess\b/.test(e.message)) {
console.error(e.message);
}
if (!browser.tabs.executeScript) {
console.error(`MV3 fatality, cannot script tab ${tabId}! ${JSON.stringify(args)}`);
break;
}
if (attempts % 1000 === 0) {
console.error(`DocStartInjection at ${url} ${attempts} failed attempts`, e);
}
} finally {
if (!repeat) break;
}
}
pending.delete(id);
debug(`DocStartInjection at ${url}, ${attempts} attempts, success = ${success}, repeat = ${repeat}.`);
}
function end(request, immediate = false) {
let id = getId(request);
let script = pending.get(id);
if (script) {
if (repeating) {
run(request, false);
} else {
pending.delete(id);
if (immediate) {
script.unregister();
} else {
setTimeout(() => script.unregister(), 500);
}
}
}
}
let listeners = {
onBeforeNavigate: begin,
onErrorOccurred: end,
onCompleted: end,
}
function listen(enabled) {
let {webNavigation, webRequest} = browser;
let method = `${enabled ? "add" : "remove"}Listener`;
let reqFilter = {urls: ["<all_urls>"], types: ["main_frame", "sub_frame", "object"]};
function setup(api, eventName, listener, ...args) {
let event = api[eventName];
if (event) {
event[method].apply(event, enabled ? [listener, ...args] : [listener]);
}
}
if (repeating) {
// Just Chromium
setup(webRequest, "onResponseStarted", begin, reqFilter);
} else {
// add or remove Firefox's webNavigation listeners for non-http loads
// and asynchronous blocking onHeadersReceived for registration on http
let navFilter = enabled && {url: [{schemes: ["file", "ftp"]}]};
for (let [eventName, listener] of Object.entries(listeners)) {
setup(webNavigation, eventName, listener, navFilter)
}
setup(webRequest, "onHeadersReceived", begin, reqFilter, ["blocking"]);
browser.runtime.onMessage[method](onMessage);
}
// add or remove common webRequest listener
for (let [eventName, listener] of Object.entries(listeners)) {
setup(webRequest, eventName, listener, reqFilter);
}
}
return {
mv3Callbacks,
register(scriptBuilder) {
if (scriptBuilders.size === 0) listen(true);
scriptBuilders.add(scriptBuilder);
},
unregister(scriptBuilder) {
scriptBuilders.delete(scriptBuilder);
if (scriptBuilders.size === 0) listen(false);
}
};
})();
|