diff --git a/assets/cookie-notice/frontconsent-cookie-notice.js b/assets/cookie-notice/frontconsent-cookie-notice.js index 6db7e55..27fba1c 100644 --- a/assets/cookie-notice/frontconsent-cookie-notice.js +++ b/assets/cookie-notice/frontconsent-cookie-notice.js @@ -43,6 +43,57 @@ } } + /** + * Whether a cookie name matches one of the purge patterns: an exact name + * ('_gid') or a prefix ending in '*' ('_ga_*'). + */ + function matchesPurgePattern(name, patterns) { + return patterns.some(function (pattern) { + if ('*' === pattern.charAt(pattern.length - 1)) { + return 0 === name.indexOf(pattern.slice(0, -1)); + } + + return name === pattern; + }); + } + + /** + * Delete the analytics/marketing cookies a tracking script may already + * have written (see CookieNotice::get_purge_cookie_patterns()). Rejecting + * or withdrawing consent only stops new tags from loading; without this, + * cookies set while consent was granted (e.g. `_ga`) would stay on the + * visitor's device. Each cookie is expired with no domain and with every + * parent domain of the current host, since tags such as GA set theirs + * on the registrable domain ('.example.com') rather than the exact host. + */ + function purgeTrackingCookies() { + var patterns = Array.isArray(frcnCookieNotice.purgeCookies) ? frcnCookieNotice.purgeCookies : []; + + if (!patterns.length || !document.cookie) { + return; + } + + var hostname = window.location && window.location.hostname ? window.location.hostname : ''; + var labels = hostname.split('.'); + var domains = ['']; + + for (var i = 0; i < labels.length - 1; i++) { + domains.push('; domain=.' + labels.slice(i).join('.')); + } + + document.cookie.split('; ').forEach(function (pair) { + var name = pair.split('=')[0]; + + if (!name || name === frcnCookieNotice.cookieName || !matchesPurgePattern(name, patterns)) { + return; + } + + domains.forEach(function (domain) { + document.cookie = name + '=; path=/; max-age=0' + domain; + }); + }); + } + function defineActivateGatedHelper() { window.frcnCookieNoticeActivateGated = window.frcnCookieNoticeActivateGated || function (allowedCategories) { if (allowedCategories && !allowedCategories.analytics) { @@ -333,6 +384,9 @@ reopenTriggerWired = true; reopenBtn.addEventListener('click', function () { document.cookie = frcnCookieNotice.cookieName + '=; path=' + frcnCookieNotice.cookiePath + '; max-age=0; SameSite=Lax'; + // Withdrawing consent must not leave behind what was set while it + // was granted: the page reloads undecided, so nothing is allowed. + purgeTrackingCookies(); if (frcnCookieNotice.isPolicyPage && frcnCookieNotice.homeUrl) { window.location.href = frcnCookieNotice.homeUrl; @@ -360,6 +414,13 @@ requestTrackingIfNeeded(); setUpReopenTrigger(); + // A rejected visitor may still carry cookies from before the decision + // (an earlier acceptance, or a tag that ran before FrontConsent was + // installed): clear them on every page view. + if (readCookie(frcnCookieNotice.cookieName) === 'rejected') { + purgeTrackingCookies(); + } + var banner = document.getElementById('frcn-cookie-notice'); if (!banner) { @@ -530,6 +591,8 @@ if (decision === 'accepted') { fetchAndInjectScripts(); + } else { + purgeTrackingCookies(); } } diff --git a/includes/Frontend/CookieNotice.php b/includes/Frontend/CookieNotice.php index 1734f46..929b23c 100644 --- a/includes/Frontend/CookieNotice.php +++ b/includes/Frontend/CookieNotice.php @@ -121,6 +121,44 @@ public static function get_gated_script_handles() { return is_array( $handles ) ? array_map( 'strval', $handles ) : array(); } + /** + * Cookie names deleted client-side when the visitor rejects or withdraws + * consent. An entry ending in '*' matches every cookie starting with that + * prefix. Covers the tags FrontConsent loads itself (GTM/GA4, Brevo) plus + * the common ones a GTM container or gated script tends to add. + * + * @return string[] + */ + public static function get_purge_cookie_patterns() { + $patterns = array( + // Google Analytics and Google Ads. + '_ga', + '_ga_*', + '_gid', + '_gat*', + '_gcl_*', + // Meta Pixel. + '_fbp', + '_fbc', + // Microsoft Clarity. + '_clck', + '_clsk', + // Brevo. + 'sib_cuid', + // WooCommerce order attribution (sourcebuster). + 'sbjs_*', + ); + + /** + * Filters the cookies deleted when the visitor rejects or withdraws consent. + * + * @param string[] $patterns Cookie names; a trailing '*' matches a prefix. + */ + $patterns = apply_filters( 'frcn_cookie_notice_purge_cookies', $patterns ); + + return is_array( $patterns ) ? array_values( array_filter( array_map( 'strval', $patterns ) ) ) : array(); + } + /** * Turn a gated script's tag into an inert one. The tag is always printed, * identically for every visitor (cache-neutral, like the rest of the @@ -440,6 +478,7 @@ public function enqueue_assets() { // home, where the banner is guaranteed to render. 'isPolicyPage' => $this->is_policy_page(), 'homeUrl' => home_url( '/' ), + 'purgeCookies' => self::get_purge_cookie_patterns(), ) ); diff --git a/readme.md b/readme.md index 32652e2..1a79610 100644 --- a/readme.md +++ b/readme.md @@ -9,6 +9,7 @@ Repository for FrontConsent, a WordPress plugin providing a GDPR/ePrivacy-compli - **Migration from FrontBlocks** — automatically imports settings and stats from FrontBlocks Site Tools' bundled Cookie Notice module, which FrontConsent replaces. - **Import from GDPR Cookie Compliance** — explicit "Import settings" action that maps its Integrations tab (GA4, GTM, and the container configured in GTM4WP) and banner texts/expiration/position into FrontConsent without overwriting existing values; unsupported integrations (Google Ads, Meta Pixel, Microsoft UET/Clarity, reCAPTCHA) are reported, not imported. See `includes/GDPR_Cookie_Compliance_Migration.php`. - **Consent-gated attribution cookies** — WooCommerce order attribution scripts (`sbjs_*` cookies) stay inert until the visitor accepts (filter `frcn_cookie_notice_gated_script_handles`), and GTM4WP's own Consent Mode default is suppressed so FrontConsent's denied default is the only one (filter `frcn_cookie_notice_suppress_gtm4wp_consent_default`). +- **Tracking cookies deleted on rejection** — rejecting, withdrawing an earlier acceptance, or returning after a rejection deletes known analytics/marketing cookies (`_ga`, `_ga_*`, `_gid`, `_gcl_*`, `_fbp`, `sbjs_*`…) on the host and its parent domains, so nothing set while consent was granted stays behind (filter `frcn_cookie_notice_purge_cookies`). - **Extensible settings tabs** — the settings page renders as a tab shell (Settings, plus a PRO upsell tab by default). A companion plugin such as FrontConsent PRO can add its own tab via the `frontconsent_settings_tabs` filter and render its panel on the `frontconsent_settings_form_tab_panels` action (fields saved through the main form) or `frontconsent_settings_tab_panels` action (a panel with its own form, e.g. a License tab). See [docs/plan.md](docs/plan.md) for the product plan (market, Free/Pro split, roadmap) and [AGENTS.md](AGENTS.md) for guidelines for AI coding agents working on this plugin. diff --git a/readme.txt b/readme.txt index 2860bee..a3251a6 100644 --- a/readme.txt +++ b/readme.txt @@ -54,6 +54,10 @@ Yes. If its settings are found, FrontConsent shows an "Import settings" button o Yes. WooCommerce's order attribution scripts (`sourcebuster-js` and `wc-order-attribution`) set `sbjs_*` cookies on the first page view, so FrontConsent keeps them inert and runs them only after the visitor accepts. Use the `frcn_cookie_notice_gated_script_handles` filter to change the list, or return an empty array to disable this. += What happens to analytics cookies when a visitor rejects or withdraws consent? = + +FrontConsent deletes them. Rejecting, withdrawing an earlier acceptance from the cookie icon, or visiting again after rejecting removes the known tracking cookies (Google Analytics `_ga`/`_ga_*`/`_gid`/`_gat*`, Google Ads `_gcl_*`, Meta Pixel `_fbp`/`_fbc`, Microsoft Clarity `_clck`/`_clsk`, Brevo `sib_cuid` and WooCommerce `sbjs_*`), including those set on the parent domain. Use the `frcn_cookie_notice_purge_cookies` filter to change the list; an entry ending in `*` matches a prefix. + = GTM4WP sends its own Consent Mode default. Is that a problem? = FrontConsent already sends a denied default first. To avoid a second, conflicting default (GTM4WP can grant analytics storage), FrontConsent turns GTM4WP's own consent default off. Return false on the `frcn_cookie_notice_suppress_gtm4wp_consent_default` filter to keep it. diff --git a/tests/js/cookie-notice-purge.test.js b/tests/js/cookie-notice-purge.test.js new file mode 100644 index 0000000..6743f4a --- /dev/null +++ b/tests/js/cookie-notice-purge.test.js @@ -0,0 +1,159 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); + +const scriptPath = path.resolve(__dirname, '../../assets/cookie-notice/frontconsent-cookie-notice.js'); +const cookieNoticeScript = fs.readFileSync(scriptPath, 'utf8'); + +const PURGE_COOKIES = ['_ga', '_ga_*', '_gid', 'sbjs_*']; + +/** + * Minimal cookie jar keyed by name + domain, so a cookie set on + * '.example.com' is only removed by a deletion for that same domain — + * the case a host-only deletion silently misses in a real browser. + */ +function createCookieJar(initial) { + const jar = new Map(); + // Browsers ignore a leading dot: 'domain=.example.com' and + // 'domain=example.com' address the same cookie. + const normalizeDomain = (domain) => (domain || '').replace(/^\./, ''); + + initial.forEach(([name, value, domain]) => jar.set(name + '|' + normalizeDomain(domain), { name, value })); + + return { + jar, + get() { + return Array.from(jar.values()).map((cookie) => cookie.name + '=' + cookie.value).join('; '); + }, + set(raw) { + const parts = raw.split(';').map((part) => part.trim()); + const [name, value] = parts[0].split('='); + const domainPart = parts.find((part) => 0 === part.indexOf('domain=')); + const domain = normalizeDomain(domainPart ? domainPart.slice('domain='.length) : ''); + const key = name + '|' + domain; + + if (parts.includes('max-age=0')) { + jar.delete(key); + } else { + jar.set(key, { name, value }); + } + } + }; +} + +function createEnvironment(initialCookies) { + const cookies = createCookieJar(initialCookies); + const listeners = {}; + const actionListeners = {}; + const reopenListeners = {}; + const banner = { + classList: { add() {}, contains() { return false; }, remove() {} }, + parentNode: { removeChild() {} }, + querySelector(selector) { + const actionMatch = selector.match(/^\[data-frcn-cookie-action="(accept|reject)"\]$/); + if (actionMatch) { + return { + addEventListener(event, callback) { + actionListeners[actionMatch[1]] = callback; + } + }; + } + return null; + }, + querySelectorAll() { return []; }, + style: {} + }; + const reopenBtn = { + hidden: true, + addEventListener(event, callback) { reopenListeners[event] = callback; } + }; + const document = { + activeElement: null, + body: { classList: { add() {}, remove() {} } }, + get cookie() { return cookies.get(); }, + set cookie(raw) { cookies.set(raw); }, + head: { appendChild() {} }, + readyState: 'loading', + addEventListener(event, callback) { listeners[event] = callback; }, + createElement() { return {}; }, + dispatchEvent() {}, + getElementById(id) { return id === 'frcn-cookie-reopen' ? reopenBtn : banner; }, + getElementsByTagName() { return []; }, + querySelectorAll() { return []; }, + removeEventListener() {} + }; + const window = { + location: { protocol: 'https:', hostname: 'www.example.com', reload() {} }, + setTimeout(callback) { callback(); } + }; + + vm.runInNewContext(cookieNoticeScript, { + Array, + CustomEvent: function () {}, + Date, + FormData: function () { this.append = function () {}; }, + decodeURIComponent, + document, + encodeURIComponent, + fetch() { return Promise.resolve({ json() { return Promise.resolve({}); } }); }, + frcnCookieNotice: { + ajaxUrl: 'https://www.example.com/wp-admin/admin-ajax.php', + cookieName: 'frcn_cookie_consent', + cookiePath: '/', + expirationDays: 365, + isPolicyPage: '', + homeUrl: 'https://www.example.com/', + purgeCookies: PURGE_COOKIES + }, + window + }); + listeners.DOMContentLoaded(); + + return { actionListeners, cookieNames: () => Array.from(cookies.jar.values()).map((cookie) => cookie.name), reopenListeners }; +} + +test('rejecting deletes tracking cookies set on the host and on parent domains', () => { + const environment = createEnvironment([ + ['_ga', 'GA1.1.1', '.example.com'], + ['_ga_ABC123', 'GS1.1', '.example.com'], + ['_gid', 'GA1.1.2', ''], + ['sbjs_first', 'typ=typein', 'www.example.com'], + ['woocommerce_items_in_cart', '1', ''] + ]); + + environment.actionListeners.reject({ preventDefault() {} }); + + assert.deepEqual(environment.cookieNames().sort(), ['frcn_cookie_consent', 'woocommerce_items_in_cart']); +}); + +test('accepting keeps tracking cookies', () => { + const environment = createEnvironment([['_ga', 'GA1.1.1', '.example.com']]); + + environment.actionListeners.accept({ preventDefault() {} }); + + assert.ok(environment.cookieNames().includes('_ga')); +}); + +test('a returning rejected visitor has leftover tracking cookies cleared on page load', () => { + const environment = createEnvironment([ + ['frcn_cookie_consent', 'rejected', ''], + ['_ga', 'GA1.1.1', '.example.com'] + ]); + + assert.deepEqual(environment.cookieNames(), ['frcn_cookie_consent']); +}); + +test('withdrawing an earlier acceptance deletes tracking cookies', () => { + const environment = createEnvironment([ + ['frcn_cookie_consent', 'accepted', ''], + ['_ga', 'GA1.1.1', '.example.com'], + ['_ga_ABC123', 'GS1.1', '.example.com'] + ]); + + assert.ok(environment.cookieNames().includes('_ga')); + environment.reopenListeners.click(); + + assert.deepEqual(environment.cookieNames(), []); +});