all files / src/gdpr/ ConsentManagementProvider.js

11.36% Statements 15/132
0% Branches 0/71
7.14% Functions 2/28
11.54% Lines 15/130
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                10× 10×         10× 10× 10× 10× 10× 10× 10× 10× 10×       10×                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import Cookies from 'js-cookie';
 
import { CmpApi } from '@iabtcf/cmpapi';
import { GVL, TCModel, TCString, VendorList } from '@iabtcf/core';
import { default as installCMPStub } from '@iabtcf/stub';
 
import { debug, getCookieDomain, getJSON } from '../shared/utils';
 
export const CMP_VERSION = 5; // Increment to force modal again
export const API_STATUS = {
    UI_VISIBLE_NEW: 'ui-visible-new',
    UI_VISIBLE_RESET: 'ui-visible-reset',
    DISABLED: 'disable',
};
const CMP_ID = 141;
const CMP_DEFAULT_LANGUAGE = 'en';
const DEPRECATED_VENDOR_CONSENT_COOKIE_NAME = 'euconsent-v2';
const VENDOR_CONSENT_COOKIE_NAME = 'eupubconsent-v2';
const PROVIDER_CONSENT_COOKIE_NAME = 'addtl_consent';
const VENDOR_LIST_URL_BASE = 'https://script.wikia.nocookie.net/fandom-ae-assets/tcf/v2/';
const VENDOR_LIST_FILE_NAME = 'vendor-list.json';
const VENDOR_LIST_VERSION_NAME = 'archives/vendor-list-v[VERSION].json';
const getDefaultCookieAttributes = () => ({
    domain: getCookieDomain(window.location.hostname),
    expires: 390 // thirteen 30-day months
});
const getDefaultOptions = () => ({
    allowedVendors: null,
    allowedVendorPurposes: null,
    allowedSpecialFeatures: null,
    cookieAttributes: getDefaultCookieAttributes(),
    gdprApplies: false,
    language: CMP_DEFAULT_LANGUAGE,
});
 
class ConsentManagementProvider {
    /** @type Promise<VendorList> */
    loaded = null;
    mounted = false;
    /** @type VendorList */
    vendorList = undefined;
 
    static installStub() {
        installCMPStub();
 
        debug('GDPR', 'Stub installed');
    }
 
    /**
     * @returns Promise<VendorList>
     */
    static fetchVendorList() {
        return getJSON(`${VENDOR_LIST_URL_BASE}${VENDOR_LIST_FILE_NAME}`);
    }
 
    constructor(options) {
        this.options = Object.assign(getDefaultOptions(), options);
 
        debug('GDPR', 'Constructed with params', options);
 
        GVL.baseUrl = VENDOR_LIST_URL_BASE;
        GVL.latestFilename = VENDOR_LIST_FILE_NAME;
        GVL.versionedFilename = VENDOR_LIST_VERSION_NAME;
 
        // Install temporary stub until full CMP will be ready
        if (typeof window.__tcfapi === 'undefined') {
            this.installStub();
        }
    }
 
    configure(options) {
        Object.assign(this.options, options);
 
        debug('GDPR', 'Configured with params', options);
    }
 
    installStub() {
        return ConsentManagementProvider.installStub();
    }
 
    initialize() {
        const addtlConsentMiddleware = (next, tcData, status) => {
            if (tcData && typeof tcData !== 'boolean') {
                tcData.addtlConsent = this.acString;
            }
 
            next(tcData, status);
        };
 
        this.cmpApi = new CmpApi(CMP_ID, CMP_VERSION, true, {
            'getTCData': addtlConsentMiddleware,
            'getInAppTCData': addtlConsentMiddleware,
            'isGalactusAllowed': (callback) => {
                window.__tcfapi('addEventListener', 2, (tcData, success) => {
                    if (!['tcloaded', 'useractioncomplete'].includes(tcData.eventStatus)) {
                        return;
                    }
 
                    if (success) {
                        callback(!!(tcData && tcData.vendor && tcData.vendor.consents && tcData.vendor.consents[756]));
                    } else {
                        callback(false);
                    }
 
                    window.__tcfapi('removeEventListener', 2, () => {}, tcData.listenerId);
                });
            }
        });
 
        debug('GDPR', 'Initialized with version', CMP_VERSION);
 
        const { gdprApplies } = this.options;
 
        if (gdprApplies && !this.vendorList) {
            debug('GDPR', 'Applies - fetching vendor list');
            this.loadVendorList();
        }
    }
 
    /**
     * @returns Promise<VendorList>
     */
    loadVendorList() {
        if (this.loaded) {
            return this.loaded;
        }
 
        this.loaded = ConsentManagementProvider.fetchVendorList()
            .then((vendorList) => {
                this.vendorList = vendorList;
 
                debug('GDPR', 'Vendor list fetched and saved', vendorList);
 
                return this.vendorList
            });
 
        return this.loaded;
    }
 
 
    uninstall() {
        debug('GDPR', 'Uninstalled');
 
        this.options = getDefaultOptions();
        this.setProviderConsentCookie(null);
        this.setVendorConsentCookie(null);
        delete window.__tcfapi;
    }
 
    unmount() {
        debug('GDPR', 'Unmounted');
 
        this.setProviderConsentCookie(null);
        this.setVendorConsentCookie(null);
        delete window.__tcfapi;
 
        this.initialize();
 
        this.mounted = false;
    }
 
    updateApi(event) {
        switch (event) {
            case API_STATUS.UI_VISIBLE_NEW:
                this.cmpApi.update('', true);
                debug('GDPR', 'UI displayed for the first time');
                break;
 
            case API_STATUS.UI_VISIBLE_RESET:
                this.cmpApi.update(this.getDeprecatedVendorConsentCookie() || '', true);
                debug('GDPR', 'UI displayed after policy change');
                break;
 
            case API_STATUS.DISABLED:
                this.cmpApi.disable();
                debug('GDPR', 'Unable to perform the operations in compliance with the TCF');
                break;
 
            default:
                break;
        }
    }
 
    install() {
        if (this.mounted) {
            this.unmount();
        }
 
        const { gdprApplies } = this.options;
 
        if (!gdprApplies) {
            this.cmpApi.update(null);
 
            debug('GDPR', 'Does not apply');
 
            return Promise.resolve();
        }
 
        return this.loaded.then(() => {
            const consentStrings = this.createConsent();
 
            this.acString = consentStrings[0];
            this.tcString = consentStrings[1];
 
            if (!this.hasUserConsent()) {
                debug('GDPR', 'Cookie not found - saving');
 
                this.setProviderConsentCookie(this.acString);
                this.setVendorConsentCookie(this.tcString);
            }
 
            this.cmpApi.update(this.tcString, false);
            this.mounted = true;
        });
    }
 
    createConsent() {
        let acString = this.getProviderConsentCookie();
        let tcString = this.getDeprecatedVendorConsentCookie();
 
        if (acString && tcString) {
            debug('GDPR', 'ACString and TCString read from cookie', acString, tcString, TCString.decode(tcString));
 
            return [acString, tcString];
        }
 
        const gvList = new GVL(this.vendorList);
        const tcModel = new TCModel(gvList);
        const { allowedVendorPurposes, allowedSpecialFeatures, allowedVendors, allowedProviders, consentScreen, language } = this.options;
 
        tcModel.cmpId = CMP_ID;
        tcModel.cmpVersion = CMP_VERSION;
        tcModel.consentScreen = Number(consentScreen) || 0;
        tcModel.consentLanguage = String(language).toLowerCase() || CMP_DEFAULT_LANGUAGE;
        tcModel.isServiceSpecific = true;
        tcModel.publisherCountryCode = 'US';
        tcModel.purposeConsents.set(Array.isArray(allowedVendorPurposes) ? allowedVendorPurposes : []);
        tcModel.specialFeatureOptins.set(Array.isArray(allowedSpecialFeatures) ? allowedSpecialFeatures : []);
        tcModel.vendorConsents.set(Array.isArray(allowedVendors) ? allowedVendors : []);
        // ToDo: proper implementation of Right to Object
        tcModel.purposeLegitimateInterests.set(Array.isArray(allowedVendorPurposes) ? allowedVendorPurposes : []);
        tcModel.vendorLegitimateInterests.set(Array.isArray(allowedVendors) ? allowedVendors : []);
 
        debug('GDPR', 'Consent saved with vendors: ', allowedVendors, ' and purposes', allowedVendorPurposes, ' and special feature options', allowedSpecialFeatures, ' and providers', allowedProviders);
 
        acString = `1~${allowedProviders.join('.')}`;
        tcString = TCString.encode(tcModel);
 
        debug('GDPR', 'Consent strings created', acString, tcString);
 
        return [acString, tcString];
    }
 
    getDeprecatedVendorConsentCookie() {
        return Cookies.get(DEPRECATED_VENDOR_CONSENT_COOKIE_NAME) || '';
    }
 
    getVendorConsentCookie() {
        return Cookies.get(VENDOR_CONSENT_COOKIE_NAME) || '';
    }
 
    getProviderConsentCookie() {
        return Cookies.get(PROVIDER_CONSENT_COOKIE_NAME) || '';
    }
 
    setVendorConsentCookie(consentString) {
        const cookieAttributes = this.options.cookieAttributes;
 
        if (consentString) {
            Cookies.set(DEPRECATED_VENDOR_CONSENT_COOKIE_NAME, consentString, cookieAttributes);
        } else {
            Cookies.remove(DEPRECATED_VENDOR_CONSENT_COOKIE_NAME, cookieAttributes);
        }
    }
 
    setProviderConsentCookie(consentString) {
        const cookieAttributes = this.options.cookieAttributes;
 
        if (consentString) {
            Cookies.set(PROVIDER_CONSENT_COOKIE_NAME, consentString, cookieAttributes);
        } else {
            Cookies.remove(PROVIDER_CONSENT_COOKIE_NAME, cookieAttributes);
        }
    }
 
    hasUserConsent() {
        return this.options.oneTrustEnabled ?
            !!this.getVendorConsentCookie() :
            !!this.getDeprecatedVendorConsentCookie() && !!this.getProviderConsentCookie();
    }
 
    /**
     * Checks if the user is withdrawing their consent by query parameter
     * @returns boolean
     */
    isWithdrawingConsent() {
        // ToDo: upgrade Node version and replace with .? + unify window.location access
        return window &&
            window.location &&
            window.location.pathname.includes('privacy-policy') &&
            window.location.search &&
            window.location.search.includes('withdrawConsent=true');
    }
 
    /**
     * @returns boolean
     */
    isVendorTCFPolicyVersionOutdated() {
        const cookie = this.getDeprecatedVendorConsentCookie();
 
        if (!cookie) {
            return false;
        }
 
        const consent = TCString.decode(cookie);
 
        return consent.policyVersion !== this.vendorList.tcfPolicyVersion;
    }
}
 
export default ConsentManagementProvider;