From ca71fb6b0c1f0628e2d32d5d24d3667a658c5dc5 Mon Sep 17 00:00:00 2001 From: Muhammad AlAref Date: Thu, 14 Nov 2024 06:11:41 -0800 Subject: [PATCH] Limit cookies to subdomains [READ] --- packages/clarity-js/src/core/config.ts | 1 + packages/clarity-js/src/data/metadata.ts | 13 ++++++++++--- packages/clarity-js/types/core.d.ts | 1 + 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/clarity-js/src/core/config.ts b/packages/clarity-js/src/core/config.ts index 818e8d9c..6be903de 100644 --- a/packages/clarity-js/src/core/config.ts +++ b/packages/clarity-js/src/core/config.ts @@ -23,6 +23,7 @@ let config: Config = { throttleDom: true, conversions: false, longTask: 30, + includeSubdomains: true, }; export default config; diff --git a/packages/clarity-js/src/data/metadata.ts b/packages/clarity-js/src/data/metadata.ts index 392b4ef9..952c93f1 100644 --- a/packages/clarity-js/src/data/metadata.ts +++ b/packages/clarity-js/src/data/metadata.ts @@ -213,7 +213,7 @@ export function shortid(): string { function session(): Session { let output: Session = { session: shortid(), ts: Math.round(Date.now()), count: 1, upgrade: null, upload: Constant.Empty }; - let value = getCookie(Constant.SessionKey); + let value = getCookie(Constant.SessionKey, !config.includeSubdomains); if (value) { let parts = value.split(Constant.Pipe); // Making it backward & forward compatible by using greater than comparison (v0.6.21) @@ -234,7 +234,7 @@ function num(string: string, base: number = 10): number { function user(): User { let output: User = { id: shortid(), version: 0, expiry: null, consent: BooleanFlag.False, dob: 0 }; - let cookie = getCookie(Constant.CookieKey); + let cookie = getCookie(Constant.CookieKey, !config.includeSubdomains); if (cookie && cookie.length > 0) { // Splitting and looking up first part for forward compatibility, in case we wish to store additional information in a cookie let parts = cookie.split(Constant.Pipe); @@ -266,7 +266,7 @@ function user(): User { return output; } -function getCookie(key: string): string { +function getCookie(key: string, limit = false): string { if (supported(document, Constant.Cookie)) { let cookies: string[] = document.cookie.split(Constant.Semicolon); if (cookies) { @@ -285,6 +285,13 @@ function getCookie(key: string): string { [isEncoded, decodedValue] = decodeCookieValue(decodedValue); } + // If we are limiting cookies, check if the cookie value is limited + if (limit) { + return decodedValue.endsWith(`${Constant.Tilde}1`) + ? decodedValue.substring(0, decodedValue.length - 2) + : null; + } + return decodedValue; } } diff --git a/packages/clarity-js/types/core.d.ts b/packages/clarity-js/types/core.d.ts index a75bb6f2..fe9a1c80 100644 --- a/packages/clarity-js/types/core.d.ts +++ b/packages/clarity-js/types/core.d.ts @@ -137,6 +137,7 @@ export interface Config { throttleDom?: boolean; conversions?: boolean; longTask?: number; + includeSubdomains?: boolean; } export const enum Constant {