From 719b3a8f4bbb9f8676eeded55bb682993f1f3dab Mon Sep 17 00:00:00 2001 From: Paul D'Ambra Date: Mon, 23 Oct 2023 09:43:01 +0100 Subject: [PATCH] fix: heroku subdomain check (#842) * fix: heroku subdomain check * satisfy codeql like this? * more tests --- src/__tests__/utils.js | 17 +++++++++++++++++ src/posthog-core.ts | 3 ++- src/utils.ts | 12 ++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/__tests__/utils.js b/src/__tests__/utils.js index 57afc1d8b..b9a3e2c24 100644 --- a/src/__tests__/utils.js +++ b/src/__tests__/utils.js @@ -12,6 +12,7 @@ import { DEFAULT_BLOCKED_UA_STRS, loadScript, _isUrlMatchingRegex, + isCrossDomainCookie, } from '../utils' function userAgentFor(botString) { @@ -272,4 +273,20 @@ describe('loadScript', () => { expect(_isUrlMatchingRegex('https://example.com/something/test', 'example.com/(.*.)/test')).toEqual(true) }) }) + + describe('check for cross domain cookies', () => { + it.each([ + [false, 'https://test.herokuapp.com'], + [false, 'test.herokuapp.com'], + [false, 'herokuapp.com'], + // ensure it isn't matching herokuapp anywhere in the domain + [true, 'https://test.herokuapp.com.impersonator.io'], + [false, undefined], + [true, 'https://bbc.co.uk'], + [true, 'bbc.co.uk'], + [true, 'www.bbc.co.uk'], + ])('should return %s when hostname is %s', (expectedResult, hostname) => { + expect(isCrossDomainCookie({ hostname })).toEqual(expectedResult) + }) + }) }) diff --git a/src/posthog-core.ts b/src/posthog-core.ts index 5cc9d94f7..5f5fa12d0 100644 --- a/src/posthog-core.ts +++ b/src/posthog-core.ts @@ -16,6 +16,7 @@ import { userAgent, window, logger, + isCrossDomainCookie, } from './utils' import { autocapture } from './autocapture' import { PostHogFeatureFlags } from './posthog-featureflags' @@ -109,7 +110,7 @@ const defaultConfig = (): PostHogConfig => ({ token: '', autocapture: true, rageclick: true, - cross_subdomain_cookie: document?.location?.hostname?.indexOf('herokuapp.com') === -1, + cross_subdomain_cookie: isCrossDomainCookie(document?.location), persistence: 'cookie', persistence_name: '', cookie_name: '', diff --git a/src/utils.ts b/src/utils.ts index e9524cf74..7cc651b96 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -955,4 +955,16 @@ export const _info = { }, } +export function isCrossDomainCookie(documentLocation: Location | undefined) { + const hostname = documentLocation?.hostname + + if (!_isString(hostname)) { + return false + } + // split and slice isn't a great way to match arbitrary domains, + // but it's good enough for ensuring we only match herokuapp.com when it is the TLD + // for the hostname + return hostname.split('.').slice(-2).join('.').indexOf('herokuapp.com') === -1 +} + export { win as window, userAgent, document }