Files
supabase/apps/studio/hooks/misc/useAccountRecovery.test.tsx
Danny White 5cf3cf1032 feat(studio): make security the home for sign-in and recovery setup (#52358)
## Problem

- Sign-in methods are in Preferences, separate from MFA and recovery
settings.
- The risk of a single sign-in method (e.g. GitHub, and getting locked
out of that account) isn’t clearly communicated.

## Solution

- Bring sign-in methods, MFA and recovery codes together on the Security
page. If Security is disabled, sign-in methods remain accessible in
Preferences.
- Highlight the most important next step with a primary button. For
example, when MFA is off, “Set up MFA” takes priority over adding a
password.
- Explain the risk of relying on a single sign-in provider, and make it
clear which email address a new password will apply to.
- After connecting a sign-in provider, return users to the settings page
they can access. Links to password setup open the password dialog
directly.

| After |
| --- |
| <img width="1460" height="1426" alt="CleanShot 2026-11-06 at 14 54
23@2x"
src="https://github.com/user-attachments/assets/afb82601-1b6f-43be-9e98-a0edb8d529c8"
/> |
| _The “Sign-in methods” section moved to Account → Security. Note also
the new Admonition regarding the risk of a single (GitHub) sign-in
method._ |

## Review instructions

1. Open
[Security](https://studio-staging-git-dnywh-recovery-security-home-supabase.vercel.app/dashboard/account/security#sign-in-methods).
Check sign-in methods appear above MFA and recovery codes. With MFA off,
“Set up MFA” should be primary.
2. Open Preferences. Sign-in methods should be absent unless Security is
disabled.
3. On a test account, check password setup, email editing and provider
linking. [Open password setup
directly](https://studio-staging-git-dnywh-recovery-security-home-supabase.vercel.app/dashboard/account/security?securityAction=set-password#sign-in-methods),
then cancel and confirm it stays closed.
2026-11-09 17:42:43 +11:00

121 lines
4.8 KiB
TypeScript

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { renderHook, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useAccountRecovery } from './useAccountRecovery'
import { useMfaListFactorsQuery } from '@/data/profile/mfa-list-factors-query'
import { useProfileIdentitiesQuery } from '@/data/profile/profile-identities-query'
import { useRecoveryCodesStatusQuery } from '@/data/recovery-codes/recovery-codes-status-query'
const mock = vi.hoisted(() => ({
userId: 'user-a',
recoveryCodesEnabled: true,
passwordEnabled: true,
listFactors: vi.fn(),
getUser: vi.fn(),
getStatus: vi.fn(),
}))
vi.mock('common', () => ({
useFlag: (name: string) =>
name === 'enableAuthRecoveryCodes' ? mock.recoveryCodesEnabled : mock.passwordEnabled,
useUser: () => (mock.userId ? { id: mock.userId } : null),
}))
vi.mock('@/lib/gotrue', () => ({
auth: {
mfa: { listFactors: mock.listFactors, recoveryCodes: { getStatus: mock.getStatus } },
getUser: mock.getUser,
},
}))
vi.mock('@/lib/constants', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/constants')>()),
IS_PLATFORM: true,
}))
const renderRecovery = () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
return renderHook(() => useAccountRecovery(), { wrapper })
}
describe('useAccountRecovery', () => {
beforeEach(() => {
vi.clearAllMocks()
mock.userId = 'user-a'
mock.recoveryCodesEnabled = true
mock.passwordEnabled = true
mock.listFactors.mockResolvedValue({
data: { all: [{ factor_type: 'totp', status: 'verified' }] },
error: null,
})
mock.getUser.mockResolvedValue({
data: { user: { identities: [{ provider: 'email' }], email: 'person@example.com' } },
error: null,
})
mock.getStatus.mockResolvedValue({ data: { remaining: 0 }, error: null })
})
it('waits for code status before showing a code or factor finding', async () => {
let resolveStatus: (value: unknown) => void = () => undefined
mock.getStatus.mockReturnValue(new Promise((resolve) => (resolveStatus = resolve)))
const { result } = renderRecovery()
await waitFor(() => expect(mock.getStatus).toHaveBeenCalledOnce())
expect(result.current).toMatchObject({ findings: [], isPending: true, isError: false })
resolveStatus({ data: { remaining: 0 }, error: null })
await waitFor(() => expect(result.current.findings[0]?.id).toBe('recovery-codes-exhausted'))
expect(result.current.isPending).toBe(false)
expect(result.current.isFactorsSuccess).toBe(true)
})
it('does not treat a failed code read as missing codes', async () => {
mock.getStatus.mockResolvedValue({ data: null, error: new Error('Unavailable') })
const { result } = renderRecovery()
await waitFor(() => expect(result.current.isError).toBe(true))
expect(result.current.findings).toEqual([])
})
it('isolates existing callers that omit a user ID', async () => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const { result, rerender } = renderHook(
() => ({
factors: useMfaListFactorsQuery(),
identities: useProfileIdentitiesQuery(),
codes: useRecoveryCodesStatusQuery(),
}),
{
wrapper: ({ children }) => (
<QueryClientProvider client={client}>{children}</QueryClientProvider>
),
}
)
await waitFor(() => expect(result.current.codes.isSuccess).toBe(true))
await waitFor(() => expect(result.current.factors.isSuccess).toBe(true))
await waitFor(() => expect(result.current.identities.isSuccess).toBe(true))
mock.userId = 'user-b'
rerender()
expect(result.current.factors.data).toBeUndefined()
expect(result.current.identities.data).toBeUndefined()
expect(result.current.codes.data).toBeUndefined()
await waitFor(() => expect(mock.getStatus).toHaveBeenCalledTimes(2))
await waitFor(() => expect(mock.listFactors).toHaveBeenCalledTimes(2))
await waitFor(() => expect(mock.getUser).toHaveBeenCalledTimes(2))
})
it('does not reuse findings after the signed-in user changes', async () => {
const { result, rerender } = renderRecovery()
await waitFor(() => expect(result.current.findings[0]?.id).toBe('recovery-codes-exhausted'))
mock.userId = 'user-b'
mock.getStatus.mockResolvedValue({ data: { remaining: 10 }, error: null })
rerender()
expect(result.current.findings).toEqual([])
await waitFor(() => expect(mock.getStatus).toHaveBeenCalledTimes(2))
expect(result.current.findings.map((finding) => finding.id)).toEqual(['single-mfa-factor'])
})
})