Skip to content

Commit

Permalink
AG-20095 Fix 'trusted-set-cookie-reload' — website is not reloaded if…
Browse files Browse the repository at this point in the history
… '$now$' value is used. #291

Squashed commit of the following:

commit 67987c5
Author: Slava Leleka <[email protected]>
Date:   Fri Apr 28 17:21:53 2023 +0300

    fix changelog link

commit c9679ed
Author: Adam Wróblewski <[email protected]>
Date:   Fri Apr 28 16:10:29 2023 +0200

    Remove unnecessary tests
    Use toBeTruthy() instead of toBe(true) in tests
    Add better comment about path in clearCookie function
    Move fix to unreleased section in changelog

commit 91abfd2
Author: Adam Wróblewski <[email protected]>
Date:   Fri Apr 28 15:05:31 2023 +0200

    Add information about jest to readme
    Mock console.trace to fix errors in jest tests

commit c5c53db
Author: Maxim Topciu <[email protected]>
Date:   Fri Apr 28 15:34:54 2023 +0300

    AG-20095 rename test to spec

commit c39dbc2
Author: Maxim Topciu <[email protected]>
Date:   Fri Apr 28 14:14:24 2023 +0300

    Add yarn test to package.json

commit ecc65f6
Merge: 085a374 402972c
Author: Adam Wróblewski <[email protected]>
Date:   Fri Apr 28 13:13:22 2023 +0200

    Merge branch 'master' into fix/AG-20095

commit 085a374
Author: Adam Wróblewski <[email protected]>
Date:   Thu Apr 27 20:37:50 2023 +0200

    Use jest test for trusted-set-cookie-reload
    Use better approach to check cookie

commit 6ac14db
Author: Adam Wróblewski <[email protected]>
Date:   Mon Apr 3 12:01:23 2023 +0200

    Fix 'trusted-set-cookie-reload' — website is not reloaded if '$now$' value is used
  • Loading branch information
AdamWr committed Apr 28, 2023
1 parent 402972c commit 30a951a
Show file tree
Hide file tree
Showing 8 changed files with 1,871 additions and 28 deletions.
10 changes: 9 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ module.exports = {
env: {
browser: true,
qunit: true,
jest: true,
},
rules: {
'max-len': [
Expand All @@ -31,7 +32,14 @@ module.exports = {
'no-await-in-loop': 0,
'no-restricted-syntax': 0,
// jsdoc rules
'jsdoc/check-tag-names': ['error', { definedTags: ['scriptlet', 'trustedScriptlet', 'redirect'] }],
'jsdoc/check-tag-names': ['error', {
definedTags: [
'scriptlet',
'trustedScriptlet',
'redirect',
'jest-environment',
],
}],
'jsdoc/tag-lines': 'off',
'jsdoc/require-jsdoc': 0,
'jsdoc/require-param': 0,
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Fixed

- issue with reloading website if `$now$`/`$currentDate$` value is used in `trusted-set-cookie-reload` scriptlet [#291](https://github.com/AdguardTeam/Scriptlets/issues/291)

## [v1.9.7] - 2023-03-14

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,8 @@ Run next command
yarn browserstack
```

Tests run by `jest` should be named `.spec.js`, so they will be not included in the `QUnit` tests.

### Debugging

Use `debugger;` statement where you need it, run
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
"scripts": {
"build": "babel-node bundler.js",
"build-tests": "yarn build && babel-node scripts/build-tests.js",
"test": "yarn build-tests && node tests/index.js",
"test": "yarn build-tests && node tests/index.js && yarn jest",
"browserstack": "babel-node scripts/build-tests.js && node browserstack.js",
"gui-test": "babel-node scripts/build-tests.js && open http://localhost:8585 && node ./tests/server.js",
"jest": "jest trusted-set-cookie-reload.spec.js",
"lint": "eslint .",
"lint-staged": "lint-staged",
"prepare": "husky install",
Expand Down Expand Up @@ -69,6 +70,8 @@
"eslint-plugin-jsdoc": "^39.6.4",
"fs-extra": "^10.0.1",
"husky": "^8.0.3",
"jest": "^29.5.0",
"jest-environment-jsdom": "^29.5.0",
"js-reporters": "^2.1.0",
"kleur": "^4.1.4",
"lint-staged": "^12.1.2",
Expand Down
9 changes: 8 additions & 1 deletion src/scriptlets/trusted-set-cookie-reload.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
isValidCookiePath,
parseKeywordValue,
getTrustedCookieOffsetMs,
parseCookieString,
// following helpers should be imported and injected
// because they are used by helpers above
getCookiePath,
Expand Down Expand Up @@ -112,9 +113,14 @@ export function trustedSetCookieReload(source, name, value, offsetExpiresSec = '
document.cookie = cookieToSet;
hit(source);

// Get cookie value, it's required for checking purpose
// in case if $now$ or $currentDate$ value is used
// https://github.com/AdguardTeam/Scriptlets/issues/291
const cookieValueToCheck = parseCookieString(document.cookie)[name];

// Only reload the page if cookie was set
// https://github.com/AdguardTeam/Scriptlets/issues/212
if (isCookieSetWithValue(document.cookie, name, value)) {
if (isCookieSetWithValue(document.cookie, name, cookieValueToCheck)) {
window.location.reload();
}
}
Expand All @@ -133,5 +139,6 @@ trustedSetCookieReload.injections = [
isValidCookiePath,
getTrustedCookieOffsetMs,
parseKeywordValue,
parseCookieString,
getCookiePath,
];
3 changes: 2 additions & 1 deletion tests/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ export const runRedirect = (name, verbose = true) => {
* @param {string} cName
*/
export const clearCookie = (cName) => {
document.cookie = `${cName}=; max-age=0`;
// Without "path=/;" cookie is not to be re-set with no value
document.cookie = `${cName}=; path=/; max-age=0`;
};

export const isSafariBrowser = () => navigator.vendor === 'Apple Computer, Inc.';
114 changes: 114 additions & 0 deletions tests/scriptlets/trusted-set-cookie-reload.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* @jest-environment jsdom
*/
/* eslint-disable no-underscore-dangle */

import { trustedSetCookieReload } from '../../src/scriptlets/trusted-set-cookie-reload';
import { parseCookieString } from '../../src/helpers';
import {
clearGlobalProps,
clearCookie,
} from '../helpers';

beforeEach(() => {
window.__debug = () => {
window.hit = 'FIRED';
};
Object.defineProperty(window, 'location', {
configurable: true,
value: {
reload:
jest.fn(),
},
});

// Mocking console.trace() because
// it causes errors in tests using jest
window.console.trace = jest.fn();
});

afterEach(() => {
clearGlobalProps('hit', '__debug');
jest.clearAllMocks();
});

describe('Test trusted-set-cookie-reload scriptlet', () => {
const sourceParams = {
name: 'trusted-set-cookie-reload',
verbose: true,
};

test('Set cookie with current time value', () => {
const cName = '__test-cookie_current_time';
const cValue = '$now$';
const expiresSec = '';
const cPath = '/';

trustedSetCookieReload(sourceParams, cName, cValue, expiresSec, cPath);

// Some time will pass between calling scriptlet
// and jest running test
const tolerance = 125;
const cookieValue = parseCookieString(document.cookie)[cName];
const currentTime = new Date().getTime();
const timeDiff = currentTime - cookieValue;

expect(timeDiff).toBeLessThan(tolerance);
expect(document.cookie.includes(cName)).toBeTruthy();
expect(window.location.reload).toHaveBeenCalledTimes(1);
expect(window.hit).toBe('FIRED');
clearCookie(cName);
});

test('Set cookie with current date value', () => {
const cName = '__test-cookie_current_date';
const cValue = '$currentDate$';
const expiresSec = '';
const cPath = '/';

trustedSetCookieReload(sourceParams, cName, cValue, expiresSec, cPath);

// Some time will pass between calling scriptlet
// and jest running test
const cookieValue = parseCookieString(document.cookie)[cName];
// Check only day, month and year
const currentDate = encodeURIComponent(Date().split(' ', 4).join(' '));
const dateDiff = cookieValue.split(' ', 4).join(' ');

expect(dateDiff.startsWith(currentDate)).toBeTruthy();
expect(document.cookie.includes(cName)).toBeTruthy();
expect(window.location.reload).toHaveBeenCalledTimes(1);
expect(window.hit).toBe('FIRED');
clearCookie(cName);
});

test('Set cookie string', () => {
const cName = '__test-cookie_OK';
const cValue = 'OK';
const expiresSec = '';
const cPath = '/';

trustedSetCookieReload(sourceParams, cName, cValue, expiresSec, cPath);

expect(document.cookie.includes(cName)).toBeTruthy();
expect(document.cookie.includes(cValue)).toBeTruthy();
expect(window.location.reload).toHaveBeenCalledTimes(1);
expect(window.hit).toBe('FIRED');
clearCookie(cName);
});

test('Cookie already set, should not reload', () => {
const cName = '__test-cookie_set';
const cValue = 'test';
const expiresSec = '';
const cPath = '/';

document.cookie = `${cName}=${cValue};`;

trustedSetCookieReload(sourceParams, cName, cValue, expiresSec, cPath);

expect(window.location.reload).toHaveBeenCalledTimes(0);
expect(window.hit).toBe(undefined);
clearCookie(cName);
});
});
Loading

0 comments on commit 30a951a

Please sign in to comment.