mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
Part 1 of a 6-PR stack migrating all `next/router` and `next/compat/router` imports in `apps/studio` onto TanStack Router hooks and removing the router shims. | Part | PR | Scope | | --- | --- | --- | | **1** | **#54053 ← this PR** | **Core navigation helpers, `hooks/**`, `lib/**`, `data/prefetchers/**`** | | 2 | #54054 | `components/ui/**` | | 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` | | 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer, SQL Editor, Storage, Table Editor | | 5 | #54057 | Remaining `components/interfaces/**` and `QueryInsightsTable` router events | | 6 | #54058 | Remove `next/router` & `next/compat/router` shims, `_router-events.ts`, Vite aliases, and test mocks | Introduces the shared TanStack navigation helpers needed across the stack and migrates `hooks/**`, `lib/**`, and `data/prefetchers/**` off `next/router`. **Added:** - `navigateToUrl` in `apps/studio/lib/navigation.ts` (plus unit tests in `lib/navigation.test.ts`): shared helper for navigating to internal string URLs via TanStack's `useNavigate` (splitting pathname, search params, and hash via `splitInternalUrl`, and handling external/protocol-relative URLs) - `useRoutePattern` in `apps/studio/hooks/misc/useRoutePattern.ts` (plus `useRoutePattern.test.tsx`): returns the active matched TanStack route template (e.g. `/project/$ref/editor/$id`) as the replacement for Next's `router.pathname` **Changed:** - Migrated `hooks/misc/*` (`useHydratedQuery`, `useStudioCommandMenuTelemetry`, `useTableEditorFiltersSort`, `withAuth`) and `hooks/use-check-latest-deploy.tsx` to TanStack's `useLocation`, `useNavigate`, `useRoutePattern`, and `useParams` from `common` - Migrated `lib/profile.tsx` and `lib/telemetry/track.ts` off `next/router` - Migrated `data/prefetchers/project.$ref.tsx`, `project.$ref.editor.tsx`, and `project.$ref.editor.$id.tsx` to `useRouter().preloadRoute` - Wrapped `ReactQueryTestConfig` in `apps/studio/tests/helpers.tsx` with `RouterContextProvider` and updated hook/navigation tests (`useTableEditorFiltersSort*.test.*`, `useFilterLifeCycle.navigation.test.tsx`, `useTableFilter.navigation.test.tsx`, `useInboundBranding.test.ts`, `state/tabs.test.ts`) **Simplified:** - `navigateToUrl` passes `replace` straight through and documents that `url` must be an app-relative path or an external URL. `StudioFrameworkProvider`'s `push` now reuses it. - `useRoutePattern` reads matches and location in a single `useRouterState` subscription - `useTrack` and `useStudioCommandMenuTelemetry` take the pathname from `useFramework()`, the same source as pageviews, so custom events and pageviews always send the same pattern (e.g. `/project/[ref]/sql/[id]`). New tests pin the strings sent, and `toRoutePattern` now has its own unit tests. - Removed `useCurrentPath` (a one-line wrapper with one consumer): `OrganizationSettingsLayout` calls `useLocation` directly - Dropped the no-op `.catch(() => {})` on `preloadRoute` in the prefetchers (`preloadRoute` never rejects) - `useTableEditorFiltersSort` builds the next search with a spread instead of a delete loop - Added `createTestRouter()` to `tests/lib/custom-render.tsx`, and `customRender`/`customRenderHook` now return the `router`. The rest of the stack uses these instead of hand-copied `createRouter` setups. Addresses [FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks) ## To test - [ ] Auth redirect flow (`withAuth`) still preserves `returnTo` query parameters when redirecting unauthenticated users to `/sign-in` - [ ] Table Editor sort and filter URL sync (`useTableEditorFiltersSort`) persists and clears `?sort=` / `?filter=` across table switches - [ ] Hovering project and table editor links still triggers route/data prefetching without console errors - [ ] Page view and command menu telemetry still records route patterns and paths accurately --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
165 lines
5.7 KiB
TypeScript
165 lines
5.7 KiB
TypeScript
import { useLocation, useNavigate, useRouter } from '@tanstack/react-router'
|
|
import { useAuth, useParams } from 'common'
|
|
import { ComponentType, useCallback, useEffect, useRef, useState } from 'react'
|
|
import { toast } from 'sonner'
|
|
|
|
import { SessionTimeoutModal } from '@/components/interfaces/SignIn/SessionTimeoutModal'
|
|
import { usePermissionsQuery } from '@/data/permissions/permissions-query'
|
|
import { useAuthenticatorAssuranceLevelQuery } from '@/data/profile/mfa-authenticator-assurance-level-query'
|
|
import { useSignOut } from '@/lib/auth'
|
|
import { IS_PLATFORM } from '@/lib/constants'
|
|
import { searchParamsToRecord } from '@/lib/router-search-params'
|
|
|
|
const MAX_TIMEOUT = 10000 // 10 seconds
|
|
|
|
export function withAuth<T>(
|
|
WrappedComponent: ComponentType<T>,
|
|
options: {
|
|
/**
|
|
* The auth level used to check the user credentials. In most cases, if the user has MFA enabled
|
|
* we want the highest level (which is 2) for all pages, as the platform API rejects sessions
|
|
* that haven't completed the MFA challenge. Only opt out for pages that don't read from the
|
|
* platform API and are meant to be reachable before the user has finished signing in.
|
|
* @default true
|
|
*/
|
|
useHighestAAL: boolean
|
|
} = { useHighestAAL: true }
|
|
) {
|
|
// ignore auth in self-hosted
|
|
if (!IS_PLATFORM) {
|
|
return WrappedComponent
|
|
}
|
|
|
|
const WithAuthHOC: ComponentType<T> = (props) => {
|
|
const router = useRouter()
|
|
const navigate = useNavigate()
|
|
const currentPathname = useLocation({ select: (location) => location.pathname })
|
|
const { ref, organizationSlug } = useParams()
|
|
const signOut = useSignOut()
|
|
const { isLoading, session } = useAuth()
|
|
|
|
const timeoutIdRef = useRef<NodeJS.Timeout | null>(null)
|
|
const [isSessionTimeoutModalOpen, setIsSessionTimeoutModalOpen] = useState(false)
|
|
|
|
const {
|
|
isPending: isAALLoading,
|
|
data: aalData,
|
|
isError: isErrorAAL,
|
|
isSuccess: isSuccessAAL,
|
|
error: errorAAL,
|
|
} = useAuthenticatorAssuranceLevelQuery()
|
|
|
|
const isAtHighestAAL = isSuccessAAL && aalData.currentLevel === aalData.nextLevel
|
|
|
|
useEffect(() => {
|
|
if (isErrorAAL) {
|
|
toast.error(
|
|
`Failed to fetch authenticator assurance level: ${errorAAL?.message}. Try refreshing your browser, or reach out to us via a support ticket if the issue persists`
|
|
)
|
|
}
|
|
}, [isErrorAAL, errorAAL])
|
|
|
|
const { isError: isErrorPermissions, error: errorPermissions } = usePermissionsQuery()
|
|
|
|
useEffect(() => {
|
|
if (isErrorPermissions && isAtHighestAAL) {
|
|
toast.error(
|
|
`Failed to fetch permissions: ${errorPermissions?.message}. Try refreshing your browser, or reach out to us via a support ticket if the issue persists`
|
|
)
|
|
}
|
|
}, [isErrorPermissions, errorPermissions, isAtHighestAAL])
|
|
|
|
const isLoggedIn = Boolean(session)
|
|
const isFinishedLoading = !isLoading && !isAALLoading
|
|
|
|
const isCorrectLevel = options.useHighestAAL ? isAtHighestAAL : true
|
|
const needsMfaElevation = isLoggedIn && !isCorrectLevel
|
|
|
|
const redirectToSignIn = useCallback(() => {
|
|
const { pathname, searchStr } = router.state.location
|
|
|
|
if (pathname === '/sign-in' || pathname === '/sign-in-mfa') {
|
|
// If the user is already on the sign in page, we don't need to redirect them
|
|
return
|
|
}
|
|
|
|
const searchParams = new URLSearchParams(searchStr)
|
|
searchParams.set('returnTo', pathname)
|
|
const search = searchParamsToRecord(searchParams)
|
|
|
|
if (needsMfaElevation) {
|
|
// Session is valid at AAL1 but needs to be elevated to AAL2. Preserve the session
|
|
// and send the user to the MFA challenge — typically the IdP-initiated SSO path,
|
|
// where the user lands directly on /dashboard without going through /sign-in-mfa.
|
|
void navigate({ to: '/sign-in-mfa', search })
|
|
return
|
|
}
|
|
|
|
// Sign out before redirecting to sign in page incase the user is stuck in a loading state
|
|
signOut().finally(() => {
|
|
void navigate({ to: '/sign-in', search })
|
|
})
|
|
}, [router, navigate, signOut, needsMfaElevation])
|
|
|
|
useEffect(() => {
|
|
if (!isFinishedLoading) {
|
|
timeoutIdRef.current = setTimeout(() => {
|
|
setIsSessionTimeoutModalOpen(true)
|
|
}, MAX_TIMEOUT)
|
|
} else {
|
|
if (timeoutIdRef.current) {
|
|
clearTimeout(timeoutIdRef.current)
|
|
timeoutIdRef.current = null
|
|
}
|
|
}
|
|
|
|
return () => {
|
|
if (timeoutIdRef.current) {
|
|
clearTimeout(timeoutIdRef.current)
|
|
}
|
|
}
|
|
}, [isFinishedLoading, redirectToSignIn])
|
|
|
|
const shouldRedirect = isFinishedLoading && (!isLoggedIn || !isCorrectLevel)
|
|
|
|
useEffect(() => {
|
|
if (shouldRedirect) {
|
|
// Clear the timeout if it's still active and we are redirecting
|
|
if (timeoutIdRef.current) {
|
|
clearTimeout(timeoutIdRef.current)
|
|
timeoutIdRef.current = null
|
|
}
|
|
redirectToSignIn()
|
|
}
|
|
}, [redirectToSignIn, shouldRedirect])
|
|
|
|
const InnerComponent = WrappedComponent as any
|
|
|
|
const supportContext =
|
|
typeof ref === 'string' && currentPathname.startsWith('/project/')
|
|
? {
|
|
projectRef: ref,
|
|
...(typeof organizationSlug === 'string' && {
|
|
orgSlug: organizationSlug,
|
|
}),
|
|
}
|
|
: undefined
|
|
|
|
return (
|
|
<>
|
|
<SessionTimeoutModal
|
|
visible={isSessionTimeoutModalOpen}
|
|
onClose={() => setIsSessionTimeoutModalOpen(false)}
|
|
redirectToSignIn={redirectToSignIn}
|
|
supportContext={supportContext}
|
|
/>
|
|
<InnerComponent {...props} />
|
|
</>
|
|
)
|
|
}
|
|
|
|
WithAuthHOC.displayName = `withAuth(${WrappedComponent.displayName})`
|
|
|
|
return WithAuthHOC
|
|
}
|