forked from ghostery/adblocker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adblocker.ts
393 lines (334 loc) · 11.8 KB
/
adblocker.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*!
* Copyright (c) 2017-present Cliqz GmbH. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
// Type definition
import * as puppeteer from 'puppeteer';
import { parse } from 'tldts-experimental';
import { FiltersEngine, Request, RequestType } from '@cliqz/adblocker';
import { autoRemoveScript, extractFeaturesFromDOM, DOMMonitor } from '@cliqz/adblocker-content';
function sleep(milliseconds: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
});
}
function getTopLevelUrl(frame: puppeteer.Frame | null): string {
let sourceUrl = '';
while (frame !== null) {
sourceUrl = frame.url();
if (sourceUrl.length !== 0) {
break;
}
frame = frame.parentFrame();
}
return sourceUrl;
}
/**
* Create an instance of `Request` from `puppeteer.Request`.
*/
export function fromPuppeteerDetails(details: puppeteer.HTTPRequest): Request {
const sourceUrl = getTopLevelUrl(details.frame());
const url = details.url();
const type: RequestType = details.resourceType();
return Request.fromRawDetails({
_originalRequestDetails: details,
requestId: `${type}-${url}-${sourceUrl}`,
sourceUrl,
type,
url,
});
}
/**
* Wrap `FiltersEngine` into a Puppeteer-friendly helper class.
*/
export class BlockingContext {
private readonly onFrameNavigated: (frame: puppeteer.Frame) => Promise<void>;
private readonly onRequest: (details: puppeteer.HTTPRequest) => void;
constructor(private readonly page: puppeteer.Page, private readonly blocker: PuppeteerBlocker) {
this.onFrameNavigated = (frame) => blocker.onFrameNavigated(frame);
this.onRequest = (request) => blocker.onRequest(request);
}
public async enable({ cacheSafe }: { cacheSafe: boolean }): Promise<void> {
if (this.blocker.config.loadCosmeticFilters === true) {
// Register callback to cosmetics injection (CSS + scriptlets)
this.page.on('frameattached', this.onFrameNavigated);
this.page.on('domcontentloaded', () => {
this.onFrameNavigated(this.page.mainFrame());
});
}
if (this.blocker.config.loadNetworkFilters === true) {
// Make sure request interception is enabled for `page` before proceeding
await this.page.setRequestInterception(true, cacheSafe);
// NOTES:
// - page.setBypassCSP(enabled) might be needed to perform
// injections on some pages.
// - we currently do not perform CSP headers injection as there is
// currently no way to modify responses in puppeteer. This feature could
// easily be added if puppeteer implements the required capability.
//
// Register callback for network requests filtering.
this.page.on('request', this.onRequest);
}
}
public async disable(): Promise<void> {
if (this.blocker.config.loadNetworkFilters === true) {
this.page.removeListener('request', this.onRequest);
await this.page.setRequestInterception(false);
}
if (this.blocker.config.loadCosmeticFilters === true) {
this.page.removeListener('frameattached', this.onFrameNavigated);
}
}
}
/**
* Wrap `FiltersEngine` into a Puppeteer-friendly helper class. It exposes
* methods to interface with Puppeteer APIs needed to block ads.
*/
export class PuppeteerBlocker extends FiltersEngine {
private readonly contexts: WeakMap<puppeteer.Page, BlockingContext> = new WeakMap();
// ----------------------------------------------------------------------- //
// Helpers to enable and disable blocking for 'browser'
// ----------------------------------------------------------------------- //
/**
* The `cacheSafe` can be set to `true` to enable the browser's resource cache. By default, caching is disabled, which is puppeteer's default behavior when request interception is enabled. Learn more here: https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#pagesetrequestinterceptionvalue-cachesafe
*/
public async enableBlockingInPage(page: puppeteer.Page, { cacheSafe = false }: { cacheSafe?: boolean } = {}): Promise<BlockingContext> {
let context: undefined | BlockingContext = this.contexts.get(page);
if (context !== undefined) {
return context;
}
context = new BlockingContext(page, this);
this.contexts.set(page, context);
await context.enable({ cacheSafe });
return context;
}
public async disableBlockingInPage(page: puppeteer.Page): Promise<void> {
const context: undefined | BlockingContext = this.contexts.get(page);
if (context === undefined) {
throw new Error('Trying to disable blocking which was not enabled');
}
this.contexts.delete(page);
await context.disable();
}
public isBlockingEnabled(page: puppeteer.Page): boolean {
return this.contexts.has(page);
}
// ----------------------------------------------------------------------- //
// PuppeteerBlocker-specific additions to FiltersEngine
// ----------------------------------------------------------------------- //
public onFrameNavigated = async (frame: puppeteer.Frame) => {
try {
await this.onFrame(frame);
} catch (ex) {
// Ignore
}
};
private onFrame = async (frame: puppeteer.Frame): Promise<void> => {
const url = frame.url();
if (url === 'chrome-error://chromewebdata/') {
return;
}
// Look for all iframes in this context and check if they should be removed
// from the DOM completely. For this we check if their `src` or `href`
// attribute would be blocked by any network filter.
this.removeBlockedFrames(frame).catch(() => {
/* ignore */
});
const parsed = parse(url);
const hostname = parsed.hostname || '';
const domain = parsed.domain || '';
// We first query for stylesheets and scriptlets which are either generic or
// based on the hostname of this frame. We need to get these as fast as
// possible to reduce blinking when page loads.
{
// TODO - implement extended filters for Puppeteer
const { active, styles, scripts /* , extended */ } = this.getCosmeticsFilters({
domain,
hostname,
url,
// Done once per frame.
getBaseRules: true,
getInjectionRules: true,
getExtendedRules: true,
getRulesFromHostname: true,
// Will handle DOM features (see below).
getRulesFromDOM: false,
});
if (active === false) {
return;
}
Promise.all([
this.injectScriptletsIntoFrame(frame, scripts),
this.injectStylesIntoFrame(frame, styles),
]).catch(() => {
/* ignore */
});
}
// Seconde step is to start monitoring the DOM of the page in order to
// inject more specific selectors based on `id`, `class`, or `href` found on
// nodes. We first query all of them, then monitor the DOM for a few
// seconds (or until one of the stopping conditions is met, see below).
const observer = new DOMMonitor((update) => {
if (update.type === 'features') {
const { active, styles } = this.getCosmeticsFilters({
domain,
hostname,
url,
// DOM information
...update,
// Only done once per frame (see above).
getBaseRules: false,
getInjectionRules: false,
getExtendedRules: false,
getRulesFromHostname: false,
// Allows to get styles for updated DOM.
getRulesFromDOM: true,
});
// Abort if cosmetics are disabled
if (active === false) {
return;
}
this.injectStylesIntoFrame(frame, styles).catch(() => {
/* ignore */
});
}
});
// This loop will periodically check if any new custom styles should be
// injected in the page (using values of attributes `id`, `class`, or `href`).
//
// We stop looking in the following cases:
// * Frame was detached.
// * No new attribute was found.
// * Number of iterations exceeded 10 (i.e. 5 seconds).
// * Exception was raised.
//
// Additionally, we might stop after the first lookup if
// `enableMutationObserver` is disabled in config, which means that we
// should not actively monitor the DOM for changes.
let numberOfIterations = 0;
do {
if (frame.isDetached()) {
break;
}
try {
const foundNewFeatures = observer.handleNewFeatures(
await frame.$$eval(':root', extractFeaturesFromDOM),
);
numberOfIterations += 1;
if (numberOfIterations === 10) {
break;
}
if (foundNewFeatures === false) {
break;
}
} catch (ex) {
break;
}
if (this.config.enableMutationObserver === false) {
break;
}
await sleep(500);
} while (true);
};
public onRequest = (details: puppeteer.HTTPRequest): void => {
const request = fromPuppeteerDetails(details);
if (this.config.guessRequestTypeFromUrl === true && request.type === 'other') {
request.guessTypeOfRequest();
}
const frame = details.frame();
if (
request.isMainFrame() ||
(request.type === 'document' && frame !== null && frame.parentFrame() === null)
) {
details.continue();
return;
}
const { redirect, match } = this.match(request);
if (redirect !== undefined) {
if (redirect.contentType.endsWith(';base64')) {
details.respond({
status: 200,
headers: {},
body: Buffer.from(redirect.body, 'base64'),
contentType: redirect.contentType.slice(0, -7),
});
} else {
details.respond({
status: 200,
headers: {},
body: redirect.body,
contentType: redirect.contentType,
});
}
} else if (match === true) {
details.abort('blockedbyclient');
} else {
details.continue();
}
};
private async injectStylesIntoFrame(frame: puppeteer.Frame, styles: string): Promise<void> {
if (styles.length !== 0) {
await frame.addStyleTag({
content: styles,
});
}
}
private async injectScriptletsIntoFrame(
frame: puppeteer.Frame,
scripts: string[],
): Promise<void> {
const promises: Promise<void>[] = [];
if (scripts.length !== 0) {
for (let i = 0; i < scripts.length; i += 1) {
promises.push(
frame
.addScriptTag({
content: autoRemoveScript(scripts[i]),
})
.then(() => {
/* Ignore result */
}),
);
}
}
await Promise.all(promises);
}
/**
* Look for sub-frames in `frame`, check if their `src` or `href` would be
* blocked, and then proceed to removing them from the DOM completely.
*/
private async removeBlockedFrames(frame: puppeteer.Frame): Promise<void> {
const promises: Promise<void>[] = [];
const sourceUrl = getTopLevelUrl(frame);
for (const url of await frame.$$eval('iframe[src],iframe[href]', (elements) =>
elements.map(({ src, href }: any) => src || href),
)) {
const { match } = this.match(
Request.fromRawDetails({
url,
sourceUrl,
type: 'sub_frame',
}),
);
if (match) {
promises.push(
frame
.$$eval(`iframe[src="${url}"],iframe[href="${url}"]`, (iframes) => {
for (const iframe of iframes) {
iframe?.parentNode?.removeChild(iframe);
}
})
.catch(() => {
/* ignore */
}),
);
}
}
await Promise.all(promises);
}
}
// Re-export symboles from @cliqz/adblocker for convenience
export * from '@cliqz/adblocker';