summaryrefslogtreecommitdiff
path: root/data/extensions/jsr@javascriptrestrictor/fp_report.js
blob: f9f44e36c71b9ed37a27a96e2d0864692486df40 (plain)
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
/** \file
 * \brief Functions that summarize fingerprints and generate FPD report
 * \ingroup FPD
 *
 *  \author Copyright (C) 2022  Marek Salon
 *
 *  \license 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/>.
//

let hiddenTraces = {};

/**
 * Event listener that listens for a load of FPD report page. If the page is loaded, fetch FPD data from background.
 *
 * \param callback Function that initializes FPD report creation from fetched data.
 */
window.addEventListener('load', () => {
	browser.runtime.sendMessage({
		purpose: "fpd-get-report-data",
		tabId: new URLSearchParams(window.location.search).get("id")
	}).then((result) => {
		createReport(result);
	});
});

/**
 * The function that populates FPD report page with data from the latest evaluation and hooks up listeners.
 *
 * \param data Information about latest fingerprinting evaluation consisting of all essential FPD objects.
 */
function createReport(data) {
	var {tabObj, groups, latestEvals, fpDb, exceptionWrappers} = data;
	var reportContainer = document.getElementById("fpd-report-container");
	if (!tabObj || !groups || !groups.root || !groups.all || !fpDb || !latestEvals) {
		report.innerHTML =`<div class="alert">${browser.i18n.getMessage("FPDReportMissingData")}</div>`;
		return;
	}

	// parse latestEvals to create more useful representation for FPD report generation
	var processedEvals = {};
	for (let item of latestEvals.evalStats) {
		processedEvals[item.title] = processedEvals[item.title] || {};
		processedEvals[item.title].type = item.type;
		let total = 0;
		if (fpDb[item.title]) {
			for (let stat of Object.values(fpDb[item.title])) {
				total += stat.total;
			}
		}
		processedEvals[item.title].total = total;
	}

	// add page URL and FavIcon to header section of the report
	if (tabObj) {
		let urlObj = new URL(tabObj.url);
		var url = urlObj.hostname + (urlObj.pathname.length > 1 ? urlObj.pathname : "");
		document.getElementById("report-url").innerHTML = url;
		let img = document.getElementById("pageFavicon");
		img.src = tabObj.favIconUrl;
	}

	var html = "";

	// generate html code for evaluated group
	let generateGroup = (group) => {
		if (processedEvals[group]) {
			if (groups.all[group].description) {
				html += "<div id=\"" + group + "\" class=\"fpd-group access\">";
				html += "<h2>" + group + "</h2>";
				html += `<button class="help" id="expand${group}" >⤵</button>`;
				html += "<section>";
				html += "<p>" + groups.all[group].description + "</p>";
			}
			for (let [item, type] of Object.entries(groups.all[group].items)) {
				if (type == "group") {
					generateGroup(item);
				}
				else {
					generateResource(item)
				}
			}
			if (groups.all[group].description) {
				html += "</section></div>";
			}
		}
	}

	// generate html code for evaluated resource (get,set,call)
	let generateResource = (resource) => {
		if (processedEvals[resource]) {
			let callers = "";
			if (fpDb[resource]) {
				for (let t of Object.values(fpDb[resource])) {
					let traces = Object.keys(t.callers);
					for (trace of traces) {
						if (trace !== "" && !(trace in hiddenTraces)) {
							callers += "<p>" + trace.replace(/\n/g, '<br>') + "</p>";
						}
					}
				}
			}
			let accessRaw = processedEvals[resource].total;
			let accessCount = accessRaw >= 1000 ? "1000+" : accessRaw;
			html += `<div class="details ${accessRaw > 0 ? "access" : "no-access"}"><h4><span class="dot">-</span> ` +
			`${resource} (${exceptionWrappers.includes(resource) ? "n/a" : accessCount})</h4>\n${callers}</div>`;
		}
	}

	// start generating FPD report from the first group (root group)
	generateGroup(groups.root);
	var report = document.getElementById("fpd-report");
	report.innerHTML = html;

	// process generated document
	let groupElements = document.querySelectorAll(".fpd-group.access");
	for (let i = groupElements.length; i > 0; i--) {
		// remove duplicit entries from groups
		let duplicitArray = [];
		let elements = groupElements[i-1].querySelectorAll(":scope > section > div.details > h4");
		elements.forEach((d) => {
			if (duplicitArray.indexOf(d.innerHTML) > -1) {
				d.remove();
			}
			else {
				duplicitArray.push(d.innerHTML);
			}
		});

		// hide groups with no relevant entries
		if (!document.querySelectorAll(`#${groupElements[i-1].id} > section > .access`).length) {
			groupElements[i-1].classList.replace("access", "no-access");
		}
	}

	// function that enables to show accessed resources of the group
	function toggleResources(event) {
		let parent =  event.target.parentElement;
		for (let i = 0; i < parent.children.length; i++) {
			let child = parent.children[i];
			if (child.tagName == "SECTION") {
				child.classList.toggle("hidden");
			}
		}
	}

	// make group name clickable only if it makes sense - groups with resources
	function makeGroupExpansionsClickable() {
		for (let element of document.querySelectorAll(".fpd-group")) {
			let button;

			for (let i = 0; i < element.children.length; i++) {
				let child = element.children[i];
				if (child.tagName == "BUTTON") {
					button = child;
				}
			}

			if (button) {
				button.classList.add("clickable");
				button.addEventListener("click", toggleResources);
			}
		}
	}
	makeGroupExpansionsClickable();

	// show resources for every group in FPD report
	let showAll = (event) => {
		for (let element of document.querySelectorAll(".fpd-group div.details")) {
			element.classList.remove("hidden");
		}
		showBtn.classList.add("hidden");
		hideBtn.classList.remove("hidden");
	}

	// hide resources for every group in FPD report
	let hideDetails = (event) => {
		for (let element of document.querySelectorAll(".fpd-group div.details")) {
			element.classList.add("hidden");
		}
		showBtn.classList.remove("hidden");
		hideBtn.classList.add("hidden");
	}
	hideDetails();

	// refresh data in the report
	function refreshReport() {
		browser.runtime.sendMessage({
			purpose: "fpd-get-report-data",
			tabId: tabId
		}).then((result) => {
			createReport(result);
			showAll();
		});
		browser.runtime.sendMessage({purpose: "fpd-track-callers-stop"});
		document.getElementById("updateReportBtn").classList.remove("hidden");
		document.getElementById("forgetCurrentBtn").classList.remove("hidden");
		let trackCallersBtn = document.getElementById("trackCallersBtn");
		trackCallersBtn.innerText = browser.i18n.getMessage("FPDReportTrackCallersRestart");
		trackCallersBtn.classList.remove("hidden");
	}

	// Reload the report with data on the identity of the calling scripts
	function trackCallers() {
		tabId = new URLSearchParams(window.location.search).get("id");
		function onReloaded() {
			setTimeout(refreshReport, 5000);
			report.innerHTML = browser.i18n.getMessage("FPDReportTrackCallersWaiting");
			document.getElementById("trackCallersBtn").classList.add("hidden");
			document.getElementById("updateReportBtn").classList.add("hidden");
			document.getElementById("forgetCurrentBtn").classList.add("hidden");
		}
		function onError(error) {
			document.getElementById("fpdError").innerHTML = browser.i18n.getMessage("FPDReportTrackCallersFailed", error);
			browser.runtime.sendMessage({purpose: "fpd-track-callers-stop"});
		}
		browser.runtime.sendMessage({
			purpose: "fpd-track-callers",
			tabId: tabId
		}).then(onReloaded, onError);
	}

	function updateReport() {
	}

	// show all groups/resources even if not accessed
	let showNotAccessed = () => {
		for (let element of document.querySelectorAll(".no-access")) {
			element.classList.remove("no-access");
		}
		makeGroupExpansionsClickable();
	}

	function forgetTraces() {
		for (resource of Object.values(fpDb)) {
			for (type of Object.values(resource)) {
				for (trace of Object.keys(type.callers)) {
					hiddenTraces[trace] = true;
				}
			}
		}
		createReport(data);
	}

	// create on-site JSON representation of FPD evaluation data and download it
	function exportReport(filename) {
		let element = document.createElement("a");
		let obj = {
			fpd_evaluation_statistics: latestEvals.evalStats,
			fpd_access_logs: fpDb
		}
		element.setAttribute("href", "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj)));
		element.setAttribute("download", filename);
		element.style.display = "none";
		document.body.appendChild(element);
		element.click();
		document.body.removeChild(element);
	}

	document.getElementById("showBtn").onclick = showAll;
	document.getElementById("hideBtn").onclick = hideDetails;
	document.getElementById("exportBtn").onclick = exportReport.bind(null, `fpd_report_${url}.json`);
	document.getElementById("trackCallersBtn").onclick = trackCallers;
	document.getElementById("forgetCurrentBtn").onclick = forgetTraces;
	document.getElementById("updateReportBtn").onclick = refreshReport;
	document.getElementById("unhideAll").onclick = showNotAccessed;
}

// show description/help for the report
let showDescription = () => {
	for (let element of document.querySelectorAll(".description")) {
		element.classList.toggle("hidden");
	}
}

window.addEventListener("DOMContentLoaded", function() {
	document.getElementById("titletext").innerHTML += '<button id="help" class="help">?</button>';
	document.getElementById("help").addEventListener("click", showDescription);
});