Skip to content

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

feat: capture Freebuff ad click ids (#50181)

Aleksi Immonen66e6cd163973
diff --git a/packages/common/consent-state.ts b/packages/common/consent-state.ts
index 5b39ae5f99a..cd3a36658fc 100644
--- a/packages/common/consent-state.ts
+++ b/packages/common/consent-state.ts
@@ -131,6 +131,14 @@ export const consentState = proxy({
UC: null as Usercentrics | null,
categories: null as BaseCategory[] | null,
+ /**
+ * Whether the consent decision has settled, either from the SDK or from a
+ * failure to load it. Consumers that must act on a decision need to tell
+ * "not decided yet" apart from "decided against", which `hasConsented`
+ * alone cannot express.
+ */
+ isResolved: false,
+
showConsentToast: false,
hasConsented: false,
acceptAll: () => {
@@ -191,7 +199,7 @@ export function applyPriorDecisionToSDK(
UC: Usercentrics,
initialUIValues: { initialLayer: number },
priorDecision: PriorConsentDecision
-): void {
+): void | Promise<void> {
// ref() prevents valtio from recursively proxying the SDK instance's internals in place,
// which would corrupt them the same way it once corrupted the AI Assistant's message array
consentState.UC = ref(UC)
@@ -211,7 +219,7 @@ export function applyPriorDecisionToSDK(
// including any added to the ruleset since the user's decision was
// stored — acceptAllServices applies to all current services.
consentState.hasConsented = true
- UC.acceptAllServices()
+ return UC.acceptAllServices()
.then(() => {
consentState.categories = UC.getCategoriesBaseInfo()
})
@@ -219,7 +227,6 @@ export function applyPriorDecisionToSDK(
consentState.hasConsented = false
consentState.showConsentToast = true
})
- return
}
// priorDecision.kind === 'decisions'. Only suppress the banner if the
@@ -246,7 +253,7 @@ export function applyPriorDecisionToSDK(
// 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)
+ return UC.updateServices(priorDecision.decisions)
.then(() => {
consentState.hasConsented = UC.areAllConsentsAccepted()
consentState.categories = UC.getCategoriesBaseInfo()
@@ -256,7 +263,6 @@ export function applyPriorDecisionToSDK(
// uniform state the user didn't choose.
consentState.showConsentToast = true
})
- return
}
// 0 = first layer, aka show consent toast
@@ -282,6 +288,7 @@ async function initUserCentrics() {
process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging'
) {
consentState.hasConsented = true
+ consentState.isResolved = true
return
}
@@ -298,7 +305,7 @@ async function initUserCentrics() {
})
const initialUIValues = await UC.init()
- applyPriorDecisionToSDK(UC, initialUIValues, priorDecision)
+ await applyPriorDecisionToSDK(UC, initialUIValues, priorDecision)
} catch (error) {
console.error('Failed to initialize Usercentrics:', error)
// If SDK fails but user previously accepted uniformly, honor that.
@@ -307,6 +314,8 @@ async function initUserCentrics() {
if (priorDecision?.kind === 'uniform-accept') {
consentState.hasConsented = true
}
+ } finally {
+ consentState.isResolved = true
}
}
diff --git a/packages/common/consented-url-cookie.test.ts b/packages/common/consented-url-cookie.test.ts
new file mode 100644
index 00000000000..0445448d128
--- /dev/null
+++ b/packages/common/consented-url-cookie.test.ts
@@ -0,0 +1,300 @@
+// @vitest-environment jsdom
+/// <reference types="vitest/jsdom" />
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { consentState } from './consent-state'
+import {
+ clearConsentedUrlCookie,
+ createConsentedUrlCookieSync,
+ discardConsentedUrlValue,
+} from './consented-url-cookie'
+
+vi.hoisted(() => {
+ vi.stubEnv('NEXT_PUBLIC_VERCEL_ENV', 'production')
+ // The shared browser helpers also read this API during module initialization.
+ window.matchMedia = vi.fn().mockReturnValue({ matches: false })
+})
+
+const COOKIE_VALUE = 'bfc_test_1.Opaque_Value.signature'
+const SECOND_COOKIE_VALUE = 'bfc_test_1.Second_Value.signature'
+
+function openPage(url = `https://supabase.com/?bfcid=${COOKIE_VALUE}`) {
+ jsdom.reconfigure({ url })
+ return jsdom
+}
+
+beforeEach(() => {
+ // Undecided: the sync writes the cookie on an explicit `true` regardless of
+ // proxy state, so this default lets both paths be exercised.
+ consentState.isResolved = false
+ consentState.showConsentToast = false
+ consentState.hasConsented = false
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ jsdom.cookieJar.removeAllCookiesSync()
+ sessionStorage.clear()
+})
+
+describe('consented URL cookie', () => {
+ it('keeps the URL parameter in memory until consent, including after SPA navigation', () => {
+ const page = openPage()
+ const sync = createConsentedUrlCookieSync()
+
+ sync(false)
+ expect(document.cookie).toBe('')
+ window.history.replaceState(null, '', '/next-page')
+ sync(false)
+ expect(document.cookie).toBe('')
+
+ sync(true)
+ expect(page.cookieJar.getCookieStringSync('https://subdomain.supabase.com/endpoint')).toBe(
+ `bfcid=${COOKIE_VALUE}`
+ )
+ })
+
+ it('recovers the parameter after a page load that happened before consent', () => {
+ openPage()
+ createConsentedUrlCookieSync()(false)
+ expect(document.cookie).toBe('')
+
+ // A new page load builds a fresh closure and the URL no longer carries the parameter.
+ jsdom.reconfigure({ url: 'https://supabase.com/pricing' })
+ const afterNavigation = createConsentedUrlCookieSync()
+ afterNavigation(false)
+ afterNavigation(true)
+
+ expect(document.cookie).toBe(`bfcid=${COOKIE_VALUE}`)
+ })
+
+ it('drops the retained parameter once consent is denied', () => {
+ openPage()
+ createConsentedUrlCookieSync()(false)
+
+ discardConsentedUrlValue()
+
+ jsdom.reconfigure({ url: 'https://supabase.com/pricing' })
+ createConsentedUrlCookieSync()(true)
+ expect(document.cookie).toBe('')
+ })
+
+ it('does not throw when session storage is blocked', () => {
+ openPage()
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('Storage access blocked')
+ })
+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
+ throw new Error('Storage access blocked')
+ })
+
+ const sync = createConsentedUrlCookieSync()
+ expect(() => sync(false)).not.toThrow()
+ expect(() => sync(true)).not.toThrow()
+ })
+
+ it('makes the unchanged cookie value available across subdomains and paths', () => {
+ const page = openPage()
+ createConsentedUrlCookieSync()(true)
+
+ const cookies = page.cookieJar.getCookiesSync('https://subdomain.supabase.com/endpoint')
+ expect(cookies).toHaveLength(1)
+ expect(cookies[0]).toMatchObject({
+ key: 'bfcid',
+ value: COOKIE_VALUE,
+ domain: 'supabase.com',
+ path: '/',
+ secure: true,
+ sameSite: 'lax',
+ maxAge: 2_592_000,
+ })
+ expect(page.cookieJar.getCookieStringSync('https://supabase.com/next-page')).toBe(
+ `bfcid=${COOKIE_VALUE}`
+ )
+ expect(page.cookieJar.getCookieStringSync('https://example.com/')).toBe('')
+ expect(page.cookieJar.getCookieStringSync('http://subdomain.supabase.com/endpoint')).toBe('')
+ })
+
+ it('preserves the cookie on later visits without refreshing its lifetime', () => {
+ const page = openPage()
+ createConsentedUrlCookieSync()(true)
+ const writeCookie = vi.spyOn(document, 'cookie', 'set')
+
+ createConsentedUrlCookieSync()(true)
+ window.history.replaceState(null, '', '/next-page')
+ createConsentedUrlCookieSync()(true)
+
+ expect(writeCookie).not.toHaveBeenCalled()
+ expect(page.cookieJar.getCookieStringSync('https://subdomain.supabase.com/')).toBe(
+ `bfcid=${COOKIE_VALUE}`
+ )
+ })
+
+ it('replaces the cookie when a new consented URL parameter arrives', () => {
+ openPage()
+ createConsentedUrlCookieSync()(true)
+ window.history.replaceState(null, '', `/?bfcid=${SECOND_COOKIE_VALUE}`)
+ createConsentedUrlCookieSync()(true)
+ expect(document.cookie).toBe(`bfcid=${SECOND_COOKIE_VALUE}`)
+ })
+
+ it('does not erase a returning visitor’s cookie while consent initializes', () => {
+ openPage()
+ createConsentedUrlCookieSync()(true)
+ window.history.replaceState(null, '', '/next-page')
+ const sync = createConsentedUrlCookieSync()
+
+ sync(false)
+ sync(true)
+ expect(document.cookie).toBe(`bfcid=${COOKIE_VALUE}`)
+ })
+
+ it('keeps the retained value while the banner is still showing', async () => {
+ openPage()
+ createConsentedUrlCookieSync()(false)
+ expect(sessionStorage.getItem('sb-bfcid-pending')).not.toBeNull()
+
+ consentState.isResolved = true
+ consentState.showConsentToast = true
+
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ // An undecided visitor may still accept, so the value waits for them.
+ expect(sessionStorage.getItem('sb-bfcid-pending')).not.toBeNull()
+ })
+
+ it('clears an existing cookie when the decision resolves to no consent', async () => {
+ openPage()
+ createConsentedUrlCookieSync()(true)
+ document.cookie = 'unrelated=keep; Path=/'
+
+ consentState.isResolved = true
+ consentState.showConsentToast = true
+
+ await vi.waitFor(() => expect(document.cookie).toBe('unrelated=keep'))
+ })
+
+ // acceptAll sets hasConsented before the Usercentrics promise settles, so
+ // the cookie is written optimistically. Its failure path flips consent back
+ // and re-shows the banner, which has to take the cookie with it.
+ it('clears the cookie when an optimistic acceptance is rolled back', async () => {
+ openPage()
+ createConsentedUrlCookieSync()(true)
+ expect(document.cookie).toContain('bfcid=')
+
+ consentState.isResolved = true
+ consentState.hasConsented = false
+ consentState.showConsentToast = true
+
+ await vi.waitFor(() => expect(document.cookie).not.toContain('bfcid='))
+ })
+
+ it('discards the retained value once the visitor declines', async () => {
+ openPage()
+ createConsentedUrlCookieSync()(false)
+ expect(sessionStorage.getItem('sb-bfcid-pending')).not.toBeNull()
+
+ consentState.isResolved = true
+
+ await vi.waitFor(() => expect(sessionStorage.getItem('sb-bfcid-pending')).toBeNull())
+ expect(document.cookie).not.toContain('bfcid=')
+ })
+
+ it('does not clear anything before the consent decision resolves', async () => {
+ openPage()
+ createConsentedUrlCookieSync()(true)
+
+ consentState.isResolved = false
+ consentState.hasConsented = false
+
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ expect(document.cookie).toContain('bfcid=')
+ })
+
+ it('clears host-only and shared cookies for an explicit denial', () => {
+ const page = openPage()
+ createConsentedUrlCookieSync()(true)
+ document.cookie = `bfcid=${SECOND_COOKIE_VALUE}; Path=/`
+
+ clearConsentedUrlCookie()
+ expect(document.cookie).toBe('')
+ expect(page.cookieJar.getCookieStringSync('https://subdomain.supabase.com/')).toBe('')
+ })
+
+ it.each([
+ '',
+ '?bfcid=',
+ '?bfcid=bfc_',
+ '?bfcid=invalid-value',
+ '?bfcid=bfc_unsafe%3Bvalue',
+ '?bfcid=bfc_unsafe%0A',
+ '?bfcid=bfc_unsafe%0D',
+ '?bfcid=bfc_unsafe+value',
+ `?bfcid=bfc_${'a'.repeat(509)}`,
+ `?bfcid=${COOKIE_VALUE}&bfcid=${SECOND_COOKIE_VALUE}`,
+ ])('does not store missing, ambiguous or unsafe values: %s', (query) => {
+ openPage(`https://supabase.com/${query}`)
+ createConsentedUrlCookieSync()(true)
+ expect(document.cookie).toBe('')
+ })
+
+ it('preserves the full 512-character identifier without truncation', () => {
+ // Freebuff validates with /^bfc_[A-Za-z0-9._-]{1,508}$/, so anything
+ // longer would be stored here and then rejected by them.
+ const cookieValue = `bfc_${'a'.repeat(508)}`
+ openPage(`https://supabase.com/?bfcid=${cookieValue}`)
+ createConsentedUrlCookieSync()(true)
+ expect(document.cookie).toBe(`bfcid=${cookieValue}`)
+ })
+
+ it.each(['http://localhost:3000', 'https://preview.example.com', 'https://supabase.com.example'])(
+ 'uses host-only storage on a development or preview origin: %s',
+ (origin) => {
+ const page = openPage(`${origin}/?bfcid=${COOKIE_VALUE}`)
+ createConsentedUrlCookieSync()(true)
+ expect(document.cookie).toBe(`bfcid=${COOKIE_VALUE}`)
+ expect(page.cookieJar.getCookiesSync(origin)[0].hostOnly).toBe(true)
+ expect(page.cookieJar.getCookieStringSync('https://subdomain.supabase.com/')).toBe('')
+ }
+ )
+
+ it('follows the shared host-only policy for preview deployments on a Supabase subdomain', async () => {
+ const page = openPage(`https://preview.supabase.com/?bfcid=${COOKIE_VALUE}`)
+ vi.stubEnv('NEXT_PUBLIC_VERCEL_ENV', 'preview')
+ vi.resetModules()
+
+ try {
+ const { createConsentedUrlCookieSync: createPreviewCookieSync } =
+ await import('./consented-url-cookie')
+ createPreviewCookieSync()(true)
+
+ expect(document.cookie).toBe(`bfcid=${COOKIE_VALUE}`)
+ expect(page.cookieJar.getCookiesSync('https://preview.supabase.com/')[0].hostOnly).toBe(true)
+ expect(page.cookieJar.getCookieStringSync('https://subdomain.supabase.com/')).toBe('')
+ } finally {
+ vi.stubEnv('NEXT_PUBLIC_VERCEL_ENV', 'production')
+ }
+ })
+
+ it('does not throw during cookie setup or consent changes when storage is blocked', () => {
+ openPage()
+ vi.spyOn(document, 'cookie', 'get').mockImplementation(() => {
+ throw new Error('Cookie access blocked')
+ })
+ vi.spyOn(document, 'cookie', 'set').mockImplementation(() => {
+ throw new Error('Cookie access blocked')
+ })
+
+ const sync = createConsentedUrlCookieSync()
+ expect(() => sync(true)).not.toThrow()
+ expect(() => sync(false)).not.toThrow()
+ expect(() => clearConsentedUrlCookie()).not.toThrow()
+ })
+
+ it('does not access browser globals during server rendering', () => {
+ vi.stubGlobal('window', undefined)
+ vi.stubGlobal('document', undefined)
+ expect(() => createConsentedUrlCookieSync()(true)).not.toThrow()
+ expect(() => clearConsentedUrlCookie()).not.toThrow()
+ })
+})
diff --git a/packages/common/consented-url-cookie.ts b/packages/common/consented-url-cookie.ts
new file mode 100644
index 00000000000..e9224b02c11
--- /dev/null
+++ b/packages/common/consented-url-cookie.ts
@@ -0,0 +1,137 @@
+import { subscribe } from 'valtio'
+
+import { consentState } from './consent-state'
+import { getTelemetryCookieOptions } from './telemetry-utils'
+
+const COOKIE_NAME = 'bfcid'
+const COOKIE_MAX_AGE = 60 * 60 * 24 * 30
+// Not held in memory, because it has to survive the page load the visitor
+// landed on. Session-scoped, so it never outlives the tab.
+const PENDING_STORAGE_KEY = 'sb-bfcid-pending'
+
+// Mirrors the validator Freebuff publishes, so a value stored here is never
+// one they reject.
+const CLICK_ID_SHAPE = /^bfc_[A-Za-z0-9._-]{1,508}$/
+
+function readPendingValue(): string | null {
+ try {
+ return sessionStorage.getItem(PENDING_STORAGE_KEY)
+ } catch {
+ return null
+ }
+}
+
+function writePendingValue(value: string): void {
+ try {
+ sessionStorage.setItem(PENDING_STORAGE_KEY, value)
+ } catch {
+ // Storage restrictions must not prevent the page from rendering.
+ }
+}
+
+function clearPendingValue(): void {
+ try {
+ sessionStorage.removeItem(PENDING_STORAGE_KEY)
+ } catch {
+ // Storage restrictions must not prevent a consent update.
+ }
+}
+
+function getParameterValue(url: string): string | null {
+ try {
+ const values = new URL(url).searchParams.getAll(COOKIE_NAME)
+ if (values.length !== 1) return null
+
+ const value = values[0]
+ return CLICK_ID_SHAPE.test(value) ? value : null
+ } catch {
+ return null
+ }
+}
+
+function getCookieOptions(): string {
+ return `${getTelemetryCookieOptions()}${window.location.protocol === 'https:' ? '; Secure' : ''}`
+}
+
+/** Remove the cookie, leaving any value still awaiting a consent decision. */
+export function clearConsentedUrlCookie(): void {
+ if (typeof document === 'undefined') return
+
+ try {
+ document.cookie = `${COOKIE_NAME}=; Max-Age=0; ${getCookieOptions()}`
+ // Outside production the write is host-only, so clear that variant too.
+ document.cookie = `${COOKIE_NAME}=; Max-Age=0; Path=/; SameSite=Lax`
+ } catch {
+ // Cookie restrictions must not break the page.
+ }
+}
+
+/** Remove the cookie and any value awaiting a consent decision. */
+export function discardConsentedUrlValue(): void {
+ clearPendingValue()
+ clearConsentedUrlCookie()
+}
+
+/** True until the visitor has either accepted or declined. */
+function isDecisionPending(): boolean {
+ return !consentState.isResolved || consentState.showConsentToast
+}
+
+/**
+ * The single rule tying the stored click id to the consent decision.
+ *
+ * Undecided and declined both mean there is no consent to point at, so the
+ * cookie goes either way. They differ in the retained value: an undecided
+ * visitor may still accept, so it is kept until they decide.
+ */
+function enforceConsentDecision(): void {
+ if (!consentState.isResolved || consentState.hasConsented) return
+
+ if (consentState.showConsentToast) {
+ clearConsentedUrlCookie()
+ return
+ }
+
+ discardConsentedUrlValue()
+}
+
+if (typeof window !== 'undefined') {
+ subscribe(consentState, enforceConsentDecision)
+}
+
+/**
+ * Retain the click id until consent permits writing a cookie.
+ *
+ * The cookie is scoped to `domain=supabase.com` so the management API receives
+ * it, and is written only after consent, which is how the API knows consent
+ * was granted.
+ */
+export function createConsentedUrlCookieSync() {
+ return (hasAccepted: boolean): void => {
+ if (typeof window === 'undefined') return
+
+ const valueFromUrl = getParameterValue(window.location.href)
+ if (valueFromUrl && !hasAccepted && isDecisionPending()) {
+ writePendingValue(valueFromUrl)
+ }
+
+ if (!hasAccepted) return
+
+ const value = valueFromUrl ?? readPendingValue()
+ if (!value) return
+
+ try {
+ const cookie = `${COOKIE_NAME}=${value}`
+ const hasSameValue = document.cookie.split(';').some((part) => part.trim() === cookie)
+
+ // Ordinary navigation must not extend the original cookie lifetime.
+ if (!hasSameValue) {
+ document.cookie = `${cookie}; Max-Age=${COOKIE_MAX_AGE}; ${getCookieOptions()}`
+ }
+ } catch {
+ // Cookie restrictions must not break the page.
+ }
+
+ clearPendingValue()
+ }
+}
diff --git a/packages/common/telemetry.tsx b/packages/common/telemetry.tsx
index f3cce2f6286..df65839f461 100644
--- a/packages/common/telemetry.tsx
+++ b/packages/common/telemetry.tsx
@@ -4,11 +4,12 @@ import { components } from 'api-types'
import { useRouter } from 'next/compat/router'
import { usePathname } from 'next/navigation'
import Script from 'next/script'
-import { useCallback, useEffect, useRef } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
import { useLatest } from 'react-use'
import { useUser } from './auth'
import { hasConsented, useConsentState } from './consent-state'
+import { createConsentedUrlCookieSync } from './consented-url-cookie'
import { IS_PLATFORM } from './constants'
import { useFeatureFlags } from './feature-flags'
import { post } from './fetchWrappers'
@@ -46,11 +47,18 @@ export {
export const TelemetryTagManager = () => {
const { hasAccepted } = useConsentState()
+ const [syncCookie] = useState(createConsentedUrlCookieSync)
const isGTMEnabled = Boolean(
IS_PLATFORM && process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID && hasAccepted
)
+ // Ad attribution capture is independent of GTM, so this runs even when the
+ // container is not configured.
+ useEffect(() => {
+ syncCookie(hasAccepted)
+ }, [hasAccepted, syncCookie])
+
if (!isGTMEnabled) return null
return (
@@ -95,6 +103,7 @@ function getFirstTouchAttributionProps(telemetryData: SharedTelemetryData) {
...(getParam('ttclid') && { ttclid: getParam('ttclid') }), // TikTok Ads
...(getParam('twclid') && { twclid: getParam('twclid') }), // X Ads (Twitter)
...(getParam('li_fat_id') && { li_fat_id: getParam('li_fat_id') }), // LinkedIn Ads
+ ...(getParam('bfcid') && { bfcid: getParam('bfcid') }), // Freebuff Ads
}
return {