@whotracksme/reporting 5.1.17
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/.editorconfig +12 -0
- package/.eslintignore +3 -0
- package/.eslintrc +16 -0
- package/.github/workflows/release.yml +34 -0
- package/.github/workflows/tests.yml +20 -0
- package/.prettierrc +9 -0
- package/.tool-versions +1 -0
- package/CHANGELOG.md +795 -0
- package/LICENSE +373 -0
- package/README.md +1 -0
- package/communication/README.md +11 -0
- package/communication/example/index.js +43 -0
- package/communication/example/manifest.json +16 -0
- package/communication/karma.conf.cjs +19 -0
- package/communication/package.json +52 -0
- package/communication/rollup.common-config.cjs +17 -0
- package/communication/rollup.config.cjs +10 -0
- package/communication/src/encoding.js +54 -0
- package/communication/src/errors.js +84 -0
- package/communication/src/index.js +76 -0
- package/communication/src/logger.js +41 -0
- package/communication/src/padding.js +60 -0
- package/communication/src/proxied-http.js +231 -0
- package/communication/src/server-public-key-accessor.js +123 -0
- package/communication/src/timestamps.js +37 -0
- package/communication/src/trusted-clock.js +58 -0
- package/communication/src/utils.js +28 -0
- package/communication/src/zlib.js +17 -0
- package/communication/test/helpers/in-memory-database.js +43 -0
- package/communication/test/server-public-key-accessor.spec.js +135 -0
- package/communication/test/utils.spec.js +43 -0
- package/package.json +50 -0
- package/reporting/TODO.md +2 -0
- package/reporting/assets/request/bloom_filter.dat +0 -0
- package/reporting/assets/request/update.json +1 -0
- package/reporting/example/content.js +11 -0
- package/reporting/example/index.js +132 -0
- package/reporting/example/inspector/index.html +17 -0
- package/reporting/example/inspector/index.js +27 -0
- package/reporting/example/manifests/chromium.json +37 -0
- package/reporting/example/manifests/firefox.json +35 -0
- package/reporting/example/rules.json +62 -0
- package/reporting/example/setup.js +1 -0
- package/reporting/example/tests/test1.html +10 -0
- package/reporting/karma.conf.cjs +22 -0
- package/reporting/package.json +63 -0
- package/reporting/rollup.common-config.cjs +19 -0
- package/reporting/rollup.config.cjs +20 -0
- package/reporting/src/LRU.js +149 -0
- package/reporting/src/activity-estimator.js +298 -0
- package/reporting/src/alive-check.js +139 -0
- package/reporting/src/alive-message-generator.js +142 -0
- package/reporting/src/bloom-filters.js +345 -0
- package/reporting/src/country-provider.js +295 -0
- package/reporting/src/cyrb53.js +32 -0
- package/reporting/src/digest.js +33 -0
- package/reporting/src/doublefetch-page-handler.js +548 -0
- package/reporting/src/duplicate-detector.js +233 -0
- package/reporting/src/errors.js +84 -0
- package/reporting/src/event-listener-queue.js +121 -0
- package/reporting/src/fixed-size-cache.js +63 -0
- package/reporting/src/hash-detector.js +1526 -0
- package/reporting/src/html-parser.js +17 -0
- package/reporting/src/http.js +265 -0
- package/reporting/src/index.js +14 -0
- package/reporting/src/job-scheduler.js +912 -0
- package/reporting/src/logger.js +121 -0
- package/reporting/src/md5.js +334 -0
- package/reporting/src/message-sender.js +51 -0
- package/reporting/src/network.js +140 -0
- package/reporting/src/new-page-approver.js +119 -0
- package/reporting/src/page-aggregator.js +185 -0
- package/reporting/src/page-quorum-check-handler.js +200 -0
- package/reporting/src/page-structure.js +136 -0
- package/reporting/src/pagedb.js +671 -0
- package/reporting/src/pages.js +1798 -0
- package/reporting/src/patterns-updater.js +310 -0
- package/reporting/src/patterns.js +416 -0
- package/reporting/src/persisted-bitarray.js +265 -0
- package/reporting/src/persisted-hashes.js +189 -0
- package/reporting/src/quorum-checker.js +327 -0
- package/reporting/src/random.js +39 -0
- package/reporting/src/reporting.js +290 -0
- package/reporting/src/request/config.js +116 -0
- package/reporting/src/request/content-script.js +77 -0
- package/reporting/src/request/database.js +147 -0
- package/reporting/src/request/dnt.js +24 -0
- package/reporting/src/request/hash.js +101 -0
- package/reporting/src/request/index.js +874 -0
- package/reporting/src/request/page-telemetry.js +42 -0
- package/reporting/src/request/qs-whitelist2.js +247 -0
- package/reporting/src/request/resources/prob.js +601 -0
- package/reporting/src/request/steps/block-rules.js +40 -0
- package/reporting/src/request/steps/check-context.js +37 -0
- package/reporting/src/request/steps/cookie-context.js +209 -0
- package/reporting/src/request/steps/oauth-detector.js +101 -0
- package/reporting/src/request/steps/page-logger.js +177 -0
- package/reporting/src/request/steps/redirect-tagger.js +75 -0
- package/reporting/src/request/steps/subdomain-check.js +34 -0
- package/reporting/src/request/steps/token-checker/index.js +189 -0
- package/reporting/src/request/steps/token-checker/token-domain.js +129 -0
- package/reporting/src/request/steps/token-examiner.js +182 -0
- package/reporting/src/request/steps/token-telemetry/cached-entry-pipeline.js +210 -0
- package/reporting/src/request/steps/token-telemetry/index.js +234 -0
- package/reporting/src/request/steps/token-telemetry/key-pipeline.js +109 -0
- package/reporting/src/request/steps/token-telemetry/token-pipeline.js +105 -0
- package/reporting/src/request/time.js +73 -0
- package/reporting/src/request/utils/bloom-filter-packed.js +107 -0
- package/reporting/src/request/utils/chrome-storage-map.js +282 -0
- package/reporting/src/request/utils/subject.js +37 -0
- package/reporting/src/request/utils/temp-set.js +56 -0
- package/reporting/src/request/utils/tlds.js +55 -0
- package/reporting/src/request/utils.js +41 -0
- package/reporting/src/request-reporter.js +111 -0
- package/reporting/src/sanitizer.js +519 -0
- package/reporting/src/search-extractor.js +338 -0
- package/reporting/src/self-check.js +105 -0
- package/reporting/src/seq-executor.js +43 -0
- package/reporting/src/session-storage.js +399 -0
- package/reporting/src/url-analyzer.js +161 -0
- package/reporting/src/url-cleaner.js +60 -0
- package/reporting/src/utils/pacemaker.js +279 -0
- package/reporting/src/utils/url.js +114 -0
- package/reporting/src/utils.js +345 -0
- package/reporting/src/webrequest-pipeline/cname-uncloak.js +110 -0
- package/reporting/src/webrequest-pipeline/index.js +287 -0
- package/reporting/src/webrequest-pipeline/logger.js +14 -0
- package/reporting/src/webrequest-pipeline/page-store.js +282 -0
- package/reporting/src/webrequest-pipeline/page.js +140 -0
- package/reporting/src/webrequest-pipeline/pipeline.js +249 -0
- package/reporting/src/webrequest-pipeline/utils/webrequest.js +113 -0
- package/reporting/src/webrequest-pipeline/webrequest-context.js +153 -0
- package/reporting/test/README.md +2 -0
- package/reporting/test/activity-estimator.spec.js +356 -0
- package/reporting/test/alive-check.spec.js +156 -0
- package/reporting/test/alive-message-generator.spec.js +186 -0
- package/reporting/test/country-provider.spec.js +263 -0
- package/reporting/test/doublefetch-page-handler.spec.js +818 -0
- package/reporting/test/duplicate-detector.spec.js +689 -0
- package/reporting/test/helpers/dom-parsers.js +41 -0
- package/reporting/test/helpers/fake-session-storage.js +69 -0
- package/reporting/test/helpers/fast-check-utils.js +28 -0
- package/reporting/test/helpers/fetch-mock.js +57 -0
- package/reporting/test/helpers/in-memory-database.js +14 -0
- package/reporting/test/helpers/memory-map.js +72 -0
- package/reporting/test/helpers/pagedb-mocks.js +41 -0
- package/reporting/test/index.js +47 -0
- package/reporting/test/job-scheduler.spec.js +691 -0
- package/reporting/test/network.spec.js +72 -0
- package/reporting/test/page-aggregator.spec.js +104 -0
- package/reporting/test/page-quorum-check-handler.spec.js +86 -0
- package/reporting/test/pagedb.spec.js +250 -0
- package/reporting/test/pages.spec.js +693 -0
- package/reporting/test/patterns-updater.spec.js +446 -0
- package/reporting/test/patterns.spec.js +751 -0
- package/reporting/test/persisted-hashes.spec.js +169 -0
- package/reporting/test/reporting.spec.js +205 -0
- package/reporting/test/request/database.spec.js +59 -0
- package/reporting/test/request/hash.spec.js +108 -0
- package/reporting/test/request/index.spec.js +378 -0
- package/reporting/test/request/qs-whitelist2.spec.js +189 -0
- package/reporting/test/request/steps/check-context.spec.js +51 -0
- package/reporting/test/request/steps/oauth-detector.spec.js +339 -0
- package/reporting/test/request/test-pages.js +1246 -0
- package/reporting/test/request/utils/bloom-filter-packed.spec.js +37 -0
- package/reporting/test/request/utils/chrome-storage-map.spec.js +28 -0
- package/reporting/test/request/utils/tldts.spec.js +62 -0
- package/reporting/test/request/utils.spec.js +168 -0
- package/reporting/test/sanitizer.spec.js +1087 -0
- package/reporting/test/search-extractor.spec.js +590 -0
- package/reporting/test/seq-executor.spec.js +158 -0
- package/reporting/test/session-storage.spec.js +400 -0
- package/reporting/test/setup.js +24 -0
- package/reporting/test/url-analyzer.spec.js +451 -0
- package/reporting/test/url-cleaner.spec.js +102 -0
- package/reporting/test/utils/pacemaker.spec.js +222 -0
- package/reporting/test/utils/url.spec.js +660 -0
- package/reporting/test/utils.spec.js +299 -0
- package/reporting/test/webrequest-pipeline/pipeline.spec.js +251 -0
|
@@ -0,0 +1,671 @@
|
|
|
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 SeqExecutor from './seq-executor';
|
|
14
|
+
import { chunk, equalityCanBeProven } from './utils';
|
|
15
|
+
import SelfCheck from './self-check';
|
|
16
|
+
|
|
17
|
+
const SECOND = 1000;
|
|
18
|
+
const MINUTE = 60 * SECOND;
|
|
19
|
+
const HOUR = 60 * MINUTE;
|
|
20
|
+
|
|
21
|
+
const DEFAULT_PAGE_COOLDOWN_IN_MS = 1 * HOUR;
|
|
22
|
+
|
|
23
|
+
function normalizeUrl(url) {
|
|
24
|
+
try {
|
|
25
|
+
// Remove URL fragement:
|
|
26
|
+
// https://abc.test/foo#bar
|
|
27
|
+
// -> https://abc.test/foo
|
|
28
|
+
const tmp = new URL(url);
|
|
29
|
+
tmp.hash = '';
|
|
30
|
+
return tmp.toString();
|
|
31
|
+
} catch (e) {
|
|
32
|
+
// It is not necessarily a bug this code path hits, but ideally
|
|
33
|
+
// invalid URLs should have been filtered already.
|
|
34
|
+
logger.warn('Bad URL detected:', url, '(ignore this page and continue)');
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function toPersistedKey(url, createdAt) {
|
|
40
|
+
return `${createdAt}:${url}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function parsePersistedKey(key) {
|
|
44
|
+
const pos = key.indexOf(':');
|
|
45
|
+
if (pos === -1) {
|
|
46
|
+
throw new Error(`Corrupted key (<${key}>)`);
|
|
47
|
+
}
|
|
48
|
+
const createdAt = +key.slice(0, pos);
|
|
49
|
+
if (isNaN(createdAt)) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
`Corrupted key (<${key}>). Failed to parse timestamp (<${createdAt}>)`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
const url = key.slice(pos + 1);
|
|
55
|
+
return { createdAt, url };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The data fields of the page description that needs to be
|
|
60
|
+
* persisted to disk.
|
|
61
|
+
*/
|
|
62
|
+
const pageDataSchema = [
|
|
63
|
+
'url',
|
|
64
|
+
'status',
|
|
65
|
+
'pageLoadMethod',
|
|
66
|
+
'title',
|
|
67
|
+
'search',
|
|
68
|
+
'ref',
|
|
69
|
+
'redirects',
|
|
70
|
+
'preDoublefetch',
|
|
71
|
+
'lang',
|
|
72
|
+
'lastUpdatedAt',
|
|
73
|
+
];
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Project only on the set of fields that we need. When the "page" class
|
|
77
|
+
* describe its current state, it may include additional fields in its
|
|
78
|
+
* description.
|
|
79
|
+
*
|
|
80
|
+
* This function also defines the (implicit) schema of the documents that
|
|
81
|
+
* we store in the database.
|
|
82
|
+
*/
|
|
83
|
+
function pageWithAggregationInfo(page, now = Date.now()) {
|
|
84
|
+
const result = {
|
|
85
|
+
aggregator: {
|
|
86
|
+
// Timestamps when the page aggregator first and last saw it.
|
|
87
|
+
// This is not equivalent to when the page was opened or closed,
|
|
88
|
+
// but rather when it reached the page aggregator and how long
|
|
89
|
+
// it stayed there.
|
|
90
|
+
firstSeenAt: now,
|
|
91
|
+
lastSeenAt: now,
|
|
92
|
+
|
|
93
|
+
// The timestamp when it was stored in the database
|
|
94
|
+
// (or "null" as long as it is only kept in memory).
|
|
95
|
+
lastWrittenAt: null,
|
|
96
|
+
|
|
97
|
+
activity: page.activity ?? 0.0,
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
pageDataSchema.forEach((field) => {
|
|
102
|
+
if (page[field] !== undefined) {
|
|
103
|
+
result[field] = page[field];
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
return result;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* In general, it is best to prefer the latest information; but there
|
|
111
|
+
* are special cases where it would lose information
|
|
112
|
+
*/
|
|
113
|
+
function shouldOverrideField({ field, oldEntry, newEntry }) {
|
|
114
|
+
if (newEntry === undefined) {
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
if (oldEntry === undefined) {
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// prefer entries with "depth === 1", since it implies that
|
|
122
|
+
// the page is publically indexed
|
|
123
|
+
if (field === 'search') {
|
|
124
|
+
return newEntry.depth === 1 || oldEntry.depth !== 1;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// fallback: prefer the newer entry
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function mergeRightIntoLeft(left, right) {
|
|
132
|
+
pageDataSchema.forEach((field) => {
|
|
133
|
+
const oldEntry = left[field];
|
|
134
|
+
const newEntry = right[field];
|
|
135
|
+
if (shouldOverrideField({ field, oldEntry, newEntry })) {
|
|
136
|
+
left[field] = newEntry;
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
left.aggregator.firstSeenAt = Math.min(
|
|
141
|
+
left.aggregator.firstSeenAt,
|
|
142
|
+
right.aggregator.firstSeenAt,
|
|
143
|
+
);
|
|
144
|
+
left.aggregator.lastSeenAt = Math.max(
|
|
145
|
+
left.aggregator.lastSeenAt,
|
|
146
|
+
right.aggregator.lastSeenAt,
|
|
147
|
+
);
|
|
148
|
+
left.aggregator.lastWrittenAt = null;
|
|
149
|
+
left.aggregator.activity = Math.max(
|
|
150
|
+
left.aggregator.activity,
|
|
151
|
+
right.aggregator.activity,
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
return left;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Merges information together. If there is conflicting information,
|
|
159
|
+
* the newest information should win. The function may perform
|
|
160
|
+
* updates in-place.
|
|
161
|
+
*/
|
|
162
|
+
function mergePages(pages) {
|
|
163
|
+
if (pages.length === 0) {
|
|
164
|
+
throw Error('Internal error: the list of pages cannot be empty');
|
|
165
|
+
}
|
|
166
|
+
pages.sort((x, y) => x.lastUpdatedAt - y.lastUpdatedAt);
|
|
167
|
+
|
|
168
|
+
let merged = pages[0];
|
|
169
|
+
for (let i = 1; i < pages.length; i += 1) {
|
|
170
|
+
merged = mergeRightIntoLeft(merged, pages[i]);
|
|
171
|
+
}
|
|
172
|
+
return merged;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export default class PageDB {
|
|
176
|
+
constructor({ newPageApprover, database }) {
|
|
177
|
+
this.newPageApprover = newPageApprover;
|
|
178
|
+
this.db = database;
|
|
179
|
+
this._dbLock = new SeqExecutor();
|
|
180
|
+
this.maxAllowedMappings = 2000;
|
|
181
|
+
|
|
182
|
+
// An in-memory cache of the database. The keys will be always
|
|
183
|
+
// in sync with the database, but the entries will be lazy-loaded.
|
|
184
|
+
// Initially, the entries will start as "null"; but once a key has
|
|
185
|
+
// been loaded, it will be kept in memory. The assumption is that
|
|
186
|
+
// the memory footprint is no concern. Instead, lazy-loading is
|
|
187
|
+
// intended to improve startup performance.
|
|
188
|
+
this.aggregatedPages = new Map(); // url -> page|null
|
|
189
|
+
this.urlsToPersistedKeys = new Map(); // url -> key
|
|
190
|
+
this.dirty = new Set(); // keys: url
|
|
191
|
+
|
|
192
|
+
// sorted by timestamp (with the oldest entry at first position)
|
|
193
|
+
this.expiration = []; // entries: { url, createdAt }
|
|
194
|
+
|
|
195
|
+
this.verboseLogging = false;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async ready() {
|
|
199
|
+
if (!this._ready) {
|
|
200
|
+
this._ready = this._restoreKeysFromDisk();
|
|
201
|
+
}
|
|
202
|
+
await this._ready;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async updatePages(openPages_, activePage_) {
|
|
206
|
+
await this.ready();
|
|
207
|
+
await this._dbLock.run(async () => {
|
|
208
|
+
// First, normalize all URLs that will be used as keys
|
|
209
|
+
const openPages = openPages_
|
|
210
|
+
.map((page) => ({ ...page, url: normalizeUrl(page.url) }))
|
|
211
|
+
.filter((page) => page.url);
|
|
212
|
+
let activePage = null;
|
|
213
|
+
if (activePage_) {
|
|
214
|
+
const url = normalizeUrl(activePage_.url);
|
|
215
|
+
if (url) {
|
|
216
|
+
activePage = { ...activePage_, url };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// It is possible that the same page is opened in multiple tabs
|
|
221
|
+
const openPagesMultimap = new Map();
|
|
222
|
+
const now = Date.now();
|
|
223
|
+
for (const page of openPages) {
|
|
224
|
+
const url = normalizeUrl(page.url);
|
|
225
|
+
const pageWithInfo = pageWithAggregationInfo(page, now);
|
|
226
|
+
let value = openPagesMultimap.get(url);
|
|
227
|
+
if (value) {
|
|
228
|
+
value.push(pageWithInfo);
|
|
229
|
+
} else {
|
|
230
|
+
openPagesMultimap.set(url, [pageWithInfo]);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const activeUrl = activePage?.url;
|
|
234
|
+
|
|
235
|
+
const pending = [];
|
|
236
|
+
for (const [url, pages] of openPagesMultimap) {
|
|
237
|
+
const inMemoryEntry = this.aggregatedPages.get(url);
|
|
238
|
+
if (inMemoryEntry === undefined) {
|
|
239
|
+
pending.push(
|
|
240
|
+
(async () => {
|
|
241
|
+
const { ok, reason } = await this.newPageApprover.allowCreation(
|
|
242
|
+
url,
|
|
243
|
+
now,
|
|
244
|
+
);
|
|
245
|
+
if (ok) {
|
|
246
|
+
logger.debug('New page found:', url);
|
|
247
|
+
const page = mergePages(pages);
|
|
248
|
+
this.aggregatedPages.set(url, page);
|
|
249
|
+
this.urlsToPersistedKeys.set(url, toPersistedKey(url, now));
|
|
250
|
+
this.expiration.push({ url, createdAt: now });
|
|
251
|
+
this._markPageAsDirty(url);
|
|
252
|
+
} else {
|
|
253
|
+
logger.debug(
|
|
254
|
+
'Skipping aggregation for url',
|
|
255
|
+
url,
|
|
256
|
+
':',
|
|
257
|
+
reason || '<no reason given>',
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
})(),
|
|
261
|
+
);
|
|
262
|
+
} else {
|
|
263
|
+
const shouldUpdate =
|
|
264
|
+
url == activeUrl ||
|
|
265
|
+
(inMemoryEntry !== null &&
|
|
266
|
+
pages.some((x) => x.lastUpdatedAt) > inMemoryEntry.lastUpdatedAt);
|
|
267
|
+
if (shouldUpdate) {
|
|
268
|
+
const updateDB = (oldEntry) => {
|
|
269
|
+
const page = mergePages([oldEntry, ...pages]);
|
|
270
|
+
this.aggregatedPages.set(url, page);
|
|
271
|
+
this._markPageAsDirty(url);
|
|
272
|
+
};
|
|
273
|
+
if (inMemoryEntry === null) {
|
|
274
|
+
logger.debug('Loading page from disk:', url);
|
|
275
|
+
pending.push(
|
|
276
|
+
(async () => {
|
|
277
|
+
const persistedKey = this.urlsToPersistedKeys.get(url);
|
|
278
|
+
const contentFromDB = await this.db.get(persistedKey);
|
|
279
|
+
if (contentFromDB) {
|
|
280
|
+
updateDB(contentFromDB);
|
|
281
|
+
} else {
|
|
282
|
+
logger.warn(
|
|
283
|
+
'Mappings out of sync: key',
|
|
284
|
+
persistedKey,
|
|
285
|
+
'vanished (skipping update)',
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
})(),
|
|
289
|
+
);
|
|
290
|
+
} else {
|
|
291
|
+
updateDB(inMemoryEntry);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (pending.length > 0) {
|
|
297
|
+
await Promise.all(pending); // TODO: what to do if this fails?
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async updateActivity(urls, activityEstimator) {
|
|
303
|
+
await this.ready();
|
|
304
|
+
return this._dbLock.run(async () => {
|
|
305
|
+
const now = Date.now();
|
|
306
|
+
const pending = [];
|
|
307
|
+
for (const url_ of urls) {
|
|
308
|
+
const url = normalizeUrl(url_);
|
|
309
|
+
const persistedKey = this.urlsToPersistedKeys.get(url);
|
|
310
|
+
if (persistedKey) {
|
|
311
|
+
const score = activityEstimator.estimate(url, now);
|
|
312
|
+
if (score > 0.0) {
|
|
313
|
+
const updateScore = (entry) => {
|
|
314
|
+
if (score > entry.aggregator.activity) {
|
|
315
|
+
entry.aggregator.activity = score;
|
|
316
|
+
this._markPageAsDirty(url);
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
const inMemoryEntry = this.aggregatedPages.get(url);
|
|
320
|
+
if (inMemoryEntry === null) {
|
|
321
|
+
logger.debug('Loading page from disk:', url);
|
|
322
|
+
pending.push(
|
|
323
|
+
(async () => {
|
|
324
|
+
const contentFromDB = await this.db.get(persistedKey);
|
|
325
|
+
if (contentFromDB) {
|
|
326
|
+
this.aggregatedPages.set(url, contentFromDB);
|
|
327
|
+
updateScore(contentFromDB);
|
|
328
|
+
} else {
|
|
329
|
+
logger.warn(
|
|
330
|
+
'Mappings out of sync: key',
|
|
331
|
+
persistedKey,
|
|
332
|
+
'vanished (skipping update)',
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
})(),
|
|
336
|
+
);
|
|
337
|
+
} else {
|
|
338
|
+
updateScore(inMemoryEntry);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (pending.length > 0) {
|
|
344
|
+
await Promise.all(pending); // TODO: what to do if this fails?
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Scans for expired pages. That means, for pages that have been in the
|
|
351
|
+
* aggregation state long enough.
|
|
352
|
+
*
|
|
353
|
+
* Hint: the behavior can be overriden, which can be useful for debugging.
|
|
354
|
+
*/
|
|
355
|
+
async acquireExpiredPages({
|
|
356
|
+
minPageCooldownInMs = DEFAULT_PAGE_COOLDOWN_IN_MS,
|
|
357
|
+
forceExpiration = false,
|
|
358
|
+
maxEntriesToCheck = 1,
|
|
359
|
+
} = {}) {
|
|
360
|
+
await this.ready();
|
|
361
|
+
return this._dbLock.run(async () => {
|
|
362
|
+
let end;
|
|
363
|
+
if (forceExpiration) {
|
|
364
|
+
end = this.expiration.length;
|
|
365
|
+
logger.debug('Forcing expiration of all entries:', end, 'in total');
|
|
366
|
+
} else {
|
|
367
|
+
const maxEnd = Math.min(this.expiration.length, maxEntriesToCheck);
|
|
368
|
+
const now = Date.now();
|
|
369
|
+
end = 0;
|
|
370
|
+
while (
|
|
371
|
+
end < maxEnd &&
|
|
372
|
+
now >= this.expiration[end].createdAt + minPageCooldownInMs
|
|
373
|
+
) {
|
|
374
|
+
end += 1;
|
|
375
|
+
}
|
|
376
|
+
if (end > 0 || this.verboseLogging) {
|
|
377
|
+
logger.debug(end, 'of', this.expiration.length, 'pages expired');
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (end === 0) {
|
|
381
|
+
return [];
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const expired = this.expiration.splice(0, end);
|
|
385
|
+
logger.debug('Processing expired pages:', expired);
|
|
386
|
+
const allExpiredPages = await Promise.all(
|
|
387
|
+
expired.map(async ({ url }) => {
|
|
388
|
+
const persistedKey = this.urlsToPersistedKeys.get(url);
|
|
389
|
+
let page;
|
|
390
|
+
try {
|
|
391
|
+
page = this.aggregatedPages.get(url);
|
|
392
|
+
if (page === null) {
|
|
393
|
+
logger.debug('Loading expired page from disk:', persistedKey);
|
|
394
|
+
page = await this.db.get(persistedKey);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const { promotedPage } = await this._processExpiredPage(url, page);
|
|
398
|
+
return promotedPage;
|
|
399
|
+
} catch (e) {
|
|
400
|
+
logger.error('Failed to process URL:', { url, page }, e);
|
|
401
|
+
return null;
|
|
402
|
+
} finally {
|
|
403
|
+
this.aggregatedPages.delete(url);
|
|
404
|
+
this.urlsToPersistedKeys.delete(url);
|
|
405
|
+
this.dirty.delete(url);
|
|
406
|
+
await this.db.remove(persistedKey).catch(console.warn);
|
|
407
|
+
}
|
|
408
|
+
}),
|
|
409
|
+
);
|
|
410
|
+
const promotedPages = allExpiredPages.filter((x) => x);
|
|
411
|
+
logger.info(
|
|
412
|
+
promotedPages.length,
|
|
413
|
+
'expired pages have been promoted to the next step:',
|
|
414
|
+
promotedPages,
|
|
415
|
+
);
|
|
416
|
+
return promotedPages;
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async _processExpiredPage(url, page) {
|
|
421
|
+
const reject = (reason) => {
|
|
422
|
+
logger.debug('Dropping page:', { url, reason, page });
|
|
423
|
+
return { promotedPage: null, reason };
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
const rejectForever = async (reason) => {
|
|
427
|
+
logger.info('Mark page as private:', { url, reason, page });
|
|
428
|
+
try {
|
|
429
|
+
await this.newPageApprover.markAsPrivate(url);
|
|
430
|
+
} catch (e) {
|
|
431
|
+
logger.error('Failed to mark url', url, 'as private', e);
|
|
432
|
+
}
|
|
433
|
+
return { promotedPage: null, reason };
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
// check that page has complete information
|
|
437
|
+
if (!page.preDoublefetch) {
|
|
438
|
+
return reject('incomplete information: preDoublefetch missing');
|
|
439
|
+
}
|
|
440
|
+
if (page.status !== 'complete') {
|
|
441
|
+
return reject('incomplete information: page not fully loaded');
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// check static heuristics
|
|
445
|
+
if (page.preDoublefetch.noindex) {
|
|
446
|
+
return rejectForever('marked as noindex');
|
|
447
|
+
}
|
|
448
|
+
if (page.search && page.search.depth === 0) {
|
|
449
|
+
return rejectForever('ignore search engine result pages');
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
return { promotedPage: page };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async flush() {
|
|
456
|
+
this._clearAutoFlush();
|
|
457
|
+
if (this.dirty.size === 0) {
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const pendingKeys = [...this.dirty];
|
|
462
|
+
this.dirty.clear();
|
|
463
|
+
if (this.verboseLogging) {
|
|
464
|
+
logger.debug(
|
|
465
|
+
'flushing',
|
|
466
|
+
pendingKeys.length,
|
|
467
|
+
'keys to disk:',
|
|
468
|
+
pendingKeys,
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const now = Date.now();
|
|
473
|
+
await Promise.all(
|
|
474
|
+
pendingKeys.map(async (url) => {
|
|
475
|
+
const entry = this.aggregatedPages.get(url);
|
|
476
|
+
if (entry) {
|
|
477
|
+
entry.aggregator.lastWrittenAt = now;
|
|
478
|
+
const persistedKey = this.urlsToPersistedKeys.get(url);
|
|
479
|
+
await this.db.set(persistedKey, entry);
|
|
480
|
+
} else {
|
|
481
|
+
logger.warn(
|
|
482
|
+
`Corrupted state: key=${url} marked as dirty, but not present. Ignoring and continuing...`,
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
}),
|
|
486
|
+
);
|
|
487
|
+
if (this.verboseLogging) {
|
|
488
|
+
logger.debug(pendingKeys.length, 'keys successfully written');
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
_markPageAsDirty(url) {
|
|
493
|
+
this.dirty.add(url);
|
|
494
|
+
if (!this._autoFlushTimer) {
|
|
495
|
+
this._autoFlushTimer = setTimeout(() => {
|
|
496
|
+
this.flush().catch(logger.error);
|
|
497
|
+
}, 100); // TODO: reconsider
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
_clearAutoFlush() {
|
|
502
|
+
if (this._autoFlushTimer) {
|
|
503
|
+
clearTimeout(this._autoFlushTimer);
|
|
504
|
+
this._autoFlushTimer = null;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Hopefully this should not be reached. It is a fail-safe if the extension starts
|
|
510
|
+
* producing more keys than it deletes. If this happen, it can only be because of a bug
|
|
511
|
+
* (or if the threshold was unrealistically small).
|
|
512
|
+
*/
|
|
513
|
+
async _emergencyCleanup(allKeys) {
|
|
514
|
+
logger.error(
|
|
515
|
+
`The keys on the profile ran full: ${allKeys.length} keys, but the limit is ${this.maxAllowedMappings}.`,
|
|
516
|
+
'Purging now to prevent performance impacts.',
|
|
517
|
+
);
|
|
518
|
+
|
|
519
|
+
// This is not an efficient to delete lots of values from IndexedDB;
|
|
520
|
+
// batching is done only to avoid freezing the browser when deleting possibly
|
|
521
|
+
// thousands of entries at the same time.
|
|
522
|
+
let count = 0;
|
|
523
|
+
for (const keyBatch of chunk(allKeys, 100)) {
|
|
524
|
+
await Promise.all(keyBatch.map((key) => this.db.remove(key)));
|
|
525
|
+
count += keyBatch.length;
|
|
526
|
+
logger.info(
|
|
527
|
+
`Emergency cleanup in progress: ${count} of ${allKeys.length} deleted`,
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
logger.info('Emergency cleanup finished:', count, 'keys deleted');
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
async _restoreKeysFromDisk() {
|
|
534
|
+
if (
|
|
535
|
+
this.aggregatedPages.size !== 0 ||
|
|
536
|
+
this.urlsToPersistedKeys.size !== 0 ||
|
|
537
|
+
this.dirty.size !== 0 ||
|
|
538
|
+
this.expiration.length !== 0
|
|
539
|
+
) {
|
|
540
|
+
throw new Error('Illegal state');
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
const allKeys = await this.db.keys();
|
|
544
|
+
if (allKeys.length > this.maxAllowedMappings) {
|
|
545
|
+
await this._emergencyCleanup(allKeys).catch((e) => {
|
|
546
|
+
logger.error('Unexpected error during emergency cleanup', e);
|
|
547
|
+
});
|
|
548
|
+
} else {
|
|
549
|
+
// preparation: validate keys and group by url
|
|
550
|
+
// (to verify that URLs in the keys are unique)
|
|
551
|
+
const now = Date.now();
|
|
552
|
+
const badKeys = [];
|
|
553
|
+
const groupedByUrl = new Map();
|
|
554
|
+
allKeys.forEach((key) => {
|
|
555
|
+
try {
|
|
556
|
+
const { createdAt, url } = parsePersistedKey(key);
|
|
557
|
+
if (createdAt > now + 5 * MINUTE) {
|
|
558
|
+
throw new Error(`Timestamp lies in the future: ${createdAt}`);
|
|
559
|
+
}
|
|
560
|
+
let entry = groupedByUrl.get(url);
|
|
561
|
+
if (entry) {
|
|
562
|
+
entry.push({ createdAt, url, key });
|
|
563
|
+
} else {
|
|
564
|
+
groupedByUrl.set(url, [{ createdAt, url, key }]);
|
|
565
|
+
}
|
|
566
|
+
} catch (e) {
|
|
567
|
+
logger.warn('Corrupted key detected:', key, e);
|
|
568
|
+
badKeys.push(key);
|
|
569
|
+
}
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
for (const group of groupedByUrl.values()) {
|
|
573
|
+
if (group.length === 1) {
|
|
574
|
+
const { createdAt, url, key } = group[0];
|
|
575
|
+
this.aggregatedPages.set(url, null); // pages are lazy loaded
|
|
576
|
+
this.urlsToPersistedKeys.set(url, key);
|
|
577
|
+
this.expiration.push({ url, createdAt });
|
|
578
|
+
} else {
|
|
579
|
+
const duplicatedKeys = group.map((x) => x.key);
|
|
580
|
+
logger.warn(
|
|
581
|
+
'Assumption violated that URLs are unique:',
|
|
582
|
+
duplicatedKeys,
|
|
583
|
+
);
|
|
584
|
+
badKeys.push(...duplicatedKeys);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
this.expiration.sort((x, y) => x.createdAt - y.createdAt);
|
|
588
|
+
|
|
589
|
+
if (badKeys.length > 0) {
|
|
590
|
+
await Promise.all(
|
|
591
|
+
badKeys.map(async (key) => {
|
|
592
|
+
try {
|
|
593
|
+
await this.db.remove(key);
|
|
594
|
+
} catch (e) {
|
|
595
|
+
logger.warn(`Failed to delete key=${key}`, e);
|
|
596
|
+
}
|
|
597
|
+
}),
|
|
598
|
+
);
|
|
599
|
+
logger.warn(badKeys.length, 'corrupted keys deleted:', badKeys);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Intended for debugging and testing only.
|
|
606
|
+
*/
|
|
607
|
+
async describeState({ inMemoryOnly = false } = {}) {
|
|
608
|
+
return this._dbLock.run(async () => {
|
|
609
|
+
const result = {
|
|
610
|
+
keys: {},
|
|
611
|
+
memory: {},
|
|
612
|
+
dirty: [...this.dirty],
|
|
613
|
+
};
|
|
614
|
+
if (!inMemoryOnly) {
|
|
615
|
+
result.disk = {};
|
|
616
|
+
}
|
|
617
|
+
await Promise.all(
|
|
618
|
+
[...this.aggregatedPages].map(async ([url, page]) => {
|
|
619
|
+
const key = this.urlsToPersistedKeys.get(url);
|
|
620
|
+
let state;
|
|
621
|
+
if (this.dirty.has(url)) {
|
|
622
|
+
state = 'dirty';
|
|
623
|
+
} else {
|
|
624
|
+
state = page !== null ? 'loaded' : 'not loaded';
|
|
625
|
+
}
|
|
626
|
+
result.keys[url] = {
|
|
627
|
+
state,
|
|
628
|
+
keyInDB: key,
|
|
629
|
+
};
|
|
630
|
+
result.memory[url] = page;
|
|
631
|
+
if (!inMemoryOnly) {
|
|
632
|
+
try {
|
|
633
|
+
result.disk[key] = await this.db.get(key);
|
|
634
|
+
} catch (e) {
|
|
635
|
+
logger.warn(
|
|
636
|
+
`Unable to load page from disk (url=${url}, persistedKey=${key})`,
|
|
637
|
+
e,
|
|
638
|
+
);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}),
|
|
642
|
+
);
|
|
643
|
+
return result;
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
async selfChecks(check = new SelfCheck()) {
|
|
648
|
+
if (this.aggregatedPages.size > this.maxAllowedMappings) {
|
|
649
|
+
check.warn('Number of persisted pages exceeds limits', {
|
|
650
|
+
numKeys: this.aggregatedPages.size,
|
|
651
|
+
limit: this.maxAllowedMappings,
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
const urls1 = [...this.aggregatedPages.keys()].sort();
|
|
655
|
+
const urls2 = [...this.urlsToPersistedKeys.keys()].sort();
|
|
656
|
+
const urls3 = this.expiration.map((x) => x.url).sort();
|
|
657
|
+
if (
|
|
658
|
+
!equalityCanBeProven(urls1, urls2) ||
|
|
659
|
+
!equalityCanBeProven(urls1, urls3)
|
|
660
|
+
) {
|
|
661
|
+
check.fail('Logical bug: data structures out of sync');
|
|
662
|
+
}
|
|
663
|
+
for (let i = 0; i < this.expiration.length - 1; i += 1) {
|
|
664
|
+
if (this.expiration[i].createdAt > this.expiration[i + 1].createdAt) {
|
|
665
|
+
check.fail('Logical bug: expirations are not ordered');
|
|
666
|
+
break;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
return check;
|
|
670
|
+
}
|
|
671
|
+
}
|