From 13b90f7e44c380e80bb06d5e7092e4624352ec01 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:46:16 -0300 Subject: [PATCH 01/14] feat(analytics): track navigation params on screen views --- .../providers/analytics-tracking.test.tsx | 96 ++++++++++++++++++- docs/src/content/docs/guides/analytics.mdx | 10 +- .../providers/analytics-tracking.ts | 64 +++++++++++-- 3 files changed, 159 insertions(+), 11 deletions(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index f1ea02243..0420a2ae2 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -1,4 +1,4 @@ -import { useSegments } from 'expo-router'; +import { useGlobalSearchParams, useSegments } from 'expo-router'; import { AnalyticsProvider } from '@/components/providers/analytics'; import { @@ -11,6 +11,7 @@ import { clearUserIdentified, hasIdentifiedUser, markUserIdentified } from '@/li import { renderHook, waitFor } from '@/lib/test-utils'; jest.mock('expo-router', () => ({ + useGlobalSearchParams: jest.fn(), useSegments: jest.fn(), })); @@ -19,6 +20,9 @@ jest.mock('@/components/providers/auth', () => ({ })); const mockUseSegments = useSegments as jest.MockedFunction<() => string[]>; +const mockUseGlobalSearchParams = useGlobalSearchParams as jest.MockedFunction< + () => Record | undefined> +>; const mockUseAuth = useAuth as jest.MockedFunction; function mockAuthenticated(isAuthenticated: boolean) { @@ -50,6 +54,7 @@ function renderWithAnalytics(hook: () => void, providers: ReadonlyArray { beforeEach(() => { jest.clearAllMocks(); + mockUseGlobalSearchParams.mockReturnValue({}); }); it('tracks the current screen on mount', async () => { @@ -75,6 +80,95 @@ describe('useAnalyticsScreenTracking', () => { }); }); + it('sends the route params along with the route pattern', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', tab: 'comments' }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', { id: '42', tab: 'comments' }); + }); + }); + + it('joins repeated params with commas and drops undefined values', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed']); + mockUseGlobalSearchParams.mockReturnValue({ tag: ['news', 'sports'], page: undefined }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed', { tag: 'news,sports' }); + }); + }); + + it('does not send the URL fragment', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed']); + mockUseGlobalSearchParams.mockReturnValue({ '#': 'access_token=secret', 'tab': 'comments' }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed', { tab: 'comments' }); + }); + }); + + it('converts primitive values to strings and drops nested objects', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed']); + (mockUseGlobalSearchParams as jest.Mock).mockReturnValue({ + page: 2, + draft: false, + filter: { status: 'open' }, + empty: null, + }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed', { draft: 'false', page: '2' }); + }); + }); + + it('tracks again when only the params change', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '1' }); + + const { rerender } = renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + mockUseGlobalSearchParams.mockReturnValue({ id: '2' }); + rerender({}); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(2); + }); + expect(provider.trackScreen).toHaveBeenLastCalledWith('/feed/[id]', { id: '2' }); + }); + + it('does not track again when the same params come back in a new object or order', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '1', tab: 'comments' }); + + const { rerender } = renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + mockUseGlobalSearchParams.mockReturnValue({ tab: 'comments', id: '1' }); + rerender({}); + await new Promise(resolve => setImmediate(resolve)); + + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + it('reports the index route of a group as the root screen', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['(app)']); diff --git a/docs/src/content/docs/guides/analytics.mdx b/docs/src/content/docs/guides/analytics.mdx index 2d22150db..d3c3115fb 100644 --- a/docs/src/content/docs/guides/analytics.mdx +++ b/docs/src/content/docs/guides/analytics.mdx @@ -78,9 +78,15 @@ Keep params flat and primitive (`string`, `number`, `boolean`, `null`) so they c ## Automatic screen tracking -`useAnalyticsScreenTracking` is called once in `AnalyticsTrackers`, a component that renders nothing and sits next to the root `Stack` in `GuardedStack` (`src/app/_layout.tsx`). `GuardedStack` only renders after auth has been hydrated, so the placeholder stack shown while auth loads is not reported, and keeping the hook in its own component means route changes re-render only that component, not the root `Stack`. It reads the current route with `useSegments()` from expo-router and calls `trackScreen` every time it changes, without any code in the screens themselves. The report waits one tick so that when a route guard redirects on launch (for example to `/sign-in`) only the screen the user lands on is reported, and the same screen is never reported twice in a row. +`useAnalyticsScreenTracking` is called once in `AnalyticsTrackers`, a component that renders nothing and sits next to the root `Stack` in `GuardedStack` (`src/app/_layout.tsx`). `GuardedStack` only renders after auth has been hydrated, so the placeholder stack shown while auth loads is not reported, and keeping the hook in its own component means route changes re-render only that component, not the root `Stack`. It reads the current route with `useSegments()` and its params with `useGlobalSearchParams()` from expo-router, and calls `trackScreen` every time either changes, without any code in the screens themselves. The report waits one tick so that when a route guard redirects on launch (for example to `/sign-in`) only the screen the user lands on is reported, and the same screen with the same params is never reported twice in a row. -Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small and keeps ids and other path values out of your vendors. If you need the concrete value, track it as an event param. +Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small. + +The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values are dropped, so params stay flat. The URL fragment (`#...`) is never sent. Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. + +:::caution +Route param values are forwarded to every registered provider. If your app puts sensitive values in routes (emails, tokens, personal data), drop or filter those keys inside the adapter's `trackScreen` before calling the vendor SDK. +::: diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index 74362abd0..e7702d320 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -1,10 +1,17 @@ -import { useSegments } from 'expo-router'; +import type { AnalyticsParams } from '@/lib/analytics'; +import { useGlobalSearchParams, useSegments } from 'expo-router'; import { useEffect, useRef } from 'react'; import { useAnalytics } from '@/components/providers/analytics'; import { useAuth } from '@/components/providers/auth'; import { hasIdentifiedUser } from '@/lib/analytics'; +/** + * expo-router exposes the URL fragment as a `#` param. It is not a route or + * search param and often carries credentials (e.g. `#access_token=...`). + */ +const HASH_PARAM = '#'; + function isRouteGroup(segment: string) { return segment.startsWith('(') && segment.endsWith(')'); } @@ -13,25 +20,66 @@ function toScreenName(segments: ReadonlyArray) { return `/${segments.filter(segment => !isRouteGroup(segment)).join('/')}`; } +function isPrimitiveParam(value: unknown): value is string | number | boolean { + return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'; +} + +/** + * Navigation params can hold non-string values at runtime (numbers, nested + * objects), so values are converted to strings and anything that is not a + * primitive (or an array of primitives) is dropped, keeping params flat. + */ +function toParamValue(value: unknown) { + if (Array.isArray(value)) { + return value.filter(isPrimitiveParam).map(String).join(','); + } + return isPrimitiveParam(value) ? String(value) : undefined; +} + +/** + * Serialises the route params into a stable key (sorted by name), so the same + * params in a different order are not reported as a new screen view. + * Repeated params are joined with commas. Returns an empty string when the + * route has no params. + */ +function toParamsKey(routeParams: Readonly>) { + const entries = Object.keys(routeParams) + .filter(key => key !== HASH_PARAM) + .sort() + .flatMap((key) => { + const value = toParamValue(routeParams[key]); + return value === undefined ? [] : [[key, value] as const]; + }); + return entries.length > 0 ? JSON.stringify(Object.fromEntries(entries)) : ''; +} + +function fromParamsKey(paramsKey: string): AnalyticsParams | undefined { + return paramsKey ? (JSON.parse(paramsKey) as Record) : undefined; +} + /** - * Reports a screen view to every analytics provider whenever the route - * changes. Call it once, inside `AnalyticsProvider`, after auth is ready. + * Reports a screen view to every analytics provider whenever the route or its + * params change, sending the route params (dynamic segments and search params) + * along with the route pattern. Call it once, inside `AnalyticsProvider`, + * after auth is ready. */ export function useAnalyticsScreenTracking() { const screenName = toScreenName(useSegments()); + const paramsKey = toParamsKey(useGlobalSearchParams()); const { trackScreen } = useAnalytics(); - const lastTrackedRef = useRef(null); + const lastTrackedRef = useRef<{ screenName: string; paramsKey: string } | null>(null); useEffect(() => { const timeout = setTimeout(() => { - if (lastTrackedRef.current === screenName) { + const last = lastTrackedRef.current; + if (last?.screenName === screenName && last.paramsKey === paramsKey) { return; } - lastTrackedRef.current = screenName; - trackScreen(screenName); + lastTrackedRef.current = { screenName, paramsKey }; + trackScreen(screenName, fromParamsKey(paramsKey)); }, 0); return () => clearTimeout(timeout); - }, [screenName, trackScreen]); + }, [screenName, paramsKey, trackScreen]); } /** From 7917068ca13993ef077c4c886660d7929354bbba Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:48:49 -0300 Subject: [PATCH 02/14] fix(analytics): never send sensitive-looking route params --- .../providers/analytics-tracking.test.tsx | 18 ++++++++++++++++++ docs/src/content/docs/guides/analytics.mdx | 4 ++-- src/components/providers/analytics-tracking.ts | 13 ++++++++++++- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index 0420a2ae2..2d30d3312 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -116,6 +116,24 @@ describe('useAnalyticsScreenTracking', () => { }); }); + it('does not send params whose name looks sensitive', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['update-password']); + mockUseGlobalSearchParams.mockReturnValue({ + access_token: 'fake-token', + resetCode: '123456', + Email: 'example@example.com', + apiKey: 'your-api-key', + tab: 'comments', + }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/update-password', { tab: 'comments' }); + }); + }); + it('converts primitive values to strings and drops nested objects', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['(app)', 'feed']); diff --git a/docs/src/content/docs/guides/analytics.mdx b/docs/src/content/docs/guides/analytics.mdx index d3c3115fb..ca93c86e3 100644 --- a/docs/src/content/docs/guides/analytics.mdx +++ b/docs/src/content/docs/guides/analytics.mdx @@ -82,10 +82,10 @@ Keep params flat and primitive (`string`, `number`, `boolean`, `null`) so they c Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small. -The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values are dropped, so params stay flat. The URL fragment (`#...`) is never sent. Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. +The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (it matches `SENSITIVE_PARAM_PATTERN`: `token`, `secret`, `password`, `code`, `otp`, `email`, `key`, `auth`, `session`, `signature` or `credential`, in any case and anywhere in the name, such as `resetCode` or `access_token`). Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. :::caution -Route param values are forwarded to every registered provider. If your app puts sensitive values in routes (emails, tokens, personal data), drop or filter those keys inside the adapter's `trackScreen` before calling the vendor SDK. +Every other route param value is forwarded to every registered provider. If your app puts sensitive values in routes under other names, add them to `SENSITIVE_PARAM_PATTERN` in `src/components/providers/analytics-tracking.ts`, or filter them inside the adapter's `trackScreen` before calling the vendor SDK. ::: diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index e7702d320..e1a17a33c 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -12,6 +12,17 @@ import { hasIdentifiedUser } from '@/lib/analytics'; */ const HASH_PARAM = '#'; +/** + * Params whose name looks like it holds a credential or personal data + * (deep-link tokens, reset codes, emails...) are never sent to vendors. + * Adjust the pattern to your app's routes; adapters can filter further. + */ +const SENSITIVE_PARAM_PATTERN = /token|secret|password|code|otp|email|key|auth|session|signature|credential/i; + +function isTrackableParam(key: string) { + return key !== HASH_PARAM && !SENSITIVE_PARAM_PATTERN.test(key); +} + function isRouteGroup(segment: string) { return segment.startsWith('(') && segment.endsWith(')'); } @@ -44,7 +55,7 @@ function toParamValue(value: unknown) { */ function toParamsKey(routeParams: Readonly>) { const entries = Object.keys(routeParams) - .filter(key => key !== HASH_PARAM) + .filter(isTrackableParam) .sort() .flatMap((key) => { const value = toParamValue(routeParams[key]); From f12a0128ab7451f4f1f235a18f4e044fff7271f6 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:50:06 -0300 Subject: [PATCH 03/14] fix(analytics): match sensitive param names by whole word --- .../providers/analytics-tracking.test.tsx | 7 ++++-- docs/src/content/docs/guides/analytics.mdx | 4 ++-- .../providers/analytics-tracking.ts | 22 ++++++++++++++----- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index 2d30d3312..342e9e2e2 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -116,7 +116,7 @@ describe('useAnalyticsScreenTracking', () => { }); }); - it('does not send params whose name looks sensitive', async () => { + it('does not send sensitive-looking or empty params but keeps similar names', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['update-password']); mockUseGlobalSearchParams.mockReturnValue({ @@ -125,12 +125,15 @@ describe('useAnalyticsScreenTracking', () => { Email: 'example@example.com', apiKey: 'your-api-key', tab: 'comments', + author: 'jane', + keyboard: 'compact', + empty: [], }); renderWithAnalytics(useAnalyticsScreenTracking, [provider]); await waitFor(() => { - expect(provider.trackScreen).toHaveBeenCalledWith('/update-password', { tab: 'comments' }); + expect(provider.trackScreen).toHaveBeenCalledWith('/update-password', { author: 'jane', keyboard: 'compact', tab: 'comments' }); }); }); diff --git a/docs/src/content/docs/guides/analytics.mdx b/docs/src/content/docs/guides/analytics.mdx index ca93c86e3..97a9ca263 100644 --- a/docs/src/content/docs/guides/analytics.mdx +++ b/docs/src/content/docs/guides/analytics.mdx @@ -82,10 +82,10 @@ Keep params flat and primitive (`string`, `number`, `boolean`, `null`) so they c Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small. -The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (it matches `SENSITIVE_PARAM_PATTERN`: `token`, `secret`, `password`, `code`, `otp`, `email`, `key`, `auth`, `session`, `signature` or `credential`, in any case and anywhere in the name, such as `resetCode` or `access_token`). Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. +The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (one of the words in `SENSITIVE_PARAM_WORDS`: `token`, `secret`, `password`, `code`, `otp`, `email`, `key`, `auth`, `session`, `signature` or `credential`, as a whole word of a camelCase, snake_case or kebab-case name, such as `resetCode` or `access_token`; `author` or `keyboard` are still sent). Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. :::caution -Every other route param value is forwarded to every registered provider. If your app puts sensitive values in routes under other names, add them to `SENSITIVE_PARAM_PATTERN` in `src/components/providers/analytics-tracking.ts`, or filter them inside the adapter's `trackScreen` before calling the vendor SDK. +Every other route param value is forwarded to every registered provider. If your app puts sensitive values in routes under other names, add their names to `SENSITIVE_PARAM_WORDS` in `src/components/providers/analytics-tracking.ts`, or filter them inside the adapter's `trackScreen` before calling the vendor SDK. ::: diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index e1a17a33c..294003d19 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -13,14 +13,23 @@ import { hasIdentifiedUser } from '@/lib/analytics'; const HASH_PARAM = '#'; /** - * Params whose name looks like it holds a credential or personal data - * (deep-link tokens, reset codes, emails...) are never sent to vendors. - * Adjust the pattern to your app's routes; adapters can filter further. + * Params with a word in their name that suggests a credential or personal + * data (deep-link tokens, reset codes, emails...) are never sent to vendors. + * Names are split on camelCase, `_` and `-` boundaries, so `resetCode` and + * `access_token` are dropped while `author` or `keyboard` are kept. + * Adjust the list to your app's routes; adapters can filter further. */ -const SENSITIVE_PARAM_PATTERN = /token|secret|password|code|otp|email|key|auth|session|signature|credential/i; +const SENSITIVE_PARAM_WORDS = new Set(['token', 'secret', 'password', 'code', 'otp', 'email', 'key', 'auth', 'session', 'signature', 'credential']); + +function toWords(key: string) { + return key + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .toLowerCase() + .split(/[^a-z0-9]+/); +} function isTrackableParam(key: string) { - return key !== HASH_PARAM && !SENSITIVE_PARAM_PATTERN.test(key); + return key !== HASH_PARAM && !toWords(key).some(word => SENSITIVE_PARAM_WORDS.has(word)); } function isRouteGroup(segment: string) { @@ -42,7 +51,8 @@ function isPrimitiveParam(value: unknown): value is string | number | boolean { */ function toParamValue(value: unknown) { if (Array.isArray(value)) { - return value.filter(isPrimitiveParam).map(String).join(','); + const values = value.filter(isPrimitiveParam); + return values.length > 0 ? values.map(String).join(',') : undefined; } return isPrimitiveParam(value) ? String(value) : undefined; } From daa60d900f550810c53ee470f61b9fb3a52f460d Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:51:58 -0300 Subject: [PATCH 04/14] fix(analytics): split acronyms when matching sensitive param names --- __tests__/components/providers/analytics-tracking.test.tsx | 2 ++ src/components/providers/analytics-tracking.ts | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index 342e9e2e2..0956dcdd6 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -124,6 +124,8 @@ describe('useAnalyticsScreenTracking', () => { resetCode: '123456', Email: 'example@example.com', apiKey: 'your-api-key', + APIKey: 'your-api-key', + XMLToken: 'fake-token', tab: 'comments', author: 'jane', keyboard: 'compact', diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index 294003d19..a8eadace9 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -15,14 +15,15 @@ const HASH_PARAM = '#'; /** * Params with a word in their name that suggests a credential or personal * data (deep-link tokens, reset codes, emails...) are never sent to vendors. - * Names are split on camelCase, `_` and `-` boundaries, so `resetCode` and - * `access_token` are dropped while `author` or `keyboard` are kept. + * Names are split on camelCase (including acronyms such as `APIKey`), `_` and + * `-` boundaries, so `resetCode`, `APIKey` and `access_token` are dropped while `author` or `keyboard` are kept. * Adjust the list to your app's routes; adapters can filter further. */ const SENSITIVE_PARAM_WORDS = new Set(['token', 'secret', 'password', 'code', 'otp', 'email', 'key', 'auth', 'session', 'signature', 'credential']); function toWords(key: string) { return key + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') .replace(/([a-z0-9])([A-Z])/g, '$1 $2') .toLowerCase() .split(/[^a-z0-9]+/); From da869b51cbccefe936d98b325dd9fd52898a31e1 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:44:08 -0300 Subject: [PATCH 05/14] feat(analytics): add trackParams option and widen sensitive param denylist --- .../providers/analytics-tracking.test.tsx | 68 ++++++++++++++--- docs/src/content/docs/guides/analytics.mdx | 20 ++++- .../providers/analytics-tracking.ts | 76 ++++++++++++++++--- 3 files changed, 141 insertions(+), 23 deletions(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index 0956dcdd6..feb5bbe60 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -120,16 +120,25 @@ describe('useAnalyticsScreenTracking', () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['update-password']); mockUseGlobalSearchParams.mockReturnValue({ - access_token: 'fake-token', - resetCode: '123456', - Email: 'example@example.com', - apiKey: 'your-api-key', - APIKey: 'your-api-key', - XMLToken: 'fake-token', - tab: 'comments', - author: 'jane', - keyboard: 'compact', - empty: [], + 'access_token': 'fake-token', + 'resetCode': '123456', + 'Email': 'example@example.com', + 'apiKey': 'your-api-key', + 'APIKey': 'your-api-key', + 'XMLToken': 'fake-token', + 'access-token': 'fake-token', + 'client': 'fake-client', + 'client_id': 'fake-client', + 'uid': 'example@example.com', + 'emails': 'example@example.com', + 'apikey': 'your-api-key', + 'accesstoken': 'fake-token', + 'authorization': 'Bearer fake-token', + 'passcode': '1234', + 'tab': 'comments', + 'author': 'jane', + 'keyboard': 'compact', + 'empty': [], }); renderWithAnalytics(useAnalyticsScreenTracking, [provider]); @@ -187,11 +196,48 @@ describe('useAnalyticsScreenTracking', () => { mockUseGlobalSearchParams.mockReturnValue({ tab: 'comments', id: '1' }); rerender({}); - await new Promise(resolve => setImmediate(resolve)); + // Wait past the tracker's setTimeout so a wrongly scheduled report would land. + await new Promise(resolve => setTimeout(resolve, 20)); expect(provider.trackScreen).toHaveBeenCalledTimes(1); }); + it('sends no params when param tracking is turned off', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', tab: 'comments' }); + + renderWithAnalytics(() => useAnalyticsScreenTracking({ trackParams: false }), [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', undefined); + }); + }); + + it('sends only the params accepted by a trackParams function', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', tab: 'comments' }); + + renderWithAnalytics(() => useAnalyticsScreenTracking({ trackParams: name => name === 'tab' }), [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', { tab: 'comments' }); + }); + }); + + it('never sends a denylisted param, even when a trackParams function accepts it', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['reset-password']); + mockUseGlobalSearchParams.mockReturnValue({ resetToken: 'abc', step: '2' }); + + renderWithAnalytics(() => useAnalyticsScreenTracking({ trackParams: () => true }), [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/reset-password', { step: '2' }); + }); + }); + it('reports the index route of a group as the root screen', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['(app)']); diff --git a/docs/src/content/docs/guides/analytics.mdx b/docs/src/content/docs/guides/analytics.mdx index 97a9ca263..9c5f59182 100644 --- a/docs/src/content/docs/guides/analytics.mdx +++ b/docs/src/content/docs/guides/analytics.mdx @@ -82,12 +82,26 @@ Keep params flat and primitive (`string`, `number`, `boolean`, `null`) so they c Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small. -The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (one of the words in `SENSITIVE_PARAM_WORDS`: `token`, `secret`, `password`, `code`, `otp`, `email`, `key`, `auth`, `session`, `signature` or `credential`, as a whole word of a camelCase, snake_case or kebab-case name, such as `resetCode` or `access_token`; `author` or `keyboard` are still sent). Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. +The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (a word of a camelCase, snake_case or kebab-case name that ends with one of the words in `SENSITIVE_PARAM_WORDS`, singular or plural: `token`, `secret`, `password`, `passwd`, `pwd`, `code`, `otp`, `email`, `key`, `auth`, `authorization`, `jwt`, `session`, `signature`, `credential`, `client` or `uid`, such as `resetCode`, `access_token`, `apikey` or `emails`; `client` and `uid` are the Devise Token Auth credentials the password-reset redirect puts in the URL; `author` or `keyboard` are still sent). Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. -:::caution -Every other route param value is forwarded to every registered provider. If your app puts sensitive values in routes under other names, add their names to `SENSITIVE_PARAM_WORDS` in `src/components/providers/analytics-tracking.ts`, or filter them inside the adapter's `trackScreen` before calling the vendor SDK. +:::caution[Route params are sent by default] +This is a deliberate default: every route param is sent with the screen view except the URL fragment and the denylisted names above, and every value is forwarded to every registered provider. A name-based denylist cannot catch everything (an id in a dynamic segment, or a credential passed under an unrelated name such as `ref` or `state`), so review your routes before shipping. The default lives in `DEFAULT_TRACK_PARAMS` in `src/components/providers/analytics-tracking.ts`. ::: +To change what is sent, pass the `trackParams` option where `useAnalyticsScreenTracking` is called in `AnalyticsTrackers` (`src/app/_layout.tsx`): + +```tsx +// Send no params at all: trackScreen always receives `undefined`. +useAnalyticsScreenTracking({ trackParams: false }); + +// Send only the params you list (an allowlist). The denylist still applies +// first, so a sensitive name is never sent even if the function accepts it. +const TRACKED_PARAMS = new Set(['id', 'tab']); +useAnalyticsScreenTracking({ trackParams: name => TRACKED_PARAMS.has(name) }); +``` + +If your app puts sensitive values in routes under other names, you can also add those words to `SENSITIVE_PARAM_WORDS` in the same file, or filter params inside the adapter's `trackScreen` before calling the vendor SDK. + If you prefer manual screen tracking, remove the `useAnalyticsScreenTracking()` call from `AnalyticsTrackers` in the layout and call `trackScreen` from the screens you care about. diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index a8eadace9..df2aeb079 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -16,10 +16,32 @@ const HASH_PARAM = '#'; * Params with a word in their name that suggests a credential or personal * data (deep-link tokens, reset codes, emails...) are never sent to vendors. * Names are split on camelCase (including acronyms such as `APIKey`), `_` and - * `-` boundaries, so `resetCode`, `APIKey` and `access_token` are dropped while `author` or `keyboard` are kept. + * `-` boundaries, and a word is sensitive when it ends with one of these + * (singular or plural), so `resetCode`, `APIKey`, `access_token`, `apikey` + * and `emails` are dropped while `author` or `keyboard` are kept. + * `client` and `uid` are Devise Token Auth credentials (see `HEADER_KEYS`) + * that the password-reset redirect puts in the URL. * Adjust the list to your app's routes; adapters can filter further. */ -const SENSITIVE_PARAM_WORDS = new Set(['token', 'secret', 'password', 'code', 'otp', 'email', 'key', 'auth', 'session', 'signature', 'credential']); +const SENSITIVE_PARAM_WORDS = [ + 'token', + 'secret', + 'password', + 'passwd', + 'pwd', + 'code', + 'otp', + 'email', + 'key', + 'auth', + 'authorization', + 'jwt', + 'session', + 'signature', + 'credential', + 'client', + 'uid', +]; function toWords(key: string) { return key @@ -29,8 +51,42 @@ function toWords(key: string) { .split(/[^a-z0-9]+/); } +function isSensitiveWord(word: string) { + const singular = word.endsWith('s') ? word.slice(0, -1) : word; + return SENSITIVE_PARAM_WORDS.some(sensitive => word.endsWith(sensitive) || singular.endsWith(sensitive)); +} + function isTrackableParam(key: string) { - return key !== HASH_PARAM && !toWords(key).some(word => SENSITIVE_PARAM_WORDS.has(word)); + return key !== HASH_PARAM && !toWords(key).some(isSensitiveWord); +} + +/** + * Which route params are sent with each screen view: + * - `true` (the default): every param except the URL fragment and the names + * matched by `SENSITIVE_PARAM_WORDS`. + * - `false`: no params; `trackScreen` always receives `undefined`. + * - a function: only the params whose name it accepts. The denylist still + * applies first, so it can narrow what is sent but never re-enable a + * sensitive name. + */ +export type TrackScreenParamsOption = boolean | ((name: string) => boolean); + +export type AnalyticsScreenTrackingOptions = { + trackParams?: TrackScreenParamsOption; +}; + +/** + * Default decided for the template: route params are sent with screen views + * (denylist approach, not an opt-in allowlist). Pass `trackParams` to + * `useAnalyticsScreenTracking` to turn this off or narrow it per app. + */ +const DEFAULT_TRACK_PARAMS: TrackScreenParamsOption = true; + +function acceptsParam(trackParams: TrackScreenParamsOption, key: string) { + if (trackParams === false || !isTrackableParam(key)) { + return false; + } + return trackParams === true || trackParams(key); } function isRouteGroup(segment: string) { @@ -64,9 +120,9 @@ function toParamValue(value: unknown) { * Repeated params are joined with commas. Returns an empty string when the * route has no params. */ -function toParamsKey(routeParams: Readonly>) { +function toParamsKey(routeParams: Readonly>, trackParams: TrackScreenParamsOption) { const entries = Object.keys(routeParams) - .filter(isTrackableParam) + .filter(key => acceptsParam(trackParams, key)) .sort() .flatMap((key) => { const value = toParamValue(routeParams[key]); @@ -82,12 +138,14 @@ function fromParamsKey(paramsKey: string): AnalyticsParams | undefined { /** * Reports a screen view to every analytics provider whenever the route or its * params change, sending the route params (dynamic segments and search params) - * along with the route pattern. Call it once, inside `AnalyticsProvider`, - * after auth is ready. + * along with the route pattern. By default every param is sent except the + * denylisted names (see `DEFAULT_TRACK_PARAMS` and `TrackScreenParamsOption`); + * pass `{ trackParams: false }` to send none, or a function to narrow them. + * Call it once, inside `AnalyticsProvider`, after auth is ready. */ -export function useAnalyticsScreenTracking() { +export function useAnalyticsScreenTracking({ trackParams = DEFAULT_TRACK_PARAMS }: AnalyticsScreenTrackingOptions = {}) { const screenName = toScreenName(useSegments()); - const paramsKey = toParamsKey(useGlobalSearchParams()); + const paramsKey = toParamsKey(useGlobalSearchParams(), trackParams); const { trackScreen } = useAnalytics(); const lastTrackedRef = useRef<{ screenName: string; paramsKey: string } | null>(null); From 59f80bc6b07938bf4bc279345e3f33b52114b444 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:45:49 -0300 Subject: [PATCH 06/14] fix(analytics): match sensitive param names with digits or longer suffixes --- .../providers/analytics-tracking.test.tsx | 5 ++++ docs/src/content/docs/guides/analytics.mdx | 2 +- .../providers/analytics-tracking.ts | 26 +++++++++++++++---- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index feb5bbe60..3b723bec6 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -135,6 +135,11 @@ describe('useAnalyticsScreenTracking', () => { 'accesstoken': 'fake-token', 'authorization': 'Bearer fake-token', 'passcode': '1234', + 'token2': 'fake-token', + 'code1': '123456', + 'tokenvalue': 'fake-token', + 'secretkey2': 'fake-secret', + 'passwordconfirm': 'fake-password', 'tab': 'comments', 'author': 'jane', 'keyboard': 'compact', diff --git a/docs/src/content/docs/guides/analytics.mdx b/docs/src/content/docs/guides/analytics.mdx index 9c5f59182..de4e556e7 100644 --- a/docs/src/content/docs/guides/analytics.mdx +++ b/docs/src/content/docs/guides/analytics.mdx @@ -82,7 +82,7 @@ Keep params flat and primitive (`string`, `number`, `boolean`, `null`) so they c Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small. -The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (a word of a camelCase, snake_case or kebab-case name that ends with one of the words in `SENSITIVE_PARAM_WORDS`, singular or plural: `token`, `secret`, `password`, `passwd`, `pwd`, `code`, `otp`, `email`, `key`, `auth`, `authorization`, `jwt`, `session`, `signature`, `credential`, `client` or `uid`, such as `resetCode`, `access_token`, `apikey` or `emails`; `client` and `uid` are the Devise Token Auth credentials the password-reset redirect puts in the URL; `author` or `keyboard` are still sent). Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. +The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (a word of a camelCase, snake_case or kebab-case name, also split between letters and digits, that ends with one of the words in `SENSITIVE_PARAM_WORDS`, singular or plural, or starts with one of its words of five letters or more: `token`, `secret`, `password`, `passwd`, `pwd`, `code`, `otp`, `email`, `key`, `auth`, `authorization`, `jwt`, `session`, `signature`, `credential`, `client` or `uid`, such as `resetCode`, `access_token`, `apikey`, `emails`, `token2` or `tokenvalue`; `client` and `uid` are the Devise Token Auth credentials the password-reset redirect puts in the URL; `author` or `keyboard` are still sent). Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. :::caution[Route params are sent by default] This is a deliberate default: every route param is sent with the screen view except the URL fragment and the denylisted names above, and every value is forwarded to every registered provider. A name-based denylist cannot catch everything (an id in a dynamic segment, or a credential passed under an unrelated name such as `ref` or `state`), so review your routes before shipping. The default lives in `DEFAULT_TRACK_PARAMS` in `src/components/providers/analytics-tracking.ts`. diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index df2aeb079..348fed46a 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -16,9 +16,10 @@ const HASH_PARAM = '#'; * Params with a word in their name that suggests a credential or personal * data (deep-link tokens, reset codes, emails...) are never sent to vendors. * Names are split on camelCase (including acronyms such as `APIKey`), `_` and - * `-` boundaries, and a word is sensitive when it ends with one of these - * (singular or plural), so `resetCode`, `APIKey`, `access_token`, `apikey` - * and `emails` are dropped while `author` or `keyboard` are kept. + * `-` and letter/digit boundaries, and a word is sensitive when it ends with + * one of these (singular or plural) or, for terms of 5+ letters, starts with + * one. So `resetCode`, `APIKey`, `access_token`, `apikey`, `emails`, `token2` + * and `tokenvalue` are dropped while `author` or `keyboard` are kept. * `client` and `uid` are Devise Token Auth credentials (see `HEADER_KEYS`) * that the password-reset redirect puts in the URL. * Adjust the list to your app's routes; adapters can filter further. @@ -47,13 +48,28 @@ function toWords(key: string) { return key .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .replace(/([a-z])(\d)/gi, '$1 $2') + .replace(/(\d)([a-z])/gi, '$1 $2') .toLowerCase() - .split(/[^a-z0-9]+/); + .split(/[^a-z]+/) + .filter(Boolean); } +/** + * Terms this long are distinctive enough to also match at the start of a word + * (`tokenvalue`, `passwordconfirm`). Shorter ones (`key`, `auth`, `code`...) + * only match at the end, so `keyboard` and `author` are still sent. + */ +const MIN_PREFIX_TERM_LENGTH = 5; + function isSensitiveWord(word: string) { const singular = word.endsWith('s') ? word.slice(0, -1) : word; - return SENSITIVE_PARAM_WORDS.some(sensitive => word.endsWith(sensitive) || singular.endsWith(sensitive)); + return SENSITIVE_PARAM_WORDS.some( + sensitive => + word.endsWith(sensitive) + || singular.endsWith(sensitive) + || (sensitive.length >= MIN_PREFIX_TERM_LENGTH && word.startsWith(sensitive)), + ); } function isTrackableParam(key: string) { From b1681141b9d8e74fc4cf1a1d30048495cd2ddb22 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:47:33 -0300 Subject: [PATCH 07/14] fix(analytics): drop more sensitive param names and email or JWT values --- .../providers/analytics-tracking.test.tsx | 36 +++++++++++++++++++ docs/src/content/docs/guides/analytics.mdx | 4 +-- .../providers/analytics-tracking.ts | 31 +++++++++++++--- 3 files changed, 65 insertions(+), 6 deletions(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index 3b723bec6..64407cf2f 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -140,6 +140,14 @@ describe('useAnalyticsScreenTracking', () => { 'tokenvalue': 'fake-token', 'secretkey2': 'fake-secret', 'passwordconfirm': 'fake-password', + 'pass': 'fake-password', + 'pin': '1234', + 'sid': 'fake-session', + 'sig': 'fake-signature', + 'hash': 'fake-hash', + 'bearer': 'fake-token', + 'phone': '555-0100', + 'ssn': '000-00-0000', 'tab': 'comments', 'author': 'jane', 'keyboard': 'compact', @@ -207,6 +215,34 @@ describe('useAnalyticsScreenTracking', () => { expect(provider.trackScreen).toHaveBeenCalledTimes(1); }); + it('does not send values that look like an email or a JWT under any name', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed']); + mockUseGlobalSearchParams.mockReturnValue({ + ref: 'example@example.com', + state: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJleGFtcGxlIn0.fake-signature', + tab: 'comments', + }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed', { tab: 'comments' }); + }); + }); + + it('sends every non-sensitive param by default', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', tab: 'comments', ref: 'home' }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', { id: '42', ref: 'home', tab: 'comments' }); + }); + }); + it('sends no params when param tracking is turned off', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); diff --git a/docs/src/content/docs/guides/analytics.mdx b/docs/src/content/docs/guides/analytics.mdx index de4e556e7..59789bf5e 100644 --- a/docs/src/content/docs/guides/analytics.mdx +++ b/docs/src/content/docs/guides/analytics.mdx @@ -82,10 +82,10 @@ Keep params flat and primitive (`string`, `number`, `boolean`, `null`) so they c Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small. -The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (a word of a camelCase, snake_case or kebab-case name, also split between letters and digits, that ends with one of the words in `SENSITIVE_PARAM_WORDS`, singular or plural, or starts with one of its words of five letters or more: `token`, `secret`, `password`, `passwd`, `pwd`, `code`, `otp`, `email`, `key`, `auth`, `authorization`, `jwt`, `session`, `signature`, `credential`, `client` or `uid`, such as `resetCode`, `access_token`, `apikey`, `emails`, `token2` or `tokenvalue`; `client` and `uid` are the Devise Token Auth credentials the password-reset redirect puts in the URL; `author` or `keyboard` are still sent). Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. +The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (a word of a camelCase, snake_case or kebab-case name, also split between letters and digits, that ends with one of the words in `SENSITIVE_PARAM_WORDS`, singular or plural, or starts with one of its words of five letters or more: `token`, `secret`, `password`, `passwd`, `pwd`, `code`, `otp`, `email`, `key`, `auth`, `authorization`, `jwt`, `session`, `signature`, `credential`, `client`, `uid`, `pass`, `pin`, `sid`, `sig`, `hash`, `bearer`, `phone` or `ssn`, such as `resetCode`, `access_token`, `apikey`, `emails`, `token2` or `tokenvalue`; `client` and `uid` are the Devise Token Auth credentials the password-reset redirect puts in the URL; `author` or `keyboard` are still sent). Values that look like an email address or a JWT are dropped too, whatever the param is called. Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. :::caution[Route params are sent by default] -This is a deliberate default: every route param is sent with the screen view except the URL fragment and the denylisted names above, and every value is forwarded to every registered provider. A name-based denylist cannot catch everything (an id in a dynamic segment, or a credential passed under an unrelated name such as `ref` or `state`), so review your routes before shipping. The default lives in `DEFAULT_TRACK_PARAMS` in `src/components/providers/analytics-tracking.ts`. +This is a deliberate default chosen by the template maintainers over an opt-in allowlist: every route param is sent with the screen view except the URL fragment and the denylisted names above, and every value is forwarded to every registered provider. The denylist and the value checks are best effort and cannot catch everything (an id in a dynamic segment, or an opaque credential passed under an unrelated name such as `ref` or `state`), so review your routes before shipping, and turn param tracking off or narrow it as shown below if your routes carry sensitive data. The default lives in `DEFAULT_TRACK_PARAMS` in `src/components/providers/analytics-tracking.ts`. ::: To change what is sent, pass the `trackParams` option where `useAnalyticsScreenTracking` is called in `AnalyticsTrackers` (`src/app/_layout.tsx`): diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index 348fed46a..4f52339b4 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -42,8 +42,28 @@ const SENSITIVE_PARAM_WORDS = [ 'credential', 'client', 'uid', + 'pass', + 'pin', + 'sid', + 'sig', + 'hash', + 'bearer', + 'phone', + 'ssn', ]; +const EMAIL_VALUE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +const JWT_VALUE = /^eyJ[\w-]*\.[\w-]+\.[\w-]*$/; + +/** + * Second layer for credentials or personal data passed under a harmless name + * (`?ref=`, `?state=`): values that look like an email address or + * a JWT are never sent, whatever the param is called. + */ +function isSensitiveValue(value: string) { + return EMAIL_VALUE.test(value) || JWT_VALUE.test(value); +} + function toWords(key: string) { return key .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') @@ -92,9 +112,12 @@ export type AnalyticsScreenTrackingOptions = { }; /** - * Default decided for the template: route params are sent with screen views - * (denylist approach, not an opt-in allowlist). Pass `trackParams` to - * `useAnalyticsScreenTracking` to turn this off or narrow it per app. + * Default decided by the template maintainers: route params are sent with + * screen views (denylist approach). An opt-in allowlist and `false` were + * considered as defaults and not chosen, so screen views carry useful context + * out of the box. The denylist and the value checks above are best effort, + * not a guarantee: apps that route sensitive data should pass `trackParams` + * to `useAnalyticsScreenTracking` to turn this off or narrow it. */ const DEFAULT_TRACK_PARAMS: TrackScreenParamsOption = true; @@ -142,7 +165,7 @@ function toParamsKey(routeParams: Readonly>, trackParams .sort() .flatMap((key) => { const value = toParamValue(routeParams[key]); - return value === undefined ? [] : [[key, value] as const]; + return value === undefined || isSensitiveValue(value) ? [] : [[key, value] as const]; }); return entries.length > 0 ? JSON.stringify(Object.fromEntries(entries)) : ''; } From 670ceda0fb0992c36e4858cd94d0eedb5f292050 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:49:52 -0300 Subject: [PATCH 08/14] fix(analytics): check each value of a repeated param for emails or JWTs --- .../providers/analytics-tracking.test.tsx | 4 +++- docs/src/content/docs/guides/analytics.mdx | 2 +- .../providers/analytics-tracking.ts | 20 +++++++++++++------ 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index 64407cf2f..52b7ff5ec 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -222,12 +222,14 @@ describe('useAnalyticsScreenTracking', () => { ref: 'example@example.com', state: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJleGFtcGxlIn0.fake-signature', tab: 'comments', + tag: ['news', 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJleGFtcGxlIn0.fake-signature', 'example@example.com', 'sports'], + to: ['example@example.com'], }); renderWithAnalytics(useAnalyticsScreenTracking, [provider]); await waitFor(() => { - expect(provider.trackScreen).toHaveBeenCalledWith('/feed', { tab: 'comments' }); + expect(provider.trackScreen).toHaveBeenCalledWith('/feed', { tab: 'comments', tag: 'news,sports' }); }); }); diff --git a/docs/src/content/docs/guides/analytics.mdx b/docs/src/content/docs/guides/analytics.mdx index 59789bf5e..d49f236b0 100644 --- a/docs/src/content/docs/guides/analytics.mdx +++ b/docs/src/content/docs/guides/analytics.mdx @@ -82,7 +82,7 @@ Keep params flat and primitive (`string`, `number`, `boolean`, `null`) so they c Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small. -The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (a word of a camelCase, snake_case or kebab-case name, also split between letters and digits, that ends with one of the words in `SENSITIVE_PARAM_WORDS`, singular or plural, or starts with one of its words of five letters or more: `token`, `secret`, `password`, `passwd`, `pwd`, `code`, `otp`, `email`, `key`, `auth`, `authorization`, `jwt`, `session`, `signature`, `credential`, `client`, `uid`, `pass`, `pin`, `sid`, `sig`, `hash`, `bearer`, `phone` or `ssn`, such as `resetCode`, `access_token`, `apikey`, `emails`, `token2` or `tokenvalue`; `client` and `uid` are the Devise Token Auth credentials the password-reset redirect puts in the URL; `author` or `keyboard` are still sent). Values that look like an email address or a JWT are dropped too, whatever the param is called. Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. +The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (a word of a camelCase, snake_case or kebab-case name, also split between letters and digits, that ends with one of the words in `SENSITIVE_PARAM_WORDS`, singular or plural, or starts with one of its words of five letters or more: `token`, `secret`, `password`, `passwd`, `pwd`, `code`, `otp`, `email`, `key`, `auth`, `authorization`, `jwt`, `session`, `signature`, `credential`, `client`, `uid`, `pass`, `pin`, `sid`, `sig`, `hash`, `bearer`, `phone` or `ssn`, such as `resetCode`, `access_token`, `apikey`, `emails`, `token2` or `tokenvalue`; `client` and `uid` are the Devise Token Auth credentials the password-reset redirect puts in the URL; `author` or `keyboard` are still sent). Values that look like an email address or a JWT are dropped too, whatever the param is called (for a repeated param, each value is checked on its own). Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. :::caution[Route params are sent by default] This is a deliberate default chosen by the template maintainers over an opt-in allowlist: every route param is sent with the screen view except the URL fragment and the denylisted names above, and every value is forwarded to every registered provider. The denylist and the value checks are best effort and cannot catch everything (an id in a dynamic segment, or an opaque credential passed under an unrelated name such as `ref` or `state`), so review your routes before shipping, and turn param tracking off or narrow it as shown below if your routes carry sensitive data. The default lives in `DEFAULT_TRACK_PARAMS` in `src/components/providers/analytics-tracking.ts`. diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index 4f52339b4..53c2cf4ec 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -144,13 +144,15 @@ function isPrimitiveParam(value: unknown): value is string | number | boolean { * Navigation params can hold non-string values at runtime (numbers, nested * objects), so values are converted to strings and anything that is not a * primitive (or an array of primitives) is dropped, keeping params flat. + * Each value (each element of a repeated param) is checked on its own, and + * the ones that look like an email or a JWT are dropped before joining. */ function toParamValue(value: unknown) { - if (Array.isArray(value)) { - const values = value.filter(isPrimitiveParam); - return values.length > 0 ? values.map(String).join(',') : undefined; - } - return isPrimitiveParam(value) ? String(value) : undefined; + const values = (Array.isArray(value) ? value : [value]) + .filter(isPrimitiveParam) + .map(String) + .filter(item => !isSensitiveValue(item)); + return values.length > 0 ? values.join(',') : undefined; } /** @@ -165,11 +167,17 @@ function toParamsKey(routeParams: Readonly>, trackParams .sort() .flatMap((key) => { const value = toParamValue(routeParams[key]); - return value === undefined || isSensitiveValue(value) ? [] : [[key, value] as const]; + return value === undefined ? [] : [[key, value] as const]; }); return entries.length > 0 ? JSON.stringify(Object.fromEntries(entries)) : ''; } +/** + * The serialised key is the only value the tracking effect depends on, so a + * new params object on every render never re-triggers it; the params are read + * back from that key when a screen view is reported. `toParamsKey` only ever + * serialises a flat object of strings, which is what the cast states. + */ function fromParamsKey(paramsKey: string): AnalyticsParams | undefined { return paramsKey ? (JSON.parse(paramsKey) as Record) : undefined; } From 6a02409ad7fc2fee89a2ccea092b8e151eedc2f8 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:10:11 -0300 Subject: [PATCH 09/14] refactor(analytics): send all route params on screen views --- .../providers/analytics-tracking.test.tsx | 82 +------------ docs/src/content/docs/guides/analytics.mdx | 9 +- .../providers/analytics-tracking.ts | 116 ++---------------- 3 files changed, 19 insertions(+), 188 deletions(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index 52b7ff5ec..5bee385c6 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -116,51 +116,6 @@ describe('useAnalyticsScreenTracking', () => { }); }); - it('does not send sensitive-looking or empty params but keeps similar names', async () => { - const provider = createMockProvider(); - mockUseSegments.mockReturnValue(['update-password']); - mockUseGlobalSearchParams.mockReturnValue({ - 'access_token': 'fake-token', - 'resetCode': '123456', - 'Email': 'example@example.com', - 'apiKey': 'your-api-key', - 'APIKey': 'your-api-key', - 'XMLToken': 'fake-token', - 'access-token': 'fake-token', - 'client': 'fake-client', - 'client_id': 'fake-client', - 'uid': 'example@example.com', - 'emails': 'example@example.com', - 'apikey': 'your-api-key', - 'accesstoken': 'fake-token', - 'authorization': 'Bearer fake-token', - 'passcode': '1234', - 'token2': 'fake-token', - 'code1': '123456', - 'tokenvalue': 'fake-token', - 'secretkey2': 'fake-secret', - 'passwordconfirm': 'fake-password', - 'pass': 'fake-password', - 'pin': '1234', - 'sid': 'fake-session', - 'sig': 'fake-signature', - 'hash': 'fake-hash', - 'bearer': 'fake-token', - 'phone': '555-0100', - 'ssn': '000-00-0000', - 'tab': 'comments', - 'author': 'jane', - 'keyboard': 'compact', - 'empty': [], - }); - - renderWithAnalytics(useAnalyticsScreenTracking, [provider]); - - await waitFor(() => { - expect(provider.trackScreen).toHaveBeenCalledWith('/update-password', { author: 'jane', keyboard: 'compact', tab: 'comments' }); - }); - }); - it('converts primitive values to strings and drops nested objects', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['(app)', 'feed']); @@ -169,6 +124,7 @@ describe('useAnalyticsScreenTracking', () => { draft: false, filter: { status: 'open' }, empty: null, + none: [], }); renderWithAnalytics(useAnalyticsScreenTracking, [provider]); @@ -215,33 +171,15 @@ describe('useAnalyticsScreenTracking', () => { expect(provider.trackScreen).toHaveBeenCalledTimes(1); }); - it('does not send values that look like an email or a JWT under any name', async () => { - const provider = createMockProvider(); - mockUseSegments.mockReturnValue(['(app)', 'feed']); - mockUseGlobalSearchParams.mockReturnValue({ - ref: 'example@example.com', - state: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJleGFtcGxlIn0.fake-signature', - tab: 'comments', - tag: ['news', 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJleGFtcGxlIn0.fake-signature', 'example@example.com', 'sports'], - to: ['example@example.com'], - }); - - renderWithAnalytics(useAnalyticsScreenTracking, [provider]); - - await waitFor(() => { - expect(provider.trackScreen).toHaveBeenCalledWith('/feed', { tab: 'comments', tag: 'news,sports' }); - }); - }); - - it('sends every non-sensitive param by default', async () => { + it('sends every param by default, whatever its name', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); - mockUseGlobalSearchParams.mockReturnValue({ id: '42', tab: 'comments', ref: 'home' }); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', mode: 'edit', resetCode: '123456', ref: 'home' }); renderWithAnalytics(useAnalyticsScreenTracking, [provider]); await waitFor(() => { - expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', { id: '42', ref: 'home', tab: 'comments' }); + expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', { id: '42', mode: 'edit', ref: 'home', resetCode: '123456' }); }); }); @@ -269,18 +207,6 @@ describe('useAnalyticsScreenTracking', () => { }); }); - it('never sends a denylisted param, even when a trackParams function accepts it', async () => { - const provider = createMockProvider(); - mockUseSegments.mockReturnValue(['reset-password']); - mockUseGlobalSearchParams.mockReturnValue({ resetToken: 'abc', step: '2' }); - - renderWithAnalytics(() => useAnalyticsScreenTracking({ trackParams: () => true }), [provider]); - - await waitFor(() => { - expect(provider.trackScreen).toHaveBeenCalledWith('/reset-password', { step: '2' }); - }); - }); - it('reports the index route of a group as the root screen', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['(app)']); diff --git a/docs/src/content/docs/guides/analytics.mdx b/docs/src/content/docs/guides/analytics.mdx index d49f236b0..cd37e6c60 100644 --- a/docs/src/content/docs/guides/analytics.mdx +++ b/docs/src/content/docs/guides/analytics.mdx @@ -82,10 +82,10 @@ Keep params flat and primitive (`string`, `number`, `boolean`, `null`) so they c Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small. -The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, and neither is any param whose name looks sensitive (a word of a camelCase, snake_case or kebab-case name, also split between letters and digits, that ends with one of the words in `SENSITIVE_PARAM_WORDS`, singular or plural, or starts with one of its words of five letters or more: `token`, `secret`, `password`, `passwd`, `pwd`, `code`, `otp`, `email`, `key`, `auth`, `authorization`, `jwt`, `session`, `signature`, `credential`, `client`, `uid`, `pass`, `pin`, `sid`, `sig`, `hash`, `bearer`, `phone` or `ssn`, such as `resetCode`, `access_token`, `apikey`, `emails`, `token2` or `tokenvalue`; `client` and `uid` are the Devise Token Auth credentials the password-reset redirect puts in the URL; `author` or `keyboard` are still sent). Values that look like an email address or a JWT are dropped too, whatever the param is called (for a repeated param, each value is checked on its own). Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. +The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, as it is not a route or search param. Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. :::caution[Route params are sent by default] -This is a deliberate default chosen by the template maintainers over an opt-in allowlist: every route param is sent with the screen view except the URL fragment and the denylisted names above, and every value is forwarded to every registered provider. The denylist and the value checks are best effort and cannot catch everything (an id in a dynamic segment, or an opaque credential passed under an unrelated name such as `ref` or `state`), so review your routes before shipping, and turn param tracking off or narrow it as shown below if your routes carry sensitive data. The default lives in `DEFAULT_TRACK_PARAMS` in `src/components/providers/analytics-tracking.ts`. +This is a deliberate default chosen by the template maintainers: every route param except the URL fragment is sent with the screen view and forwarded to every registered provider. Route params are treated as non-sensitive by design, since they only carry ids, modes and similar values, so never put tokens or personal data in route params. The default lives in `DEFAULT_TRACK_PARAMS` in `src/components/providers/analytics-tracking.ts`. ::: To change what is sent, pass the `trackParams` option where `useAnalyticsScreenTracking` is called in `AnalyticsTrackers` (`src/app/_layout.tsx`): @@ -94,14 +94,11 @@ To change what is sent, pass the `trackParams` option where `useAnalyticsScreenT // Send no params at all: trackScreen always receives `undefined`. useAnalyticsScreenTracking({ trackParams: false }); -// Send only the params you list (an allowlist). The denylist still applies -// first, so a sensitive name is never sent even if the function accepts it. +// Send only the params you list (an allowlist). const TRACKED_PARAMS = new Set(['id', 'tab']); useAnalyticsScreenTracking({ trackParams: name => TRACKED_PARAMS.has(name) }); ``` -If your app puts sensitive values in routes under other names, you can also add those words to `SENSITIVE_PARAM_WORDS` in the same file, or filter params inside the adapter's `trackScreen` before calling the vendor SDK. - If you prefer manual screen tracking, remove the `useAnalyticsScreenTracking()` call from `AnalyticsTrackers` in the layout and call `trackScreen` from the screens you care about. diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index 53c2cf4ec..21ff9544b 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -8,102 +8,15 @@ import { hasIdentifiedUser } from '@/lib/analytics'; /** * expo-router exposes the URL fragment as a `#` param. It is not a route or - * search param and often carries credentials (e.g. `#access_token=...`). + * search param, so it is never sent. */ const HASH_PARAM = '#'; -/** - * Params with a word in their name that suggests a credential or personal - * data (deep-link tokens, reset codes, emails...) are never sent to vendors. - * Names are split on camelCase (including acronyms such as `APIKey`), `_` and - * `-` and letter/digit boundaries, and a word is sensitive when it ends with - * one of these (singular or plural) or, for terms of 5+ letters, starts with - * one. So `resetCode`, `APIKey`, `access_token`, `apikey`, `emails`, `token2` - * and `tokenvalue` are dropped while `author` or `keyboard` are kept. - * `client` and `uid` are Devise Token Auth credentials (see `HEADER_KEYS`) - * that the password-reset redirect puts in the URL. - * Adjust the list to your app's routes; adapters can filter further. - */ -const SENSITIVE_PARAM_WORDS = [ - 'token', - 'secret', - 'password', - 'passwd', - 'pwd', - 'code', - 'otp', - 'email', - 'key', - 'auth', - 'authorization', - 'jwt', - 'session', - 'signature', - 'credential', - 'client', - 'uid', - 'pass', - 'pin', - 'sid', - 'sig', - 'hash', - 'bearer', - 'phone', - 'ssn', -]; - -const EMAIL_VALUE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; -const JWT_VALUE = /^eyJ[\w-]*\.[\w-]+\.[\w-]*$/; - -/** - * Second layer for credentials or personal data passed under a harmless name - * (`?ref=`, `?state=`): values that look like an email address or - * a JWT are never sent, whatever the param is called. - */ -function isSensitiveValue(value: string) { - return EMAIL_VALUE.test(value) || JWT_VALUE.test(value); -} - -function toWords(key: string) { - return key - .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') - .replace(/([a-z0-9])([A-Z])/g, '$1 $2') - .replace(/([a-z])(\d)/gi, '$1 $2') - .replace(/(\d)([a-z])/gi, '$1 $2') - .toLowerCase() - .split(/[^a-z]+/) - .filter(Boolean); -} - -/** - * Terms this long are distinctive enough to also match at the start of a word - * (`tokenvalue`, `passwordconfirm`). Shorter ones (`key`, `auth`, `code`...) - * only match at the end, so `keyboard` and `author` are still sent. - */ -const MIN_PREFIX_TERM_LENGTH = 5; - -function isSensitiveWord(word: string) { - const singular = word.endsWith('s') ? word.slice(0, -1) : word; - return SENSITIVE_PARAM_WORDS.some( - sensitive => - word.endsWith(sensitive) - || singular.endsWith(sensitive) - || (sensitive.length >= MIN_PREFIX_TERM_LENGTH && word.startsWith(sensitive)), - ); -} - -function isTrackableParam(key: string) { - return key !== HASH_PARAM && !toWords(key).some(isSensitiveWord); -} - /** * Which route params are sent with each screen view: - * - `true` (the default): every param except the URL fragment and the names - * matched by `SENSITIVE_PARAM_WORDS`. + * - `true` (the default): every param except the URL fragment. * - `false`: no params; `trackScreen` always receives `undefined`. - * - a function: only the params whose name it accepts. The denylist still - * applies first, so it can narrow what is sent but never re-enable a - * sensitive name. + * - a function: only the params whose name it accepts. */ export type TrackScreenParamsOption = boolean | ((name: string) => boolean); @@ -112,17 +25,15 @@ export type AnalyticsScreenTrackingOptions = { }; /** - * Default decided by the template maintainers: route params are sent with - * screen views (denylist approach). An opt-in allowlist and `false` were - * considered as defaults and not chosen, so screen views carry useful context - * out of the box. The denylist and the value checks above are best effort, - * not a guarantee: apps that route sensitive data should pass `trackParams` - * to `useAnalyticsScreenTracking` to turn this off or narrow it. + * Default decided by the template maintainers: every route param is sent with + * screen views. Route params are treated as non-sensitive by design: they only + * carry ids, modes and similar values, so never put tokens or personal data + * in route params. */ const DEFAULT_TRACK_PARAMS: TrackScreenParamsOption = true; function acceptsParam(trackParams: TrackScreenParamsOption, key: string) { - if (trackParams === false || !isTrackableParam(key)) { + if (trackParams === false || key === HASH_PARAM) { return false; } return trackParams === true || trackParams(key); @@ -144,14 +55,11 @@ function isPrimitiveParam(value: unknown): value is string | number | boolean { * Navigation params can hold non-string values at runtime (numbers, nested * objects), so values are converted to strings and anything that is not a * primitive (or an array of primitives) is dropped, keeping params flat. - * Each value (each element of a repeated param) is checked on its own, and - * the ones that look like an email or a JWT are dropped before joining. */ function toParamValue(value: unknown) { const values = (Array.isArray(value) ? value : [value]) .filter(isPrimitiveParam) - .map(String) - .filter(item => !isSensitiveValue(item)); + .map(String); return values.length > 0 ? values.join(',') : undefined; } @@ -185,9 +93,9 @@ function fromParamsKey(paramsKey: string): AnalyticsParams | undefined { /** * Reports a screen view to every analytics provider whenever the route or its * params change, sending the route params (dynamic segments and search params) - * along with the route pattern. By default every param is sent except the - * denylisted names (see `DEFAULT_TRACK_PARAMS` and `TrackScreenParamsOption`); - * pass `{ trackParams: false }` to send none, or a function to narrow them. + * along with the route pattern. By default every param is sent (see + * `DEFAULT_TRACK_PARAMS` and `TrackScreenParamsOption`); pass + * `{ trackParams: false }` to send none, or a function to narrow them. * Call it once, inside `AnalyticsProvider`, after auth is ready. */ export function useAnalyticsScreenTracking({ trackParams = DEFAULT_TRACK_PARAMS }: AnalyticsScreenTrackingOptions = {}) { From a08336b9a1328989eeb62093f71b30a97a1cba12 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:12:13 -0300 Subject: [PATCH 10/14] docs(analytics): document why route params are sent unfiltered --- .../components/providers/analytics-tracking.test.tsx | 8 +++++--- src/components/providers/analytics-tracking.ts | 9 ++++++--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index 5bee385c6..0b34644ee 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -171,15 +171,17 @@ describe('useAnalyticsScreenTracking', () => { expect(provider.trackScreen).toHaveBeenCalledTimes(1); }); - it('sends every param by default, whatever its name', async () => { + // Route params only carry ids, modes and similar values by design, so the + // default sends all of them without filtering by name or value. + it('sends every route param by default', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); - mockUseGlobalSearchParams.mockReturnValue({ id: '42', mode: 'edit', resetCode: '123456', ref: 'home' }); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', mode: 'edit', tab: 'comments', ref: 'home' }); renderWithAnalytics(useAnalyticsScreenTracking, [provider]); await waitFor(() => { - expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', { id: '42', mode: 'edit', ref: 'home', resetCode: '123456' }); + expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', { id: '42', mode: 'edit', ref: 'home', tab: 'comments' }); }); }); diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index 21ff9544b..d9913b34e 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -26,9 +26,12 @@ export type AnalyticsScreenTrackingOptions = { /** * Default decided by the template maintainers: every route param is sent with - * screen views. Route params are treated as non-sensitive by design: they only - * carry ids, modes and similar values, so never put tokens or personal data - * in route params. + * screen views, with no filtering by name or value. Route params are treated + * as non-sensitive by design: they only carry ids, modes and similar values. + * Tokens, codes and personal data must never be passed as route params (keep + * them in secure storage or request bodies instead). A name or value denylist + * was used before and intentionally removed. Apps that do not follow this rule + * can pass `trackParams: false` or an allowlist function. */ const DEFAULT_TRACK_PARAMS: TrackScreenParamsOption = true; From d80e39e944992ae8a997c26d64c9dcbc834c0af9 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:13:30 -0300 Subject: [PATCH 11/14] test(analytics): cover deep links and params ignored by trackParams --- .../providers/analytics-tracking.test.tsx | 18 ++++++++++++++++++ docs/src/content/docs/guides/analytics.mdx | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index 0b34644ee..c14257966 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -209,6 +209,24 @@ describe('useAnalyticsScreenTracking', () => { }); }); + it('does not track again when only a param rejected by trackParams changes', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', tab: 'comments' }); + + const { rerender } = renderWithAnalytics(() => useAnalyticsScreenTracking({ trackParams: name => name === 'tab' }), [provider]); + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + mockUseGlobalSearchParams.mockReturnValue({ id: '43', tab: 'comments' }); + rerender({}); + // Wait past the tracker's setTimeout so a wrongly scheduled report would land. + await new Promise(resolve => setTimeout(resolve, 20)); + + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + it('reports the index route of a group as the root screen', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['(app)']); diff --git a/docs/src/content/docs/guides/analytics.mdx b/docs/src/content/docs/guides/analytics.mdx index cd37e6c60..967b96f3b 100644 --- a/docs/src/content/docs/guides/analytics.mdx +++ b/docs/src/content/docs/guides/analytics.mdx @@ -85,7 +85,7 @@ Screen names are route patterns, not resolved paths: route groups are dropped an The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, as it is not a route or search param. Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. :::caution[Route params are sent by default] -This is a deliberate default chosen by the template maintainers: every route param except the URL fragment is sent with the screen view and forwarded to every registered provider. Route params are treated as non-sensitive by design, since they only carry ids, modes and similar values, so never put tokens or personal data in route params. The default lives in `DEFAULT_TRACK_PARAMS` in `src/components/providers/analytics-tracking.ts`. +This is a deliberate default chosen by the template maintainers: every route param except the URL fragment is sent with the screen view and forwarded to every registered provider. Route params are treated as non-sensitive by design, since they only carry ids, modes and similar values, so never put tokens or personal data in route params. This also applies to incoming deep links and universal links (password reset, magic links, OAuth callbacks): their query params become route params, so design those links to carry ids only, or turn param tracking off or narrow it with `trackParams` for apps whose links carry credentials. The default lives in `DEFAULT_TRACK_PARAMS` in `src/components/providers/analytics-tracking.ts`. ::: To change what is sent, pass the `trackParams` option where `useAnalyticsScreenTracking` is called in `AnalyticsTrackers` (`src/app/_layout.tsx`): From ece4c92da5a39c4a92740154df9051949f9f8175 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:14:30 -0300 Subject: [PATCH 12/14] docs(analytics): explain why screen params are not redacted --- src/components/providers/analytics-tracking.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index d9913b34e..060c39a9f 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -29,9 +29,13 @@ export type AnalyticsScreenTrackingOptions = { * screen views, with no filtering by name or value. Route params are treated * as non-sensitive by design: they only carry ids, modes and similar values. * Tokens, codes and personal data must never be passed as route params (keep - * them in secure storage or request bodies instead). A name or value denylist - * was used before and intentionally removed. Apps that do not follow this rule - * can pass `trackParams: false` or an allowlist function. + * them in secure storage or request bodies instead). This includes incoming + * deep links: the app defines its own link routes, so they must carry ids + * only. A name or value denylist was used before and intentionally removed, + * since it could never be complete and gave a false sense of safety; the + * trade-off (no redaction when an app breaks this rule) is accepted. Apps + * whose links carry credentials pass `trackParams: false` or an allowlist + * function. */ const DEFAULT_TRACK_PARAMS: TrackScreenParamsOption = true; From d7350fab1f784726389ed679dc0c11cac2d7c809 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:19:44 -0300 Subject: [PATCH 13/14] refactor(analytics): pass an explicit compare function when sorting param names --- src/components/providers/analytics-tracking.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index 060c39a9f..a10fbd1a3 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -79,7 +79,9 @@ function toParamValue(value: unknown) { function toParamsKey(routeParams: Readonly>, trackParams: TrackScreenParamsOption) { const entries = Object.keys(routeParams) .filter(key => acceptsParam(trackParams, key)) - .sort() + // Same UTF-16 code unit order as the default sort, stated explicitly + // rather than with `localeCompare`, which would depend on the device locale. + .sort((a, b) => Number(a > b) - Number(a < b)) .flatMap((key) => { const value = toParamValue(routeParams[key]); return value === undefined ? [] : [[key, value] as const]; From f018c2771933e9f40770424164a0ac818abc4637 Mon Sep 17 00:00:00 2001 From: devs-rootstrap <112487182+devs-rootstrap@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:19:56 -0300 Subject: [PATCH 14/14] test(analytics): cover params bouncing back within a tick and param name order --- .../providers/analytics-tracking.test.tsx | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index c14257966..d6546bc7d 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -171,6 +171,39 @@ describe('useAnalyticsScreenTracking', () => { expect(provider.trackScreen).toHaveBeenCalledTimes(1); }); + it('does not track again when the params change and come back within the same tick', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '1' }); + + const { rerender } = renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + mockUseGlobalSearchParams.mockReturnValue({ id: '2' }); + rerender({}); + mockUseGlobalSearchParams.mockReturnValue({ id: '1' }); + rerender({}); + // Wait past the tracker's setTimeout so a wrongly scheduled report would land. + await new Promise(resolve => setTimeout(resolve, 20)); + + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + it('sorts params by name in code unit order', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed']); + mockUseGlobalSearchParams.mockReturnValue({ b: '2', a: '1', B: '3' }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + expect(Object.keys(provider.trackScreen.mock.calls[0][1])).toEqual(['B', 'a', 'b']); + }); + // Route params only carry ids, modes and similar values by design, so the // default sends all of them without filtering by name or value. it('sends every route param by default', async () => {