@whotracksme/reporting 11.1.1 → 12.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/package.json +1 -1
- package/reporting/README.md +13 -0
- package/reporting/example/README.md +4 -0
- package/reporting/example/e2e/README.md +263 -0
- package/reporting/example/e2e/console-capture.js +67 -0
- package/reporting/example/e2e/control.js +423 -0
- package/reporting/example/e2e/hub.mjs +380 -0
- package/reporting/example/e2e/launch.mjs +92 -0
- package/reporting/example/e2e/mock-extension.mjs +106 -0
- package/reporting/example/e2e/pages/private-fixture.html +16 -0
- package/reporting/example/e2e/run.mjs +187 -0
- package/reporting/example/e2e/scenarios/privacy-guards.json +26 -0
- package/reporting/example/e2e/scenarios/smoke.json +15 -0
- package/reporting/example/e2e/verify.mjs +159 -0
- package/reporting/example/index.js +55 -46
- package/reporting/example/manifests/chromium.json +1 -0
- package/reporting/example/storage.js +65 -0
- package/reporting/package.json +5 -1
- package/reporting/rollup.config.cjs +1 -1
- package/reporting/src/doublefetch-page-handler.js +24 -0
- package/reporting/src/doublefetch-unbreak.js +186 -0
- package/reporting/src/http.js +197 -19
- package/reporting/src/offscreen/doublefetch/capture.js +90 -0
- package/reporting/src/patterns.js +5 -2
- package/reporting/src/search-extractor.js +2 -0
- package/reporting/test/doublefetch-unbreak.spec.js +133 -0
- package/reporting/test/http.spec.js +113 -0
- package/reporting/test/index.js +1 -0
- package/reporting/test/patterns.spec.js +10 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WhoTracks.Me
|
|
3
|
+
* https://whotracks.me/
|
|
4
|
+
*
|
|
5
|
+
* Copyright 2017-present Ghostery GmbH. All rights reserved.
|
|
6
|
+
*
|
|
7
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
8
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
9
|
+
* file, You can obtain one at http://mozilla.org/MPL/2.0
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import logger from './logger';
|
|
13
|
+
import { findPlaceholders } from './http';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The goal of double-fetch is to reject content that only a logged-in user
|
|
17
|
+
* could see, because such content may leak private information; that is why it
|
|
18
|
+
* loads a page as anonymously as possible: no credentials, no cookies. In
|
|
19
|
+
* practice that is too limiting: a site behind AWS WAF, for instance, may be
|
|
20
|
+
* configured to require its token.
|
|
21
|
+
*
|
|
22
|
+
* Since it is infeasible to detect login-related cookies, we use an allowlist
|
|
23
|
+
* approach. The only rule is that an entry must not unlock non-public content,
|
|
24
|
+
* which rules out anything session-like (e.g. "oauth_token", "api_token").
|
|
25
|
+
*
|
|
26
|
+
* Note: being on this list is necessary but not sufficient. A cookie is read
|
|
27
|
+
* only if a double-fetch configuration names it, and only if it is scoped to
|
|
28
|
+
* the site being fetched - exactly as the browser would scope it.
|
|
29
|
+
*/
|
|
30
|
+
const TRUSTED_COOKIES = new Set([
|
|
31
|
+
'_abck',
|
|
32
|
+
'acw_tc',
|
|
33
|
+
'addtl_consent',
|
|
34
|
+
'AEC',
|
|
35
|
+
'ak_bmsc',
|
|
36
|
+
'aws-waf-token',
|
|
37
|
+
'AWSALB',
|
|
38
|
+
'AWSALBCORS',
|
|
39
|
+
'axeptio_authorized_vendors',
|
|
40
|
+
'axeptio_cookies',
|
|
41
|
+
'bm_sv',
|
|
42
|
+
'bm_sz',
|
|
43
|
+
'borlabs-cookie',
|
|
44
|
+
'__cf_bm',
|
|
45
|
+
'cf_clearance',
|
|
46
|
+
'__cfduid',
|
|
47
|
+
'__cflb',
|
|
48
|
+
'_cfuvid',
|
|
49
|
+
'cky-consent',
|
|
50
|
+
'__cmpcc',
|
|
51
|
+
'__cmpconsent',
|
|
52
|
+
'cmphitorder',
|
|
53
|
+
'__cmpiab',
|
|
54
|
+
'cmplz_banner-status',
|
|
55
|
+
'cmplz_consented_services',
|
|
56
|
+
'cmpsessid',
|
|
57
|
+
'CONSENT',
|
|
58
|
+
'consent-policy',
|
|
59
|
+
'consentUUID',
|
|
60
|
+
'CookieConsentBulkTicket',
|
|
61
|
+
'cookie_consent',
|
|
62
|
+
'CookieConsent',
|
|
63
|
+
'CookieConsentPolicy',
|
|
64
|
+
'cookieconsent_seen',
|
|
65
|
+
'cookieconsent_status',
|
|
66
|
+
'cookiefirst-consent',
|
|
67
|
+
'cookielawinfo-checkbox-necessary',
|
|
68
|
+
'CookieLawInfoConsent',
|
|
69
|
+
'cookieyes-consent',
|
|
70
|
+
'datadome',
|
|
71
|
+
'didomi_token',
|
|
72
|
+
'disable-cmp',
|
|
73
|
+
'euconsent',
|
|
74
|
+
'euconsent-v2',
|
|
75
|
+
'f5_cspm',
|
|
76
|
+
'FCCDCF',
|
|
77
|
+
'FCNEC',
|
|
78
|
+
'GOOGLE_ABUSE_EXEMPTION',
|
|
79
|
+
'gdpr_popup',
|
|
80
|
+
'gpp',
|
|
81
|
+
'gpp_sid',
|
|
82
|
+
'gpp-string',
|
|
83
|
+
'https_waf_cookie',
|
|
84
|
+
'KP_UIDz',
|
|
85
|
+
'NID',
|
|
86
|
+
'OptanonAlertBoxClosed',
|
|
87
|
+
'OptanonConsent',
|
|
88
|
+
'OptanonControl',
|
|
89
|
+
'osano_consentmanager',
|
|
90
|
+
'pow_challenge',
|
|
91
|
+
'pow_nonce',
|
|
92
|
+
'_px3',
|
|
93
|
+
'pxcts',
|
|
94
|
+
'_pxhd',
|
|
95
|
+
'_pxvid',
|
|
96
|
+
'rbzid',
|
|
97
|
+
'reese84',
|
|
98
|
+
'ROUTEID',
|
|
99
|
+
'__Secure-ENID',
|
|
100
|
+
'SOCS',
|
|
101
|
+
'sp_consent',
|
|
102
|
+
'_sp_enable_dfp_personalized_ads',
|
|
103
|
+
'_sp_v1_consent',
|
|
104
|
+
'__tlbcpv',
|
|
105
|
+
'usercentrics',
|
|
106
|
+
'usprivacy',
|
|
107
|
+
'viewed_cookie_policy',
|
|
108
|
+
'waf_captcha_marker',
|
|
109
|
+
'x-amz-continuous-deployment-state',
|
|
110
|
+
]);
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Finds the cookies that the given double-fetch configuration is allowed to
|
|
114
|
+
* borrow from the user: on the trusted list, asked for by the configuration,
|
|
115
|
+
* and scoped to the URL that is about to be fetched.
|
|
116
|
+
*
|
|
117
|
+
* The lookup passes no "storeId", so it sees only the cookie store of the
|
|
118
|
+
* extension's own background context, which is the user's normal profile.
|
|
119
|
+
* Private windows and Firefox containers are separate stores, so their cookies
|
|
120
|
+
* are never even visible here - they are excluded by not asking for them,
|
|
121
|
+
* rather than by filtering them out afterwards.
|
|
122
|
+
*/
|
|
123
|
+
export async function findSafeCookies(url, params) {
|
|
124
|
+
const requested = requestedCookies(params);
|
|
125
|
+
if (requested.size === 0) {
|
|
126
|
+
return new Map();
|
|
127
|
+
}
|
|
128
|
+
if (!chrome?.cookies?.getAll) {
|
|
129
|
+
logger.debug('cookie API unavailable: no safe cookie');
|
|
130
|
+
return new Map();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const found = new Map();
|
|
134
|
+
await Promise.all(
|
|
135
|
+
[...requested].map(async (name) => {
|
|
136
|
+
try {
|
|
137
|
+
// The first match is the most specific one, i.e. the one that the
|
|
138
|
+
// browser itself would send first.
|
|
139
|
+
const cookies = await chrome.cookies.getAll({ url, name });
|
|
140
|
+
const value = cookies?.[0]?.value;
|
|
141
|
+
if (value) {
|
|
142
|
+
found.set(name, value);
|
|
143
|
+
}
|
|
144
|
+
} catch (e) {
|
|
145
|
+
logger.warn('Unable to look up cookie:', name, e);
|
|
146
|
+
}
|
|
147
|
+
}),
|
|
148
|
+
);
|
|
149
|
+
return found;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Collects the names of all trusted cookies that the given configuration
|
|
154
|
+
* references. Placeholders can occur in headers and in "requires" entries,
|
|
155
|
+
* both in the shared configuration and in each step; the "onError"
|
|
156
|
+
* configuration is scanned recursively.
|
|
157
|
+
*/
|
|
158
|
+
function requestedCookies(params, requested = new Set()) {
|
|
159
|
+
for (const { headers = {}, requires = [] } of [
|
|
160
|
+
params || {},
|
|
161
|
+
...(params?.steps || []),
|
|
162
|
+
]) {
|
|
163
|
+
for (const template of [...Object.values(headers), ...requires]) {
|
|
164
|
+
collectSafeCookies(template, requested);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (params?.onError) {
|
|
168
|
+
requestedCookies(params.onError, requested);
|
|
169
|
+
}
|
|
170
|
+
return requested;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function collectSafeCookies(template, requested) {
|
|
174
|
+
for (const expression of findPlaceholders(template)) {
|
|
175
|
+
for (const placeholder of expression.split('||')) {
|
|
176
|
+
if (placeholder.startsWith('safecookie:')) {
|
|
177
|
+
const name = placeholder.slice('safecookie:'.length);
|
|
178
|
+
if (TRUSTED_COOKIES.has(name)) {
|
|
179
|
+
requested.add(name);
|
|
180
|
+
} else {
|
|
181
|
+
logger.warn('Ignoring', placeholder, '(not a trusted cookie)');
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
package/reporting/src/http.js
CHANGED
|
@@ -316,8 +316,96 @@ async function tryCloseOffscreenDocument() {
|
|
|
316
316
|
|
|
317
317
|
const OFFSCREEN_DOCUMENT_PREFIX = 'offscreen/doublefetch';
|
|
318
318
|
const OFFSCREEN_DOCUMENT_INDEX_HTML = `${OFFSCREEN_DOCUMENT_PREFIX}/index.html`;
|
|
319
|
+
const OFFSCREEN_DOCUMENT_CAPTURE_JS = `${OFFSCREEN_DOCUMENT_PREFIX}/capture.js`;
|
|
320
|
+
const CAPTURE_CONTENT_SCRIPT_ID = 'wtm-doublefetch-capture';
|
|
321
|
+
const CAPTURE_MESSAGE_TARGET = 'doublefetch:capture';
|
|
319
322
|
|
|
320
|
-
|
|
323
|
+
/**
|
|
324
|
+
* The page cannot be read from here (cross-origin), so a content script in the
|
|
325
|
+
* iframe sends the DOM back once the page looks ready. Content scripts cannot
|
|
326
|
+
* be aimed at a single frame of an offscreen document, so this one is
|
|
327
|
+
* registered for the whole domain; pages that the user opens meanwhile are
|
|
328
|
+
* covered by the guard in capture.js and by ignoring messages from a tab.
|
|
329
|
+
*/
|
|
330
|
+
async function installCaptureHandler(url, { waitFor = [], delay = 0 }) {
|
|
331
|
+
const { protocol, hostname } = new URL(url);
|
|
332
|
+
let resolveHtml;
|
|
333
|
+
let rejectHtml;
|
|
334
|
+
const pendingHtml = new Promise((resolve, reject) => {
|
|
335
|
+
resolveHtml = resolve;
|
|
336
|
+
rejectHtml = reject;
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
const onMessage = (message, sender, sendResponse) => {
|
|
340
|
+
if (message?.target !== CAPTURE_MESSAGE_TARGET) {
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
if (sender.tab) {
|
|
344
|
+
logger.warn(
|
|
345
|
+
'Ignoring a double-fetch capture message from a tab:',
|
|
346
|
+
sender.tab.id,
|
|
347
|
+
);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
if (message.type === 'config') {
|
|
351
|
+
logger.debug('Capture script is ready in:', message.url);
|
|
352
|
+
sendResponse({ waitFor, delay });
|
|
353
|
+
} else if (message.type === 'content' && typeof message.html === 'string') {
|
|
354
|
+
logger.debug('Captured', message.html.length, 'characters');
|
|
355
|
+
resolveHtml(message.html);
|
|
356
|
+
} else if (message.type === 'permanent-error') {
|
|
357
|
+
logger.warn('Unable to capture:', url, message.code, message.details);
|
|
358
|
+
rejectHtml(
|
|
359
|
+
new PermanentlyUnableToFetchUrlError(
|
|
360
|
+
`Unable to capture ${url} (${message.code})`,
|
|
361
|
+
),
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
chrome.runtime.onMessage.addListener(onMessage);
|
|
366
|
+
|
|
367
|
+
try {
|
|
368
|
+
// Leftovers are not expected (the script is registered for the duration of
|
|
369
|
+
// one step only), but the service worker could have been killed in between.
|
|
370
|
+
await chrome.scripting
|
|
371
|
+
.unregisterContentScripts({ ids: [CAPTURE_CONTENT_SCRIPT_ID] })
|
|
372
|
+
.catch(() => {});
|
|
373
|
+
await chrome.scripting.registerContentScripts([
|
|
374
|
+
{
|
|
375
|
+
id: CAPTURE_CONTENT_SCRIPT_ID,
|
|
376
|
+
// Note: match patterns have no port, so this covers any port on the host.
|
|
377
|
+
matches: [`${protocol}//${hostname}/*`],
|
|
378
|
+
js: [OFFSCREEN_DOCUMENT_CAPTURE_JS],
|
|
379
|
+
runAt: 'document_start',
|
|
380
|
+
allFrames: true,
|
|
381
|
+
world: 'ISOLATED',
|
|
382
|
+
persistAcrossSessions: false,
|
|
383
|
+
},
|
|
384
|
+
]);
|
|
385
|
+
} catch (e) {
|
|
386
|
+
chrome.runtime.onMessage.removeListener(onMessage);
|
|
387
|
+
throw e;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
return {
|
|
391
|
+
pendingHtml,
|
|
392
|
+
cleanup: async () => {
|
|
393
|
+
chrome.runtime.onMessage.removeListener(onMessage);
|
|
394
|
+
await chrome.scripting
|
|
395
|
+
.unregisterContentScripts({ ids: [CAPTURE_CONTENT_SCRIPT_ID] })
|
|
396
|
+
.catch((e) => {
|
|
397
|
+
logger.error('cleanup failed: unable to remove capture script:', e);
|
|
398
|
+
});
|
|
399
|
+
},
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
async function withOffscreenDocumentReady(
|
|
404
|
+
url,
|
|
405
|
+
headers,
|
|
406
|
+
captureConfig,
|
|
407
|
+
asyncCallback,
|
|
408
|
+
) {
|
|
321
409
|
const cleanups = [];
|
|
322
410
|
try {
|
|
323
411
|
const domain = new URL(url).hostname;
|
|
@@ -347,16 +435,26 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
|
|
|
347
435
|
});
|
|
348
436
|
cleanups.push(undoHeaderOverride);
|
|
349
437
|
|
|
438
|
+
let pendingHtml = null;
|
|
439
|
+
if (captureConfig) {
|
|
440
|
+
const handler = await installCaptureHandler(url, captureConfig);
|
|
441
|
+
cleanups.push(handler.cleanup);
|
|
442
|
+
pendingHtml = handler.pendingHtml;
|
|
443
|
+
}
|
|
444
|
+
|
|
350
445
|
const offscreenUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_INDEX_HTML);
|
|
351
446
|
const existingContexts = await chrome.runtime.getContexts({
|
|
352
447
|
contextTypes: ['OFFSCREEN_DOCUMENT'],
|
|
353
448
|
documentUrls: [offscreenUrl],
|
|
354
449
|
});
|
|
355
450
|
if (existingContexts.length > 0) {
|
|
356
|
-
//
|
|
357
|
-
//
|
|
358
|
-
|
|
359
|
-
|
|
451
|
+
// A leftover from an earlier run: the service worker must have died
|
|
452
|
+
// before its cleanup could run. Since the lookup is by URL, it can only
|
|
453
|
+
// be our own document, so it is safe to close it and start over.
|
|
454
|
+
// (Otherwise, it would break all further dynamic double-fetches: the
|
|
455
|
+
// browser allows only one offscreen document per extension.)
|
|
456
|
+
logger.warn('Closing a stale offscreen document:', existingContexts);
|
|
457
|
+
await tryCloseOffscreenDocument();
|
|
360
458
|
}
|
|
361
459
|
|
|
362
460
|
await chrome.offscreen.createDocument({
|
|
@@ -366,7 +464,7 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
|
|
|
366
464
|
});
|
|
367
465
|
cleanups.push(() => tryCloseOffscreenDocument());
|
|
368
466
|
|
|
369
|
-
return await asyncCallback();
|
|
467
|
+
return await asyncCallback(pendingHtml);
|
|
370
468
|
} finally {
|
|
371
469
|
await Promise.all(
|
|
372
470
|
cleanups.map(async (x) => {
|
|
@@ -567,6 +665,19 @@ const LOCK = new SeqExecutor();
|
|
|
567
665
|
* can be used in later requests. Still, the chain of requests always
|
|
568
666
|
* starts from a clean state. In other words, the temporary context is
|
|
569
667
|
* fully isolated and will be discarded once all steps have completed.
|
|
668
|
+
*
|
|
669
|
+
* A step with "dynamic" set renders the URL in an iframe instead of
|
|
670
|
+
* fetching it; if it is the last step, the rendered page is returned.
|
|
671
|
+
* Two optional keys say when it counts as rendered:
|
|
672
|
+
* * waitFor: CSS selectors that all have to match ('a, b' for either)
|
|
673
|
+
* * delay: milliseconds to wait after that (default: 0), for pages
|
|
674
|
+
* that render progressively
|
|
675
|
+
* Without selectors, the delay alone decides; without either, the load
|
|
676
|
+
* event. If the page never gets there, the step ends in a timeout.
|
|
677
|
+
* - safecookie (optional):
|
|
678
|
+
* Allows to predefine cookies (see "findSafeCookies"). Must be an ES6 Map.
|
|
679
|
+
* Example: if a website uses AWS WAF, steps can set
|
|
680
|
+
* "{{safecookie:aws-waf-token}}".
|
|
570
681
|
* - onError (optional):
|
|
571
682
|
* A fallback configuration for error recovery.
|
|
572
683
|
* - emptyHtml (default: false):
|
|
@@ -580,7 +691,13 @@ export async function anonymousHttpGet(originalUrl, params = {}) {
|
|
|
580
691
|
}
|
|
581
692
|
|
|
582
693
|
async function anonymousHttpGet_(originalUrl, params = {}) {
|
|
583
|
-
const {
|
|
694
|
+
const {
|
|
695
|
+
steps = [],
|
|
696
|
+
emptyHtml = false,
|
|
697
|
+
onError,
|
|
698
|
+
safecookie = new Map(),
|
|
699
|
+
...sharedParams
|
|
700
|
+
} = params;
|
|
584
701
|
if (emptyHtml) {
|
|
585
702
|
logger.debug('Returning empty HTML for URL:', originalUrl);
|
|
586
703
|
return EMPTY_RESCUE_HTML;
|
|
@@ -588,7 +705,10 @@ async function anonymousHttpGet_(originalUrl, params = {}) {
|
|
|
588
705
|
|
|
589
706
|
try {
|
|
590
707
|
if (steps.length === 0) {
|
|
591
|
-
|
|
708
|
+
const headers =
|
|
709
|
+
sharedParams.headers &&
|
|
710
|
+
replacePlaceholders(sharedParams.headers, { safecookie });
|
|
711
|
+
return await singleHttpGetStep(originalUrl, { ...sharedParams, headers });
|
|
592
712
|
}
|
|
593
713
|
if (!chrome?.webRequest?.onHeadersReceived) {
|
|
594
714
|
throw new MultiStepDoublefetchNotSupportedError();
|
|
@@ -597,6 +717,13 @@ async function anonymousHttpGet_(originalUrl, params = {}) {
|
|
|
597
717
|
if (hasDynamicSteps && !chrome?.offscreen?.createDocument) {
|
|
598
718
|
throw new DynamicDoublefetchNotSupportedError();
|
|
599
719
|
}
|
|
720
|
+
// Reading the rendered page needs a content script in the iframe.
|
|
721
|
+
if (
|
|
722
|
+
steps[steps.length - 1].dynamic &&
|
|
723
|
+
!chrome?.scripting?.registerContentScripts
|
|
724
|
+
) {
|
|
725
|
+
throw new DynamicDoublefetchNotSupportedError();
|
|
726
|
+
}
|
|
600
727
|
|
|
601
728
|
// The context that can be queried with the placeholder syntax (e.g.
|
|
602
729
|
// "foo={{cookie:bar}}"). The context is built from the requests from
|
|
@@ -612,6 +739,7 @@ async function anonymousHttpGet_(originalUrl, params = {}) {
|
|
|
612
739
|
cookie: new Map(), // default ('set-cookies' in response)
|
|
613
740
|
cookie0: new Map(), // fallback ('cookies' in request)
|
|
614
741
|
param: new Map(), // URL params
|
|
742
|
+
safecookie,
|
|
615
743
|
},
|
|
616
744
|
observer,
|
|
617
745
|
);
|
|
@@ -627,6 +755,16 @@ async function anonymousHttpGet_(originalUrl, params = {}) {
|
|
|
627
755
|
const nextStep = steps[stepIdx + 1];
|
|
628
756
|
const localParams = { ...sharedParams, ...currentStep };
|
|
629
757
|
|
|
758
|
+
// check "requires": they resolve like normal placeholders, but if they
|
|
759
|
+
// would result in an empty string, it will fail the current chain-of-steps.
|
|
760
|
+
const isMet = (entry) => !!replacePlaceholders({ v: entry }, ctx).v;
|
|
761
|
+
const missing = currentStep.requires?.find((entry) => !isMet(entry));
|
|
762
|
+
if (missing) {
|
|
763
|
+
throw new PermanentlyUnableToFetchUrlError(
|
|
764
|
+
`Step ${stepIdx + 1} requires <<${missing}>>, but it did not resolve`,
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
|
|
630
768
|
const readyForNextStep = new Promise((resolve, reject) => {
|
|
631
769
|
observer.onChange = null;
|
|
632
770
|
if (!currentStep.dynamic) {
|
|
@@ -635,7 +773,7 @@ async function anonymousHttpGet_(originalUrl, params = {}) {
|
|
|
635
773
|
}
|
|
636
774
|
|
|
637
775
|
try {
|
|
638
|
-
const graph = buildDependencyGraph(nextStep);
|
|
776
|
+
const graph = buildDependencyGraph(nextStep, ctx);
|
|
639
777
|
if (graph.allReady) {
|
|
640
778
|
resolve();
|
|
641
779
|
return;
|
|
@@ -749,14 +887,19 @@ async function anonymousHttpGet_(originalUrl, params = {}) {
|
|
|
749
887
|
}
|
|
750
888
|
try {
|
|
751
889
|
if (currentStep.dynamic) {
|
|
752
|
-
//
|
|
753
|
-
|
|
754
|
-
|
|
890
|
+
// The content comes from the last step, so only it needs a capture.
|
|
891
|
+
const captureConfig = nextStep
|
|
892
|
+
? null
|
|
893
|
+
: {
|
|
894
|
+
waitFor: localParams.waitFor,
|
|
895
|
+
delay: localParams.delay,
|
|
896
|
+
};
|
|
755
897
|
|
|
756
898
|
await withOffscreenDocumentReady(
|
|
757
899
|
localUrl,
|
|
758
900
|
localParams.headers,
|
|
759
|
-
|
|
901
|
+
captureConfig,
|
|
902
|
+
async (pendingHtml) => {
|
|
760
903
|
const { ok, error } = await chrome.runtime.sendMessage({
|
|
761
904
|
target: 'offscreen:urlReporting',
|
|
762
905
|
type: 'request',
|
|
@@ -770,7 +913,7 @@ async function anonymousHttpGet_(originalUrl, params = {}) {
|
|
|
770
913
|
|
|
771
914
|
let timeout = null;
|
|
772
915
|
const timedOut = new Promise((resolve, reject) => {
|
|
773
|
-
const maxTime =
|
|
916
|
+
const maxTime = localParams.timeout || 15 * SECOND;
|
|
774
917
|
timeout = setTimeout(() => {
|
|
775
918
|
timeout = null;
|
|
776
919
|
logger.warn(
|
|
@@ -790,7 +933,13 @@ async function anonymousHttpGet_(originalUrl, params = {}) {
|
|
|
790
933
|
}, maxTime);
|
|
791
934
|
});
|
|
792
935
|
try {
|
|
793
|
-
|
|
936
|
+
// The last step waits for the rendered page, the others for
|
|
937
|
+
// the values that the step after them needs.
|
|
938
|
+
if (pendingHtml) {
|
|
939
|
+
content = await Promise.race([pendingHtml, timedOut]);
|
|
940
|
+
} else {
|
|
941
|
+
await Promise.race([readyForNextStep, timedOut]);
|
|
942
|
+
}
|
|
794
943
|
} finally {
|
|
795
944
|
clearTimeout(timeout);
|
|
796
945
|
}
|
|
@@ -811,6 +960,7 @@ async function anonymousHttpGet_(originalUrl, params = {}) {
|
|
|
811
960
|
if (onError) {
|
|
812
961
|
const rescueParams = {
|
|
813
962
|
...sharedParams,
|
|
963
|
+
safecookie,
|
|
814
964
|
...onError,
|
|
815
965
|
};
|
|
816
966
|
logger.info(
|
|
@@ -859,6 +1009,9 @@ export function replacePlaceholders(headers, ctx) {
|
|
|
859
1009
|
} else if (expr.startsWith('param:')) {
|
|
860
1010
|
const key = expr.slice('param:'.length);
|
|
861
1011
|
resolved = ctx.param.get(key);
|
|
1012
|
+
} else if (expr.startsWith('safecookie:')) {
|
|
1013
|
+
const key = expr.slice('safecookie:'.length);
|
|
1014
|
+
resolved = ctx.safecookie.get(key);
|
|
862
1015
|
} else {
|
|
863
1016
|
throw new Error(
|
|
864
1017
|
`Unsupported expression: stopped at <<${expr}>> (full expression: ${fullExpression})`,
|
|
@@ -894,17 +1047,28 @@ export function findPlaceholders(text) {
|
|
|
894
1047
|
}
|
|
895
1048
|
|
|
896
1049
|
// Note: exported for tests only
|
|
897
|
-
export function buildDependencyGraph(nextStep) {
|
|
1050
|
+
export function buildDependencyGraph(nextStep, ctx = {}) {
|
|
898
1051
|
const graph = {
|
|
899
1052
|
allReady: true,
|
|
900
1053
|
onChange: null,
|
|
901
1054
|
onReady: () => {}, // can be overwritten by the caller
|
|
902
1055
|
};
|
|
903
1056
|
|
|
1057
|
+
// Unlike cookies and params, safecookie values are provided by the caller
|
|
1058
|
+
// instead of being observed during the run: an absent one never arrives.
|
|
1059
|
+
const isUnresolvable = (x) =>
|
|
1060
|
+
x.startsWith('safecookie:') &&
|
|
1061
|
+
!ctx.safecookie.get(x.slice('safecookie:'.length));
|
|
1062
|
+
|
|
904
1063
|
// 1) find all dependencies
|
|
905
1064
|
// (if there are none, we can exit early without entering "observe-mode")
|
|
906
|
-
if (nextStep
|
|
907
|
-
|
|
1065
|
+
if (nextStep) {
|
|
1066
|
+
// "requires" entries are templates as well, so they are dependencies of
|
|
1067
|
+
// the step in the same way that its headers are.
|
|
1068
|
+
const allTemplates = [
|
|
1069
|
+
...Object.values(nextStep.headers || {}),
|
|
1070
|
+
...(nextStep.requires || []),
|
|
1071
|
+
];
|
|
908
1072
|
if (allTemplates.length > 0) {
|
|
909
1073
|
// Keep track of which placeholders expression exist and by what
|
|
910
1074
|
// (atomic) placeholders they get resolved. For instance, in the
|
|
@@ -922,9 +1086,14 @@ export function buildDependencyGraph(nextStep) {
|
|
|
922
1086
|
|
|
923
1087
|
for (const template of allTemplates) {
|
|
924
1088
|
for (const expression of findPlaceholders(template)) {
|
|
1089
|
+
const placeholders = expression.split('||');
|
|
1090
|
+
if (placeholders.every(isUnresolvable)) {
|
|
1091
|
+
logger.debug('[observe-mode] not waiting for:', expression);
|
|
1092
|
+
continue;
|
|
1093
|
+
}
|
|
925
1094
|
pendingExpressions.add(expression);
|
|
926
1095
|
|
|
927
|
-
for (const placeholder of
|
|
1096
|
+
for (const placeholder of placeholders) {
|
|
928
1097
|
const unlocks =
|
|
929
1098
|
expressionResolvedByPlaceholder.get(placeholder) || [];
|
|
930
1099
|
if (!unlocks.includes(expression)) {
|
|
@@ -969,6 +1138,15 @@ export function buildDependencyGraph(nextStep) {
|
|
|
969
1138
|
}
|
|
970
1139
|
}
|
|
971
1140
|
}
|
|
1141
|
+
|
|
1142
|
+
// A value that the context already holds (a borrowed cookie, or one that an
|
|
1143
|
+
// earlier step captured) will not be set again, so feed it through the same
|
|
1144
|
+
// path that a later value would take.
|
|
1145
|
+
for (const [type, values] of Object.entries(ctx)) {
|
|
1146
|
+
for (const [key, value] of values) {
|
|
1147
|
+
graph.onChange?.(type, key, value);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
972
1150
|
return graph;
|
|
973
1151
|
}
|
|
974
1152
|
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Content script for a dynamic double-fetch step: sends back the rendered DOM.
|
|
2
|
+
(() => {
|
|
3
|
+
const TARGET = 'doublefetch:capture';
|
|
4
|
+
|
|
5
|
+
// Avoid performance bugs if pages are extremely large (>10MB).
|
|
6
|
+
const MAX_HTML_LENGTH = 10 * 1024 * 1024;
|
|
7
|
+
|
|
8
|
+
// This script is registered for the whole domain while a step runs, so it can
|
|
9
|
+
// also land in a page that the user opened. Only the credentialless iframe
|
|
10
|
+
// may be read: "credentialless" is false in the user's tabs, and since the
|
|
11
|
+
// flag is inherited by nested iframes, also check that this is the document
|
|
12
|
+
// the offscreen document embedded (a direct child of the top document).
|
|
13
|
+
if (
|
|
14
|
+
window.credentialless !== true ||
|
|
15
|
+
window === window.top ||
|
|
16
|
+
window.parent !== window.top
|
|
17
|
+
) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let done = false;
|
|
22
|
+
const send = (message) =>
|
|
23
|
+
chrome.runtime.sendMessage({ target: TARGET, ...message }).catch(() => {
|
|
24
|
+
// nobody is listening anymore
|
|
25
|
+
done = true;
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
// When to capture the HTML? Once all selectors match. With no selectors,
|
|
29
|
+
// right away, because then the delay is the whole wait. With no delay
|
|
30
|
+
// either, at the load event, because before that the document is empty.
|
|
31
|
+
const whenReady = (waitFor, delay, callback) => {
|
|
32
|
+
if (waitFor.length === 0) {
|
|
33
|
+
if (delay > 0 || document.readyState === 'complete') {
|
|
34
|
+
callback();
|
|
35
|
+
} else {
|
|
36
|
+
window.addEventListener('load', callback, { once: true });
|
|
37
|
+
}
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const isReady = () => waitFor.every((x) => document.querySelector(x));
|
|
42
|
+
if (isReady()) {
|
|
43
|
+
callback();
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const observer = new MutationObserver(() => {
|
|
47
|
+
if (isReady()) {
|
|
48
|
+
observer.disconnect();
|
|
49
|
+
callback();
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
observer.observe(document, { childList: true, subtree: true });
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
send({ type: 'config', url: location.href })
|
|
56
|
+
.then((config) => {
|
|
57
|
+
if (!config || done) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const { waitFor = [], delay = 0 } = config;
|
|
61
|
+
whenReady(waitFor, delay, () => {
|
|
62
|
+
// A selector can match before the element is finished filling in.
|
|
63
|
+
setTimeout(() => {
|
|
64
|
+
if (!done) {
|
|
65
|
+
done = true;
|
|
66
|
+
const html = document.documentElement.outerHTML;
|
|
67
|
+
if (html.length <= MAX_HTML_LENGTH) {
|
|
68
|
+
send({ type: 'content', html });
|
|
69
|
+
} else {
|
|
70
|
+
send({
|
|
71
|
+
type: 'permanent-error',
|
|
72
|
+
code: 'too-large',
|
|
73
|
+
details: { length: html.length },
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}, delay);
|
|
78
|
+
});
|
|
79
|
+
})
|
|
80
|
+
.catch((e) => {
|
|
81
|
+
// The configuration cannot be used (for instance, it could contain a
|
|
82
|
+
// selector that is not valid CSS). A retry will not fix that.
|
|
83
|
+
done = true;
|
|
84
|
+
send({
|
|
85
|
+
type: 'permanent-error',
|
|
86
|
+
code: 'bad-config',
|
|
87
|
+
details: { message: `${e}` },
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
})();
|
|
@@ -340,7 +340,7 @@ export function lookupBuiltinTransform(name) {
|
|
|
340
340
|
* to disable clients that do not meet the minimum requirements of the
|
|
341
341
|
* current patterns.
|
|
342
342
|
*/
|
|
343
|
-
const PATTERN_DSL_VERSION =
|
|
343
|
+
const PATTERN_DSL_VERSION = 8;
|
|
344
344
|
|
|
345
345
|
/**
|
|
346
346
|
* "Magic" empty rule set, which exists only if patterns were loaded, but
|
|
@@ -418,7 +418,7 @@ export default class Patterns {
|
|
|
418
418
|
return null;
|
|
419
419
|
}
|
|
420
420
|
const convert = (
|
|
421
|
-
{ followRedirects, headers, steps, emptyHtml, onError },
|
|
421
|
+
{ followRedirects, headers, steps, timeout, emptyHtml, onError },
|
|
422
422
|
target = {},
|
|
423
423
|
) => {
|
|
424
424
|
if (followRedirects) {
|
|
@@ -430,6 +430,9 @@ export default class Patterns {
|
|
|
430
430
|
if (steps) {
|
|
431
431
|
target.steps = steps;
|
|
432
432
|
}
|
|
433
|
+
if (timeout) {
|
|
434
|
+
target.timeout = timeout;
|
|
435
|
+
}
|
|
433
436
|
if (typeof emptyHtml === 'boolean') {
|
|
434
437
|
target.emptyHtml = emptyHtml;
|
|
435
438
|
}
|
|
@@ -17,6 +17,7 @@ import { fastHash } from './utils';
|
|
|
17
17
|
import random from './random';
|
|
18
18
|
import { timezoneAgnosticDailyExpireAt } from './cooldowns';
|
|
19
19
|
import { anonymousHttpGet } from './http';
|
|
20
|
+
import { findSafeCookies } from './doublefetch-unbreak';
|
|
20
21
|
import { lookupBuiltinTransform } from './patterns';
|
|
21
22
|
import { BadPatternError } from './errors';
|
|
22
23
|
|
|
@@ -138,6 +139,7 @@ export default class SearchExtractor {
|
|
|
138
139
|
const { url, ...params } = doublefetchRequest;
|
|
139
140
|
const html = await anonymousHttpGet(url, {
|
|
140
141
|
...params,
|
|
142
|
+
safecookie: await findSafeCookies(url, params),
|
|
141
143
|
treat429AsPermanentError: true,
|
|
142
144
|
});
|
|
143
145
|
doc = await parseHtml(html);
|