Skip to content

Commit

Permalink
Limit cookies to subdomains
Browse files Browse the repository at this point in the history
  • Loading branch information
Muhammad AlAref committed Nov 8, 2024
1 parent 6c2de87 commit 3074fa4
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/clarity-js/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ let config: Config = {
throttleDom: true,
conversions: false,
longTask: 30,
limitCookies: false,
};

export default config;
18 changes: 18 additions & 0 deletions packages/clarity-js/src/data/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,12 @@ function getCookie(key: string): string {
[isEncoded, decodedValue] = decodeCookieValue(decodedValue);
}

// If we are limiting cookies to subdomains, check if it matches the current one
if (config.limitCookies) {
const parts = decodedValue.split(Constant.Tilde);
return parts.length > 1 && parts[1] === location.hostname ? parts[0] : null;
}

return decodedValue;
}
}
Expand Down Expand Up @@ -312,6 +318,11 @@ function setCookie(key: string, value: string, time: number): void {
// only write cookies if we are currently in a cookie writing mode (and they are supported)
// OR if we are trying to write an empty cookie (i.e. clear the cookie value out)
if ((config.track || value == Constant.Empty) && ((navigator && navigator.cookieEnabled) || supported(document, Constant.Cookie))) {
// If we are limiting cookies to subdomains, append the current one to the cookie value
if (config.limitCookies) {
value = `${value}${Constant.Tilde}${location.hostname}`;
}

// Some browsers automatically url encode cookie values if they are not url encoded.
// We therefore encode and decode cookie values ourselves.
let encodedValue = encodeCookieValue(value);
Expand All @@ -320,6 +331,13 @@ function setCookie(key: string, value: string, time: number): void {
expiry.setDate(expiry.getDate() + time);
let expires = expiry ? Constant.Expires + expiry.toUTCString() : Constant.Empty;
let cookie = `${key}=${encodedValue}${Constant.Semicolon}${expires}${Constant.Path}`;

// If we are limiting cookies to subdomains, we only write to the current one.
if (config.limitCookies) {
document.cookie = `${cookie}${Constant.Semicolon}${Constant.Domain}.${location.hostname}`;
return;
}

try {
// Attempt to get the root domain only once and fall back to writing cookie on the current domain.
if (rootDomain === null) {
Expand Down
1 change: 1 addition & 0 deletions packages/clarity-js/types/core.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ export interface Config {
throttleDom?: boolean;
conversions?: boolean;
longTask?: number;
limitCookies?: boolean;
}

export const enum Constant {
Expand Down

0 comments on commit 3074fa4

Please sign in to comment.