diff --git a/src/__tests__/components/analytics.test.tsx b/src/__tests__/components/analytics.test.tsx new file mode 100644 index 00000000000..31fea287098 --- /dev/null +++ b/src/__tests__/components/analytics.test.tsx @@ -0,0 +1,164 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { render } from "@testing-library/react"; +import { Analytics, buildGtagInitScript } from "@/components/layout/analytics"; +import { applyAnalyticsAuthState } from "@/lib/analytics"; + +type SessionStatus = "loading" | "authenticated" | "unauthenticated"; + +const sessionState = vi.hoisted(() => ({ + status: "loading" as SessionStatus, + user: null as null | { id: string; analyticsId?: string }, +})); + +vi.mock("next-auth/react", () => ({ + useSession: () => ({ + status: sessionState.status, + data: sessionState.user ? { user: sessionState.user } : null, + }), +})); + +vi.mock("next/script", () => ({ + default: () => null, +})); + +function gtagCalls(dataLayer: unknown[]) { + return dataLayer.map((entry) => Array.from(entry as ArrayLike)); +} + +function runInitScript(script: string, consent: string | null) { + const fakeWindow = { dataLayer: [] as unknown[] }; + const fakeStorage = { getItem: (key: string) => (key === "cookie-consent" ? consent : null) }; + new Function("window", "dataLayer", "localStorage", script)(fakeWindow, fakeWindow.dataLayer, fakeStorage); + return gtagCalls(fakeWindow.dataLayer); +} + +describe("buildGtagInitScript", () => { + it("sets logged_in and user_id before config so the first page_view carries them", () => { + const script = buildGtagInitScript({ gaId: "G-MSNHFWTE77", loggedIn: true, analyticsId: "abc123" }); + const calls = runInitScript(script, "accepted"); + + expect(calls.map((c) => c[0])).toEqual(["js", "set", "set", "config"]); + expect(calls[1]).toEqual(["set", "user_properties", { logged_in: "true" }]); + expect(calls[2]).toEqual(["set", { user_id: "abc123" }]); + expect(calls[3]).toEqual(["config", "G-MSNHFWTE77"]); + }); + + it("does not send user_id without analytics cookie consent", () => { + const script = buildGtagInitScript({ gaId: "G-TEST", loggedIn: true, analyticsId: "abc123" }); + for (const consent of [null, "rejected"]) { + const calls = runInitScript(script, consent); + expect(calls).toContainEqual(["set", "user_properties", { logged_in: "true" }]); + expect(calls.some((c) => (c[1] as { user_id?: unknown })?.user_id !== undefined)).toBe(false); + } + }); + + it("marks anonymous visitors as logged_in=false and sends no user_id", () => { + const calls = runInitScript(buildGtagInitScript({ gaId: "G-TEST", loggedIn: false, analyticsId: null }), "accepted"); + expect(calls).toEqual([ + ["js", expect.any(Date)], + ["set", "user_properties", { logged_in: "false" }], + ["config", "G-TEST"], + ]); + }); + + it("omits the user property when the server could not resolve the session", () => { + const calls = runInitScript(buildGtagInitScript({ gaId: "G-TEST" }), "accepted"); + expect(calls.map((c) => c[0])).toEqual(["js", "config"]); + }); + + it("escapes values so they cannot break out of the script tag", () => { + const script = buildGtagInitScript({ gaId: "G-"); + }); +}); + +describe("applyAnalyticsAuthState", () => { + beforeEach(() => { + delete window.gtag; + window.dataLayer = []; + }); + + it("queues commands on dataLayer when gtag is not defined yet", () => { + applyAnalyticsAuthState({ loggedIn: true, userId: "abc" }); + expect(gtagCalls(window.dataLayer!)).toEqual([ + ["set", "user_properties", { logged_in: "true" }], + ["set", { user_id: "abc" }], + ]); + }); + + it("clears user_id with null only when one was previously set", () => { + const gtag = vi.fn(); + window.gtag = gtag; + + applyAnalyticsAuthState({ loggedIn: false, userId: null }, { loggedIn: true, userId: "abc" }); + expect(gtag.mock.calls).toEqual([ + ["set", "user_properties", { logged_in: "false" }], + ["set", { user_id: null }], + ]); + + gtag.mockClear(); + applyAnalyticsAuthState({ loggedIn: false, userId: null }, null); + expect(gtag.mock.calls).toEqual([["set", "user_properties", { logged_in: "false" }]]); + }); +}); + +describe("Analytics session sync", () => { + let gtag: ReturnType; + + beforeEach(() => { + gtag = vi.fn(); + window.gtag = gtag; + localStorage.clear(); + sessionState.status = "loading"; + sessionState.user = null; + }); + + it("does nothing while the client session matches the server state", () => { + sessionState.status = "authenticated"; + sessionState.user = { id: "u1", analyticsId: "abc" }; + localStorage.setItem("cookie-consent", "accepted"); + + render(); + expect(gtag).not.toHaveBeenCalled(); + }); + + it("updates GA when the user signs in without a full page load", () => { + localStorage.setItem("cookie-consent", "accepted"); + sessionState.status = "unauthenticated"; + const { rerender } = render(); + expect(gtag).not.toHaveBeenCalled(); + + sessionState.status = "authenticated"; + sessionState.user = { id: "u1", analyticsId: "abc" }; + rerender(); + + expect(gtag.mock.calls).toEqual([ + ["set", "user_properties", { logged_in: "true" }], + ["set", { user_id: "abc" }], + ]); + }); + + it("clears user_id when the session ends", () => { + localStorage.setItem("cookie-consent", "accepted"); + sessionState.status = "authenticated"; + sessionState.user = { id: "u1", analyticsId: "abc" }; + const { rerender } = render(); + + sessionState.status = "unauthenticated"; + sessionState.user = null; + rerender(); + + expect(gtag.mock.calls).toEqual([ + ["set", "user_properties", { logged_in: "false" }], + ["set", { user_id: null }], + ]); + }); + + it("sets logged_in but not user_id without consent", () => { + sessionState.status = "authenticated"; + sessionState.user = { id: "u1", analyticsId: "abc" }; + + render(); + expect(gtag.mock.calls).toEqual([["set", "user_properties", { logged_in: "true" }]]); + }); +}); diff --git a/src/__tests__/lib/analytics-user.test.ts b/src/__tests__/lib/analytics-user.test.ts new file mode 100644 index 00000000000..8caaf8e070b --- /dev/null +++ b/src/__tests__/lib/analytics-user.test.ts @@ -0,0 +1,48 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { getAnalyticsUserId } from "@/lib/analytics-user"; + +describe("getAnalyticsUserId", () => { + const originalEnv = { ...process.env }; + + beforeEach(() => { + process.env.GOOGLE_ANALYTICS_ID = "G-TEST123"; + process.env.AUTH_SECRET = "secret-a"; + }); + + afterEach(() => { + process.env = { ...originalEnv }; + }); + + it("returns a stable 32-char hex id that does not contain the raw id", () => { + const id = getAnalyticsUserId("cluser123"); + expect(id).toMatch(/^[0-9a-f]{32}$/); + expect(id).not.toContain("cluser123"); + expect(getAnalyticsUserId("cluser123")).toBe(id); + }); + + it("differs per user and per secret", () => { + const a = getAnalyticsUserId("user-a"); + expect(getAnalyticsUserId("user-b")).not.toBe(a); + process.env.AUTH_SECRET = "secret-b"; + expect(getAnalyticsUserId("user-a")).not.toBe(a); + }); + + it("falls back to NEXTAUTH_SECRET", () => { + delete process.env.AUTH_SECRET; + process.env.NEXTAUTH_SECRET = "legacy-secret"; + expect(getAnalyticsUserId("user-a")).toMatch(/^[0-9a-f]{32}$/); + }); + + it("returns null without a user id, GA id, or secret", () => { + expect(getAnalyticsUserId(undefined)).toBeNull(); + expect(getAnalyticsUserId("")).toBeNull(); + + delete process.env.GOOGLE_ANALYTICS_ID; + expect(getAnalyticsUserId("user-a")).toBeNull(); + + process.env.GOOGLE_ANALYTICS_ID = "G-TEST123"; + delete process.env.AUTH_SECRET; + delete process.env.NEXTAUTH_SECRET; + expect(getAnalyticsUserId("user-a")).toBeNull(); + }); +}); diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 4124c77b1b1..ebfde63336a 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,6 +1,7 @@ import type { Metadata } from "next"; import { Inter, Noto_Sans_Arabic, Geist_Mono, Playfair_Display } from "next/font/google"; import { headers } from "next/headers"; +import { unstable_rethrow } from "next/navigation"; import { getMessages, getLocale } from "next-intl/server"; import { Providers } from "@/components/providers"; import { Header } from "@/components/layout/header"; @@ -11,6 +12,7 @@ import { AppBanner } from "@/components/layout/app-banner"; import { AnnouncementBanner } from "@/components/layout/announcement-banner"; import { LocaleDetector } from "@/components/providers/locale-detector"; import { getConfig } from "@/lib/config"; +import { auth } from "@/lib/auth"; import { isRtlLocale } from "@/lib/i18n/config"; import { getBaseUrl } from "@/lib/seo"; import "./globals.css"; @@ -117,6 +119,20 @@ const radiusValues = { lg: "0.75rem", }; +async function getAnalyticsAuth(): Promise<{ loggedIn: boolean; analyticsId: string | null } | undefined> { + try { + const session = await auth(); + return { + loggedIn: !!session?.user, + analyticsId: session?.user?.analyticsId ?? null, + }; + } catch (error) { + unstable_rethrow(error); + // Leave it to the client-side session sync rather than failing the page + return undefined; + } +} + function hexToOklch(hex: string): string { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if (!result) return "oklch(0.5 0.2 260)"; @@ -155,6 +171,8 @@ export default async function RootLayout({ const messages = await getMessages(); const config = await getConfig(); const isRtl = isRtlLocale(locale); + const gaId = process.env.GOOGLE_ANALYTICS_ID; + const analyticsAuth = gaId ? await getAnalyticsAuth() : undefined; // Calculate theme values server-side const themeClasses = `theme-${config.theme.variant} density-${config.theme.density}`; @@ -183,10 +201,10 @@ export default async function RootLayout({ )} - {process.env.GOOGLE_ANALYTICS_ID && ( - - )} + {gaId && ( + + )} {isEmbedRoute || isKidsRoute ? ( children ) : ( diff --git a/src/app/privacy/page.tsx b/src/app/privacy/page.tsx index d3a4fa2923f..1d42e101973 100644 --- a/src/app/privacy/page.tsx +++ b/src/app/privacy/page.tsx @@ -99,7 +99,9 @@ export default function PrivacyPage() {

We use essential cookies for authentication and session management. We use Google Analytics to understand how the service is used, including tracking events such as prompt views, searches, - and interactions. On self-hosted instances, analytics can be disabled by not setting the + and interactions. Analytics records whether a visit is signed in, and, if you accept analytics + cookies, a pseudonymous identifier derived from your account (never your email, username, or + account id) so visits can be counted across devices. On self-hosted instances, analytics can be disabled by not setting the GOOGLE_ANALYTICS_ID environment variable.

diff --git a/src/components/layout/analytics.tsx b/src/components/layout/analytics.tsx index 0d4bd68a067..3a825c8f59a 100644 --- a/src/components/layout/analytics.tsx +++ b/src/components/layout/analytics.tsx @@ -1,19 +1,81 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useRef } from "react"; import Script from "next/script"; -import { getCookieConsent } from "./cookie-consent"; +import { useSession } from "next-auth/react"; +import { + applyAnalyticsAuthState, + GA_LOGGED_IN_PROPERTY, + type AnalyticsAuthState, +} from "@/lib/analytics"; +import { COOKIE_CONSENT_KEY, getCookieConsent } from "./cookie-consent"; interface AnalyticsProps { gaId: string; + /** Server-resolved sign-in state; undefined when it could not be determined. */ + loggedIn?: boolean; + analyticsId?: string | null; } -export function Analytics({ gaId }: AnalyticsProps) { - const [hasConsent, setHasConsent] = useState(false); +function toScriptLiteral(value: string): string { + return JSON.stringify(value).replace(/(null); + const sessionLoggedIn = !!session?.user; + const sessionAnalyticsId = session?.user?.analyticsId ?? null; useEffect(() => { - setHasConsent(getCookieConsent() === "accepted"); - }, []); + const consented = getCookieConsent() === "accepted"; + + if (applied.current === null && loggedIn !== undefined) { + applied.current = { + loggedIn, + userId: loggedIn && consented ? analyticsId ?? null : null, + }; + } + + if (status === "loading") return; + + const next: AnalyticsAuthState = { + loggedIn: sessionLoggedIn, + userId: sessionLoggedIn && consented ? sessionAnalyticsId : null, + }; + const current = applied.current; + if (current && current.loggedIn === next.loggedIn && current.userId === next.userId) return; + + applyAnalyticsAuthState(next, current); + applied.current = next; + }, [status, sessionLoggedIn, sessionAnalyticsId, loggedIn, analyticsId]); return ( <> @@ -22,12 +84,7 @@ export function Analytics({ gaId }: AnalyticsProps) { strategy="afterInteractive" /> ); diff --git a/src/components/layout/cookie-consent.tsx b/src/components/layout/cookie-consent.tsx index 1b440d9f2a2..ad4f3207439 100644 --- a/src/components/layout/cookie-consent.tsx +++ b/src/components/layout/cookie-consent.tsx @@ -5,7 +5,7 @@ import { useTranslations } from "next-intl"; import { Button } from "@/components/ui/button"; import { Cookie } from "lucide-react"; -const COOKIE_CONSENT_KEY = "cookie-consent"; +export const COOKIE_CONSENT_KEY = "cookie-consent"; export type CookieConsent = "accepted" | "rejected" | null; diff --git a/src/lib/analytics-user.ts b/src/lib/analytics-user.ts new file mode 100644 index 00000000000..320f7718261 --- /dev/null +++ b/src/lib/analytics-user.ts @@ -0,0 +1,21 @@ +import { createHmac } from "crypto"; + +/** + * Derives the pseudonymous id sent to Google Analytics as `user_id`. + * + * HMAC-SHA256 keyed with the server's auth secret, so it cannot be reversed + * to the database id (or brute-forced from it) without that secret. Returns + * null when analytics is not configured or no secret is available, in which + * case no `user_id` is sent at all. + */ +export function getAnalyticsUserId(userId: string | null | undefined): string | null { + if (!userId || !process.env.GOOGLE_ANALYTICS_ID) return null; + + const secret = process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET; + if (!secret) return null; + + return createHmac("sha256", secret) + .update(`ga-user-id:${userId}`) + .digest("hex") + .slice(0, 32); +} diff --git a/src/lib/analytics.ts b/src/lib/analytics.ts index 2ca28eba7da..f27d1721bf1 100644 --- a/src/lib/analytics.ts +++ b/src/lib/analytics.ts @@ -7,14 +7,54 @@ declare global { interface Window { + dataLayer?: unknown[]; gtag?: ( - command: "event" | "config" | "js", - action: string, + command: "event" | "config" | "js" | "set", + target: string | Date | Record, params?: Record ) => void; } } +export const GA_LOGGED_IN_PROPERTY = "logged_in"; + +export interface AnalyticsAuthState { + loggedIn: boolean; + /** Pseudonymous id from `getAnalyticsUserId`, or null to send no `user_id`. */ + userId: string | null; +} + +/** + * Applies the signed-in state to every subsequent GA hit on the page via + * `gtag('set')`. Only called when GA is configured, so the stub it may create + * is drained once gtag.js loads, keeping command order intact. + */ +export function applyAnalyticsAuthState( + state: AnalyticsAuthState, + previous?: AnalyticsAuthState | null +) { + if (typeof window === "undefined") return; + + if (!window.gtag) { + const dataLayer = (window.dataLayer = window.dataLayer || []); + window.gtag = function gtag() { + // gtag.js only processes Arguments objects, not arrays + // eslint-disable-next-line prefer-rest-params + dataLayer.push(arguments); + }; + } + + window.gtag("set", "user_properties", { + [GA_LOGGED_IN_PROPERTY]: state.loggedIn ? "true" : "false", + }); + + if (state.userId) { + window.gtag("set", { user_id: state.userId }); + } else if (previous?.userId) { + window.gtag("set", { user_id: null }); + } +} + type GTagEvent = { action: string; category: string; diff --git a/src/lib/auth/index.ts b/src/lib/auth/index.ts index 6a844c59acd..f4d49df4896 100644 --- a/src/lib/auth/index.ts +++ b/src/lib/auth/index.ts @@ -4,6 +4,7 @@ import { db } from "@/lib/db"; import { isUniqueConstraintViolation } from "@/lib/db-errors"; import { getConfig } from "@/lib/config"; import { initializePlugins, getAuthPlugin } from "@/lib/plugins"; +import { getAnalyticsUserId } from "@/lib/analytics-user"; import type { Adapter, AdapterUser } from "next-auth/adapters"; // Initialize plugins before use @@ -208,6 +209,8 @@ async function buildAuthConfig() { session.user.locale = token.locale as string; session.user.name = token.name ?? null; session.user.image = token.picture ?? null; + const analyticsId = getAnalyticsUserId(token.id as string); + if (analyticsId) session.user.analyticsId = analyticsId; } return session; }, @@ -231,6 +234,7 @@ declare module "next-auth" { role: string; username: string; locale: string; + analyticsId?: string; }; } }