-
Notifications
You must be signed in to change notification settings - Fork 1
/
attributes.js
453 lines (393 loc) · 14 KB
/
attributes.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
447
448
449
450
451
452
453
/*
-----------------
ENVIRONMENT VALUES
-----------------
*/
// always on
export const PAGE_PROPS = {
"PAGE → full url (/)": decodeURIComponent(document.location.href),
"PAGE → short url (/)": decodeURIComponent(window.location.pathname),
// pash hashes should be private...
// "PAGE → hash (#)": window.location.hash,
"PAGE → url params (?)": qsToObj(window.location.search),
"PAGE → height": window.innerHeight,
"PAGE → width": window.innerWidth,
"PAGE → title": document.title,
"SESSION → # pages": window.history.length,
$source: "mpEZTrack"
};
export const DEVICE_PROPS = mixpanel => {
const { $os, $browser, $referrer, $referring_domain, $browser_version, $screen_height, $screen_width } = mixpanel._.info.properties();
//ugh side fx
mixpanel.ez.register_once({ "DEVICE → first referrer": $referrer, "DEVICE → first referring domain": $referring_domain });
return {
"DEVICE → operating system": $os,
"DEVICE → browser": $browser,
"DEVICE → browser version": $browser_version,
"DEVICE → last referrer": $referrer,
"DEVICE → last referring domain": $referring_domain,
"DEVICE → screen height (px)": $screen_height,
"DEVICE → screen width (px)": $screen_width,
"DEVICE → screen dim": `${window.screen?.width} x ${window.screen?.height}`,
"DEVICE → language": window.navigator.language,
"DEVICE → pixel ratio": window.devicePixelRatio,
// eslint-disable-next-line compat/compat
"DEVICE → bandwidth": window.navigator.connection ? window.navigator.connection.effectiveType : "unknown",
// eslint-disable-next-line compat/compat
"DEVICE → memory (GB)": window.navigator.deviceMemory ? window.navigator.deviceMemory : "unknown",
// eslint-disable-next-line compat/compat
"DEVICE → platform": window.navigator.userAgentData ? window.navigator.userAgentData.platform : "unknown",
// eslint-disable-next-line compat/compat
"DEVICE → is mobile?": window.navigator.userAgentData ? window.navigator.userAgentData.mobile : "unknown"
};
};
export const BLACKLIST_ELEMENTS = `*[type="password"], *[type="hidden"], *.sensitive, *.pendo-ignore, *[data-heap-redact-text], *[data-heap-redact-attributes], label`;
export const LISTENER_OPTIONS = {
passive: true
};
/*
------------------
SELECTORS + FIELDS
------------------
*/
export const STANDARD_FIELDS = (el, label = `ELEM`) => ({
[`${label} → classes`]: el.classList ? [...el.classList] : [],
[`${label} → height`]: el.offsetHeight,
[`${label} → width`]: el.offsetWidth,
[`${label} → tag (<>)`]: "".concat("<", el.tagName, ">"),
...conditionalFields(el, label),
...enumNodeProps(el, label)
});
export const LINK_SELECTORS = `a`;
export const LINK_FIELDS = (el, label = `LINK`) => ({
[`${label} → text`]: squish(el.textContent)
});
export const BUTTON_SELECTORS = `button, .button, .btn, input[type="button"], input[type="file"], input[type="image"], input[type="submit"], input[type="reset"]`;
export const BUTTON_FIELDS = el => ({
"BUTTON → text": squish(el.textContent)
});
export const FORM_SELECTORS = `form`;
export const FORM_FIELDS = el => ({
"FORM → # inputs": el.length,
"FORM → method": el.method,
"FORM → action": el.action,
"FORM → encoding": el.encoding
});
export const DROPDOWN_SELECTOR = `select, input[list], input[type="radio"], input[type="checkbox"], input[type="range"], input[type="color"], input[type="range"]`;
export const DROPDOWN_FIELDS = el => {
let props = {
"OPTION → user selected": el.value === "on" ? el.checked : el.value,
"OPTION → labels": [...el.labels].map(label => label.textContent?.trim())
};
// solve for possible choices
try {
let choices = el.innerText.split("\n");
if (choices.length > 1) {
props["OPTION → choices"] = choices;
} else if (el?.list) {
choices = [...el.list.children].map(opt => opt.value);
props["OPTION → choices"] = choices;
}
} catch (e) {
//noop
(() => {})();
}
return props;
};
export const INPUT_SELECTOR = `input[type="text"], input[type="email"], input[type="url"], input[type="search"], textarea`;
export const INPUT_FIELDS = el => ({
"CONTENT → user content": isSensitiveData(el.value) ? "******" : el.value,
"CONTENT → labels": [...el.labels].map(label => squish(label.textContent))
});
// 🚨 guard against sensitive fields 🚨
export const ALL_SELECTOR = `*:not(script):not(title):not(meta):not(link):not([type="password"])`;
export const ANY_TAG_FIELDS = (el, guard = false) => {
const fields = {
"ELEM → text": guard ? "******" : el.textContent?.trim() || el.value?.trim(),
"ELEM → is editable?": el.isContentEditable
};
if (isSensitiveData(fields["ELEM → text"])) {
fields["ELEM → text"] = "******";
}
return fields;
};
export const VIDEO_SELECTOR = `video`;
export const VIDEO_FIELDS = el => ({
"VIDEO → watch time": el.currentTime,
"VIDEO → total time": el.duration,
"VIDEO → watch %": Number(Number((el.currentTime / el.duration) * 100).toFixed(2)),
"VIDEO → autoplay?": el.autoplay,
"VIDEO → controls visible?": el.controls,
"VIDEO → loops?": el.loop,
"VIDEO → muted?": el.muted,
"VIDEO → thumbnail": el.poster,
"VIDEO → source(s)": el.src || [...el.querySelectorAll("source")].map(source => source.src),
"VIDEO → source type(s)": el.src.split(".").slice(-1)[0] || [...el.querySelectorAll("source")].map(source => source.type)
});
export const YOUTUBE_SELECTOR = `iframe`;
/*
---------
UTILITIES
---------
*/
export function enumNodeProps(el, label = "ELEM") {
const result = {};
// https://meiert.com/en/blog/boolean-attributes-of-html/
const boolAttrs = [
"allowfullscreen",
"async",
"autofocus",
"autoplay",
"checked",
"controls",
"default",
"defer",
"disabled",
"formnovalidate",
"ismap",
"itemscope",
"loop",
"multiple",
"muted",
"nomodule",
"novalidate",
"open",
"playsinline",
"readonly",
"required",
"reversed",
"selected",
"truespeed"
];
const replaceAttrs = {
"aria-": "DATA → ",
"data-": "DATA → ",
src: "source",
alt: "desc",
class: "class (delete)"
};
let potentialPassEl = false;
loopAttributes: for (var att, i = 0, atts = el.attributes, n = atts?.length || 0; i < n; i++) {
att = atts[i];
let potentialPassAttr = false;
let keySuffix = mapReplace(att.name, replaceAttrs);
let keyName = `${label} → ${keySuffix}`;
let val = att.value?.trim();
if (keySuffix?.toLowerCase()?.includes("pass")) {
potentialPassAttr = true;
potentialPassEl = true;
}
if (keySuffix?.startsWith("on")) continue loopAttributes; //skip inline js handlers
if (keySuffix === "nonce") continue loopAttributes; //skip crypto
if (keySuffix === "d") continue loopAttributes; //skip svg paths
if (boolAttrs.some(attr => attr === att.name)) {
//attrs which have no value are "boolean" and therefore true when present
val = true;
keyName += "?";
}
if (potentialPassAttr) val = `******`;
if (isSensitiveData(val)) val = `******`;
if (val) result[keyName] = val; //note value might be blank
}
//tags to delete
delete result[`${label} → class (delete)`];
delete result[`${label} → style`];
// 🚨 guard against sensitive fields
if (potentialPassEl) {
//scrub all data inputs
result[`${label} → user content`] = `******`;
result[`${label} → text`] = `******`;
result[`${label} → value`] = `******`;
}
return result;
}
export function conditionalFields(el, label = "ELEM") {
const results = {};
const labelString = `${label} → label`;
// LABELS
// sometimes labels are not explicitly tied to elements with <label for ="">
// in this case, we run around the dom, trying to find a label
if (Array.from(el?.labels || "").length === 0) {
// siblings
if (el.previousElementSibling?.nodeName === `LABEL`) {
results[labelString] = el.previousElementSibling.textContent.trim();
}
if (el.nextElementSibling?.nodeName === `LABEL`) {
results[labelString] = el.nextElementSibling.textContent.trim();
}
// parents + children
if (el.parentElement?.nodeName === `LABEL`) {
results[labelString] = el.parentElement.textContent.trim();
}
// todo: look through all children
if (el.childNodes?.[0]?.nodeName === `LABEL`) {
results[labelString] = el.childNodes[0].textContent.trim();
}
// labels can also be parent elements attrs
if (el.parentElement?.title) results[labelString] = el.parentElement.title.trim();
if (el.parentElement?.name) results[labelString] = el.parentElement.name.trim();
if (el.parentElement?.id) results[labelString] = el.parentElement.id.trim();
// if we haven't found anything recursively find the closest textContent by moving up the DOM
if (!results[labelString]) {
// eslint-disable-next-line no-inner-declarations
function findLabelRecursively(el) {
try {
if (!el) {
return false;
}
if (el.textContent) {
if (el.textContent.trim() !== "") {
results[labelString] = truncate(squish(el.textContent));
return true;
}
} else {
findLabelRecursively(el?.parentElement);
}
} catch (e) {
return false;
}
}
findLabelRecursively(el);
}
}
// CHECKBOXES
if (typeof el.checked === "boolean") {
results[`${label} → checked`] = el.checked;
}
if (typeof el.required === "boolean") {
results[`${label} → required?`] = el.checked;
}
// // CHILDREN
// if (el.childElementCount > 0) {
// results[`${label} → child`] = squish(el.innerHTML);
// }
return results;
}
/*
-------
HELPERS
-------
*/
export function linkOrNav(el) {
const href = el?.getAttribute("href") || "";
const linkType = {
eventName: ``,
label: ``
};
if (href?.startsWith("#")) {
linkType.eventName = `navigation`;
linkType.label = `NAV`;
} else if (href?.startsWith("/")) {
linkType.eventName = `navigation`;
linkType.label = `NAV`;
} else if (href?.startsWith(".")) {
linkType.eventName = `navigation`;
linkType.label = `NAV`;
} else if (href?.includes(this.host)) {
linkType.eventName = `navigation`;
linkType.label = `NAV`;
} else if (href?.startsWith("javascript")) {
linkType.eventName = `navigation`;
linkType.label = `NAV`;
} else if (!href) {
linkType.eventName = `navigation`;
linkType.label = `NAV`;
} else {
linkType.eventName = `link`;
linkType.label = `LINK`;
}
return linkType;
}
export function isSensitiveData(text = "") {
if (!text) return false;
const sensitiveTests = [isCreditCardNo, isSSN];
const tests = sensitiveTests.map(testFn => {
return testFn(text);
});
return tests.some(bool => bool);
}
export function escape(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
export function mapReplace(str, replacements) {
var regex = [];
for (var prop in replacements) {
regex.push(escape(prop));
}
regex = new RegExp(regex.join("|"), "g");
return str.replace(regex, function (match) {
return replacements[match];
});
}
export function squish(string = "") {
const CONSECUTIVE_SPACES = /\s+/g;
return string.trim().replace(CONSECUTIVE_SPACES, " ");
}
export function truncate(text, n = 50, useWordBoundary = true) {
if (!text) {
return "";
}
if (text.length <= n) {
return text;
}
var subString = text.substr(0, n - 1);
return (useWordBoundary ? subString.substr(0, subString.lastIndexOf(" ")) : subString) + "...";
}
export function qsToObj(queryString) {
try {
// eslint-disable-next-line compat/compat
const parsedQs = new URLSearchParams(queryString);
const params = Object.fromEntries(parsedQs);
return params;
} catch (e) {
return {};
}
}
export function isCreditCardNo(cardNo = "") {
// https://stackoverflow.com/a/30727110
if (!cardNo) return false;
if (typeof cardNo !== "string") cardNo = cardNo?.toString();
if (cardNo === "0") return false;
var s = 0;
var doubleDigit = false;
for (var i = cardNo.length - 1; i >= 0; i--) {
var digit = +cardNo[i];
if (doubleDigit) {
digit *= 2;
if (digit > 9) digit -= 9;
}
s += digit;
doubleDigit = !doubleDigit;
}
return s % 10 == 0;
}
export function isSSN(ssn = "") {
if (!ssn) return false;
// https://www.w3resource.com/javascript-exercises/javascript-regexp-exercise-15.php
var regexp = /^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$/;
if (regexp.test(ssn)) {
return true;
} else {
return false;
}
}
/*
-------
UNUSED
-------
*/
export function isHTML(str) {
try {
var doc = new DOMParser().parseFromString(str, "text/html");
return Array.from(doc.body.childNodes).some(node => node.nodeType === 1);
} catch (e) {
return false;
}
}
export function parseDatasetAttrs(dataset) {
try {
return { ...dataset };
} catch (e) {
return {};
}
}