Skip to content

Commit

Permalink
add log helpers & refactor logging in scriptlets
Browse files Browse the repository at this point in the history
  • Loading branch information
stanislav-atr committed Nov 11, 2022
1 parent 959fe50 commit dfd8ce1
Show file tree
Hide file tree
Showing 32 changed files with 185 additions and 132 deletions.
2 changes: 1 addition & 1 deletion src/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export * from './adjust-set-utils';
export * from './array-utils';
export * from './constants';
export * from './cookie-utils';
export * from './log-utils';
export * from './noop-utils';
export * from './number-utils';
export * from './object-utils';
Expand All @@ -22,7 +23,6 @@ export * from './get-descriptor-addon';
export * from './get-property-in-chain';
export * from './get-wildcard-property-in-chain';
export * from './hit';
export * from './logMessage';
export * from './match-request-props';
export * from './match-stack';
export * from './observer';
Expand Down
22 changes: 22 additions & 0 deletions src/helpers/log-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Logs message to console.
* Used when logging is a part of a scriptlet's functionality.
* @param {string} message
*/
export const logMessage = (message) => {
// eslint-disable-next-line no-console
console.log(message);
};

/**
* Logs message to console in debug mode.
* Used to log errors, such as exceptions, invalid input etc.
* @param {string} message
* @param {boolean} verbose
*/
export const logVerbose = (message, verbose) => {
if (verbose) {
// eslint-disable-next-line no-console
console.log(message);
}
};
6 changes: 5 additions & 1 deletion src/scriptlets/abort-current-inline-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
startsWith,
createOnErrorHandler,
hit,
logVerbose,
// following helpers should be imported and injected
// because they are used by helpers above
isEmptyObject,
Expand Down Expand Up @@ -139,7 +140,9 @@ export function abortCurrentInlineScript(source, property, search) {
const props = property.split('.');
const propIndex = props.indexOf(prop);
const baseName = props[propIndex - 1];
console.log(`The scriptlet had been executed before the ${baseName} was loaded.`); // eslint-disable-line no-console, max-len

const message = `The scriptlet had been executed before the ${baseName} was loaded.`;
logVerbose(message, source.verbose);
return;
}

Expand Down Expand Up @@ -233,6 +236,7 @@ abortCurrentInlineScript.injections = [
startsWith,
createOnErrorHandler,
hit,
logVerbose,
isEmptyObject,
getDescriptorAddon,
];
5 changes: 3 additions & 2 deletions src/scriptlets/abort-on-stack-trace.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
isValidStrPattern,
matchStackTrace,
getDescriptorAddon,
logVerbose,
// following helpers are needed for helpers above
escapeRegExp,
toRegExp,
Expand Down Expand Up @@ -76,8 +77,7 @@ export function abortOnStackTrace(source, property, stack) {
}

if (!isValidStrPattern(stack)) {
// eslint-disable-next-line no-console
console.log(`Invalid parameter: ${stack}`);
logVerbose(`Invalid parameter: ${stack}`, source.verbose);
return;
}

Expand Down Expand Up @@ -138,6 +138,7 @@ abortOnStackTrace.injections = [
escapeRegExp,
matchStackTrace,
getDescriptorAddon,
logVerbose,
toRegExp,
isEmptyObject,
getNativeRegexpTest,
Expand Down
9 changes: 5 additions & 4 deletions src/scriptlets/adjust-setInterval.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
toRegExp,
getBoostMultiplier,
isDelayMatched,
logVerbose,
// following helpers are needed for helpers above
nativeIsNaN,
nativeIsFinite,
Expand Down Expand Up @@ -70,10 +71,9 @@ export function adjustSetInterval(source, matchCallback, matchDelay, boost) {
const intervalWrapper = (callback, delay, ...args) => {
// https://github.com/AdguardTeam/Scriptlets/issues/221
if (!isValidCallback(callback)) {
if (source.verbose) {
// eslint-disable-next-line no-console, max-len
console.log(`Scriptlet adjust-setInterval can not be applied because of invalid callback: '${String(callback)}'.`);
}
// eslint-disable-next-line max-len
const message = `Scriptlet adjust-setInterval can not be applied because of invalid callback: '${String(callback)}'.`;
logVerbose(message, source.verbose);
} else if (matchRegexp.test(callback.toString()) && isDelayMatched(matchDelay, delay)) {
delay *= getBoostMultiplier(boost);
hit(source);
Expand All @@ -100,6 +100,7 @@ adjustSetInterval.injections = [
toRegExp,
getBoostMultiplier,
isDelayMatched,
logVerbose,
// following helpers should be injected as helpers above use them
nativeIsNaN,
nativeIsFinite,
Expand Down
9 changes: 5 additions & 4 deletions src/scriptlets/adjust-setTimeout.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
toRegExp,
getBoostMultiplier,
isDelayMatched,
logVerbose,
// following helpers are needed for helpers above
nativeIsNaN,
nativeIsFinite,
Expand Down Expand Up @@ -70,10 +71,9 @@ export function adjustSetTimeout(source, matchCallback, matchDelay, boost) {
const timeoutWrapper = (callback, delay, ...args) => {
// https://github.com/AdguardTeam/Scriptlets/issues/221
if (!isValidCallback(callback)) {
if (source.verbose) {
// eslint-disable-next-line no-console, max-len
console.log(`Scriptlet adjust-setTimeout can not be applied because of invalid callback: '${String(callback)}'.`);
}
// eslint-disable-next-line max-len
const message = `Scriptlet adjust-setTimeout can not be applied because of invalid callback: '${String(callback)}'.`;
logVerbose(message, source.verbose);
} else if (matchRegexp.test(callback.toString()) && isDelayMatched(matchDelay, delay)) {
delay *= getBoostMultiplier(boost);
hit(source);
Expand Down Expand Up @@ -102,6 +102,7 @@ adjustSetTimeout.injections = [
toRegExp,
getBoostMultiplier,
isDelayMatched,
logVerbose,
// following helpers should be injected as helpers above use them
nativeIsNaN,
nativeIsFinite,
Expand Down
23 changes: 13 additions & 10 deletions src/scriptlets/close-window.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { hit, toRegExp } from '../helpers/index';
import {
hit,
toRegExp,
logVerbose,
} from '../helpers/index';

/**
* @scriptlet close-window
Expand Down Expand Up @@ -28,15 +32,10 @@ import { hit, toRegExp } from '../helpers/index';
* ```
*/
export function forceWindowClose(source, path = '') {
// eslint-disable-next-line no-console
const log = console.log.bind(console);

// https://github.com/AdguardTeam/Scriptlets/issues/158#issuecomment-993423036
if (typeof window.close !== 'function') {
if (source.verbose) {
log('window.close() is not a function so \'close-window\' scriptlet is unavailable');
}
return;
const message = 'window.close() is not a function so \'close-window\' scriptlet is unavailable';
logVerbose(message, source.verbose);
}

const closeImmediately = () => {
Expand All @@ -46,7 +45,7 @@ export function forceWindowClose(source, path = '') {
} catch (e) {
// log the error if window closing is impossible
// https://developer.mozilla.org/en-US/docs/Web/API/Window/close
log(e);
logVerbose(e, source.verbose);
}
};

Expand Down Expand Up @@ -86,4 +85,8 @@ forceWindowClose.names = [
'ubo-window-close-if',
];

forceWindowClose.injections = [hit, toRegExp];
forceWindowClose.injections = [
hit,
toRegExp,
logVerbose,
];
6 changes: 5 additions & 1 deletion src/scriptlets/debug-current-inline-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
toRegExp,
createOnErrorHandler,
hit,
logVerbose,
// following helpers should be imported and injected
// because they are used by helpers above
isEmptyObject,
Expand Down Expand Up @@ -79,7 +80,9 @@ export function debugCurrentInlineScript(source, property, search) {
const props = property.split('.');
const propIndex = props.indexOf(prop);
const baseName = props[propIndex - 1];
console.log(`The scriptlet had been executed before the ${baseName} was loaded.`); // eslint-disable-line no-console, max-len

const message = `The scriptlet had been executed before the ${baseName} was loaded.`;
logVerbose(message, source.verbose);
return;
}

Expand Down Expand Up @@ -127,5 +130,6 @@ debugCurrentInlineScript.injections = [
toRegExp,
createOnErrorHandler,
hit,
logVerbose,
isEmptyObject,
];
13 changes: 8 additions & 5 deletions src/scriptlets/json-prune.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import {
hit,
matchStackTrace,
getWildcardPropertyInChain,
logVerbose,
logMessage,
// following helpers are needed for helpers above
toRegExp,
getWildcardSymbol,
Expand Down Expand Up @@ -89,8 +91,7 @@ export function jsonPrune(source, propsToRemove, requiredInitialProps, stack) {
if (!!stack && !matchStackTrace(stack, new Error().stack)) {
return;
}
// eslint-disable-next-line no-console
const log = console.log.bind(console);

const prunePaths = propsToRemove !== undefined && propsToRemove !== ''
? propsToRemove.split(/ +/)
: [];
Expand All @@ -111,7 +112,7 @@ export function jsonPrune(source, propsToRemove, requiredInitialProps, stack) {
const matchRegex = toRegExp(requiredPaths.join(''));
const shouldLog = matchRegex.test(rootString);
if (shouldLog) {
log(window.location.hostname, root);
logMessage(`${window.location.hostname} ${root}`);
shouldProcess = false;
return shouldProcess;
}
Expand Down Expand Up @@ -157,7 +158,7 @@ export function jsonPrune(source, propsToRemove, requiredInitialProps, stack) {
*/
const jsonPruner = (root) => {
if (prunePaths.length === 0 && requiredPaths.length === 0) {
log(window.location.hostname, root);
logMessage(`${window.location.hostname} ${root}`);
return root;
}

Expand All @@ -178,7 +179,7 @@ export function jsonPrune(source, propsToRemove, requiredInitialProps, stack) {
});
});
} catch (e) {
log(e.toString());
logVerbose(e.toString(), source.verbose);
}

return root;
Expand Down Expand Up @@ -229,6 +230,8 @@ jsonPrune.injections = [
hit,
matchStackTrace,
getWildcardPropertyInChain,
logVerbose,
logMessage,
toRegExp,
getWildcardSymbol,
getNativeRegexpTest,
Expand Down
20 changes: 11 additions & 9 deletions src/scriptlets/log-addEventListener.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import {
validateListener,
listenerToString,
convertTypeToString,
logMessage,
logVerbose,
// following helpers are needed for helpers above
objectToString,
isEmptyObject,
Expand All @@ -25,22 +27,20 @@ import {
* ```
*/
export function logAddEventListener(source) {
// eslint-disable-next-line no-console
const log = console.log.bind(console);
const nativeAddEventListener = window.EventTarget.prototype.addEventListener;

function addEventListenerWrapper(type, listener, ...args) {
if (validateType(type) && validateListener(listener)) {
const logMessage = `addEventListener("${type}", ${listenerToString(listener)})`;
log(logMessage);
const message = `addEventListener("${type}", ${listenerToString(listener)})`;
logMessage(message);
hit(source);
} else if (source.verbose) {
// logging while debugging
const logMessage = `Invalid event type or listener passed to addEventListener:
}

// logging while debugging
const message = `Invalid event type or listener passed to addEventListener:
type: ${convertTypeToString(type)}
listener: ${convertTypeToString(listener)}`;
log(logMessage);
}
logVerbose(message);

return nativeAddEventListener.apply(this, [type, listener, ...args]);
}
Expand Down Expand Up @@ -74,6 +74,8 @@ logAddEventListener.injections = [
validateListener,
listenerToString,
convertTypeToString,
logMessage,
logVerbose,
objectToString,
isEmptyObject,
getObjectEntries,
Expand Down
11 changes: 5 additions & 6 deletions src/scriptlets/log-eval.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable no-console, no-eval */
import { hit } from '../helpers/index';
/* eslint-disable no-eval */
import { hit, logMessage } from '../helpers/index';

/**
* @scriptlet log-eval
Expand All @@ -13,12 +13,11 @@ import { hit } from '../helpers/index';
* ```
*/
export function logEval(source) {
const log = console.log.bind(console);
// wrap eval function
const nativeEval = window.eval;
function evalWrapper(str) {
hit(source);
log(`eval("${str}")`);
logMessage(`eval("${str}")`);
return nativeEval(str);
}
window.eval = evalWrapper;
Expand All @@ -28,7 +27,7 @@ export function logEval(source) {

function FunctionWrapper(...args) {
hit(source);
log(`new Function(${args.join(', ')})`);
logMessage(`new Function(${args.join(', ')})`);
return nativeFunction.apply(this, [...args]);
}

Expand All @@ -42,4 +41,4 @@ logEval.names = [
'log-eval',
];

logEval.injections = [hit];
logEval.injections = [hit, logMessage];
6 changes: 5 additions & 1 deletion src/scriptlets/nowebrtc.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import {
hit,
noopFunc,
logVerbose,
convertRtcConfigToString,
} from '../helpers/index';

Expand Down Expand Up @@ -35,7 +36,9 @@ export function nowebrtc(source) {

const rtcReplacement = (config) => {
// eslint-disable-next-line max-len
hit(source, `Document tried to create an RTCPeerConnection: ${convertRtcConfigToString(config)}`);
const message = `Document tried to create an RTCPeerConnection: ${convertRtcConfigToString(config)}`;
logVerbose(message, source.verbose);
hit(source);
};
rtcReplacement.prototype = {
close: noopFunc,
Expand Down Expand Up @@ -66,5 +69,6 @@ nowebrtc.names = [
nowebrtc.injections = [
hit,
noopFunc,
logVerbose,
convertRtcConfigToString,
];
Loading

0 comments on commit dfd8ce1

Please sign in to comment.