Skip to content

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

fix: Send a hashed user id with every Sentry event (#39430)

Ivan Vasilovd32ccb0d1712
diff --git a/apps/studio/components/interfaces/HomePageActions.tsx b/apps/studio/components/interfaces/HomePageActions.tsx
index 2bfdfcb673b..cfaacaf23d6 100644
--- a/apps/studio/components/interfaces/HomePageActions.tsx
+++ b/apps/studio/components/interfaces/HomePageActions.tsx
@@ -91,7 +91,7 @@ export const HomePageActions = ({
{ key: PROJECT_STATUS.ACTIVE_HEALTHY, label: 'Active' },
{ key: PROJECT_STATUS.INACTIVE, label: 'Paused' },
].map(({ key, label }) => (
- <div className="flex items-center gap-x-2 py-1">
+ <div className="flex items-center gap-x-2 py-1" key={key}>
<Checkbox_Shadcn_
id={key}
name={key}
diff --git a/apps/studio/components/ui/GroupsTelemetry.tsx b/apps/studio/components/ui/GroupsTelemetry.tsx
deleted file mode 100644
index c6477f8c4d5..00000000000
--- a/apps/studio/components/ui/GroupsTelemetry.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-/* eslint-disable react-hooks/rules-of-hooks */
-import * as Sentry from '@sentry/nextjs'
-import { useRouter } from 'next/router'
-import { useEffect } from 'react'
-
-import { LOCAL_STORAGE_KEYS, useParams, useTelemetryCookie, useUser } from 'common'
-import { useSendGroupsIdentifyMutation } from 'data/telemetry/send-groups-identify-mutation'
-import { useSendGroupsResetMutation } from 'data/telemetry/send-groups-reset-mutation'
-import { usePrevious } from 'hooks/deprecated'
-import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
-import { IS_PLATFORM } from 'lib/constants'
-
-const getAnonId = async (id: string) => {
- const encoder = new TextEncoder()
- const data = encoder.encode(id)
- const hashBuffer = await crypto.subtle.digest('SHA-256', data)
- const hashArray = Array.from(new Uint8Array(hashBuffer))
- const base64String = btoa(hashArray.map((byte) => String.fromCharCode(byte)).join(''))
-
- return base64String
-}
-
-const GroupsTelemetry = ({ hasAcceptedConsent }: { hasAcceptedConsent: boolean }) => {
- // Although this is "technically" breaking the rules of hooks
- // IS_PLATFORM never changes within a session, so this won't cause any issues
- if (!IS_PLATFORM) return null
-
- const user = useUser()
- const router = useRouter()
- const { ref, slug } = useParams()
- const { data: organization } = useSelectedOrganizationQuery()
-
- const previousPathname = usePrevious(router.pathname)
-
- const { mutate: sendGroupsIdentify } = useSendGroupsIdentifyMutation()
- const { mutate: sendGroupsReset } = useSendGroupsResetMutation()
-
- const title = typeof document !== 'undefined' ? document?.title : ''
- const referrer = typeof document !== 'undefined' ? document?.referrer : ''
- useTelemetryCookie({ hasAcceptedConsent, title, referrer })
-
- useEffect(() => {
- // don't set the sentry user id if the user hasn't logged in (so that Sentry errors show null user id instead of anonymous id)
- if (!user?.id) {
- return
- }
-
- const setSentryId = async () => {
- let sentryUserId = localStorage.getItem(LOCAL_STORAGE_KEYS.SENTRY_USER_ID)
- if (!sentryUserId) {
- sentryUserId = await getAnonId(user?.id)
- localStorage.setItem(LOCAL_STORAGE_KEYS.SENTRY_USER_ID, sentryUserId)
- }
- Sentry.setUser({ id: sentryUserId })
- }
-
- // if an error happens, continue without setting a sentry id
- setSentryId().catch((e) => console.error(e))
- }, [user?.id])
-
- useEffect(() => {
- const isLandingOnProjectRoute =
- router.pathname.includes('[ref]') && previousPathname === router.pathname
- const isEnteringProjectRoute =
- !(previousPathname ?? '').includes('[ref]') && router.pathname.includes('[ref]')
- const isLeavingProjectRoute =
- (previousPathname ?? '').includes('[ref]') && !router.pathname.includes('[ref]')
-
- const isLandingOnOrgRoute =
- router.pathname.includes('[slug]') && previousPathname === router.pathname
- const isEnteringOrgRoute =
- !(previousPathname ?? '').includes('[slug]') && router.pathname.includes('[slug]')
- const isLeavingOrgRoute =
- (previousPathname ?? '').includes('[slug]') && !router.pathname.includes('[slug]')
-
- if (hasAcceptedConsent) {
- if (ref && (isLandingOnProjectRoute || isEnteringProjectRoute)) {
- sendGroupsIdentify({ organization_slug: organization?.slug, project_ref: ref as string })
- } else if (slug && (isLandingOnOrgRoute || isEnteringOrgRoute)) {
- sendGroupsIdentify({ organization_slug: slug, project_ref: undefined })
- } else if (isLeavingProjectRoute || isLeavingOrgRoute) {
- sendGroupsReset({
- reset_organization: isLeavingOrgRoute || isLeavingProjectRoute,
- reset_project: isLeavingProjectRoute,
- })
- }
- }
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [hasAcceptedConsent, slug, ref, router.pathname])
-
- return null
-}
-
-export default GroupsTelemetry
diff --git a/apps/studio/data/telemetry/send-groups-identify-mutation.ts b/apps/studio/data/telemetry/send-groups-identify-mutation.ts
deleted file mode 100644
index 07d8b316fc9..00000000000
--- a/apps/studio/data/telemetry/send-groups-identify-mutation.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { useMutation, UseMutationOptions } from '@tanstack/react-query'
-
-import { components } from 'api-types'
-import { hasConsented } from 'common'
-import { handleError, post } from 'data/fetchers'
-import { IS_PLATFORM } from 'lib/constants'
-import type { ResponseError } from 'types'
-
-export type SendGroupsIdentifyVariables = components['schemas']['TelemetryGroupsIdentityBody']
-
-export async function sendGroupsIdentify({ body }: { body: SendGroupsIdentifyVariables }) {
- const consent = hasConsented()
-
- if (!consent || !IS_PLATFORM) return undefined
-
- const { data, error } = await post(`/platform/telemetry/groups/identify`, {
- body,
- credentials: 'include',
- })
- if (error) handleError(error)
- return data
-}
-
-type SendGroupsIdentifyData = Awaited<ReturnType<typeof sendGroupsIdentify>>
-
-export const useSendGroupsIdentifyMutation = ({
- onSuccess,
- onError,
- ...options
-}: Omit<
- UseMutationOptions<SendGroupsIdentifyData, ResponseError, SendGroupsIdentifyVariables>,
- 'mutationFn'
-> = {}) => {
- return useMutation<SendGroupsIdentifyData, ResponseError, SendGroupsIdentifyVariables>(
- (vars) => sendGroupsIdentify({ body: vars }),
- {
- async onSuccess(data, variables, context) {
- await onSuccess?.(data, variables, context)
- },
- async onError(data, variables, context) {
- if (onError === undefined) {
- console.error(`Failed to send Telemetry groups identify: ${data.message}`)
- } else {
- onError(data, variables, context)
- }
- },
- ...options,
- }
- )
-}
diff --git a/apps/studio/data/telemetry/send-groups-reset-mutation.ts b/apps/studio/data/telemetry/send-groups-reset-mutation.ts
deleted file mode 100644
index 6f8524547f4..00000000000
--- a/apps/studio/data/telemetry/send-groups-reset-mutation.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { useMutation, UseMutationOptions } from '@tanstack/react-query'
-
-import { components } from 'api-types'
-import { hasConsented } from 'common'
-import { handleError, post } from 'data/fetchers'
-import { IS_PLATFORM } from 'lib/constants'
-import type { ResponseError } from 'types'
-
-export type SendGroupsResetVariables = components['schemas']['TelemetryGroupsResetBody']
-
-export async function sendGroupsReset({ body }: { body: SendGroupsResetVariables }) {
- const consent = hasConsented()
-
- if (!consent || !IS_PLATFORM) return undefined
-
- const { data, error } = await post(`/platform/telemetry/groups/reset`, {
- body,
- credentials: 'include',
- })
- if (error) handleError(error)
- return data
-}
-
-type SendGroupsResetData = Awaited<ReturnType<typeof sendGroupsReset>>
-
-export const useSendGroupsResetMutation = ({
- onSuccess,
- onError,
- ...options
-}: Omit<
- UseMutationOptions<SendGroupsResetData, ResponseError, SendGroupsResetVariables>,
- 'mutationFn'
-> = {}) => {
- return useMutation<SendGroupsResetData, ResponseError, SendGroupsResetVariables>(
- (vars) => sendGroupsReset({ body: vars }),
- {
- async onSuccess(data, variables, context) {
- await onSuccess?.(data, variables, context)
- },
- async onError(data, variables, context) {
- if (onError === undefined) {
- console.error(`Failed to send Telemetry groups reset: ${data.message}`)
- } else {
- onError(data, variables, context)
- }
- },
- ...options,
- }
- )
-}
diff --git a/apps/studio/lib/telemetry.tsx b/apps/studio/lib/telemetry.tsx
index 5c4f9932aef..4e17c8cf78d 100644
--- a/apps/studio/lib/telemetry.tsx
+++ b/apps/studio/lib/telemetry.tsx
@@ -1,7 +1,20 @@
-import { PageTelemetry } from 'common'
+import * as Sentry from '@sentry/nextjs'
+import { useEffect } from 'react'
+
+import { LOCAL_STORAGE_KEYS, PageTelemetry, useUser } from 'common'
+import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { API_URL, IS_PLATFORM } from 'lib/constants'
import { useConsentToast } from 'ui-patterns/consent'
-import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+
+const getAnonId = async (id: string) => {
+ const encoder = new TextEncoder()
+ const data = encoder.encode(id)
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data)
+ const hashArray = Array.from(new Uint8Array(hashBuffer))
+ const base64String = btoa(hashArray.map((byte) => String.fromCharCode(byte)).join(''))
+
+ return base64String
+}
export function Telemetry() {
// Although this is "technically" breaking the rules of hooks
@@ -13,6 +26,27 @@ export function Telemetry() {
// always available in the URL params
const { data: organization } = useSelectedOrganizationQuery()
+ const user = useUser()
+
+ useEffect(() => {
+ // don't set the sentry user id if the user hasn't logged in (so that Sentry errors show null user id instead of anonymous id)
+ if (!user?.id) {
+ return
+ }
+
+ const setSentryId = async () => {
+ let sentryUserId = localStorage.getItem(LOCAL_STORAGE_KEYS.SENTRY_USER_ID)
+ if (!sentryUserId) {
+ sentryUserId = await getAnonId(user?.id)
+ localStorage.setItem(LOCAL_STORAGE_KEYS.SENTRY_USER_ID, sentryUserId)
+ }
+ Sentry.setUser({ id: sentryUserId })
+ }
+
+ // if an error happens, continue without setting a sentry id
+ setSentryId().catch((e) => console.error(e))
+ }, [user?.id])
+
return (
<PageTelemetry
API_URL={API_URL}