Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/swift-countries-worry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@scaleway/cookie-consent": patch
---

Remove the default object All: false of integrations when integrations are set. This will only apply on empty integrations array to protect users
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ type Context = {
needConsent: boolean
isSegmentAllowed: boolean
isSegmentIntegrationsLoaded: boolean
segmentIntegrations: { All: boolean } & Record<string, boolean>
segmentIntegrations: Record<string, boolean>
categoriesConsent: Partial<Consent>
saveConsent: (categoriesConsent: Partial<Consent>) => void
}
Expand All @@ -51,6 +51,8 @@ export const useCookieConsent = (): Context => {
return context
}

const getCookies = () => cookie.parse(document.cookie)

export const CookieConsentProvider = ({
children,
isConsentRequired,
Expand All @@ -71,16 +73,11 @@ export const CookieConsentProvider = ({
}>) => {
const [needConsent, setNeedsConsent] = useState(false)

const [cookies, setCookies] = useState<Record<string, string>>()
const {
integrations: segmentIntegrations,
isLoaded: isSegmentIntegrationsLoaded,
} = useSegmentIntegrations(config)

useEffect(() => {
setCookies(cookie.parse(document.cookie))
}, [needConsent])

const integrations: Integrations = useMemo(
() =>
uniq([
Expand All @@ -104,7 +101,7 @@ export const CookieConsentProvider = ({
...essentialIntegrations,
])
.sort()
.join(),
.join(undefined),
),
[segmentIntegrations, essentialIntegrations],
)
Expand All @@ -115,17 +112,17 @@ export const CookieConsentProvider = ({
// to false after receiving segment answer and flicker the UI
setNeedsConsent(
isConsentRequired &&
cookies?.[HASH_COOKIE] !== integrationsHash.toString() &&
getCookies()[HASH_COOKIE] !== integrationsHash.toString() &&
segmentIntegrations !== undefined,
)
}, [isConsentRequired, cookies, integrationsHash, segmentIntegrations])
}, [isConsentRequired, integrationsHash, segmentIntegrations])

// We store unique categories names in an array
const categories = useMemo(
() =>
uniq([
...(segmentIntegrations ?? []).map(({ category }) => category),
]).sort(),
uniq((segmentIntegrations ?? []).map(({ category }) => category)).sort(
undefined,
),
[segmentIntegrations],
)

Expand All @@ -138,12 +135,12 @@ export const CookieConsentProvider = ({
(acc, category) => ({
...acc,
[category]: isConsentRequired
? cookies?.[`${cookiePrefix}_${category}`] === 'true'
? getCookies()[`${cookiePrefix}_${category}`] === 'true'
: true,
}),
{},
),
[isConsentRequired, categories, cookies, cookiePrefix],
[isConsentRequired, categories, cookiePrefix],
)

const saveConsent = useCallback(
Expand Down Expand Up @@ -205,18 +202,20 @@ export const CookieConsentProvider = ({
[isConsentRequired, segmentIntegrations, cookieConsent, needConsent],
)

// 'All': false tells Segment not to send data to any Destinations by default, unless they’re explicitly listed as true in the next lines.
// In this case we should not have any integration, so we protect the user. Maybe unecessary as we always set true of false for an integration.
const segmentEnabledIntegrations = useMemo(
() => ({
All: false,
...segmentIntegrations?.reduce(
(acc, integration) => ({
...acc,
[integration.name]: cookieConsent[integration.category],
}),
{},
),
}),
[cookieConsent, segmentIntegrations],
() =>
segmentIntegrations?.length === 0
? { All: !isConsentRequired }
: (segmentIntegrations ?? []).reduce<Record<string, boolean>>(
(acc, integration) => ({
...acc,
[integration.name]: cookieConsent[integration.category] ?? false,
}),
{},
),
[cookieConsent, isConsentRequired, segmentIntegrations],
)

const value = useMemo(
Expand Down
114 changes: 48 additions & 66 deletions packages/cookie-consent/src/CookieConsentProvider/__tests__/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
// useSegmentIntegrations tests have been splitted in multiple files because of https://github.com/facebook/jest/issues/8987
import { afterEach, describe, expect, it, jest } from '@jest/globals'
import { describe, expect, it, jest } from '@jest/globals'
import { act, renderHook } from '@testing-library/react'
import cookie from 'cookie'
import type { ComponentProps, ReactNode } from 'react'
import { CookieConsentProvider, useCookieConsent } from '..'
import type { Integrations } from '../types'
import type { useSegmentIntegrations } from '../useSegmentIntegrations'

const wrapper =
({
isConsentRequired,
}: Omit<ComponentProps<typeof CookieConsentProvider>, 'children'>) =>
}: Omit<
ComponentProps<typeof CookieConsentProvider>,
'children' | 'essentialIntegrations' | 'config'
>) =>
({ children }: { children: ReactNode }) => (
<CookieConsentProvider
isConsentRequired={isConsentRequired}
Expand All @@ -24,7 +29,7 @@ const wrapper =
</CookieConsentProvider>
)

const integrations = [
const integrations: Integrations = [
{
category: 'analytics',
name: 'Google Universal Analytics',
Expand All @@ -38,26 +43,33 @@ const integrations = [
name: 'Salesforce',
},
]
const mockUseSegmentIntegrations = jest.fn().mockReturnValue({

const mockUseSegmentIntegrations = jest.fn<
() => ReturnType<typeof useSegmentIntegrations>
>(() => ({
integrations,
isLoaded: true,
})
}))

jest.mock('../useSegmentIntegrations', () => ({
__esModule: true,
useSegmentIntegrations: () => mockUseSegmentIntegrations(),
}))

describe('CookieConsent - CookieConsentProvider', () => {
afterEach(() => {
document.cookie = ''
beforeEach(() => {
jest.clearAllMocks()
})

afterAll(() => {
jest.restoreAllMocks()
})

it('useCookieConsent should throw without provider', () => {
const spy = jest.spyOn(console, 'error')
spy.mockImplementation(() => {})

expect(() => renderHook(() => useCookieConsent())).toThrow(
Error('useCookieConsent must be used within a CookieConsentProvider'),
new Error('useCookieConsent must be used within a CookieConsentProvider'),
)

spy.mockRestore()
Expand All @@ -67,13 +79,6 @@ describe('CookieConsent - CookieConsentProvider', () => {
const { result } = renderHook(() => useCookieConsent(), {
wrapper: wrapper({
isConsentRequired: false,
essentialIntegrations: ['Deskpro', 'Stripe', 'Sentry'],
config: {
segment: {
cdnURL: 'url',
writeKey: 'key',
},
},
}),
})

Expand All @@ -84,7 +89,6 @@ describe('CookieConsent - CookieConsentProvider', () => {
marketing: true,
})
expect(result.current.segmentIntegrations).toStrictEqual({
All: false,
'Google Universal Analytics': true,
Salesforce: true,
'Salesforce custom destination (Scaleway)': true,
Expand All @@ -94,42 +98,24 @@ describe('CookieConsent - CookieConsentProvider', () => {

it('should know when integrations are loading', () => {
// simulate that Segment is loading
mockUseSegmentIntegrations.mockReturnValue({
mockUseSegmentIntegrations.mockReturnValueOnce({
integrations: undefined,
isLoaded: false,
})
const { result } = renderHook(() => useCookieConsent(), {
wrapper: wrapper({
isConsentRequired: true,
essentialIntegrations: ['Deskpro', 'Stripe', 'Sentry'],
config: {
segment: {
cdnURL: 'url',
writeKey: 'key',
},
},
}),
})
expect(result.current.isSegmentIntegrationsLoaded).toBe(false)

// put mock back as if segment integrations are loaded
mockUseSegmentIntegrations.mockReturnValue({
integrations,
isLoaded: true,
})
expect(mockUseSegmentIntegrations).toBeCalledTimes(1)
expect(result.current.isSegmentIntegrationsLoaded).toBe(false)
})

it('should know to ask for content when no cookie is set and consent is required', () => {
const { result } = renderHook(() => useCookieConsent(), {
wrapper: wrapper({
isConsentRequired: true,
essentialIntegrations: ['Deskpro', 'Stripe', 'Sentry'],
config: {
segment: {
cdnURL: 'url',
writeKey: 'key',
},
},
}),
})

Expand All @@ -140,7 +126,6 @@ describe('CookieConsent - CookieConsentProvider', () => {
analytics: false,
})
expect(result.current.segmentIntegrations).toStrictEqual({
All: false,
'Google Universal Analytics': false,
Salesforce: false,
'Salesforce custom destination (Scaleway)': false,
Expand All @@ -152,13 +137,6 @@ describe('CookieConsent - CookieConsentProvider', () => {
const { result } = renderHook(() => useCookieConsent(), {
wrapper: wrapper({
isConsentRequired: true,
essentialIntegrations: ['Deskpro', 'Stripe', 'Sentry'],
config: {
segment: {
cdnURL: 'url',
writeKey: 'key',
},
},
}),
})

Expand All @@ -169,7 +147,6 @@ describe('CookieConsent - CookieConsentProvider', () => {
marketing: false,
})
expect(result.current.segmentIntegrations).toStrictEqual({
All: false,
'Google Universal Analytics': false,
Salesforce: false,
'Salesforce custom destination (Scaleway)': false,
Expand Down Expand Up @@ -213,17 +190,12 @@ describe('CookieConsent - CookieConsentProvider', () => {
})

it('should not need consent if hash cookie is set', () => {
jest.spyOn(cookie, 'parse').mockReturnValue({ _scw_rgpd_hash: '913003917' })
jest
.spyOn(cookie, 'parse')
.mockImplementation(() => ({ _scw_rgpd_hash: '913003917' }))
const { result } = renderHook(() => useCookieConsent(), {
wrapper: wrapper({
isConsentRequired: true,
essentialIntegrations: ['Deskpro', 'Stripe', 'Sentry'],
config: {
segment: {
cdnURL: 'url',
writeKey: 'key',
},
},
}),
})

Expand All @@ -234,28 +206,21 @@ describe('CookieConsent - CookieConsentProvider', () => {
marketing: false,
})
expect(result.current.segmentIntegrations).toStrictEqual({
All: false,
'Google Universal Analytics': false,
Salesforce: false,
'Salesforce custom destination (Scaleway)': false,
})
})

it('should not need consent if hash cookie is set and some categories already approved', () => {
jest.spyOn(cookie, 'parse').mockReturnValue({
jest.spyOn(cookie, 'parse').mockImplementation(() => ({
_scw_rgpd_hash: '913003917',
_scw_rgpd_marketing: 'true',
})
}))

const { result } = renderHook(() => useCookieConsent(), {
wrapper: wrapper({
isConsentRequired: true,
essentialIntegrations: ['Deskpro', 'Stripe', 'Sentry'],
config: {
segment: {
cdnURL: 'url',
writeKey: 'key',
},
},
}),
})

Expand All @@ -266,10 +231,27 @@ describe('CookieConsent - CookieConsentProvider', () => {
marketing: true,
})
expect(result.current.segmentIntegrations).toStrictEqual({
All: false,
'Google Universal Analytics': false,
Salesforce: true,
'Salesforce custom destination (Scaleway)': true,
})
})

it('should return integration All: false in case there is no integrations', () => {
mockUseSegmentIntegrations.mockReturnValue({
integrations: [],
isLoaded: true,
})
const { result } = renderHook(() => useCookieConsent(), {
wrapper: wrapper({
isConsentRequired: true,
}),
})

expect(mockUseSegmentIntegrations).toBeCalledTimes(2)

expect(result.current.segmentIntegrations).toStrictEqual({
All: false,
})
})
})