Files
Danny White 767cc52c13 feat(studio): track recovery code copy and download (#53195)
## Problem

Studio tracks completion of recovery setup, but there are no events for
copying or downloading the codes.

## Solution

Track both actions in the shared recovery-code dialog. Record a copy
after the clipboard write succeeds and a download when the browser
starts it. The events carry no recovery-code values.

## Review instructions

1. Open [Recovery
codes](https://supabase.com/dashboard/account/security#recovery-codes)
on this branch's Studio preview with a disposable MFA account. Select
**Generate recovery codes** or **Regenerate** if it already has a set.
2. In **Save your recovery codes**, select **Copy**, then **Download**.
Check the browser network panel for `recovery_codes_copied` and
`recovery_codes_download_clicked` in the telemetry requests
(`telemetry/event`).
2026-11-11 09:40:32 +11:00

268 lines
9.6 KiB
TypeScript

import { useQueryClient } from '@tanstack/react-query'
import { useFeatureFlags, useFlag, useUser } from 'common'
import { ArrowRightIcon } from 'lucide-react'
import { useEffect, useState } from 'react'
import { Button, CardFooter } from 'ui'
import { WarningIcon } from 'ui-patterns/Admonition'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import { GenerateRecoveryCodesModal } from '../TOTPFactors/GenerateRecoveryCodesModal'
import { RegenerateRecoveryCodesModal } from '../TOTPFactors/RegenerateRecoveryCodesModal'
import { AuthenticatorTask } from './AuthenticatorTask'
import { getRecoveryGap, type RecoveryGap } from './RecoveryInterstitial.utils'
import { RecoveryTaskRow } from './RecoveryTaskRow'
import {
InterstitialLayout,
InterstitialLogoBadge,
SupabaseLogo,
} from '@/components/layouts/InterstitialLayout'
import { AlertError } from '@/components/ui/AlertError'
import { profileKeys } from '@/data/profile/keys'
import { recoveryCodeKeys } from '@/data/recovery-codes/keys'
import { useAccountRecovery } from '@/hooks/misc/useAccountRecovery'
import {
clearRecoveryReminderSnooze,
getRemainingRecoveryGap,
writeRecoveryReminderSnooze,
} from '@/lib/account-recovery/recovery-reminder'
import { useTrack } from '@/lib/telemetry/track'
export const RecoveryInterstitial = ({ onDismiss }: { onDismiss: () => void }) => {
return <LiveRecoveryReminder onDismiss={onDismiss} />
}
const LiveRecoveryReminder = ({ onDismiss }: { onDismiss: () => void }) => {
const user = useUser()
const queryClient = useQueryClient()
const track = useTrack()
const { hasLoaded, isConfigCatStale } = useFeatureFlags()
const flagsReady = hasLoaded === true && !isConfigCatStale
const isEnabled = useFlag('enableAuthRecoveryCodes')
const { findings, isPending, isFetching, isError, verifiedFactorCount } = useAccountRecovery({
enabled: flagsReady && isEnabled,
})
const isLoading = !flagsReady || isPending || isFetching
const isUnavailable = flagsReady && !isEnabled
const gap = isError || !flagsReady || isPending || isUnavailable ? null : getRecoveryGap(findings)
let announcement = 'Account recovery check complete'
if (gap) announcement = 'Account recovery action needed'
if (isUnavailable) announcement = 'Account recovery check unavailable'
if (isLoading) announcement = 'Checking account recovery'
if (isError) announcement = ''
return (
<>
<span className="sr-only" role="status">
{announcement}
</span>
<RecoveryReminder
key={user?.id}
gap={gap}
onDismiss={onDismiss}
isLoading={isLoading}
isUnavailable={isUnavailable}
hasAuthenticatorTask={verifiedFactorCount === 1}
isError={isError}
onAction={(actionType) => track('account_recovery_action_clicked', { actionType })}
onTaskComplete={(taskType) => track('account_recovery_task_completed', { taskType })}
onExit={({ gap: activeGap, areCodesSaved, isFactorComplete }) => {
if (user?.id) {
// Completed mutations can precede the refreshed status response.
const remainingGap = getRemainingRecoveryGap({
currentGap: getRecoveryGap(findings),
activeGap,
isReadUnavailable: isPending || isError,
areCodesSaved,
isFactorComplete,
})
if (remainingGap) writeRecoveryReminderSnooze(user.id, remainingGap)
else clearRecoveryReminderSnooze(user.id)
}
track('account_recovery_reminder_closed', {
hasCompletedTask: areCodesSaved || isFactorComplete,
})
}}
onCodesComplete={() => {
queryClient.invalidateQueries({ queryKey: recoveryCodeKeys.status(user?.id) })
}}
onFactorComplete={() => {
queryClient.invalidateQueries({ queryKey: profileKeys.mfaFactors(user?.id) })
}}
/>
</>
)
}
export const RecoveryReminder = ({
gap,
onDismiss,
isLoading = false,
isError = false,
isUnavailable = false,
hasAuthenticatorTask = true,
onCodesComplete,
onFactorComplete,
onAction,
onTaskComplete,
onExit,
}: {
gap: RecoveryGap | null
onDismiss: () => void
isLoading?: boolean
isError?: boolean
isUnavailable?: boolean
hasAuthenticatorTask?: boolean
onCodesComplete?: () => void
onFactorComplete?: () => void
onAction?: (action: 'generate_codes' | 'regenerate_codes' | 'add_factor') => void
onTaskComplete?: (task: 'recovery_codes' | 'authenticator') => void
onExit?: (state: { gap: RecoveryGap; areCodesSaved: boolean; isFactorComplete: boolean }) => void
}) => {
const [startedGap, setStartedGap] = useState<RecoveryGap | null>(null)
const [startedHasAuthenticatorTask, setStartedHasAuthenticatorTask] = useState<boolean | null>(
null
)
const [areCodesSaved, setAreCodesSaved] = useState(false)
const [isFactorComplete, setIsFactorComplete] = useState(false)
// Preserve all task dialogs and completed rows during background status updates.
const activeGap = startedGap ?? gap
useEffect(() => {
if (isUnavailable || (!activeGap && !isLoading && !isError)) onDismiss()
}, [activeGap, isLoading, isError, isUnavailable, onDismiss])
if (isUnavailable || (!activeGap && !isLoading && !isError)) return null
if (!activeGap && isError) {
return (
<InterstitialLayout
logo={<SupabaseLogo />}
title="Account recovery check unavailable"
widthClassName="max-w-md"
>
<div className="px-6">
<AlertError subject="Failed to check account recovery" />
</div>
<CardFooter className="justify-center">
<Button size="tiny" onClick={onDismiss}>
Continue
</Button>
</CardFooter>
</InterstitialLayout>
)
}
if (!activeGap) {
return (
<InterstitialLayout
logo={<SupabaseLogo />}
title={
<div role="status" aria-label="Checking account recovery">
<ShimmeringLoader className="h-7 w-40 py-0" />
</div>
}
widthClassName="max-w-md"
description={<ShimmeringLoader className="h-5 w-64 max-w-full py-0" />}
>
<CardFooter className="justify-center px-6 py-5 min-h-16" />
</InterstitialLayout>
)
}
const isExhausted = activeGap === 'exhausted'
const handleStart = () => {
setStartedGap(activeGap)
setStartedHasAuthenticatorTask(startedHasAuthenticatorTask ?? hasAuthenticatorTask)
}
const handleCodesSaved = () => {
setAreCodesSaved(true)
onCodesComplete?.()
onTaskComplete?.('recovery_codes')
}
const flowProps = {
surface: 'recovery_interstitial' as const,
showSecurityLink: true,
onStart: () => {
handleStart()
onAction?.(isExhausted ? 'regenerate_codes' : 'generate_codes')
},
onComplete: handleCodesSaved,
variant: 'primary' as const,
size: 'tiny' as const,
}
let codesTitle = isExhausted ? 'Recovery codes used up' : 'No recovery codes'
if (areCodesSaved) codesTitle = 'Recovery codes saved'
return (
<InterstitialLayout
logo={
<SupabaseLogo
badge={
<InterstitialLogoBadge variant="warning">
<WarningIcon />
</InterstitialLogoBadge>
}
/>
}
title="Secure your account"
description="Complete the following tasks to reduce the risk of being locked out of your Supabase account."
widthClassName="max-w-md"
containerClassName="relative before:pointer-events-none before:absolute before:inset-x-0 before:top-0 before:h-64 before:bg-gradient-to-b before:from-warning-600/10 before:to-transparent"
cardClassName="relative"
>
<div className="border-t divide-y">
<RecoveryTaskRow
title={codesTitle}
description={getCodesDescription(isExhausted, areCodesSaved)}
isComplete={areCodesSaved}
>
{!areCodesSaved && isExhausted && (
<RegenerateRecoveryCodesModal
{...flowProps}
label="Regenerate codes"
showIcon={false}
/>
)}
{!areCodesSaved && !isExhausted && (
<GenerateRecoveryCodesModal {...flowProps} label="Generate codes" />
)}
</RecoveryTaskRow>
{(startedHasAuthenticatorTask ?? hasAuthenticatorTask) && (
<AuthenticatorTask
onStart={() => {
handleStart()
onAction?.('add_factor')
}}
onComplete={() => {
setIsFactorComplete(true)
onFactorComplete?.()
onTaskComplete?.('authenticator')
}}
onRecoveryCodesSaved={handleCodesSaved}
/>
)}
</div>
<CardFooter className="justify-center px-6 py-5 border-t">
<Button
variant="text"
size="tiny"
onClick={() => {
onExit?.({ gap: activeGap, areCodesSaved, isFactorComplete })
onDismiss()
}}
className={areCodesSaved || isFactorComplete ? '' : 'text-foreground-lighter'}
iconRight={
areCodesSaved || isFactorComplete ? (
<ArrowRightIcon size={14} aria-hidden="true" />
) : undefined
}
>
{areCodesSaved || isFactorComplete ? 'Continue' : 'Skip for now'}
</Button>
</CardFooter>
</InterstitialLayout>
)
}
function getCodesDescription(isExhausted: boolean, areCodesSaved: boolean) {
if (areCodesSaved) return 'Keep your recovery codes somewhere safe.'
return isExhausted
? 'Generate a new set for future use.'
: 'Save codes in case you lose access to your MFA methods.'
}