Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix(growth): preserve non-accept consent decisions on banner re-init (#45187)

Sean Oliver1f318582e1d6
diff --git a/packages/common/consent-state.test.ts b/packages/common/consent-state.test.ts
index 71a96d892e4..cedda69c4b0 100644
--- a/packages/common/consent-state.test.ts
+++ b/packages/common/consent-state.test.ts
@@ -1,7 +1,8 @@
// @vitest-environment jsdom
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import type { UserDecision } from '@usercentrics/cmp-browser-sdk'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { detectPriorConsent } from './consent-state'
+import { applyPriorDecisionToSDK, consentState, detectPriorConsent } from './consent-state'
// jsdom's localStorage can be flaky in vitest, so ensure it's available
const storage = new Map<string, string>()
@@ -31,7 +32,7 @@ afterEach(() => {
describe('detectPriorConsent', () => {
describe('scenario 1: GTM compressed format (ucData)', () => {
- it('returns true when ucData has all services consented', () => {
+ it('returns uniform-accept when every service has consent: true', () => {
storage.set(
'ucData',
JSON.stringify({
@@ -46,64 +47,218 @@ describe('detectPriorConsent', () => {
})
)
- expect(detectPriorConsent()).toBe(true)
+ expect(detectPriorConsent()).toEqual({ kind: 'uniform-accept' })
})
- it('returns false when any service has consent: false', () => {
+ // Real customer data shape from GROWTH-790: essentials and functional
+ // services accepted, marketing/tracking services denied. This is what
+ // Opt out or a Privacy Settings toggle of the Marketing category produces
+ // in production — essentials are locked on and cannot actually be denied.
+ it('returns per-service decisions when ucData has a mixed consent state (GROWTH-790)', () => {
storage.set(
'ucData',
JSON.stringify({
+ gcm: {
+ adsDataRedaction: true,
+ adStorage: 'denied',
+ adPersonalization: 'denied',
+ adUserData: 'denied',
+ analyticsStorage: 'denied',
+ },
consent: {
services: {
- svc1: { name: 'Google Analytics', consent: true },
+ J39GyuWQq: { name: 'Amazon Web Services', consent: true },
+ HkIVcNiuoZX: { name: 'Cloudflare', consent: true },
+ H1PKqNodoWQ: { name: 'Google AJAX', consent: true },
+ HkPBYFofN: { name: 'Google Fonts', consent: true },
+ QjO6LaiOd: { name: 'hCaptcha', consent: true },
+ 'F-REmjGq7': { name: 'JSDelivr', consent: true },
+ Hko_qNsui_Q: { name: 'reCAPTCHA', consent: true },
+ rH1vNPCFR: { name: 'Sentry', consent: true },
+ ry3w9Vo_oZ7: { name: 'Stripe', consent: true },
+ BJTzqNi_i_m: { name: 'Twitter Plugin', consent: true },
+ HLap0udLC: { name: 'Twitter Syndication', consent: true },
+ H1Vl5NidjWX: { name: 'Usercentrics Consent Management Platform', consent: true },
+ BJz7qNsdj_7: { name: 'YouTube Video', consent: true },
+ S1_9Vsuj_Q: { name: 'Google Ads', consent: false },
+ HkocEodjb7: { name: 'Google Analytics', consent: false },
+ BJ59EidsWQ: { name: 'Google Tag Manager', consent: false },
+ nV4hGUA8RQK5Ez: { name: 'Supabase Event Tracking', consent: false },
+ },
+ },
+ })
+ )
+
+ const result = detectPriorConsent()
+ if (result === null || result.kind !== 'decisions') {
+ throw new Error(`expected decisions result, got ${JSON.stringify(result)}`)
+ }
+ expect(result.decisions).toHaveLength(17)
+ // Essentials / functional services preserved as accepted
+ expect(result.decisions).toContainEqual({ serviceId: 'J39GyuWQq', status: true })
+ expect(result.decisions).toContainEqual({ serviceId: 'rH1vNPCFR', status: true })
+ // Tracking services preserved as denied
+ expect(result.decisions).toContainEqual({ serviceId: 'S1_9Vsuj_Q', status: false })
+ expect(result.decisions).toContainEqual({ serviceId: 'HkocEodjb7', status: false })
+ expect(result.decisions).toContainEqual({ serviceId: 'BJ59EidsWQ', status: false })
+ expect(result.decisions).toContainEqual({ serviceId: 'nV4hGUA8RQK5Ez', status: false })
+ })
+
+ it('returns per-service decisions (all false) when every service was denied', () => {
+ storage.set(
+ 'ucData',
+ JSON.stringify({
+ consent: {
+ services: {
+ svc1: { name: 'Google Analytics', consent: false },
svc2: { name: 'Stripe', consent: false },
},
},
})
)
- expect(detectPriorConsent()).toBe(false)
+ expect(detectPriorConsent()).toEqual({
+ kind: 'decisions',
+ decisions: [
+ { serviceId: 'svc1', status: false },
+ { serviceId: 'svc2', status: false },
+ ],
+ })
})
- it('returns false when services object is empty', () => {
+ it('returns null when services object is empty', () => {
storage.set('ucData', JSON.stringify({ consent: { services: {} } }))
- expect(detectPriorConsent()).toBe(false)
+ expect(detectPriorConsent()).toBeNull()
})
- it('returns false when ucData is malformed JSON', () => {
+ it('returns null when ucData is malformed JSON', () => {
storage.set('ucData', 'not-json')
- expect(detectPriorConsent()).toBe(false)
+ expect(detectPriorConsent()).toBeNull()
})
- it('returns false when ucData has no consent.services', () => {
+ it('returns null when ucData has no consent.services', () => {
storage.set('ucData', JSON.stringify({ gcm: {} }))
- expect(detectPriorConsent()).toBe(false)
+ expect(detectPriorConsent()).toBeNull()
})
- it('returns false when services contains non-object values', () => {
+ it('returns null when every service value is non-object', () => {
storage.set('ucData', JSON.stringify({ consent: { services: { svc1: 'not-an-object' } } }))
- expect(detectPriorConsent()).toBe(false)
+ expect(detectPriorConsent()).toBeNull()
+ })
+
+ // Partial parse failures must fail closed. Cherry-picking the valid
+ // subset and calling it uniform-accept would let corrupted third-party
+ // storage silently upgrade a user's consent — the worst-direction bias
+ // in this domain.
+ it('returns null when any entry fails schema (fails closed on partial corruption)', () => {
+ storage.set(
+ 'ucData',
+ JSON.stringify({
+ consent: {
+ services: {
+ svc1: 'not-an-object',
+ svc2: { name: 'Valid', consent: true },
+ },
+ },
+ })
+ )
+ expect(detectPriorConsent()).toBeNull()
})
})
- describe('scenario 2: fast cross-app navigation (uc_user_interaction)', () => {
- it('returns true when uc_user_interaction is "true"', () => {
+ describe('scenario 2: fast cross-app navigation (uc_settings gated by uc_user_interaction)', () => {
+ const buildUcSettings = (services: Array<{ id: string; status: boolean }>) =>
+ JSON.stringify({
+ controllerId: 'test-controller',
+ id: 'test-settings',
+ language: 'en',
+ services: services.map((s) => ({
+ id: s.id,
+ status: s.status,
+ processorId: 'test-processor',
+ history: [],
+ version: '1.0.0',
+ })),
+ version: '1.0.0',
+ })
+
+ it('returns uniform-accept when uc_settings has every service accepted', () => {
+ storage.set('uc_user_interaction', 'true')
+ storage.set(
+ 'uc_settings',
+ buildUcSettings([
+ { id: 'svc1', status: true },
+ { id: 'svc2', status: true },
+ ])
+ )
+ expect(detectPriorConsent()).toEqual({ kind: 'uniform-accept' })
+ })
+
+ it('returns per-service decisions when uc_settings has a mixed state', () => {
storage.set('uc_user_interaction', 'true')
- expect(detectPriorConsent()).toBe(true)
+ storage.set(
+ 'uc_settings',
+ buildUcSettings([
+ { id: 'essential1', status: true },
+ { id: 'tracking1', status: false },
+ { id: 'tracking2', status: false },
+ ])
+ )
+ const result = detectPriorConsent()
+ if (result === null || result.kind !== 'decisions') {
+ throw new Error(`expected decisions result, got ${JSON.stringify(result)}`)
+ }
+ expect(result.decisions).toHaveLength(3)
+ expect(result.decisions).toContainEqual({ serviceId: 'essential1', status: true })
+ expect(result.decisions).toContainEqual({ serviceId: 'tracking1', status: false })
+ expect(result.decisions).toContainEqual({ serviceId: 'tracking2', status: false })
+ })
+
+ it('returns null when uc_user_interaction is "true" but uc_settings is absent', () => {
+ storage.set('uc_user_interaction', 'true')
+ expect(detectPriorConsent()).toBeNull()
+ })
+
+ it('returns null when uc_settings is malformed JSON', () => {
+ storage.set('uc_user_interaction', 'true')
+ storage.set('uc_settings', 'not-json')
+ expect(detectPriorConsent()).toBeNull()
+ })
+
+ it('returns null when uc_settings services array is empty', () => {
+ storage.set('uc_user_interaction', 'true')
+ storage.set('uc_settings', buildUcSettings([]))
+ expect(detectPriorConsent()).toBeNull()
+ })
+
+ it('returns null when any uc_settings service entry fails schema', () => {
+ storage.set('uc_user_interaction', 'true')
+ storage.set(
+ 'uc_settings',
+ JSON.stringify({
+ services: [
+ { id: 'svc1', status: true, processorId: 'p', history: [], version: '1' },
+ { id: 'svc2', status: 'not-a-boolean', processorId: 'p', history: [], version: '1' },
+ ],
+ })
+ )
+ expect(detectPriorConsent()).toBeNull()
})
- it('returns false when uc_user_interaction is "false"', () => {
+ it('returns null when uc_user_interaction is "false" (even if uc_settings is valid)', () => {
storage.set('uc_user_interaction', 'false')
- expect(detectPriorConsent()).toBe(false)
+ storage.set('uc_settings', buildUcSettings([{ id: 'svc1', status: true }]))
+ expect(detectPriorConsent()).toBeNull()
})
- it('returns false when uc_user_interaction is absent', () => {
- expect(detectPriorConsent()).toBe(false)
+ it('returns null when uc_user_interaction is absent', () => {
+ storage.set('uc_settings', buildUcSettings([{ id: 'svc1', status: true }]))
+ expect(detectPriorConsent()).toBeNull()
})
})
describe('combined scenarios', () => {
- it('returns true when both ucData and uc_user_interaction indicate consent', () => {
+ it('returns uniform-accept when ucData is fully accepted (ignoring uc_user_interaction/uc_settings)', () => {
storage.set(
'ucData',
JSON.stringify({
@@ -111,27 +266,185 @@ describe('detectPriorConsent', () => {
})
)
storage.set('uc_user_interaction', 'true')
- expect(detectPriorConsent()).toBe(true)
+ expect(detectPriorConsent()).toEqual({ kind: 'uniform-accept' })
})
- it('returns true when ucData has consent but uc_user_interaction is false', () => {
+ it('prefers ucData decisions over uc_settings when both exist', () => {
storage.set(
'ucData',
JSON.stringify({
- consent: { services: { svc1: { name: 'GA', consent: true } } },
+ consent: { services: { svc1: { name: 'GA', consent: false } } },
})
)
- storage.set('uc_user_interaction', 'false')
- expect(detectPriorConsent()).toBe(true)
+ storage.set('uc_user_interaction', 'true')
+ storage.set(
+ 'uc_settings',
+ JSON.stringify({
+ services: [{ id: 'svc1', status: true, processorId: 'p', history: [], version: '1' }],
+ })
+ )
+ expect(detectPriorConsent()).toEqual({
+ kind: 'decisions',
+ decisions: [{ serviceId: 'svc1', status: false }],
+ })
})
- it('returns true when ucData is absent but uc_user_interaction is true', () => {
+ it('falls back to uc_settings when ucData is corrupt (scenario 1 fails closed, scenario 2 recovers)', () => {
+ storage.set('ucData', JSON.stringify({ consent: { services: { svc1: 'corrupt' } } }))
storage.set('uc_user_interaction', 'true')
- expect(detectPriorConsent()).toBe(true)
+ storage.set(
+ 'uc_settings',
+ JSON.stringify({
+ services: [{ id: 'svc1', status: false, processorId: 'p', history: [], version: '1' }],
+ })
+ )
+ expect(detectPriorConsent()).toEqual({
+ kind: 'decisions',
+ decisions: [{ serviceId: 'svc1', status: false }],
+ })
+ })
+
+ it('returns null when localStorage is completely empty', () => {
+ expect(detectPriorConsent()).toBeNull()
+ })
+ })
+})
+
+describe('applyPriorDecisionToSDK', () => {
+ type MockService = { id: string; isEssential: boolean }
+
+ const makeMockUC = (
+ opts: {
+ services?: MockService[]
+ areAllAccepted?: boolean
+ onAcceptAll?: () => Promise<void>
+ onUpdateServices?: (decisions: UserDecision[]) => Promise<void>
+ } = {}
+ ) => {
+ const services = opts.services ?? []
+ return {
+ acceptAllServices: vi.fn(opts.onAcceptAll ?? (() => Promise.resolve())),
+ denyAllServices: vi.fn(() => Promise.resolve()),
+ updateServices: vi.fn(opts.onUpdateServices ?? (() => Promise.resolve())),
+ getCategoriesBaseInfo: vi.fn(() => []),
+ getServicesBaseInfo: vi.fn(() => services),
+ areAllConsentsAccepted: vi.fn(() => opts.areAllAccepted ?? false),
+ }
+ }
+
+ beforeEach(() => {
+ consentState.UC = null
+ consentState.categories = null
+ consentState.showConsentToast = false
+ consentState.hasConsented = false
+ })
+
+ it('uniform-accept: calls acceptAllServices, sets hasConsented, suppresses banner', () => {
+ const UC = makeMockUC()
+ applyPriorDecisionToSDK(UC as never, { initialLayer: 0 }, { kind: 'uniform-accept' })
+
+ expect(UC.acceptAllServices).toHaveBeenCalledOnce()
+ expect(UC.updateServices).not.toHaveBeenCalled()
+ expect(consentState.hasConsented).toBe(true)
+ expect(consentState.showConsentToast).toBe(false)
+ })
+
+ it('decisions with full coverage: calls updateServices with stored decisions, suppresses banner', () => {
+ const UC = makeMockUC({
+ services: [
+ { id: 'essential1', isEssential: true },
+ { id: 'tracking1', isEssential: false },
+ { id: 'tracking2', isEssential: false },
+ ],
+ })
+ const decisions: UserDecision[] = [
+ { serviceId: 'tracking1', status: true },
+ { serviceId: 'tracking2', status: false },
+ ]
+
+ applyPriorDecisionToSDK(UC as never, { initialLayer: 0 }, { kind: 'decisions', decisions })
+
+ expect(UC.updateServices).toHaveBeenCalledWith(decisions)
+ expect(UC.acceptAllServices).not.toHaveBeenCalled()
+ expect(consentState.showConsentToast).toBe(false)
+ })
+
+ // GROWTH-790 compliance guard: when the ruleset adds a new non-essential
+ // service after the user's stored decisions were written, we must NOT
+ // silently restore — the user has never seen this service and can't have
+ // consented to it. Show the banner instead.
+ it('decisions with uncovered non-essential service: shows banner, does not mutate SDK', () => {
+ const UC = makeMockUC({
+ services: [
+ { id: 'tracking1', isEssential: false },
+ { id: 'tracking_new', isEssential: false }, // in ruleset, not in decisions
+ ],
})
- it('returns false when localStorage is completely empty', () => {
- expect(detectPriorConsent()).toBe(false)
+ applyPriorDecisionToSDK(
+ UC as never,
+ { initialLayer: 0 },
+ { kind: 'decisions', decisions: [{ serviceId: 'tracking1', status: false }] }
+ )
+
+ expect(UC.updateServices).not.toHaveBeenCalled()
+ expect(UC.acceptAllServices).not.toHaveBeenCalled()
+ expect(consentState.showConsentToast).toBe(true)
+ })
+
+ // Essentials are SDK-forced-on regardless of user decision, so a new
+ // essential service appearing since the stored decisions were written
+ // should not trigger a re-prompt — the user has nothing meaningful to
+ // decide about it.
+ it('decisions covering only non-essentials: still restores (essentials ignored in coverage check)', () => {
+ const UC = makeMockUC({
+ services: [
+ { id: 'essential_new', isEssential: true }, // not in decisions, but essential
+ { id: 'tracking1', isEssential: false },
+ ],
})
+
+ applyPriorDecisionToSDK(
+ UC as never,
+ { initialLayer: 0 },
+ { kind: 'decisions', decisions: [{ serviceId: 'tracking1', status: false }] }
+ )
+
+ expect(UC.updateServices).toHaveBeenCalledOnce()
+ expect(consentState.showConsentToast).toBe(false)
+ })
+
+ it('null prior decision: shows banner at default', () => {
+ const UC = makeMockUC()
+ applyPriorDecisionToSDK(UC as never, { initialLayer: 0 }, null)
+
+ expect(UC.updateServices).not.toHaveBeenCalled()
+ expect(UC.acceptAllServices).not.toHaveBeenCalled()
+ expect(consentState.showConsentToast).toBe(true)
+ })
+
+ it('SDK not requesting first-layer banner: no restore attempted even if priorDecision exists', () => {
+ const UC = makeMockUC({ areAllAccepted: true })
+ applyPriorDecisionToSDK(UC as never, { initialLayer: 1 }, { kind: 'uniform-accept' })
+
+ expect(UC.acceptAllServices).not.toHaveBeenCalled()
+ expect(UC.updateServices).not.toHaveBeenCalled()
+ expect(consentState.hasConsented).toBe(true)
+ expect(consentState.showConsentToast).toBe(false)
+ })
+
+ it('SDK already considers user consented: passes through, no restore', () => {
+ const UC = makeMockUC({ areAllAccepted: true })
+ applyPriorDecisionToSDK(
+ UC as never,
+ { initialLayer: 0 },
+ {
+ kind: 'decisions',
+ decisions: [{ serviceId: 'svc1', status: false }],
+ }
+ )
+
+ expect(UC.updateServices).not.toHaveBeenCalled()
+ expect(consentState.hasConsented).toBe(true)
})
})
diff --git a/packages/common/consent-state.ts b/packages/common/consent-state.ts
index c080efbb98f..99ffee7fea1 100644
--- a/packages/common/consent-state.ts
+++ b/packages/common/consent-state.ts
@@ -4,61 +4,133 @@ import { proxy, snapshot, useSnapshot } from 'valtio'
import { IS_PLATFORM, LOCAL_STORAGE_KEYS } from './constants'
+export type PriorConsentDecision =
+ | null
+ | { kind: 'uniform-accept' }
+ | { kind: 'decisions'; decisions: UserDecision[] }
+
+type UcDataServiceEntry = [string, { consent: boolean }]
+
+const isValidUcDataServiceEntry = (entry: [string, unknown]): entry is UcDataServiceEntry => {
+ const value = entry[1]
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ typeof (value as { consent: unknown }).consent === 'boolean'
+ )
+}
+
+type UcSettingsService = { id: string; status: boolean }
+
+const isValidUcSettingsService = (service: unknown): service is UcSettingsService =>
+ typeof service === 'object' &&
+ service !== null &&
+ typeof (service as { id: unknown }).id === 'string' &&
+ typeof (service as { status: unknown }).status === 'boolean'
+
/**
- * Check if the user previously accepted all consent services by reading
+ * Check whether the user previously made a consent decision by reading
* localStorage state that was written before UC.init() overwrites it.
*
- * Handles two scenarios (FE-2648):
+ * Returns enough information for the caller to restore the user's exact
+ * prior state via UC.updateServices, or to fast-path via UC.acceptAllServices
+ * when we can safely identify a uniform accept. Returns null when nothing
+ * trustworthy can be detected — in that case the caller should show the
+ * banner rather than fabricate a decision.
+ *
+ * Handles two scenarios (FE-2648 and GROWTH-790):
*
* 1. Slow navigation: GTM's Usercentrics integration replaced uc_settings with
- * compressed ucString/ucData after acceptAllServices(). On the next page load,
- * UC.init() can't read that format and treats the user as new.
+ * compressed ucString/ucData after the user's decision. On the next page
+ * load, UC.init() can't read that format and treats the user as new. We
+ * read ucData.consent.services directly and return every per-service
+ * decision so the caller can restore the user's exact state — including
+ * mixed states (essentials + functional accepted, tracking denied) that
+ * users produce via the Privacy Settings modal or the Opt out button.
*
- * 2. Fast navigation: User accepted on app A and navigated to app B before GTM
- * finished writing ucData. App B's UC.init() overwrites uc_settings with a
- * fresh controllerId and resets uc_user_interaction to false. We detect the
- * prior uc_user_interaction: "true" before init stomps it.
+ * 2. Fast navigation: User decided on app A and navigated to app B before GTM
+ * finished writing ucData (or before GTM loaded at all, which happens on
+ * deny since TelemetryTagManager is gated behind hasAccepted). App B's
+ * UC.init() overwrites uc_settings with a fresh controllerId and resets
+ * uc_user_interaction to false. We check uc_user_interaction: "true" as
+ * a gate confirming the user actually interacted, then parse uc_settings
+ * to extract per-service decisions. uc_user_interaction alone is not
+ * enough — without uc_settings we cannot tell accept from deny and must
+ * not fabricate a direction.
+ *
+ * Both scenarios fail closed: any schema mismatch or partial corruption
+ * returns null rather than proceeding with a subset of valid entries.
+ * Over-consenting from malformed storage is the worst-direction bias in
+ * this domain.
*
* Must be called BEFORE UC.init() since init overwrites these keys.
*/
-export function detectPriorConsent(): boolean {
+export function detectPriorConsent(): PriorConsentDecision {
try {
- // Scenario 1: GTM wrote compressed format (slow navigation / same-app refresh)
const ucData = localStorage?.getItem('ucData')
if (ucData) {
const data = JSON.parse(ucData)
const services = data?.consent?.services
if (services && typeof services === 'object') {
- const serviceValues = Object.values(services)
- if (
- serviceValues.length > 0 &&
- serviceValues.every(
- (s) =>
- typeof s === 'object' && s !== null && (s as { consent: boolean }).consent === true
- )
- ) {
- return true
+ const rawEntries = Object.entries(services) as Array<[string, unknown]>
+ if (rawEntries.length > 0) {
+ if (!rawEntries.every(isValidUcDataServiceEntry)) {
+ // Partial corruption: don't cherry-pick the valid subset. Fall
+ // through to scenario 2 — uc_settings may still be intact.
+ } else {
+ const entries = rawEntries as UcDataServiceEntry[]
+ if (entries.every(([, s]) => s.consent === true)) {
+ return { kind: 'uniform-accept' }
+ }
+ return {
+ kind: 'decisions',
+ decisions: entries.map(([serviceId, s]) => ({
+ serviceId,
+ status: s.consent,
+ })),
+ }
+ }
}
}
}
- // Scenario 2: SDK wrote uc_user_interaction: "true" (fast cross-app navigation)
+ // uc_user_interaction gates trust in uc_settings — the SDK sets it on any
+ // user interaction, which confirms uc_settings holds real decisions rather
+ // than ruleset defaults.
if (localStorage?.getItem('uc_user_interaction') === 'true') {
- return true
+ const ucSettings = localStorage?.getItem('uc_settings')
+ if (ucSettings) {
+ const parsed = JSON.parse(ucSettings)
+ const services = parsed?.services
+ if (
+ Array.isArray(services) &&
+ services.length > 0 &&
+ services.every(isValidUcSettingsService)
+ ) {
+ const decisions: UserDecision[] = services.map((s) => ({
+ serviceId: s.id,
+ status: s.status,
+ }))
+ if (decisions.every((d) => d.status === true)) {
+ return { kind: 'uniform-accept' }
+ }
+ return { kind: 'decisions', decisions }
+ }
+ }
+ // Flag says interacted but uc_settings is missing or malformed.
+ // Don't fabricate direction — show the banner on the next init.
}
- return false
+ return null
} catch {
- return false
+ return null
}
}
export const consentState = proxy({
- // Usercentrics state
UC: null as Usercentrics | null,
categories: null as BaseCategory[] | null,
- // Our state
showConsentToast: false,
hasConsented: false,
acceptAll: () => {
@@ -108,6 +180,95 @@ export const consentState = proxy({
},
})
+/**
+ * Apply a prior consent decision (or lack of one) to the freshly-initialized
+ * Usercentrics SDK and the module's consentState proxy. Extracted from
+ * initUserCentrics to make the orchestration unit-testable without mocking
+ * the dynamic SDK import. Must be called after UC.init(). Mutates
+ * consentState synchronously and may call UC methods asynchronously.
+ */
+export function applyPriorDecisionToSDK(
+ UC: Usercentrics,
+ initialUIValues: { initialLayer: number },
+ priorDecision: PriorConsentDecision
+): void {
+ consentState.UC = UC
+ const hasConsented = UC.areAllConsentsAccepted()
+
+ // If the SDK wants to show the banner but the user previously made a
+ // decision (detected via ucData or uc_settings before init overwrote
+ // them), silently re-apply that decision instead of re-prompting
+ // (FE-2648, GROWTH-790).
+ if (initialUIValues.initialLayer === 0 && !hasConsented && priorDecision) {
+ consentState.categories = UC.getCategoriesBaseInfo()
+ consentState.showConsentToast = false
+ localStorage?.removeItem(LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT)
+
+ if (priorDecision.kind === 'uniform-accept') {
+ // Uniform accept covers any currently-active service by definition,
+ // including any added to the ruleset since the user's decision was
+ // stored — acceptAllServices applies to all current services.
+ consentState.hasConsented = true
+ UC.acceptAllServices()
+ .then(() => {
+ consentState.categories = UC.getCategoriesBaseInfo()
+ })
+ .catch(() => {
+ consentState.hasConsented = false
+ consentState.showConsentToast = true
+ })
+ return
+ }
+
+ // priorDecision.kind === 'decisions'. Only suppress the banner if the
+ // stored decisions cover every non-essential service the SDK currently
+ // knows about. If the ruleset has grown since the user's ucData/
+ // uc_settings was written, force a re-prompt rather than silently
+ // defaulting the new service. Essentials are skipped because the SDK
+ // forces them on regardless of user decision.
+ const currentNonEssentialIds = UC.getServicesBaseInfo()
+ .filter((s) => !s.isEssential)
+ .map((s) => s.id)
+ const coveredIds = new Set(priorDecision.decisions.map((d) => d.serviceId))
+ const allCovered = currentNonEssentialIds.every((id) => coveredIds.has(id))
+
+ if (!allCovered) {
+ // Fall through to the banner path below. Reset the early writes
+ // so the default-branch state assignments take effect correctly.
+ consentState.showConsentToast = initialUIValues.initialLayer === 0
+ consentState.hasConsented = hasConsented
+ return
+ }
+
+ // Restore the user's exact per-service state — handles deny and any
+ // partial/category-level decision made via Privacy Settings. hasConsented
+ // is computed from SDK state after the restore resolves (will be false
+ // unless every service was accepted).
+ UC.updateServices(priorDecision.decisions)
+ .then(() => {
+ consentState.hasConsented = UC.areAllConsentsAccepted()
+ consentState.categories = UC.getCategoriesBaseInfo()
+ })
+ .catch(() => {
+ // Falling back to the banner is safer than silently flipping to a
+ // uniform state the user didn't choose.
+ consentState.showConsentToast = true
+ })
+ return
+ }
+
+ // 0 = first layer, aka show consent toast
+ consentState.showConsentToast = initialUIValues.initialLayer === 0
+ consentState.hasConsented = hasConsented
+ consentState.categories = UC.getCategoriesBaseInfo()
+
+ // If the user has previously consented (before usercentrics), accept all services
+ if (!hasConsented && localStorage?.getItem(LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT) === 'true') {
+ consentState.acceptAll()
+ localStorage.removeItem(LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT)
+ }
+}
+
async function initUserCentrics() {
if (process.env.NODE_ENV === 'test' || !IS_PLATFORM) return
@@ -124,7 +285,7 @@ async function initUserCentrics() {
// Check for prior consent BEFORE UC.init(), which can't read the compressed
// ucData format written by the GTM/Usercentrics integration (FE-2648).
- const previouslyAccepted = detectPriorConsent()
+ const priorDecision = detectPriorConsent()
try {
const { default: Usercentrics } = await import('@usercentrics/cmp-browser-sdk')
@@ -135,44 +296,13 @@ async function initUserCentrics() {
})
const initialUIValues = await UC.init()
-
- consentState.UC = UC
- const hasConsented = UC.areAllConsentsAccepted()
-
- // If the SDK wants to show the banner but the user previously accepted
- // (detected via ucData or uc_user_interaction before init overwrote them),
- // silently re-accept instead of showing the banner again (FE-2648).
- if (initialUIValues.initialLayer === 0 && !hasConsented && previouslyAccepted) {
- consentState.hasConsented = true
- consentState.showConsentToast = false
- consentState.categories = UC.getCategoriesBaseInfo()
- localStorage?.removeItem(LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT)
- UC.acceptAllServices()
- .then(() => {
- consentState.categories = UC.getCategoriesBaseInfo()
- })
- .catch(() => {
- // If re-accept fails, fall back to showing the banner
- consentState.hasConsented = false
- consentState.showConsentToast = true
- })
- return
- }
-
- // 0 = first layer, aka show consent toast
- consentState.showConsentToast = initialUIValues.initialLayer === 0
- consentState.hasConsented = hasConsented
- consentState.categories = UC.getCategoriesBaseInfo()
-
- // If the user has previously consented (before usercentrics), accept all services
- if (!hasConsented && localStorage?.getItem(LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT) === 'true') {
- consentState.acceptAll()
- localStorage.removeItem(LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT)
- }
+ applyPriorDecisionToSDK(UC, initialUIValues, priorDecision)
} catch (error) {
console.error('Failed to initialize Usercentrics:', error)
- // If SDK fails but user previously accepted, honor that
- if (previouslyAccepted) {
+ // If SDK fails but user previously accepted uniformly, honor that.
+ // For explicit per-service decisions we can't restore without the SDK,
+ // and showing the banner when the SDK is broken would fail anyway.
+ if (priorDecision?.kind === 'uniform-accept') {
consentState.hasConsented = true
}
}
@@ -183,8 +313,6 @@ if (typeof window !== 'undefined') {
initUserCentrics()
}
-// Public API for consent
-
export function hasConsented() {
return snapshot(consentState).hasConsented
}