Files
supabase/apps/studio/components/interfaces/ApiAuthorization/ApiAuthorization.Valid.tsx
Pamela Chia d336555617 fix(telemetry): redact url params and page titles (#54044)
The frontend apps send the current URL and page title with every
analytics event. The redaction added in #53500 and extended in #53955
only covers the `keywords` and `schema` params, so Table Editor filters,
search text, invite tokens, OAuth codes and the auth redirect hash still
go out in URL properties, and Studio's title carries the table, project
and org names.

**Changed:**
- **Query values are redacted by default**: every `name=value` in a URL
property now goes out as `name=redacted`, unless the name is one that
attribution reads downstream (`utm_*`, the click ids the first-referrer
cookie already collects, `dub_id`, `campaign_id`, `cid`, `promo_code`).
Param names and the `?` stay, so reports that match on a param being
present keep working. Fixed-vocabulary params such as `tab` are not on
the list: nothing reads them today, and several of those names carry
customer data on other pages.
- **A change to a redacted value no longer sends a pageview**: picking a
new filter value on the same page used to send a pageview, which would
now be identical to the previous one. The dedupe check compares the
redacted URL, so it is skipped. This lowers Studio pageview counts: on
current traffic, at most about 9% of dashboard pageviews repeat the
previous path with a query string.
- **Events from both transports are covered, and the hash is dropped**:
`identify` and `group` let the SDK stamp its own `$current_url` with the
hash, and `$set_once` pinned that on the person. `before_send` now
strips it, and the SDK no longer captures hashes itself. Custom events
skip `before_send`, so the same redaction also runs on their `pathname`
field, where www was appending the raw query string. The SDK's copy of a
search-engine referrer's query (`ph_keyword`) is dropped too.
- **Studio sends a route-level title**: `Tables | Database | Supabase`
in place of `users | Tables | Database | <project> | <org> | Supabase`.
The tab title users see is unchanged, and so are titles in the other
apps, which are public content.
- **Dead clicks, heatmaps and web vitals are pinned off**: each one puts
page text or the page URL in a nested payload the redaction does not
walk, and each can be switched on from project settings without a
deploy. All three are off today.

**Note:** One path is only partly covered. Feature-flag requests carry
the first URL and referrer the SDK stored for the browser, and they
never pass through `before_send`. The hash is now gone from them; query
values in that first URL (for example an invite link opened in a fresh
browser) still go out on those requests.

## To test

Signed in on the Studio preview, with analytics consent accepted. Check
events in the staging analytics project, filtered to the preview host.

Tested on the PR preview:
- [x] Open the Table Editor, add a filter with the value
`leaktest@example.com` and a sort, type `leaktest` in the Tables search
and in a logs search, then click through a few pages. Expect no event
containing `leaktest`, and `filter=redacted`, `sort=redacted`,
`search=redacted` and `s=redacted` in `$current_url`. Observed: zero
events from the preview host contained `leaktest`; custom events,
`$pageview`, `$pageleave` and `$set` all carried the `=redacted` forms.
The filter and sort were applied by loading the Table Editor URL with
them, which is how the app restores them
- [x] Same session: expect `page_title` and `title` on every event to
hold only page names (for example `Tables | Database | Supabase`), with
no project, org or table name. Observed: `Table Editor | Supabase`,
`Tables | Database | Supabase`, `Postgres Logs | Logs | Supabase`, `Team
| Supabase` and similar; no event carried the project, org or table
name. `explorer_*` events keep their existing fixed title `Explorer`
- [x] Load
`/dashboard/project/<ref>?token=leaktest1&projectName=leaktest2#access_token=leaktest3`,
then open `/join?token=leaktest4&slug=x`. Expect zero events containing
`leaktest`, including `$set`, `$identify` and `$groupidentify`.
Observed: zero, with `token=redacted&projectName=redacted` and no hash
on any stored URL. `$set` and `$groupidentify` fired and were clean; no
`$identify` fired in this session (the user was already identified), so
that event was not observed
- [x] Load any page with `?utm_source=readable5` appended. Expect
`utm_source=readable5` readable in `$current_url`. Observed on Database
> Tables with `?utm_source=readable5&gclid=readable6&tab=readable7`:
both attribution params readable, `tab=redacted`. The Table Editor route
rewrites its own query string and drops unknown params before any event
fires, so use another page
- [x] Open a table in the Table Editor. Expect the browser tab title to
still lead with the table name and include the project and org names.
Observed: `<table> | Table Editor | <project> | <org> | Supabase`
- [x] On the Table Editor with a filter applied, change the filter value
twice, then add a sort. Expect no new `$pageview` for the two value
changes and one for the added sort (a new param name). Observed, all
through the UI with no reload: adding the filter sent one pageview, the
two value changes sent none, adding the sort sent one, and a sidebar
navigation sent one; the staging analytics project shows the same four
pageviews

## Linear
- fixes GROWTH-1572
2026-11-27 03:41:51 +00:00

254 lines
7.6 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod'
import { useEffect, useEffectEvent, useMemo, useState, type ReactNode } from 'react'
import { useForm, type UseFormReturn } from 'react-hook-form'
import { toast } from 'sonner'
import { ApiAuthorizationApprovedScreen } from './ApiAuthorization.Approved'
import { ApiAuthorizationErrorScreen } from './ApiAuthorization.Error'
import { ApiAuthorizationMainView } from './ApiAuthorization.Form'
import { ApiAuthorizationLoadingScreen } from './ApiAuthorization.Loading'
import {
approvalFormSchema,
type ApprovalState,
type IApprovalFormSchema,
} from './ApiAuthorization.Schema'
import { useApiAuthorizationApproveMutation } from '@/data/api-authorization/api-authorization-approve-mutation'
import { useApiAuthorizationDeclineMutation } from '@/data/api-authorization/api-authorization-decline-mutation'
import { useApiAuthorizationQuery } from '@/data/api-authorization/api-authorization-query'
import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
import { buildStudioPageTitle } from '@/lib/page-title'
import type { Organization } from '@/types'
function getMatchingOrganization(
organization_slug: string | undefined,
organizations: Array<Organization> | undefined
): Organization | null {
if (!organization_slug || !organizations) return null
return organizations.find(({ slug }) => slug === organization_slug) ?? null
}
interface PreselectOrganizationSlugParameters {
form: UseFormReturn<IApprovalFormSchema>
organization_slug: string | undefined
organizations: Array<{ slug: string }>
}
function preselectOrganizationSlug({
form,
organization_slug,
organizations,
}: PreselectOrganizationSlugParameters) {
if (organization_slug) {
const preselected = organizations.find(({ slug }) => slug === organization_slug)
if (preselected) form.setValue('selectedOrgSlug', preselected.slug)
} else if (!form.getValues('selectedOrgSlug') && organizations.length === 1) {
form.setValue('selectedOrgSlug', organizations[0].slug)
}
}
function useOrganizationsState(organization_slug: string | undefined, enabled = true) {
const {
data: organizations,
isPending: isLoadingOrganizations,
isError: isErrorOrganizations,
error: organizationsError,
} = useOrganizationsQuery({ enabled })
const organizationsState = useMemo(
function calculateOrganizationsState() {
if (!enabled) {
return { _tag: 'loading' as const }
}
if (isLoadingOrganizations) {
return { _tag: 'loading' as const }
}
if (isErrorOrganizations) {
return { _tag: 'error' as const, error: organizationsError }
}
if (organizations.length === 0) {
return { _tag: 'empty' as const }
}
if (organization_slug) {
const matchingOrganization = getMatchingOrganization(organization_slug, organizations)
if (!matchingOrganization) {
return { _tag: 'not_member' as const }
}
}
return { _tag: 'success' as const, organizations }
},
[
enabled,
isLoadingOrganizations,
isErrorOrganizations,
organizationsError,
organizations,
organization_slug,
]
)
return organizationsState
}
function usePrefillFormOnOrganizationsSuccess(
form: UseFormReturn<IApprovalFormSchema>,
organizationsState: ReturnType<typeof useOrganizationsState>,
organization_slug: string | undefined
) {
const prefillForm = useEffectEvent(() => {
if (organizationsState._tag === 'success') {
preselectOrganizationSlug({
form,
organization_slug,
organizations: organizationsState.organizations,
})
}
})
useEffect(() => {
if (organizationsState._tag === 'success') {
prefillForm()
}
}, [organizationsState._tag])
}
export interface ApiAuthorizationValidScreenProps {
auth_id: string
organization_slug: string | undefined
navigate: (destination: string) => void
}
export function ApiAuthorizationValidScreen({
auth_id,
organization_slug,
navigate,
}: ApiAuthorizationValidScreenProps): ReactNode {
const [approvalState, setApprovalState] = useState<ApprovalState>('indeterminate')
const form = useForm<IApprovalFormSchema>({
resolver: zodResolver(approvalFormSchema),
defaultValues: { selectedOrgSlug: '' },
mode: 'onSubmit',
reValidateMode: 'onBlur',
})
const organizationsState = useOrganizationsState(organization_slug)
usePrefillFormOnOrganizationsSuccess(form, organizationsState, organization_slug)
const {
data: requester,
isPending: isLoading,
isError,
error,
} = useApiAuthorizationQuery({ id: auth_id })
const isApproved = (requester?.approved_at ?? null) !== null
const {
mutate: approveRequest,
error: approveError,
reset: resetApproveError,
} = useApiAuthorizationApproveMutation({
onSuccess: (res) => {
window.location.href = res.url
},
onError: () => {
setApprovalState('indeterminate')
},
})
const {
mutate: declineRequest,
error: declineError,
reset: resetDeclineError,
} = useApiAuthorizationDeclineMutation({
onSuccess: () => {
toast.success('Declined API authorization request')
navigate('/organizations')
},
onError: () => {
setApprovalState('indeterminate')
},
})
const actionError = approveError
? `Failed to authorize request: ${approveError.message}`
: declineError
? `Failed to cancel authorization request: ${declineError.message}`
: undefined
const resetActionError = () => {
resetApproveError()
resetDeclineError()
}
const onApproveRequest = form.handleSubmit((values) => {
if (approvalState !== 'indeterminate') {
return
}
resetActionError()
setApprovalState('approving')
approveRequest({ id: auth_id, slug: values.selectedOrgSlug })
})
const onDeclineRequest = form.handleSubmit((values) => {
if (approvalState !== 'indeterminate') {
return
}
resetActionError()
setApprovalState('declining')
declineRequest({ id: auth_id, slug: values.selectedOrgSlug })
})
if (isLoading) {
return <ApiAuthorizationLoadingScreen />
}
if (isError) {
return <ApiAuthorizationErrorScreen error={error} />
}
const effectiveRequester = requester
const effectiveOrganizationsState = organizationsState
const effectiveOrganizationSlug = organization_slug
const effectiveApprovalState = approvalState
const pageTitle = effectiveRequester
? buildStudioPageTitle({ entity: `Authorize ${effectiveRequester.name}`, brand: 'Supabase' })
: undefined
if (!effectiveRequester) {
return <ApiAuthorizationErrorScreen error={undefined} />
}
if (isApproved) {
const approvedOrganization =
effectiveOrganizationsState._tag === 'success'
? effectiveOrganizationsState.organizations.find(
(org) => org.slug === effectiveRequester.approved_organization_slug
)
: undefined
return (
<>
{pageTitle && <title>{pageTitle}</title>}
<ApiAuthorizationApprovedScreen
requester={effectiveRequester}
organization={approvedOrganization}
/>
</>
)
}
return (
<>
{pageTitle && <title>{pageTitle}</title>}
<ApiAuthorizationMainView
auth_id={auth_id}
approvalState={effectiveApprovalState}
form={form}
requester={effectiveRequester}
requestedOrganizationSlug={effectiveOrganizationSlug}
organizations={effectiveOrganizationsState}
actionError={actionError}
onOrganizationChange={resetActionError}
onApprove={onApproveRequest}
onDecline={onDeclineRequest}
/>
</>
)
}