summaryrefslogtreecommitdiff
path: root/data/extensions/jsr@javascriptrestrictor/fp_code_builders.js
blob: 4378a841b2dedb8b4f45f3aa4ab7883a5f6027f0 (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
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
/** \file
 * \brief Functions that help to automate process of building wrapping code for FPD module
 *
 *  \author Copyright (C) 2021  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/>.
//

/** \file
 *
 * \brief This file is part of Fingerprint Detector (FPD) and contains helper functions for automated wrappers creation. 
 * File also contains loading routine for FPD configuration files (groups-lvl_X.json, wrappers-lvl_X.json, etc...).
 *
 * \ingroup FPD
 */

//DEF_FPD_FILES_S
var fp_config_files = ["groups-lvl_0", "groups-lvl_1", "wrappers-lvl_0_1"]
//DEF_FPD_FILES_E

/**
 * The object carrying code for builded FPD wrappers
 */
var fp_wrapped_codes = {};

/**
 *  Object containing parsed input from JSON configuration files of FPD module.
 */
var fp_levels = {};

/**
 *  Additional wrappers for specialized purposes.
 */
var additional_wrappers = [
	{
		parent_object: "HTMLElement.prototype",
		parent_object_property: "offsetHeight",
		wrapped_objects: [],
		post_wrapping_code: [
			{
				code_type: "object_properties",
				parent_object: "HTMLElement.prototype",
				parent_object_property: "offsetHeight",
				wrapped_objects: [
					{
						original_name: `
							Object.getOwnPropertyDescriptor(HTMLElement.prototype, "offsetHeight") ? 
							Object.getOwnPropertyDescriptor(HTMLElement.prototype, "offsetHeight")["get"] : 
							HTMLElement.prototype.offsetHeight
						`,
						wrapped_name: "originalD_get"
					}
				],
				wrapped_properties: [
					{
						property_name: "get",
						property_value: `function() {
							// workaround - style property is bound to HTMLElement instance, check fontFamily value with every access
							let font = this.style.fontFamily;
							updateCount("CSSStyleDeclaration.prototype.fontFamily", "set", [font]);
							return originalD_get.call(this);
						}`
					}
				]
			}
		]
	},
	{
		parent_object: "HTMLElement.prototype",
		parent_object_property: "offsetWidth",
		wrapped_objects: [],
		post_wrapping_code: [
			{
				code_type: "object_properties",
				parent_object: "HTMLElement.prototype",
				parent_object_property: "offsetWidth",
				wrapped_objects: [
					{
						original_name: `
							Object.getOwnPropertyDescriptor(HTMLElement.prototype, "offsetWidth") ? 
							Object.getOwnPropertyDescriptor(HTMLElement.prototype, "offsetWidth")["get"] : 
							HTMLElement.prototype.offsetWidth
						`,
						wrapped_name: "originalD_get"
					}
				],
				wrapped_properties: [
					{
						property_name: "get",
						property_value: `function() {
							// workaround - style property is bound to HTMLElement instance, check fontFamily value with every access
							let font = this.style.fontFamily;
							updateCount("CSSStyleDeclaration.prototype.fontFamily", "set", [font]);
							return originalD_get.call(this);
						}`
					}
				]
			}
		]
	}
]

/// \cond (Exclude this section from the doxygen documentation. If this section is not excluded, it is documented as a separate function.)
{
	// parse input files into fp_levels for each level, generate wrapping code and initialize FPD module
	let loadFpdConfig = async () => {
		for (let file of fp_config_files) {
			try {
				let config = JSON.parse(await readFile(browser.runtime.getURL(`fp_config/${file}.json`)));
				let file_splitted = file.split("-");
				let file_levels = file_splitted[1].split("_").filter(x => x != 'lvl');			
				fp_levels[file_splitted[0]] = fp_levels[file_splitted[0]] || {};
				for (let level of file_levels) {
					fp_levels[file_splitted[0]][level] = config;
				}
			}
			catch (e) {
				console.error(e);
			}
		}

		// merge duplicit entries of the same resource to be wrapped only once
		let mergeWrappers = (sameResources) => {
			let mergeGroups = () => {
				let accArray = [];
				for (let resource of sameResources) {
					accArray.push(...resource.groups);
				}
				return accArray;
			}

			return {
				resource: sameResources[0].resource,
				type: sameResources[0].type,
				groups: mergeGroups()
			}
		}

		for (let level in fp_levels.wrappers) {
			let tmpWrappers = {};
			for (let wrapper of fp_levels.wrappers[level]) {
				if (!Object.keys(tmpWrappers).includes(wrapper.resource)) {
					let sameResources = fp_levels.wrappers[level].filter(x => x.resource == wrapper.resource);
					tmpWrappers[wrapper.resource] = mergeWrappers(sameResources);
				}
			}
			fp_levels.wrappers[level] = Object.values(tmpWrappers);
		}

		for (let level in fp_levels.wrappers) {
			// define wrapper for each FPD endpoint (using default JSS definition of wrappers)
			let tmp_build_wrapping_code = {};
			for (let wrap_item of fp_levels.wrappers[level]) {
				if (wrap_item.type == "property") {
					tmp_build_wrapping_code[wrap_item.resource] = fp_build_property_wrapper(wrap_item);
				}
				else if (wrap_item.type == "function") {
					tmp_build_wrapping_code[wrap_item.resource] = fp_build_function_wrapper(wrap_item);
				}
			}
				
			// if there is an additional wrapper for resource, overwrite default definition with it
			for (let additional_item of additional_wrappers) {
				let { parent_object, parent_object_property } = additional_item;
				let resource = `${parent_object}.${parent_object_property}`;			
				if (resource in tmp_build_wrapping_code) {
					tmp_build_wrapping_code[resource] = additional_item;
				}
			}

			// transform each wrapper to wrapping code and index it in memory for quick access
			fp_wrapped_codes[level] = {};
			for (let build_item in tmp_build_wrapping_code) {
				try {
					fp_wrapped_codes[level][build_item] = build_code(tmp_build_wrapping_code[build_item]);
				} catch (e) {
					console.error(e);
					fp_wrapped_codes[level][build_item] = "";
				}
			}
		}

		// initialize FPD module (background script and event listeners)
		initFpd();
	}
	loadFpdConfig();
}
/// \endcond

/**
 * The function that appends FPD wrappers into injectable code, if JSS hasn't wrapped certain FPD endpoints already.
 *
 * \param code String containing injectable code generated by "generate_code" method.
 * \param jss_wrappers Array of wrappers defined by JSS level object.
 * \param fpd_level Identifier of the current FPD level/config.
 * 
 * \returns Modified injectable code that also contains FPD wrapping code.
 */
function fp_update_wrapping_code(code, jss_wrappers, fpd_level) {
	let fpd_wrappers = Object.keys(fp_wrapped_codes[fpd_level])
		.filter(key => !jss_wrappers.map(x => x[0]).includes(key))
		.reduce((obj, key) => {
			obj[key] = fp_wrapped_codes[fpd_level][key];
			return obj;
		}, {});
	let fpd_code = joinWrappingCode(Object.values(fpd_wrappers));
	return code.replace("// FPD_S\n", `// FPD_S\n ${fpd_code}`);
}

/**
 * The function that creates injectable code specifically for FPD wrappers in case that JSS hasn't wrapped anything.
 *
 * \param fpd_level Identifier of the current FPD level/config.
 * 
 * \returns Injectable code containing only FPD wrapping code.
 */
function fp_generate_wrapping_code(fpd_level) {
	return generate_code("// FPD_S\n" + joinWrappingCode(Object.values(fp_wrapped_codes[fpd_level])) + "\n// FPD_E");
}

/**
 * The function splitting resource string into path and name.
 * For example: "window.navigator.userAgent" => path: "window.navigator", name: "userAgent"
 *
 * \param wrappers text String representing full name of resource.
 * 
 * \returns Object consisting of two properties (path, name) for given resource.
 */
function split_resource(text) {
    var index = text.lastIndexOf('.');
    return { 
		path: text.slice(0, index),
		name: text.slice(index + 1) 
	}
}

/**
 * The function that constructs implicit property wrapper object from FPD configuration.
 * 
 * \param wrap_item Single resource object from FPD wrappers definition.
 * 
 * \returns New declarative property wrapper supported by code_builder (same structure as explicitly defined wrappers).
 */
function fp_build_property_wrapper(wrap_item) {
	// return object initialization
	var wrapper_object = {};
	
	// get unique array of property types (set, get), if property not defined => implicit get
	var propTypes = Array.from(new Set(wrap_item.groups.map(
		(x) => { return x.property != undefined ? x.property : "get" })));

	// if properties to wrap exist, create property wrapper based on wrap_item input
	if (propTypes.size != 0) {
		var resource_splitted = split_resource(wrap_item.resource);
		wrapper_object = {
			parent_object: resource_splitted["path"],
			parent_object_property: resource_splitted["name"],
			wrapped_objects: [],
			post_wrapping_code: [
				{
					code_type: "object_properties",
					parent_object: resource_splitted["path"],
					parent_object_property: resource_splitted["name"],
					wrapped_objects: [],
					wrapped_properties: [],
				}
			],
		};

		// create post_wrapping_code to wrap every property type
		for (let type of propTypes) {

			// save original resource - get property from descriptor, if do not exists, save it directly
			wrapper_object.post_wrapping_code[0].wrapped_objects.push({
				original_name: `
					Object.getOwnPropertyDescriptor(${resource_splitted["path"]}, "${resource_splitted["name"]}") ?
					Object.getOwnPropertyDescriptor(${resource_splitted["path"]}, "${resource_splitted["name"]}")["${type}"] :
					${type == "get" ? wrap_item.resource : undefined}
				`,
				wrapped_name: `originalD_${type}`,
			});

			// return original property (do not change semantics)
			wrapper_object.post_wrapping_code[0].wrapped_properties.push({
				property_name: type,
				property_value: `
					originalD_${type}
				`,
			})
		};
	}
	return wrapper_object;
}

/**
 * The function that constructs implicit function wrapper object from FPD configuration.
 * 
 * \param wrap_item Single resource object from FPD wrappers definition.
 * 
 * \returns New declarative function wrapper supported by code_builder (same structure as explicitly defined wrappers).
 */
function fp_build_function_wrapper(wrap_item) {
	var resource_splitted = split_resource(wrap_item.resource);
	
	var wrapper_object = {
		parent_object: resource_splitted["path"],
		parent_object_property: resource_splitted["name"],

		// save original function into variable
		wrapped_objects: [{
			original_name: `${resource_splitted["path"]}.${resource_splitted["name"]}`,
			wrapped_name: `originalF_${resource_splitted["name"]}`
		}],
		wrapping_function_args: "...args",
		
		// call original function on return with same arguments and context (do not change semantics)
		wrapping_function_body: `
			return originalF_${resource_splitted["name"]}.call(this, ...args);
		`,
	};
	return wrapper_object;
}