forked from duckduckgo/tracker-radar-collector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crawler.js
446 lines (395 loc) · 14.9 KB
/
crawler.js
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/* eslint-disable max-lines */
const puppeteer = require('puppeteer');
const chalk = require('chalk').default;
const {createTimer} = require('./helpers/timer');
const wait = require('./helpers/wait');
const tldts = require('tldts');
const {performance} = require('perf_hooks');
const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36';
const MOBILE_USER_AGENT = 'Mozilla/5.0 (Linux; Android 10; Pixel 2 XL) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Mobile Safari/537.36';
const DEFAULT_VIEWPORT = {
width: 1440,//px
height: 812//px
};
const MOBILE_VIEWPORT = {
width: 412,
height: 691,
deviceScaleFactor: 2,
isMobile: true,
hasTouch: true
};
// for debugging: force to launch in window mode instead of headless, open devtools and don't close windows after process finishes
const VISUAL_DEBUG = false;
/**
* @param {function(...any):void} log
* @param {string} proxyHost
* @param {string} executablePath path to chromium executable to use
* @param {boolean} headed
* @param {boolean} devtools
*/
function openBrowser(log, proxyHost, executablePath, headed = false, devtools = false) {
/**
* @type {import('puppeteer').BrowserLaunchArgumentOptions}
*/
const args = {
args: [
// enable FLoC
'--enable-blink-features=InterestCohortAPI',
'--enable-features="FederatedLearningOfCohorts:update_interval/10s/minimum_history_domain_size_required/1,FlocIdSortingLshBasedComputation,InterestCohortFeaturePolicy"'
]
};
args.headless = !headed;
args.devtools = devtools;
if (proxyHost) {
let url;
try {
url = new URL(proxyHost);
} catch(e) {
log('Invalid proxy URL');
throw e;
}
args.args.push(`--proxy-server=${proxyHost}`);
args.args.push(`--host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE ${url.hostname}"`);
}
if (executablePath) {
// @ts-ignore there is no single object that encapsulates properties of both BrowserLaunchArgumentOptions and LaunchOptions that are allowed here
args.executablePath = executablePath;
}
return puppeteer.launch(args);
}
/**
* @param {puppeteer.BrowserContext} context
* @param {URL} url
* @param {GetSiteDataOptions} data
*
* @returns {Promise<CollectResult>}
*/
async function getSiteData(context, url, {
collectors,
log,
urlFilter,
emulateUserAgent,
emulateMobile,
runInEveryFrame,
maxLoadTimeMs,
extraExecutionTimeMs,
collectorFlags,
keepOpen,
onStart,
onError,
onHttpError,
}) {
const testStarted = Date.now();
if (onStart) {
onStart(testStarted);
}
/**
* @type {{cdpClient: import('puppeteer').CDPSession, type: string, url: string}[]}
*/
const targets = [];
const collectorOptions = {
context,
url,
log,
collectorFlags
};
for (let collector of collectors) {
const timer = createTimer();
try {
// eslint-disable-next-line no-await-in-loop
await collector.init(collectorOptions);
log(`${collector.id()} init took ${timer.getElapsedTime()}s`);
} catch (e) {
if (onError) {
onError(e, 'init failed', collector);
} else {
log(chalk.yellow(`${collector.id()} init failed`), e);
}
}
}
let pageTargetCreated = false;
// initiate collectors for all contexts (main page, web worker, service worker etc.)
context.on('targetcreated', async target => {
// we have already initiated collectors for the main page, so we ignore the first page target
if (target.type() === 'page' && !pageTargetCreated) {
pageTargetCreated = true;
return;
}
const timer = createTimer();
let cdpClient = null;
try {
cdpClient = await target.createCDPSession();
} catch (e) {
if (onError) {
onError(e, `failed to connect to ${target.type()} "${target.url()}"`);
} else {
log(chalk.yellow(`Failed to connect to ${target.type()} "${target.url()}"`), e);
}
return;
}
const simpleTarget = {url: target.url(), type: target.type(), cdpClient};
targets.push(simpleTarget);
for (let collector of collectors) {
try {
// eslint-disable-next-line no-await-in-loop
await collector.addTarget(simpleTarget);
} catch (e) {
if (onError) {
onError(e, `failed to attach to ${target.type()} "${target.url()}"`, collector);
} else {
log(chalk.yellow(`${collector.id()} failed to attach to ${target.type()} "${target.url()}"`), e);
}
}
}
log(`${target.url()} (${target.type()}) context initiated in ${timer.getElapsedTime()}s`);
});
// Create a new page in a pristine context.
const page = await context.newPage();
// optional function that should be run on every page (and subframe) in the browser context
if (runInEveryFrame) {
await page.evaluateOnNewDocument(runInEveryFrame);
}
// We are creating CDP connection before page target is created, if we create it only after
// new target is created we will miss some requests, API calls, etc.
const cdpClient = await page.target().createCDPSession();
const initPageTimer = createTimer();
for (let collector of collectors) {
try {
// eslint-disable-next-line no-await-in-loop
await collector.addTarget({url: url.toString(), type: 'page', cdpClient});
} catch (e) {
if (onError) {
onError(e, `failed to attach to landing page "${url}"`, collector);
} else {
log(chalk.yellow(`${collector.id()} failed to attach to page "${url}"`), e);
}
}
}
log(`page context initiated in ${initPageTimer.getElapsedTime()}s`);
if (emulateUserAgent) {
await page.setUserAgent(emulateMobile ? MOBILE_USER_AGENT : DEFAULT_USER_AGENT);
}
await page.setViewport(emulateMobile ? MOBILE_VIEWPORT : DEFAULT_VIEWPORT);
// if any prompts open on page load, they'll make the page hang unless closed
page.on('dialog', dialog => dialog.dismiss());
// catch and report crash errors
page.on('error', e => {
if (onError) {
onError(e, `error in page ${page.url()}`);
} else {
log(chalk.red(`error in page ${page.url()}`, String(e)));
}
});
let timeout = false;
let httpStatusCode;
const loadStart = performance.now();
try {
const response = await page.goto(url.toString(), {timeout: maxLoadTimeMs, waitUntil: 'networkidle0'});
httpStatusCode = response.status();
if (!response.ok()) {
let doContinue;
if (onHttpError) {
doContinue = onHttpError(httpStatusCode);
} else {
doContinue = httpStatusCode !== 404 && httpStatusCode < 500;
if (doContinue) {
log(chalk.yellow(`HTTP error ${httpStatusCode} ${response.statusText()} while loading ${page.url()}`));
}
}
if (!doContinue) {
throw new Error(`HTTP error ${httpStatusCode} ${response.statusText()} while loading ${page.url()}`);
}
}
} catch (e) {
if (e instanceof puppeteer.errors.TimeoutError || (e.name && e.name === 'TimeoutError')) {
log(chalk.yellow('navigation timeout exceeded'));
for (let target of targets) {
if (target.type === 'page') {
// eslint-disable-next-line no-await-in-loop
await target.cdpClient.send('Page.stopLoading');
}
}
timeout = true;
} else {
throw e;
}
}
const pageLoadDurationMs = performance.now() - loadStart;
// give website a bit more time for things to settle
await page.waitForTimeout(extraExecutionTimeMs);
const finalUrl = page.url();
/**
* @type {Object<string, Object>}
*/
const data = {};
for (let collector of collectors) {
const getDataTimer = createTimer();
try {
// eslint-disable-next-line no-await-in-loop
const collectorData = await collector.getData({
finalUrl,
urlFilter: urlFilter && urlFilter.bind(null, finalUrl),
pageLoadDurationMs
});
data[collector.id()] = collectorData;
log(`getting ${collector.id()} data took ${getDataTimer.getElapsedTime()}s`);
} catch (e) {
if (onError) {
onError(e, 'getting data failed', collector);
} else {
log(chalk.yellow(`getting ${collector.id()} data failed`), e);
}
data[collector.id()] = null;
}
}
for (let target of targets) {
try {
// eslint-disable-next-line no-await-in-loop
await target.cdpClient.detach();
} catch (ignore) {
// we don't care that much because in most cases an error here means that target already detached
}
}
if (!keepOpen) {
await page.close();
}
return {
initialUrl: url.toString(),
finalUrl,
timeout,
httpStatusCode,
testStarted,
testFinished: Date.now(),
data,
};
}
/**
* @param {string} documentUrl
* @param {string} requestUrl
* @returns {boolean}
*/
function isThirdPartyRequest(documentUrl, requestUrl) {
const mainPageDomain = tldts.getDomain(documentUrl);
return tldts.getDomain(requestUrl) !== mainPageDomain;
}
/**
* @param {URL} url
* @param {CrawlOptions} options
* @returns {Promise<CollectResult>}
*/
async function crawl(url, options) {
const log = options.log || (() => {});
const browser = options.browserContext ? null : await openBrowser(
log, options.proxyHost, options.executablePath,
options.headed || VISUAL_DEBUG, options.devtools || VISUAL_DEBUG
);
// Create a new incognito browser context.
const context = options.browserContext || await browser.createIncognitoBrowserContext();
if (browser) {
// Close non-incognito window
context.once(
'targetcreated',
() => browser.defaultBrowserContext().pages().then(([p]) => p.close())
);
}
let data = null;
const maxLoadTimeMs = options.maxLoadTimeMs === undefined ? 30000 : options.maxLoadTimeMs;
const extraExecutionTimeMs = options.extraExecutionTimeMs === undefined ? 2500 : options.extraExecutionTimeMs;
const maxCollectionTimeMs = options.maxCollectionTimeMs === undefined ? 5000 : options.maxCollectionTimeMs;
const maxTotalTimeMs = maxCollectionTimeMs ? (maxLoadTimeMs * 2) + extraExecutionTimeMs + maxCollectionTimeMs : 0;
const keepOpen = options.keepOpen || VISUAL_DEBUG;
try {
data = await wait(getSiteData(context, url, {
collectors: options.collectors || [],
log,
urlFilter: options.filterOutFirstParty === true ? isThirdPartyRequest.bind(null) : null,
emulateUserAgent: options.emulateUserAgent !== false, // true by default
emulateMobile: options.emulateMobile,
runInEveryFrame: options.runInEveryFrame,
maxLoadTimeMs,
extraExecutionTimeMs,
collectorFlags: options.collectorFlags,
keepOpen,
onStart: options.onStart,
onError: options.onError,
onHttpError: options.onHttpError,
}), maxTotalTimeMs);
} catch(e) {
log(chalk.red('Crawl failed'), String(e));
throw e;
} finally {
// only close the browser if it was created here and keepOpen is false
if (browser && !keepOpen) {
await context.close();
await browser.close();
}
}
return data;
}
module.exports = crawl;
/**
* @typedef CrawlOptions
* @property {import('./collectors/BaseCollector')[]} [collectors]
* @property {function(...any):void} [log]
* @property {boolean=} filterOutFirstParty
* @property {boolean=} emulateMobile
* @property {boolean=} emulateUserAgent
* @property {string=} proxyHost
* @property {puppeteer.BrowserContext=} browserContext
* @property {function():void=} runInEveryFrame
* @property {string=} executablePath
* @property {number=} maxLoadTimeMs
* @property {number=} extraExecutionTimeMs
* @property {number=} maxCollectionTimeMs 0 to disable overall timeout
* @property {Object.<string, string>=} collectorFlags
* @property {boolean=} headed
* @property {boolean=} devtools
* @property {boolean=} keepOpen
* @property {OnStart=} onStart Called with crawl start time
* @property {OnError=} onError Called on non-fatal errors, disables logging of errors
* @property {OnHttpError=} onHttpError Called on page load errors, return `false` to abort crawl,
* disables logging of such errors, when unspecified crawl is stopped on only some errors
*/
/**
* @typedef GetSiteDataOptions
* @property {import('./collectors/BaseCollector')[]} collectors
* @property {function(...any):void} log
* @property {function(string, string):boolean} urlFilter
* @property {boolean} emulateMobile
* @property {boolean} emulateUserAgent
* @property {function():void} runInEveryFrame
* @property {number} maxLoadTimeMs
* @property {number} extraExecutionTimeMs
* @property {Object.<string, string>} collectorFlags
* @property {boolean} keepOpen
* @property {OnStart=} onStart
* @property {OnError=} onError
* @property {OnHttpError=} onHttpError
*/
/**
* @callback OnStart
* @param {number} testStarted Time when the crawl started
* @returns {void}
*/
/**
* @callback OnError
* @param {unknown} error Error that was thrown
* @param {string} context Additional info
* @param {import('./collectors/BaseCollector')=} collector Collector that threw the error
* @returns {void}
*/
/**
* @callback OnHttpError
* @param {number} statusCode
* @returns {boolean} Whether to continue, `false` to abort crawl
*/
/**
* @typedef {Object} CollectResult
* @property {string} initialUrl URL from which the crawler began the crawl (as provided by the caller)
* @property {string} finalUrl URL after page has loaded (can be different from initialUrl if e.g. there was a redirect)
* @property {boolean} timeout true if page didn't fully load before the timeout and loading had to be stopped by the crawler
* @property {number=} httpStatusCode may be unset on timeout
* @property {number} testStarted time when the crawl started (unix timestamp)
* @property {number} testFinished time when the crawl finished (unix timestamp)
* @property {import('./helpers/collectorsList').CollectorData} data object containing output from all collectors
*/