The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): move CLI login to connect interstitial (#45814)
Danny White205ab69061ac
diff --git a/apps/studio/components/layouts/InterstitialLayout.tsx b/apps/studio/components/layouts/InterstitialLayout.tsxindex cd25002cfa0..ba7981cca87 100644--- a/apps/studio/components/layouts/InterstitialLayout.tsx+++ b/apps/studio/components/layouts/InterstitialLayout.tsx@@ -1,4 +1,5 @@import { motion } from 'framer-motion'+import { ArrowRightLeft } from 'lucide-react'import type { PropsWithChildren, ReactNode } from 'react'import { Card, CardContent, CardHeader, cn } from 'ui'@@ -88,6 +89,14 @@ export const LogoBox = ({ children, className }: { children: ReactNode; classNam</div>)+export const LogoPair = ({ left, right }: { left: ReactNode; right: ReactNode }) => (+ <div className="flex items-center justify-center gap-2.5">+ {left}+ <ArrowRightLeft className="size-4 text-foreground-muted" />+ {right}+ </div>+)+export const SupabaseLogo = () => (<LogoBox><img alt="Supabase" src={`${BASE_PATH}/img/supabase-logo.svg`} className="size-7" />diff --git a/apps/studio/components/ui/CopyButton.tsx b/apps/studio/components/ui/CopyButton.tsxindex 425a168775f..334ee62445d 100644--- a/apps/studio/components/ui/CopyButton.tsx+++ b/apps/studio/components/ui/CopyButton.tsx@@ -31,6 +31,9 @@ const CopyButton = forwardRef<HTMLButtonElement, CopyButtonProps>(onClick,copyLabel = 'Copy',copiedLabel = 'Copied',+ type = 'primary',+ icon,+ className,...props},ref@@ -53,9 +56,17 @@ const CopyButton = forwardRef<HTMLButtonElement, CopyButtonProps>(onClick?.(e)}}{...props}- className={cn({ 'px-1': iconOnly }, props.className)}+ type={type}+ className={cn({ 'px-1': iconOnly }, className)}icon={- showCopied ? <Check strokeWidth={2} className="text-brand" /> : (props.icon ?? <Copy />)+ showCopied ? (+ <Check+ strokeWidth={2}+ className={cn(type === 'primary' ? 'text-inherit' : 'text-brand')}+ />+ ) : (+ (icon ?? <Copy />)+ )}>{!iconOnly && <>{children ?? (showCopied ? copiedLabel : copyLabel)}</>}diff --git a/apps/studio/pages/cli/login.tsx b/apps/studio/pages/cli/login.tsxindex 912c1c5a941..280ef6793b2 100644--- a/apps/studio/pages/cli/login.tsx+++ b/apps/studio/pages/cli/login.tsx@@ -1,87 +1,267 @@import { useIsLoggedIn, useParams } from 'common'+import { Terminal } from 'lucide-react'import Head from 'next/head'import Link from 'next/link'import { useRouter } from 'next/router'-import { useEffect } from 'react'-import { toast } from 'sonner'-import { InputOTP, InputOTPGroup, InputOTPSlot, LogoLoader } from 'ui'-import { Admonition } from 'ui-patterns'+import { useEffect, useState, type ReactNode } from 'react'+import { Button, Card, CardContent } from 'ui'+import { Admonition, ShimmeringLoader } from 'ui-patterns'-import { APIAuthorizationLayout } from '@/components/layouts/APIAuthorizationLayout'+import {+ InterstitialAccountRow,+ InterstitialLayout,+ LogoBox,+ LogoPair,+ SupabaseLogo,+} from '@/components/layouts/InterstitialLayout'import CopyButton from '@/components/ui/CopyButton'+import { InlineLink } from '@/components/ui/InlineLink'import { createCliLoginSession } from '@/data/cli/login'import { withAuth } from '@/hooks/misc/withAuth'+import { buildStudioPageTitle } from '@/lib/page-title'+import { useProfile } from '@/lib/profile'import type { NextPageWithLayout } from '@/types'+const PAGE_TITLE = buildStudioPageTitle({ section: 'Authorize CLI', brand: 'Supabase' })++const CliLogo = () => (+ <LogoBox className="bg-black">+ <Terminal className="size-6 text-white" strokeWidth={2} />+ </LogoBox>+)++const CliLoginInterstitial = ({+ title,+ description,+ children,+}: {+ title: ReactNode+ description?: ReactNode+ children: ReactNode+}) => (+ <InterstitialLayout+ logo={<LogoPair left={<CliLogo />} right={<SupabaseLogo />} />}+ title={title}+ description={description}+ >+ <div className="px-6 pb-6">{children}</div>+ </InterstitialLayout>+)+const CliLoginPage: NextPageWithLayout = () => {const router = useRouter()const { session_id, public_key, token_name, device_code } = useParams()const isLoggedIn = useIsLoggedIn()+ if (!router.isReady) return null++ return (+ <>+ <Head>+ <title>{PAGE_TITLE}</title>+ </Head>+ <CliLoginScreen+ isLoggedIn={isLoggedIn}+ routerReady={router.isReady}+ sessionId={session_id}+ publicKey={public_key}+ tokenName={token_name}+ deviceCode={device_code}+ navigate={(destination) => router.push(destination)}+ />+ </>+ )+}++type CliLoginStatus =+ | { _tag: 'loading' }+ | { _tag: 'ready'; deviceCode: string }+ | { _tag: 'missing-params'; missingParameters: string[] }+ | { _tag: 'error'; message?: string }++export const CliLoginScreen = ({+ isLoggedIn,+ routerReady,+ sessionId,+ publicKey,+ tokenName,+ deviceCode,+ navigate,+}: {+ isLoggedIn: boolean+ routerReady: boolean+ sessionId?: string+ publicKey?: string+ tokenName?: string+ deviceCode?: string+ navigate: (destination: string) => void+}) => {+ const { profile } = useProfile()+ const [status, setStatus] = useState<CliLoginStatus>({ _tag: 'loading' })+ const displayName = profile?.primary_email ?? profile?.username+useEffect(() => {- if (!isLoggedIn || !router.isReady || device_code) {+ if (!isLoggedIn || !routerReady) return+ if (deviceCode) {+ setStatus({ _tag: 'ready', deviceCode })return}- async function createSession() {- if (!session_id || !public_key) {- router.push('/404')- return- }+ const missingParameters = [+ !sessionId ? 'session_id' : undefined,+ !publicKey ? 'public_key' : undefined,+ ].filter(Boolean) as string[]++ if (missingParameters.length > 0) {+ setStatus({ _tag: 'missing-params', missingParameters })+ return+ }+ let isActive = true+ setStatus({ _tag: 'loading' })++ async function createSession() {try {- const { nonce } = await createCliLoginSession(session_id, public_key, token_name)+ const { nonce } = await createCliLoginSession(sessionId!, publicKey!, tokenName)++ if (!isActive) returnif (nonce) {- router.push(`/cli/login?device_code=${nonce.substring(0, 8)}`)+ navigate(`/cli/login?device_code=${nonce.substring(0, 8)}`)} else {- router.push(`/404`)+ setStatus({ _tag: 'error', message: 'The CLI sign-in session did not return a code.' })}- } catch (error: any) {- toast.error(`Failed to create login session: ${error.message}`)- router.push(`/500`)+ } catch (error: unknown) {+ if (!isActive) return+ setStatus({+ _tag: 'error',+ message: error instanceof Error ? error.message : 'Unknown error',+ })}}createSession()- }, [isLoggedIn, router, router.isReady, session_id, public_key, token_name, device_code])++ return () => {+ isActive = false+ }+ }, [deviceCode, isLoggedIn, navigate, publicKey, routerReady, sessionId, tokenName])++ if (status._tag === 'loading') {+ return (+ <CliLoginInterstitial+ title={<ShimmeringLoader className="mx-auto h-7 w-32 max-w-full py-0" />}+ description={<ShimmeringLoader className="mx-auto h-4 w-56 max-w-full py-0" />}+ >+ <div className="flex flex-col gap-5">+ <Card className="shadow-none">+ <CardContent className="flex items-center gap-3 border-none px-4 py-3">+ <ShimmeringLoader className="size-8 flex-shrink-0 rounded-full py-0" />+ <div className="min-w-0 flex-1 space-y-2">+ <ShimmeringLoader className="h-3 w-20 py-0" />+ <ShimmeringLoader className="h-4 w-40 max-w-full py-0" />+ </div>+ </CardContent>+ </Card>+ <ShimmeringLoader className="h-20 w-full rounded-lg py-0" />+ </div>+ </CliLoginInterstitial>+ )+ }++ if (status._tag === 'missing-params') {+ const isPlural = status.missingParameters.length > 1++ return (+ <CliLoginInterstitial+ title="Missing sign-in parameters"+ description="This Supabase CLI sign-in request cannot be authorized"+ >+ <div className="flex flex-col gap-3">+ <Admonition+ type="warning"+ description={`Open the browser sign-in flow from Supabase CLI again. The URL is missing parameter${+ isPlural ? 's' : ''+ }: ${status.missingParameters.join(', ')}.`}+ />+ <Button type="default" block asChild>+ <Link href="/organizations">Back to dashboard</Link>+ </Button>+ </div>+ </CliLoginInterstitial>+ )+ }++ if (status._tag === 'error') {+ return (+ <CliLoginInterstitial+ title="Unable to create CLI sign-in"+ description="Retry the sign-in command from Supabase CLI"+ >+ <div className="flex flex-col gap-3">+ <Admonition+ type="warning"+ description={+ <>+ Supabase could not create the CLI sign-in session.+ {status.message && (+ <span className="mt-1 block text-foreground-lighter">+ Error: {status.message}+ </span>+ )}+ </>+ }+ />+ <Button type="default" block asChild>+ <Link href="/organizations">Back to dashboard</Link>+ </Button>+ </div>+ </CliLoginInterstitial>+ )+ }return (- <APIAuthorizationLayout HeadProvider={Head}>- <div className={`flex flex-col items-center justify-center h-full`}>- {device_code ? (- <>- <h2 className="py-2">Your Supabase account is being used to login on Supabase CLI</h2>- <p>Enter this verification code on Supabase CLI to authorize login.</p>- <div className="flex flex-row gap-2 py-10">- <InputOTP maxLength={8} value={device_code} disabled>- <InputOTPGroup>- {Array.from({ length: 8 }, (_, i) => (- <InputOTPSlot key={i} className="text-xl" index={i} />- ))}- </InputOTPGroup>- </InputOTP>- <CopyButton iconOnly size="large" type="text" className="px-2" text={device_code} />- </div>- <p>After authorizing the login attempt, you can close this window.</p>- <p>- If you ever want to remove your new token, go to{' '}- <Link href="/account/tokens" className="underline">- Access Tokens- </Link>{' '}- page.- </p>- <Admonition- type="tip"- title="Browser login flow requires Supabase CLI version 1.219.0 and above."- className="mt-16"- />- </>- ) : (- <LogoLoader />- )}+ <CliLoginInterstitial+ title="Authorize Supabase CLI"+ description="Enter this verification code in Supabase CLI to finish signing in"+ >+ <div className="flex flex-col gap-5">+ <div className="flex flex-col items-center gap-3">+ <div+ aria-label={`Verification code ${status.deviceCode}`}+ className="flex w-full select-text items-center font-sans text-xl text-foreground"+ onCopy={(event) => {+ event.preventDefault()+ event.clipboardData.setData('text/plain', status.deviceCode)+ }}+ >+ {Array.from(status.deviceCode.padEnd(8, ' ')).map((character, index) => (+ <span+ key={index}+ className="flex h-11 flex-1 cursor-text select-text items-center justify-center border-y border-r border-input first:rounded-l-md first:border-l last:rounded-r-md"+ >+ {character}+ </span>+ ))}+ </div>+ <CopyButton+ text={status.deviceCode}+ copyLabel="Copy code"+ copiedLabel="Copied"+ type="primary"+ size="tiny"+ className="w-full"+ />+ </div>++ <InterstitialAccountRow displayName={displayName} />++ <p className="text-center text-xs text-foreground-lighter text-balance">+ After authorizing, you can close this tab or manage tokens like this one in{' '}+ <InlineLink href="/account/tokens">Access Tokens</InlineLink>.+ </p></div>- </APIAuthorizationLayout>+ </CliLoginInterstitial>)}diff --git a/apps/studio/tests/components/CopyButton.test.tsx b/apps/studio/tests/components/CopyButton.test.tsxindex 4408ab0761e..ba8bb4eb2eb 100644--- a/apps/studio/tests/components/CopyButton.test.tsx+++ b/apps/studio/tests/components/CopyButton.test.tsx@@ -12,3 +12,14 @@ test('shows copied text', async () => {await screen.findByText('Copied')expect(callback).toBeCalled()})++test('does not show a green copied icon for primary buttons', async () => {+ const { container } = render(<CopyButton text="some text" type="primary" />)++ await userEvent.click(await screen.findByText('Copy'))+ await screen.findByText('Copied')++ const icon = container.querySelector('svg')+ expect(icon).toHaveClass('text-inherit')+ expect(icon).not.toHaveClass('text-brand')+})diff --git a/apps/studio/tests/pages/cli-login.test.tsx b/apps/studio/tests/pages/cli-login.test.tsxnew file mode 100644index 00000000000..afecbf3c642--- /dev/null+++ b/apps/studio/tests/pages/cli-login.test.tsx@@ -0,0 +1,122 @@+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, test, vi } from 'vitest'++import type { ProfileContextType } from '@/lib/profile'+import { CliLoginScreen } from '@/pages/cli/login'+import { customRender } from '@/tests/lib/custom-render'++const { createCliLoginSessionMock } = vi.hoisted(() => ({+ createCliLoginSessionMock: vi.fn(),+}))++vi.mock('@/data/cli/login', () => ({+ createCliLoginSession: createCliLoginSessionMock,+}))++const DEFAULT_PROFILE_CONTEXT: ProfileContextType = {+ profile: {+ id: 1,+ auth0_id: 'auth0|test',+ gotrue_id: 'gotrue-test',+ username: 'testuser',+ primary_email: '[email protected]',+ first_name: null,+ last_name: null,+ mobile: null,+ is_alpha_user: false,+ is_sso_user: false,+ disabled_features: [],+ free_project_limit: null,+ },+ error: null,+ isLoading: false,+ isError: false,+ isSuccess: true,+}++function renderScreen(props: Partial<Parameters<typeof CliLoginScreen>[0]> = {}) {+ const navigate = vi.fn()+ const result = customRender(+ <CliLoginScreen+ isLoggedIn+ routerReady+ sessionId="session-test"+ publicKey="public-key-test"+ tokenName="local-dev"+ navigate={navigate}+ {...props}+ />,+ { profileContext: DEFAULT_PROFILE_CONTEXT }+ )+ return { ...result, navigate }+}++describe('CliLoginScreen', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ test('creates a session and routes to the device code', async () => {+ createCliLoginSessionMock.mockResolvedValue({ nonce: 'ABCDEFGH12345678' })+ const { navigate } = renderScreen()++ await waitFor(() => {+ expect(createCliLoginSessionMock).toHaveBeenCalledWith(+ 'session-test',+ 'public-key-test',+ 'local-dev'+ )+ })+ await waitFor(() => {+ expect(navigate).toHaveBeenCalledWith('/cli/login?device_code=ABCDEFGH')+ })+ })++ test('renders ready state with verification code and copy control', async () => {+ const user = userEvent.setup()+ const writeText = vi.fn()+ vi.spyOn(window.document, 'hasFocus').mockReturnValue(true)+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: { writeText },+ })++ const { container } = renderScreen({ deviceCode: 'ZXCV9876' })++ expect(container).toHaveTextContent('ZXCV9876')+ await user.click(screen.getByRole('button', { name: 'Copy code' }))+ expect(await screen.findByRole('button', { name: 'Copied' })).toBeInTheDocument()+ expect(writeText).toHaveBeenCalledWith('ZXCV9876')+ })++ test('copies selected verification code as a single string', () => {+ renderScreen({ deviceCode: 'ZXCV9876' })++ const clipboardData = { setData: vi.fn() }+ const code = screen.getByLabelText('Verification code ZXCV9876')+ const copyEvent = new Event('copy', { bubbles: true })++ Object.defineProperty(copyEvent, 'clipboardData', {+ value: clipboardData,+ })+ code.dispatchEvent(copyEvent)++ expect(clipboardData.setData).toHaveBeenCalledWith('text/plain', 'ZXCV9876')+ })++ test('renders missing-params state without redirecting away', () => {+ renderScreen({ sessionId: undefined })++ expect(screen.getByText('Missing sign-in parameters')).toBeInTheDocument()+ expect(screen.getByText(/session_id/)).toBeInTheDocument()+ })++ test('renders creation error state in the card', async () => {+ createCliLoginSessionMock.mockRejectedValue(new Error('Session expired'))+ renderScreen()++ expect(await screen.findByText('Unable to create CLI sign-in')).toBeInTheDocument()+ expect(screen.getByText(/Session expired/)).toBeInTheDocument()+ })+})