Files
supabase/apps/studio/components/interfaces/Account/RecoveryReminderController.tsx
Danny White fdab2cc751 feat(studio): interrupt serious account recovery gaps (#51643)
## Problem

Users with serious recovery gaps may never visit Account Security, so a
manually accessible reminder is easy to miss.

## Solution

Show the existing reminder as a full-screen layout takeover after
required MFA verification and successful account reads. Keep the
original URL, query and fragment intact. The dashboard stays mounted but
inert, preserving unsaved work; dismissal reveals it. Wait for existing
dialogs to close. Keep rollout gating, eligibility and snooze unchanged.
A successfully resolved background check dismisses an untouched
takeover; started tasks and completed rows remain until Continue.


Both of these recovery flags are enabled via ConfigCat for local and
staging:
- `enableAccountRecoveryInterstitial`: this work
- `enableAuthRecoveryCodes`: the work it depends on

We’ll only flip these to `true` for production once all of this is
merged and heavily tested.

| Interruption Example |
| --- |
| <img width="654" height="800" alt="16563"
src="https://github.com/user-attachments/assets/eec71acf-78ab-473d-a9d3-9c6cdc3aff07"
/> |

The dashboard remains usable while eligibility loads. An open takeover
stays in place through background refreshes. Signing out clears
in-memory reminder state so clearing browser snooze permits retesting.

## Review instructions

1. Open [this PR’s staging
preview](https://studio-staging-git-dnywh-account-recovery-interstitial-supabase.vercel.app/dashboard/organizations)
with a non-SSO test account and complete required MFA verification.
Check `enableAccountRecoveryInterstitial` and `enableAuthRecoveryCodes`
are both true in the staging dev toolbar. Close the toolbar and other
dialogs.
2. **Exhausted codes:** use an account with existing codes and exactly
one verified authenticator. Override GET `/factors/recovery-codes` in
DevTools Network: retain JSON fields, set `remaining` to `0` and save.
Clear `account-recovery-reminder:<userId>` from Local Storage for this
preview origin, then reload. Make sure you are **not** on
`dashboard/account/security` as that won’t show the interstitial.
Confirm the request uses the override and the takeover opens without
changing the URL.
3. **Missing codes, separate scenario:** disable overrides and use an
MFA test account with no generated codes. Clear snooze and reload. A
zero remaining count simulates exhausted codes, not missing codes. A
second verified authenticator prevents the exhausted-code trigger, but
not the missing-code trigger.
4. Skip, reload and switch projects or organisations. Confirm snooze
persists. A different account must have separate reminder state. For
warning-to-critical escalation, generate codes on the missing-code
account, then override its remaining count to zero and reload without
clearing the warning snooze.
5. Disable overrides before live actions. Save codes or add an
authenticator, then Continue. Confirm the page and URL remain intact.
Tab and Command/Ctrl+K must not reach dashboard controls; nested dialogs
must still work. Editor draft and browser-history preservation are also
covered by component tests.
6. With snooze cleared, open a project URL containing a query and
fragment; opening and dismissing the takeover must leave that full URL
unchanged. Check account settings, sign-in, MFA verification and
consent/connection flows remain uninterrupted. A healthy account, failed
reads or a disabled rollout flag must not trigger a takeover.
7. Throttle the status request: the dashboard stays usable while
eligibility loads. If another dialog is already open, the takeover waits
until it closes. There is no standalone recovery route or runtime mock
parameter.
2026-10-27 12:42:05 +11:00

131 lines
4.2 KiB
TypeScript

import { useAuth, useFeatureFlags, useFlag, useUser } from 'common'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { RecoveryInterstitial } from './RecoveryInterstitial/RecoveryInterstitial'
import { getRecoveryGap, type RecoveryGap } from './RecoveryInterstitial/RecoveryInterstitial.utils'
import { RecoveryTakeover } from './RecoveryTakeover'
import { useAuthenticatorAssuranceLevelQuery } from '@/data/profile/mfa-authenticator-assurance-level-query'
import { useAccountRecovery } from '@/hooks/misc/useAccountRecovery'
import {
canInterruptRecoveryRoute,
isRecoveryReminderSnoozed,
readRecoveryReminderSnooze,
resetRecoveryReminderSession,
} from '@/lib/account-recovery/recovery-reminder'
import { BASE_PATH, IS_PLATFORM } from '@/lib/constants'
import { useTrack } from '@/lib/telemetry/track'
export const RecoveryReminderController = ({
href,
children,
}: {
children?: ReactNode
href: string
}) => {
const user = useUser()
const { session, isLoading } = useAuth()
const { hasLoaded, isConfigCatStale } = useFeatureFlags()
const isRolloutEnabled = useFlag('enableAccountRecoveryInterstitial')
const internalHref =
BASE_PATH && href.startsWith(`${BASE_PATH}/`) ? href.slice(BASE_PATH.length) : href
const isEnabled =
IS_PLATFORM &&
hasLoaded === true &&
!isConfigCatStale &&
isRolloutEnabled === true &&
!!session &&
!!user?.id &&
!isLoading &&
canInterruptRecoveryRoute(internalHref)
const assurance = useAuthenticatorAssuranceLevelQuery({ enabled: isEnabled })
const hasVerifiedSession =
isEnabled && assurance.isSuccess && assurance.data.currentLevel === assurance.data.nextLevel
const recovery = useAccountRecovery({ enabled: hasVerifiedSession })
const gap = getRecoveryGap(recovery.findings)
const track = useTrack()
const [reminder, setReminder] = useState<{ userId: string; gap: RecoveryGap } | null>(null)
const dismissedGap = useRef<string | null>(null)
const previousFocus = useRef<HTMLElement | null>(null)
const isShowing = hasVerifiedSession && reminder?.userId === user?.id
useEffect(() => {
if (!hasVerifiedSession || (reminder && reminder.userId !== user?.id)) {
setReminder(null)
dismissedGap.current = null
return
}
if (!gap) dismissedGap.current = null
if (
reminder ||
recovery.isPending ||
recovery.isFetching ||
recovery.isError ||
!gap ||
!user?.id
)
return
const userId = user.id
if (isRecoveryReminderSnoozed(readRecoveryReminderSnooze(userId), gap)) return
const show = () => {
if (
dismissedGap.current === `${userId}:${gap}` ||
isRecoveryReminderSnoozed(readRecoveryReminderSnooze(userId), gap) ||
document.querySelector(
'[role="dialog"]:not([data-state="closed"]), [role="alertdialog"]:not([data-state="closed"]), [role="menu"][data-state="open"]'
)
)
return
observer.disconnect()
previousFocus.current =
document.activeElement instanceof HTMLElement ? document.activeElement : null
setReminder({ userId, gap })
track('account_recovery_reminder_exposed', { gap })
}
const observer = new MutationObserver(show)
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['data-state'],
})
show()
return () => observer.disconnect()
}, [
hasVerifiedSession,
href,
gap,
reminder,
recovery.isPending,
recovery.isFetching,
recovery.isError,
track,
user?.id,
])
useEffect(() => {
const userId = user?.id
return () => {
if (userId) resetRecoveryReminderSession(userId)
}
}, [user?.id])
return (
<>
<div className="contents" inert={isShowing}>
{children}
</div>
{isShowing && reminder && (
<RecoveryTakeover restoreFocusTo={previousFocus.current}>
<RecoveryInterstitial
onDismiss={() => {
if (!readRecoveryReminderSnooze(reminder.userId))
dismissedGap.current = `${reminder.userId}:${reminder.gap}`
setReminder(null)
}}
/>
</RecoveryTakeover>
)}
</>
)
}