Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(studio): scoped oauth interstitial ui (#50090)

kemal.earth454a23294741
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/AuthorizeSuccessScreen.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/AuthorizeSuccessScreen.tsx
new file mode 100644
index 00000000000..89014bbf564
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/AuthorizeSuccessScreen.tsx
@@ -0,0 +1,66 @@
+import type { ReactNode } from 'react'
+import { Button } from 'ui'
+
+import { ScopeGroupCard } from './ScopeGroupCard'
+import type { OAuthAppsAuthorizeOrganizationProject, OAuthScope } from '@/data/oauth-apps/types'
+
+export type AuthorizeSuccessGrant = {
+ email: string
+ organization_slug: string
+ project_refs: string[] | null
+ projects: OAuthAppsAuthorizeOrganizationProject[]
+ scopes: OAuthScope[]
+}
+
+export interface AuthorizeSuccessScreenProps {
+ appName: string
+ grant: AuthorizeSuccessGrant
+ onReturn: () => void
+}
+
+const DetailRow = ({ label, children }: { label: string; children: ReactNode }) => (
+ <div className="flex items-start justify-between gap-4 py-2.5 text-xs">
+ <span className="shrink-0 text-foreground-light">{label}</span>
+ <span className="min-w-0 text-right text-foreground">{children}</span>
+ </div>
+)
+
+export const AuthorizeSuccessScreen = ({
+ appName,
+ grant,
+ onReturn,
+}: AuthorizeSuccessScreenProps) => {
+ const hasAllProjects = grant.project_refs === null
+
+ return (
+ <div className="flex flex-col gap-6 px-6 pb-6">
+ <div className="divide-y rounded-md border bg-surface-75 px-4">
+ <DetailRow label="Authorized by">{grant.email}</DetailRow>
+ <DetailRow label="Organization">{grant.organization_slug}</DetailRow>
+ <DetailRow label="Projects">
+ {hasAllProjects ? (
+ 'All projects, including ones created later'
+ ) : (
+ <span className="flex flex-wrap justify-end gap-x-1">
+ {grant.projects.map((project, index) => (
+ <span key={project.ref}>
+ {project.name}
+ {index < grant.projects.length - 1 ? ',' : ''}
+ </span>
+ ))}
+ </span>
+ )}
+ </DetailRow>
+ </div>
+
+ <section className="flex flex-col gap-3">
+ <p className="text-xs text-foreground">Permissions granted</p>
+ <ScopeGroupCard scopes={grant.scopes} />
+ </section>
+
+ <Button variant="text" block onClick={onReturn}>
+ Return to {appName}
+ </Button>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/AuthorizingAsCard.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/AuthorizingAsCard.tsx
new file mode 100644
index 00000000000..7f8886d8b07
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/AuthorizingAsCard.tsx
@@ -0,0 +1,63 @@
+import { LogOut } from 'lucide-react'
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+
+import { OAuthAppsAuthorizeRequest } from '@/data/oauth-apps/types'
+
+export interface AuthorizingAsCardProps {
+ email: string
+ request: OAuthAppsAuthorizeRequest
+ organizationSlug: string
+ onSignOut: () => void
+}
+
+export const AuthorizingAsCard = ({
+ email,
+ request,
+ organizationSlug,
+ onSignOut,
+}: AuthorizingAsCardProps) => {
+ return (
+ <section className="flex flex-col gap-2">
+ <div className="divide-y rounded-md border bg-surface-75 px-4">
+ <div className="flex items-center justify-between gap-4 py-1.5 text-xs">
+ <span className="shrink-0 text-foreground-light">Authorizing as</span>
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="min-w-0 truncate text-right text-foreground">{email}</span>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="text"
+ size="tiny"
+ icon={<LogOut size={14} />}
+ className="shrink-0 size-6 px-0 text-foreground-light hover:text-foreground"
+ aria-label="Sign out"
+ aria-describedby={undefined}
+ // Tooltip repeats the label; screen readers would read it twice
+ onClick={onSignOut}
+ />
+ </TooltipTrigger>
+ <TooltipContent side="top">Sign out</TooltipContent>
+ </Tooltip>
+ </span>
+ </div>
+ <div className="flex items-center justify-between gap-4 py-2.5 text-xs">
+ <span className="shrink-0 text-foreground-light">Organization</span>
+ <span className="min-w-0 truncate text-right text-foreground">{organizationSlug}</span>
+ </div>
+ {!request.project_scoping_mode && (
+ <div className="flex items-center justify-between gap-4 py-2.5 text-xs">
+ <span className="shrink-0 text-foreground-light">Projects</span>
+ <span className="min-w-0 truncate text-right text-foreground">
+ All projects, including future ones
+ </span>
+ </div>
+ )}
+ </div>
+ {request.grant_kind === 'member_bound' && (
+ <p className="text-xs text-foreground-lighter">
+ This grant acts as you, it can never do more than your role in this organization allows.
+ </p>
+ )}
+ </section>
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/NoProjectsNotice.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/NoProjectsNotice.test.tsx
new file mode 100644
index 00000000000..63314d20b90
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/NoProjectsNotice.test.tsx
@@ -0,0 +1,67 @@
+import { fireEvent, screen } from '@testing-library/react'
+import { describe, expect, test, vi } from 'vitest'
+
+import { NoProjectsNotice } from './NoProjectsNotice'
+import { customRender } from '@/tests/lib/custom-render'
+
+describe('NoProjectsNotice', () => {
+ test('interpolates the organization into the title', () => {
+ customRender(
+ <NoProjectsNotice appName="Vercel" organizationSlug="contoso-labs" onSwitchOrg={vi.fn()} />
+ )
+
+ expect(screen.getByText('No projects in contoso-labs')).toBeInTheDocument()
+ })
+
+ test('interpolates the app name into the body', () => {
+ customRender(
+ <NoProjectsNotice appName="Vercel" organizationSlug="contoso-labs" onSwitchOrg={vi.fn()} />
+ )
+
+ expect(
+ screen.getByText(
+ "Vercel needs access to at least one project, and this organization doesn't have any yet."
+ )
+ ).toBeInTheDocument()
+ })
+
+ test('fires onSwitchOrg when the inline link is clicked', () => {
+ const onSwitchOrg = vi.fn()
+ customRender(
+ <NoProjectsNotice
+ appName="Vercel"
+ organizationSlug="contoso-labs"
+ onSwitchOrg={onSwitchOrg}
+ />
+ )
+
+ fireEvent.click(screen.getByText('Switch organization'))
+
+ expect(onSwitchOrg).toHaveBeenCalledTimes(1)
+ })
+
+ test('interpolates a different app name, so the copy is not hardcoded', () => {
+ customRender(
+ <NoProjectsNotice appName="Fabrikam" organizationSlug="contoso-labs" onSwitchOrg={vi.fn()} />
+ )
+
+ expect(
+ screen.getByText(
+ "Fabrikam needs access to at least one project, and this organization doesn't have any yet."
+ )
+ ).toBeInTheDocument()
+ })
+
+ test('shows the same organization slug it was given', () => {
+ customRender(
+ <NoProjectsNotice
+ appName="Vercel"
+ organizationSlug="northwind-traders"
+ onSwitchOrg={vi.fn()}
+ />
+ )
+
+ expect(screen.getByText('No projects in northwind-traders')).toBeInTheDocument()
+ expect(screen.queryByText('No projects in contoso-labs')).not.toBeInTheDocument()
+ })
+})
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/NoProjectsNotice.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/NoProjectsNotice.tsx
new file mode 100644
index 00000000000..d02f25def30
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/NoProjectsNotice.tsx
@@ -0,0 +1,39 @@
+import { Admonition } from 'ui-patterns/Admonition'
+
+import { CONSENT_COPY } from './OAuthAppsAuthorizeScreen.utils'
+import { InlineLinkClassName } from '@/components/ui/InlineLink'
+
+export interface NoProjectsNoticeProps {
+ appName: string
+ organizationSlug: string
+ onSwitchOrg: () => void
+}
+
+export const NoProjectsNotice = ({
+ appName,
+ organizationSlug,
+ onSwitchOrg,
+}: NoProjectsNoticeProps) => {
+ return (
+ <Admonition
+ type="default"
+ title={CONSENT_COPY.noProjects.title(organizationSlug)}
+ description={
+ <>
+ <p>{CONSENT_COPY.noProjects.body(appName)}</p>
+ <p>
+ {CONSENT_COPY.noProjects.prompt}{' '}
+ <button
+ type="button"
+ tabIndex={0}
+ className={InlineLinkClassName}
+ onClick={onSwitchOrg}
+ >
+ Switch organization
+ </button>
+ </p>
+ </>
+ }
+ />
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.roleValidation.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.roleValidation.test.tsx
new file mode 100644
index 00000000000..06a36328029
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.roleValidation.test.tsx
@@ -0,0 +1,142 @@
+import { fireEvent, screen } from '@testing-library/react'
+import { describe, expect, test, vi } from 'vitest'
+
+import { OAuthAppsAuthorizeScreen } from './OAuthAppsAuthorizeScreen'
+import {
+ getMockOAuthAppsAuthorizeRequest,
+ OAUTH_APPS_MOCK_SCENARIOS,
+} from '@/data/oauth-apps/mocks'
+import { customRender } from '@/tests/lib/custom-render'
+
+function renderScreen(authId: string) {
+ return customRender(
+ <OAuthAppsAuthorizeScreen
+ authId={authId}
+ request={getMockOAuthAppsAuthorizeRequest(authId)}
+ navigate={vi.fn()}
+ />
+ )
+}
+
+const READ_ONLY_PROJECTS = ['fabrikam-api', 'fabrikam-jobs']
+const WRITABLE_PROJECT = 'northwind-cms'
+
+async function selectProjects(names: string[]) {
+ fireEvent.click(await screen.findByRole('combobox'))
+ names.forEach((name) => fireEvent.click(screen.getByText(name)))
+}
+
+function authorize() {
+ fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))
+}
+
+function deselectFlagged() {
+ fireEvent.click(screen.getByRole('button', { name: 'Deselect 2 projects' }))
+}
+
+async function submitTwoBlockedAndOneAllowed() {
+ renderScreen(OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation)
+
+ await selectProjects([...READ_ONLY_PROJECTS, WRITABLE_PROJECT])
+ authorize()
+
+ return screen.findByText("Couldn't authorize 2 projects")
+}
+
+describe('OAuthAppsAuthorizeScreen post-submit role validation', () => {
+ test('surfaces the failure banner naming the blocked project count', async () => {
+ expect(await submitTwoBlockedAndOneAllowed()).toBeInTheDocument()
+ expect(
+ screen.getByText(
+ 'Vercel needs write access but your role is read-only on the projects highlighted. Deselect them to continue.'
+ )
+ ).toBeInTheDocument()
+ })
+
+ test('counts the blocked projects against the submitted selection', async () => {
+ await submitTwoBlockedAndOneAllowed()
+
+ expect(screen.getByText(/2 of 3\s+projects unavailable/)).toBeInTheDocument()
+ })
+
+ test('turns the primary action into the deselect shortcut', async () => {
+ await submitTwoBlockedAndOneAllowed()
+
+ expect(screen.getByRole('button', { name: 'Deselect 2 projects' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /Authorize Vercel/ })).not.toBeInTheDocument()
+ })
+
+ test('marks the rejected projects in the dropdown', async () => {
+ await submitTwoBlockedAndOneAllowed()
+
+ const marks = screen.getAllByText('- Unavailable')
+ expect(marks).toHaveLength(READ_ONLY_PROJECTS.length)
+ })
+
+ test('keeps the dropdown marks after the projects are deselected', async () => {
+ await submitTwoBlockedAndOneAllowed()
+
+ deselectFlagged()
+
+ expect(screen.getAllByText('- Unavailable')).toHaveLength(READ_ONLY_PROJECTS.length)
+ })
+
+ test('drops the inline deselect link beneath the picker', async () => {
+ await submitTwoBlockedAndOneAllowed()
+
+ expect(screen.queryByText('Deselect projects')).not.toBeInTheDocument()
+ })
+
+ test('deselecting the blocked projects clears the whole failure treatment', async () => {
+ await submitTwoBlockedAndOneAllowed()
+
+ deselectFlagged()
+
+ expect(screen.queryByText("Couldn't authorize 2 projects")).not.toBeInTheDocument()
+ expect(screen.queryByText(/projects unavailable/)).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeInTheDocument()
+ })
+
+ test('retrying with only writable projects reaches the success screen', async () => {
+ await submitTwoBlockedAndOneAllowed()
+
+ deselectFlagged()
+ authorize()
+
+ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()
+ })
+
+ test('a selection of only writable projects never triggers validation', async () => {
+ renderScreen(OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation)
+
+ await selectProjects([WRITABLE_PROJECT])
+ authorize()
+
+ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()
+ })
+
+ test('a preselected read-only project still produces the post-submit banner', async () => {
+ customRender(
+ <OAuthAppsAuthorizeScreen
+ authId={OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation}
+ request={getMockOAuthAppsAuthorizeRequest(OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation)}
+ projectRef="fabrikamapi1"
+ navigate={vi.fn()}
+ />
+ )
+
+ await screen.findByText('fabrikam-api')
+ authorize()
+
+ expect(await screen.findByText("Couldn't authorize 1 project")).toBeInTheDocument()
+ })
+
+ test('a request outside the role-validated set approves read-only projects', async () => {
+ renderScreen(OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper)
+
+ await selectProjects([READ_ONLY_PROJECTS[0]])
+ authorize()
+
+ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()
+ })
+})
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.submitting.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.submitting.test.tsx
new file mode 100644
index 00000000000..118a2323622
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.submitting.test.tsx
@@ -0,0 +1,35 @@
+import { screen } from '@testing-library/react'
+import { describe, expect, test, vi } from 'vitest'
+
+import { OAuthAppsAuthorizeScreen } from './OAuthAppsAuthorizeScreen'
+import {
+ getMockOAuthAppsAuthorizeRequest,
+ OAUTH_APPS_MOCK_SCENARIOS,
+} from '@/data/oauth-apps/mocks'
+import { customRender } from '@/tests/lib/custom-render'
+
+vi.mock('@/data/oauth-apps/oauth-apps-authorize-approve-mutation', async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import('@/data/oauth-apps/oauth-apps-authorize-approve-mutation')>()
+
+ return {
+ ...actual,
+ useOAuthAppsAuthorizeApproveMutation: () => ({ mutate: vi.fn(), isPending: true }),
+ }
+})
+
+describe('OAuthAppsAuthorizeScreen while the approve mutation is in flight', () => {
+ test('shows the do-not-close message and hides the cancel action', async () => {
+ customRender(
+ <OAuthAppsAuthorizeScreen
+ authId={OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper}
+ request={getMockOAuthAppsAuthorizeRequest(OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper)}
+ navigate={vi.fn()}
+ />
+ )
+
+ expect(await screen.findByText("Don't close this window.")).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Cancel' })).not.toBeInTheDocument()
+ expect(screen.getByText('Authorizing...')).toBeInTheDocument()
+ })
+})
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.test.tsx
new file mode 100644
index 00000000000..21c0d487837
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.test.tsx
@@ -0,0 +1,361 @@
+import { fireEvent, screen } from '@testing-library/react'
+import { describe, expect, test, vi } from 'vitest'
+
+import { OAuthAppsAuthorizeScreen } from './OAuthAppsAuthorizeScreen'
+import { MAX_SELECTED_PROJECTS } from './ProjectMultiSelect'
+import {
+ getMockOAuthAppsAuthorizeRequest,
+ OAUTH_APPS_MOCK_SCENARIOS,
+} from '@/data/oauth-apps/mocks'
+import type { OAuthAppsAuthorizeRequest } from '@/data/oauth-apps/types'
+import { customRender } from '@/tests/lib/custom-render'
+
+type RenderScreenOptions = {
+ authId?: string
+ request?: OAuthAppsAuthorizeRequest
+ organizationSlug?: string
+ projectRef?: string
+}
+
+function renderScreen({
+ authId = OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper,
+ request,
+ organizationSlug,
+ projectRef,
+}: RenderScreenOptions = {}) {
+ return customRender(
+ <OAuthAppsAuthorizeScreen
+ authId={authId}
+ request={request ?? getMockOAuthAppsAuthorizeRequest(authId)}
+ organizationSlug={organizationSlug}
+ projectRef={projectRef}
+ navigate={vi.fn()}
+ />
+ )
+}
+
+function selectProject(projectName: string) {
+ fireEvent.click(screen.getByRole('combobox'))
+ fireEvent.click(screen.getByText(projectName))
+}
+
+function toggleProjectOption(projectName: string) {
+ const option = screen
+ .getAllByText(projectName)
+ .map((element) => element.closest('[role="option"]'))
+ .find((element): element is HTMLElement => element instanceof HTMLElement)
+
+ if (!option) throw new Error(`No option row found for "${projectName}"`)
+ fireEvent.click(option)
+}
+
+describe('OAuthAppsAuthorizeScreen', () => {
+ test('disables authorize and states the constraint while nothing is selected', async () => {
+ renderScreen()
+
+ expect(await screen.findByRole('button', { name: /Authorize Vercel/ })).toBeDisabled()
+ expect(screen.getByText('Must select at least one project to authorize.')).toBeInTheDocument()
+ })
+
+ test('enables authorize and drops the constraint once a project is selected', async () => {
+ renderScreen()
+
+ await screen.findByRole('combobox')
+ selectProject('northwind-storefront')
+
+ expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()
+ expect(
+ screen.queryByText('Must select at least one project to authorize.')
+ ).not.toBeInTheDocument()
+ })
+
+ test('re-disables authorize when the last project is deselected', async () => {
+ renderScreen()
+
+ fireEvent.click(await screen.findByRole('combobox'))
+ toggleProjectOption('northwind-storefront')
+ toggleProjectOption('northwind-storefront')
+
+ expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeDisabled()
+ expect(screen.getByText('Must select at least one project to authorize.')).toBeInTheDocument()
+ })
+
+ test('shows no upfront over-role warning, even for the read-only fixture', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReadOnly })
+
+ await screen.findByText('Permissions requested')
+ expect(
+ screen.queryByText('Some requested permissions exceed your role')
+ ).not.toBeInTheDocument()
+ expect(screen.queryByText('Read-only for your role')).not.toBeInTheDocument()
+ })
+
+ test('renders the empty-org notice, hides permissions, and shows the cancel footer', async () => {
+ renderScreen({ organizationSlug: 'contoso-labs' })
+
+ expect(await screen.findByText('No projects in contoso-labs')).toBeInTheDocument()
+ expect(screen.queryByText('Permissions requested')).not.toBeInTheDocument()
+ expect(
+ screen.getByText(
+ 'Cancelling will redirect you to https://vercel.com/api/integrations/supabase/callback with access denied.'
+ )
+ ).toBeInTheDocument()
+ })
+
+ test('renders the success screen after the approve mutation resolves', async () => {
+ renderScreen()
+
+ await screen.findByRole('combobox')
+ selectProject('northwind-storefront')
+ fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))
+
+ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()
+ expect(screen.getByText('You can return to Vercel to continue')).toBeInTheDocument()
+ })
+
+ test('success screen shows exactly the submitted projects and scopes', async () => {
+ renderScreen()
+
+ await screen.findByRole('combobox')
+ selectProject('northwind-cms')
+ fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))
+
+ await screen.findByText('Vercel is connected')
+
+ expect(screen.getByText('northwind-cms')).toBeInTheDocument()
+ expect(screen.queryByText('northwind-storefront, northwind-cms')).not.toBeInTheDocument()
+ expect(screen.queryByText('northwind-storefront')).not.toBeInTheDocument()
+
+ expect(screen.getByText('Permissions granted')).toBeInTheDocument()
+ expect(screen.queryByText('Permissions requested')).not.toBeInTheDocument()
+ expect(screen.getByText('Database, Environment, Secrets')).toBeInTheDocument()
+ expect(screen.getByText('Projects, Edge Functions, Storage')).toBeInTheDocument()
+ })
+
+ test('an organization-bound app reaches the success screen with the authorizing identity', async () => {
+ renderScreen({
+ authId: OAUTH_APPS_MOCK_SCENARIOS.kemalBot,
+ organizationSlug: 'fabrikam-industries',
+ })
+
+ await screen.findByRole('combobox')
+ selectProject('fabrikam-ledger')
+ fireEvent.click(screen.getByRole('button', { name: /Authorize kemal-bot/ }))
+
+ expect(await screen.findByText('kemal-bot is connected')).toBeInTheDocument()
+ expect(screen.getByText('Authorized by')).toBeInTheDocument()
+ expect(screen.getByText(/admin@example\.com/)).toBeInTheDocument()
+ })
+
+ test('tells the member an organization-bound grant is shared, exactly once', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.kemalBot })
+
+ expect(await screen.findAllByText('Want this scoped to one member?')).toHaveLength(1)
+ expect(
+ screen.getAllByText(
+ 'Have them authorize kemal-bot from their own account. Authorizing here gives it your Administrator access on every project, including ones created later.'
+ )
+ ).toHaveLength(1)
+ expect(screen.queryByText(/This grant acts as you/)).not.toBeInTheDocument()
+ })
+
+ test('keeps the no-admin-approval footer line for a member-bound grant', async () => {
+ renderScreen()
+
+ expect(
+ await screen.findByText(/No admin approval is needed if your role permits this access/)
+ ).toBeInTheDocument()
+ })
+
+ test('drops the no-admin-approval footer line for an organization-bound grant', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.kemalBot })
+
+ await screen.findByText('Permissions requested')
+ expect(screen.queryByText(/No admin approval is needed/)).not.toBeInTheDocument()
+ expect(
+ screen.getByText(/This authorization will appear in Authorized apps/)
+ ).toBeInTheDocument()
+ })
+
+ test('shows no shared-grant messaging for a member-bound grant', async () => {
+ renderScreen()
+
+ await screen.findByText('Permissions requested')
+ expect(
+ screen.queryByText('This grant is shared with the whole organization')
+ ).not.toBeInTheDocument()
+ expect(screen.queryByText(/This grant acts as you/)).toBeInTheDocument()
+ })
+
+ test('says the grant covers future projects when there is no picker', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects })
+
+ expect(await screen.findByText('All projects, including future ones')).toBeInTheDocument()
+ })
+
+ test('does not claim future projects when the member picks them', async () => {
+ renderScreen()
+
+ await screen.findByText('Permissions requested')
+ expect(screen.queryByText('This grant covers every project')).not.toBeInTheDocument()
+ })
+
+ test('authorizes an app that hides the picker, with nothing selected', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects })
+
+ expect(await screen.findByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()
+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
+ expect(
+ screen.queryByText('Must select at least one project to authorize.')
+ ).not.toBeInTheDocument()
+ })
+
+ test('does not demand projects from an empty org when the app is org-wide', async () => {
+ renderScreen({
+ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects,
+ organizationSlug: 'contoso-labs',
+ })
+
+ expect(await screen.findByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()
+ expect(screen.queryByText(/No projects in/)).not.toBeInTheDocument()
+ })
+
+ test('reports an all-projects grant as such rather than listing projects', async () => {
+ renderScreen({
+ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects,
+ organizationSlug: 'contoso-labs',
+ })
+
+ fireEvent.click(await screen.findByRole('button', { name: /Authorize Vercel/ }))
+
+ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()
+ expect(screen.getByText('All projects, including ones created later')).toBeInTheDocument()
+ })
+
+ test('the many-projects fixture offers enough projects to reach the selection cap', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelManyProjects })
+
+ fireEvent.click(await screen.findByRole('combobox'))
+
+ expect(screen.getAllByRole('option').length).toBeGreaterThan(MAX_SELECTED_PROJECTS)
+ })
+
+ test('re-consent preselects the still-live projects from the existing grant', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent })
+
+ expect(await screen.findByText('tailspin-shop')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()
+ expect(
+ screen.queryByText('Must select at least one project to authorize.')
+ ).not.toBeInTheDocument()
+ })
+
+ test('re-consent submits only the still-live preselected projects', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent })
+
+ await screen.findByText('tailspin-shop')
+ fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))
+
+ await screen.findByText('Vercel is connected')
+
+ expect(screen.getByText(/tailspin-shop/)).toBeInTheDocument()
+ expect(screen.queryByText(/tailspin-warehouse/)).not.toBeInTheDocument()
+ expect(screen.queryByText(/tailspin-deleted/)).not.toBeInTheDocument()
+ })
+
+ test('the existing grant does not leak into an organization it was not granted for', async () => {
+ renderScreen({
+ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent,
+ organizationSlug: 'northwind-traders',
+ })
+
+ expect(await screen.findByRole('button', { name: /Authorize Vercel/ })).toBeDisabled()
+ expect(screen.getByText('Must select at least one project to authorize.')).toBeInTheDocument()
+ })
+
+ test('offers the all-projects choice only when project scoping is optional', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelOptionalProjects })
+
+ expect(await screen.findByText('All current and future projects')).toBeInTheDocument()
+ })
+
+ test('choosing all projects enables authorize without a selection', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelOptionalProjects })
+
+ expect(await screen.findByRole('button', { name: /Authorize Vercel/ })).toBeDisabled()
+
+ fireEvent.click(screen.getByRole('checkbox'))
+
+ expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()
+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
+ })
+
+ test('an all-projects approval reports the grant as all projects', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelOptionalProjects })
+
+ fireEvent.click(await screen.findByRole('checkbox'))
+ fireEvent.click(screen.getByRole('button', { name: /Authorize Vercel/ }))
+
+ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()
+ expect(screen.getByText('All projects, including ones created later')).toBeInTheDocument()
+ })
+
+ test('re-consent of an all-projects grant preselects the all-projects choice', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsentAllProjects })
+
+ expect(await screen.findByRole('checkbox')).toBeChecked()
+ expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()
+ })
+
+ test('a dynamic client renders the same required picker as an authored app', async () => {
+ renderScreen({ authId: OAUTH_APPS_MOCK_SCENARIOS.dynamicMcpClient })
+
+ expect(screen.queryByText('All current and future projects')).not.toBeInTheDocument()
+ expect(screen.queryByText(/registered automatically/)).not.toBeInTheDocument()
+ })
+
+ test('preselects the project named by the project_ref param', async () => {
+ renderScreen({ projectRef: 'northwindcms1' })
+
+ expect(await screen.findByText('northwind-cms')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()
+ expect(
+ screen.queryByText('Must select at least one project to authorize.')
+ ).not.toBeInTheDocument()
+ })
+
+ test('a project_scoping_mode off app ignores the project_ref param', async () => {
+ renderScreen({
+ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects,
+ organizationSlug: 'contoso-labs',
+ projectRef: 'northwindstorefront1',
+ })
+
+ fireEvent.click(await screen.findByRole('button', { name: /Authorize Vercel/ }))
+
+ expect(await screen.findByText('Vercel is connected')).toBeInTheDocument()
+ expect(screen.getByText('All projects, including ones created later')).toBeInTheDocument()
+ expect(screen.queryByText(/northwind-storefront/)).not.toBeInTheDocument()
+ })
+
+ test('resolves the organization that owns the project_ref when none is given', async () => {
+ renderScreen({
+ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelManyProjects,
+ projectRef: 'northwindcms1',
+ })
+
+ expect(await screen.findByText('northwind-cms')).toBeInTheDocument()
+ expect(screen.getByText('northwind-traders')).toBeInTheDocument()
+ })
+
+ test('the existing grant wins over the project_ref param', async () => {
+ renderScreen({
+ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent,
+ organizationSlug: 'tailspin-toys',
+ projectRef: 'tailspinwarehouse1',
+ })
+
+ expect(await screen.findByText('tailspin-shop')).toBeInTheDocument()
+ expect(screen.getByRole('combobox')).not.toHaveTextContent('tailspin-warehouse')
+ })
+})
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.tsx
new file mode 100644
index 00000000000..cfa9a3be963
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.tsx
@@ -0,0 +1,384 @@
+import { useEffect, useRef, useState } from 'react'
+import { Button } from 'ui'
+import { Admonition } from 'ui-patterns/Admonition'
+
+import { AuthorizeSuccessScreen } from './AuthorizeSuccessScreen'
+import { AuthorizingAsCard } from './AuthorizingAsCard'
+import { NoProjectsNotice } from './NoProjectsNotice'
+import { CONSENT_COPY } from './OAuthAppsAuthorizeScreen.utils'
+import { MAX_SELECTED_PROJECTS, ProjectMultiSelect } from './ProjectMultiSelect'
+import { ScopeGroupCard } from './ScopeGroupCard'
+import { useMemberOrganization } from './useMemberOrganization'
+import {
+ DestinationLogo,
+ InterstitialLayout,
+ LogoPair,
+ SupabaseLogo,
+} from '@/components/layouts/InterstitialLayout'
+import { AlertError } from '@/components/ui/AlertError'
+import { useOAuthAppsAuthorizeApproveMutation } from '@/data/oauth-apps/oauth-apps-authorize-approve-mutation'
+import { useOAuthAppsAuthorizeDenyMutation } from '@/data/oauth-apps/oauth-apps-authorize-deny-mutation'
+import { useOAuthAppsAuthorizeOrganizationProjectsQuery } from '@/data/oauth-apps/oauth-apps-authorize-organization-projects-query'
+import { useOAuthAppsAuthorizeOrganizationsQuery } from '@/data/oauth-apps/oauth-apps-authorize-organizations-query'
+import { useOAuthOrgAppDetailsQuery } from '@/data/oauth-apps/oauth-apps-org-app-details-query'
+import { useOAuthAppsPreflightValidationQuery } from '@/data/oauth-apps/oauth-apps-preflight-validation-query'
+import type {
+ OAuthAppsAuthorizeRedirect,
+ OAuthAppsAuthorizeRequest,
+ OAuthAppsAuthorizeRoleValidationFailure,
+ OAuthAuthorizeApproveRequest,
+} from '@/data/oauth-apps/types'
+import {
+ getFailedProjects,
+ getPreselectedProjectRefs,
+ isRoleValidationFailure,
+} from '@/data/oauth-apps/types'
+import { useSignOut } from '@/lib/auth'
+
+export interface OAuthAppsAuthorizeScreenProps {
+ authId: string
+ request: OAuthAppsAuthorizeRequest
+ organizationSlug?: string
+ projectRef?: string | null
+ navigate: (destination: string) => void
+}
+
+export const OAuthAppsAuthorizeScreen = ({
+ authId,
+ request,
+ organizationSlug,
+ projectRef = null,
+ navigate,
+}: OAuthAppsAuthorizeScreenProps) => {
+ const grantKind = request.grant_kind
+ const isProjectScopingModeEnabled = request.project_scoping_mode
+
+ const [selectedProjectRefs, setSelectedProjectRefs] = useState<string[]>([])
+ const [allProjectsSelected, setAllProjectsSelected] = useState(false)
+ const [approveRedirect, setApproveRedirect] = useState<OAuthAppsAuthorizeRedirect | null>(null)
+ const [roleFailure, setRoleFailure] = useState<OAuthAppsAuthorizeRoleValidationFailure | null>(
+ null
+ )
+
+ const identityQuery = useOAuthAppsAuthorizeOrganizationsQuery({ id: authId })
+ const memberOrgQuery = useMemberOrganization({
+ authId,
+ organizationSlug,
+ projectRef,
+ request,
+ })
+
+ const projectsQuery = useOAuthAppsAuthorizeOrganizationProjectsQuery(
+ {
+ id: authId,
+ slug: memberOrgQuery.data || '',
+ },
+ {
+ enabled: !memberOrgQuery.isPending && !!memberOrgQuery.data,
+ }
+ )
+ const appDetailsQuery = useOAuthOrgAppDetailsQuery(
+ {
+ slug: memberOrgQuery.data || '',
+ appId: request.app_id,
+ },
+ {
+ enabled: !memberOrgQuery.isPending && !!memberOrgQuery.data,
+ }
+ )
+
+ const seeded = useRef(false)
+ useEffect(() => {
+ if (seeded.current || !projectsQuery.data || !appDetailsQuery.data || !memberOrgQuery.data)
+ return
+ seeded.current = true
+ if (!isProjectScopingModeEnabled) return
+
+ const grant = appDetailsQuery.data.existing_grant
+ const hasAllProjectsGrant = grant !== null && grant.project_refs.length === 0
+ if (hasAllProjectsGrant && isProjectScopingModeEnabled) {
+ setAllProjectsSelected(true)
+ return
+ }
+
+ const refs = getPreselectedProjectRefs({
+ existingGrant: grant,
+ projectRef,
+ liveProjects: projectsQuery.data,
+ })
+ if (refs.length > 0) setSelectedProjectRefs(refs.slice(0, MAX_SELECTED_PROJECTS))
+ }, [
+ appDetailsQuery.data,
+ projectsQuery.data,
+ memberOrgQuery.data,
+ isProjectScopingModeEnabled,
+ projectRef,
+ ])
+
+ const signOut = useSignOut()
+
+ const preflightQuery = useOAuthAppsPreflightValidationQuery(
+ {
+ appId: request.app_id,
+ slug: memberOrgQuery.data!,
+ },
+ {
+ enabled: !memberOrgQuery.isPending && !!memberOrgQuery.data,
+ }
+ )
+
+ const approveMutation = useOAuthAppsAuthorizeApproveMutation({
+ onSuccess: (data) => {
+ if (isRoleValidationFailure(data)) {
+ setRoleFailure(data)
+ return
+ }
+ setRoleFailure(null)
+ setApproveRedirect(data)
+ },
+ })
+ const denyMutation = useOAuthAppsAuthorizeDenyMutation({
+ onSuccess: (data) => {
+ window.location.href = data.url
+ },
+ })
+
+ const isSubmitting = approveMutation.isPending
+ const hasProjects = (projectsQuery.data?.length ?? 0) > 0
+
+ const isBlockedOnProjects = isProjectScopingModeEnabled && !hasProjects
+ const canProceed = !isBlockedOnProjects
+
+ const grantedProjects = (projectsQuery.data ?? []).filter((project) =>
+ selectedProjectRefs.includes(project.ref)
+ )
+
+ const flaggedRefs = getFailedProjects(roleFailure)
+ .map((project) => project.ref)
+ .filter((ref) => selectedProjectRefs.includes(ref))
+ const hasRoleFailure = flaggedRefs.length > 0
+ const primaryActionLabel = hasRoleFailure
+ ? `Deselect ${flaggedRefs.length} ${flaggedRefs.length === 1 ? 'project' : 'projects'}`
+ : `Authorize ${request.name}`
+ const primaryActionVariant = hasRoleFailure || isSubmitting ? 'default' : 'primary'
+
+ const usesSelectedProjects = isProjectScopingModeEnabled && !allProjectsSelected
+ const hasNoSelection = usesSelectedProjects && selectedProjectRefs.length === 0
+
+ if (identityQuery.isPending || memberOrgQuery.isPending) {
+ return null
+ }
+
+ if (identityQuery.isError) {
+ return (
+ <InterstitialLayout
+ logo={<DestinationLogo name={request.name} />}
+ title={`Authorize ${request.name}`}
+ description="This application wants to access your Supabase Account"
+ >
+ <div className="flex flex-col gap-6 px-6 pb-6">
+ <AlertError
+ subject="An error occurred while loading your data"
+ error={identityQuery.error}
+ />
+ </div>
+ </InterstitialLayout>
+ )
+ }
+
+ if (memberOrgQuery.isError) {
+ return (
+ <InterstitialLayout
+ logo={<DestinationLogo name={request.name} />}
+ title={`Authorize ${request.name}`}
+ description="This application wants to access your Supabase Account"
+ >
+ <div className="flex flex-col gap-6 px-6 pb-6">
+ <AlertError
+ subject="We couldn't find the organization for this application authorization"
+ error={memberOrgQuery.error}
+ />
+ </div>
+ </InterstitialLayout>
+ )
+ }
+
+ if (approveRedirect) {
+ return (
+ <InterstitialLayout
+ logo={<DestinationLogo name={request.name} />}
+ title={`${request.name} is connected`}
+ titleClassName="text-2xl"
+ description={`You can return to ${request.name} to continue`}
+ >
+ <AuthorizeSuccessScreen
+ appName={request.name}
+ grant={{
+ email: identityQuery.data.email,
+ organization_slug: memberOrgQuery.data,
+ project_refs: usesSelectedProjects ? selectedProjectRefs : null,
+ projects: grantedProjects,
+ scopes: request.scopes,
+ }}
+ onReturn={() => {
+ window.location.href = approveRedirect.url
+ }}
+ />
+ </InterstitialLayout>
+ )
+ }
+
+ const handleSignOut = async () => {
+ await signOut()
+ window.location.reload()
+ }
+
+ const handleSwitchOrg = () => navigate('/organizations')
+
+ const handleDeselectFlagged = () =>
+ setSelectedProjectRefs((refs) => refs.filter((ref) => !flaggedRefs.includes(ref)))
+
+ const handleApprove = () => {
+ if (hasNoSelection) return
+ const approveBody: OAuthAuthorizeApproveRequest = usesSelectedProjects
+ ? { project_refs: selectedProjectRefs }
+ : {}
+ approveMutation.mutate({ auth_id: authId, slug: memberOrgQuery.data, body: approveBody })
+ }
+
+ const handleDeny = () => {
+ denyMutation.mutate({ auth_id: authId, slug: memberOrgQuery.data })
+ }
+
+ const footerMessage = isSubmitting
+ ? "Don't close this window."
+ : canProceed
+ ? null
+ : `Cancelling will redirect you to ${request.redirect_uri} with access denied.`
+
+ const cannotApprove = preflightQuery.data?.status === 'error' || hasNoSelection
+
+ return (
+ <InterstitialLayout
+ logo={<LogoPair left={<DestinationLogo name={request.name} />} right={<SupabaseLogo />} />}
+ title={`Authorize ${request.name}`}
+ description="This application wants to access your Supabase Account"
+ >
+ <div className="flex flex-col gap-6 px-6 pb-6">
+ {preflightQuery.data?.status === 'error' && (
+ <Admonition
+ type="warning"
+ title={CONSENT_COPY.roleFailureAllProjects.title(request.name)}
+ description={CONSENT_COPY.roleFailureAllProjects.description(memberOrgQuery.data)}
+ />
+ )}
+ {hasRoleFailure && (
+ <Admonition
+ type="warning"
+ title={CONSENT_COPY.roleFailure.title(flaggedRefs.length)}
+ description={CONSENT_COPY.roleFailure.description(request.name)}
+ />
+ )}
+
+ <fieldset disabled={isSubmitting} className="contents">
+ <AuthorizingAsCard
+ email={identityQuery.data.email}
+ organizationSlug={memberOrgQuery.data}
+ onSignOut={handleSignOut}
+ request={request}
+ />
+
+ {isBlockedOnProjects && (
+ <NoProjectsNotice
+ appName={request.name}
+ organizationSlug={memberOrgQuery.data}
+ onSwitchOrg={handleSwitchOrg}
+ />
+ )}
+
+ {canProceed && isProjectScopingModeEnabled && (
+ <div className="flex flex-col gap-2">
+ <ProjectMultiSelect
+ projects={projectsQuery.data ?? []}
+ selectedRefs={selectedProjectRefs}
+ onChange={setSelectedProjectRefs}
+ maxSelected={MAX_SELECTED_PROJECTS}
+ error={hasNoSelection ? CONSENT_COPY.selectionRequired : undefined}
+ flaggedRefs={flaggedRefs}
+ unavailableRefs={getFailedProjects(roleFailure).map((project) => project.ref)}
+ allProjectsSelected={allProjectsSelected}
+ onAllProjectsChange={setAllProjectsSelected}
+ />
+ </div>
+ )}
+
+ {canProceed && (
+ <>
+ <section className="flex flex-col gap-3">
+ <p className="text-sm text-foreground">Permissions requested</p>
+ <ScopeGroupCard scopes={request.scopes} />
+ <p className="text-xs text-foreground-lighter">
+ Authorizing {request.name} grants it access to the permissions
+ {isProjectScopingModeEnabled && !allProjectsSelected
+ ? ' and selected projects '
+ : ' '}
+ above.
+ </p>
+ </section>
+
+ {grantKind === 'organization_bound' && (
+ <Admonition
+ type="default"
+ title={CONSENT_COPY.organizationBoundGrant.title}
+ description={CONSENT_COPY.organizationBoundGrant.description(request.name)}
+ />
+ )}
+ </>
+ )}
+ </fieldset>
+
+ <div className="flex flex-col gap-2">
+ {canProceed ? (
+ <Button
+ block
+ variant={primaryActionVariant}
+ loading={isSubmitting}
+ disabled={cannotApprove}
+ aria-label={primaryActionLabel}
+ onClick={hasRoleFailure ? handleDeselectFlagged : handleApprove}
+ >
+ {isSubmitting ? 'Authorizing...' : primaryActionLabel}
+ </Button>
+ ) : (
+ <Button block variant="primary" onClick={handleSwitchOrg}>
+ Switch organization
+ </Button>
+ )}
+ {!isSubmitting && (
+ <Button variant="text" block onClick={handleDeny}>
+ Cancel
+ </Button>
+ )}
+ </div>
+
+ <div className="flex flex-col gap-4 border-t pt-6 text-xs text-foreground-lighter">
+ {footerMessage ? (
+ <p>{footerMessage}</p>
+ ) : (
+ <>
+ <p>
+ {grantKind === 'member_bound' &&
+ 'No admin approval is needed if your role permits this access. '}
+ This authorization will appear in Authorized apps.
+ </p>
+ <p>
+ Authorizing will redirect you to{' '}
+ <span className="text-foreground">{request.redirect_uri}</span>
+ </p>
+ </>
+ )}
+ </div>
+ </div>
+ </InterstitialLayout>
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.utils.test.ts b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.utils.test.ts
new file mode 100644
index 00000000000..2877d64e512
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.utils.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, test } from 'vitest'
+
+import { formatPermissionName, groupScopesByLevel } from './OAuthAppsAuthorizeScreen.utils'
+
+describe('OAuthAppsAuthorizeScreen', () => {
+ describe('groupScopesByLevel', () => {
+ test('groups scopes by level', () => {
+ expect(
+ groupScopesByLevel([
+ 'projects:read',
+ 'organizations:read',
+ 'projects:write',
+ 'analytics_config:write',
+ ])
+ ).toEqual([
+ {
+ level: 'read-write',
+ permissions: ['projects'],
+ },
+ {
+ level: 'write',
+ permissions: ['analytics_config'],
+ },
+ {
+ level: 'read',
+ permissions: ['organizations'],
+ },
+ ])
+ })
+ test('excludes empty groups', () => {
+ expect(groupScopesByLevel(['projects:read', 'organizations:read', 'projects:write'])).toEqual(
+ [
+ {
+ level: 'read-write',
+ permissions: ['projects'],
+ },
+ // No write group
+ {
+ level: 'read',
+ permissions: ['organizations'],
+ },
+ ]
+ )
+ })
+ })
+ describe('formatPermissionName', () => {
+ test('formats single word permissions', () => {
+ expect(formatPermissionName('projects')).toEqual('Projects')
+ })
+ test('formats multiple words permissions', () => {
+ expect(formatPermissionName('project_settings')).toEqual('Project Settings')
+ })
+ })
+})
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.utils.ts b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.utils.ts
new file mode 100644
index 00000000000..7ecd511846c
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/OAuthAppsAuthorizeScreen.utils.ts
@@ -0,0 +1,100 @@
+import { capitalize } from 'lodash'
+
+import { OAuthScope } from '@/data/oauth-apps/types'
+
+export const CONSENT_COPY = {
+ allProjectsOption: 'All current and future projects',
+ selectionRequired: 'Must select at least one project to authorize.',
+ maxProjectsReached: 'Maximum reached. Deselect a project to choose a different one.',
+ organizationBoundGrant: {
+ title: 'Want this scoped to one member?',
+ description: (appName: string) =>
+ `Have them authorize ${appName} from their own account. Authorizing here gives it your Administrator access on every project, including ones created later.`,
+ },
+ coversEveryProject: {
+ title: 'This grant covers every project',
+ description: (appName: string, organizationSlug: string) =>
+ `${appName} can reach every project in ${organizationSlug}, including ones created later.`,
+ },
+ noProjects: {
+ title: (organizationSlug: string) => `No projects in ${organizationSlug}`,
+ body: (appName: string) =>
+ `${appName} needs access to at least one project, and this organization doesn't have any yet.`,
+ prompt: 'Expecting to see your projects?',
+ },
+ roleFailure: {
+ title: (count: number) =>
+ count === 1 ? "Couldn't authorize 1 project" : `Couldn't authorize ${count} projects`,
+ description: (appName: string) =>
+ `${appName} needs write access but your role is read-only on the projects highlighted. Deselect them to continue.`,
+ },
+ roleFailureAllProjects: {
+ title: (appName: string) => `Couldn't authorize ${appName}`,
+ description: (orgName: string) =>
+ `Your Read-only role in ${orgName} can't grant write access. Ask an admin to change your role, or switch organization.`,
+ },
+} as const
+
+export function groupScopesByLevel(scopes: OAuthScope[]) {
+ const read = new Set<string>()
+ const write = new Set<string>()
+ const readWrite = new Set<string>()
+
+ for (const scope of scopes) {
+ const [permission, level] = scope.split(':')
+ if (level === 'read') {
+ read.add(permission)
+ }
+ if (level === 'write') {
+ write.add(permission)
+ }
+ }
+
+ for (const permission of write) {
+ if (read.has(permission)) {
+ readWrite.add(permission)
+ write.delete(permission)
+ read.delete(permission)
+ }
+ }
+
+ return [
+ ...(readWrite.size > 0
+ ? [
+ {
+ level: 'read-write' as const,
+ permissions: Array.from(readWrite),
+ },
+ ]
+ : []),
+ ...(write.size > 0
+ ? [
+ {
+ level: 'write' as const,
+ permissions: Array.from(write),
+ },
+ ]
+ : []),
+ ...(read.size > 0
+ ? [
+ {
+ level: 'read' as const,
+ permissions: Array.from(read),
+ },
+ ]
+ : []),
+ ]
+}
+
+export function formatPermissionName(name: string) {
+ return name
+ .split('_')
+ .map((part) => capitalize(part))
+ .join(' ')
+}
+
+export function getScopeLevelLabel(level: 'read' | 'write' | 'read-write') {
+ if (level === 'read') return 'READ'
+ if (level === 'write') return 'WRITE'
+ return 'READ-WRITE'
+}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ProjectMultiSelect.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ProjectMultiSelect.test.tsx
new file mode 100644
index 00000000000..b82302f29f3
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ProjectMultiSelect.test.tsx
@@ -0,0 +1,243 @@
+import { fireEvent, screen } from '@testing-library/react'
+import { describe, expect, test, vi } from 'vitest'
+
+import { ProjectMultiSelect } from './ProjectMultiSelect'
+import { ADMINISTRATOR_ROLE, DEVELOPER_ROLE } from '@/data/oauth-apps/mocks'
+import type { OAuthAppsAuthorizeOrganizationProject } from '@/data/oauth-apps/types'
+import { customRender } from '@/tests/lib/custom-render'
+
+const PROJECTS: OAuthAppsAuthorizeOrganizationProject[] = [
+ { ref: 'project-1', name: 'production', role: ADMINISTRATOR_ROLE },
+ { ref: 'project-2', name: 'staging', role: DEVELOPER_ROLE },
+]
+
+const MANY_PROJECTS: OAuthAppsAuthorizeOrganizationProject[] = Array.from(
+ { length: 12 },
+ (_, index) => ({
+ ref: `project-${index + 1}`,
+ name: `project ${index + 1}`,
+ role: DEVELOPER_ROLE,
+ })
+)
+
+const refsUpTo = (count: number) => MANY_PROJECTS.slice(0, count).map((project) => project.ref)
+
+const CAP_HELPER_TEXT = 'Maximum reached. Deselect a project to choose a different one.'
+
+describe('ProjectMultiSelect', () => {
+ test('shows a placeholder when nothing is selected', () => {
+ customRender(<ProjectMultiSelect projects={PROJECTS} selectedRefs={[]} onChange={vi.fn()} />)
+
+ expect(screen.getByRole('combobox')).toHaveTextContent('Select projects...')
+ })
+
+ test('renders a single selected project by name in the trigger', () => {
+ customRender(
+ <ProjectMultiSelect projects={PROJECTS} selectedRefs={['project-1']} onChange={vi.fn()} />
+ )
+
+ const trigger = screen.getByRole('combobox')
+ expect(trigger).toHaveTextContent('production')
+ expect(trigger).not.toHaveTextContent('project-1')
+ })
+
+ test('shows two selected projects as two badges', () => {
+ customRender(
+ <ProjectMultiSelect
+ projects={PROJECTS}
+ selectedRefs={['project-1', 'project-2']}
+ onChange={vi.fn()}
+ />
+ )
+
+ const trigger = screen.getByRole('combobox')
+ expect(trigger).toHaveTextContent('production')
+ expect(trigger).toHaveTextContent('staging')
+ expect(trigger).not.toHaveTextContent('+')
+ expect(trigger).not.toHaveTextContent('project-1')
+ })
+
+ test('collapses the projects past the badge limit into a counter', () => {
+ customRender(
+ <ProjectMultiSelect projects={MANY_PROJECTS} selectedRefs={refsUpTo(3)} onChange={vi.fn()} />
+ )
+
+ const trigger = screen.getByRole('combobox')
+ expect(trigger).toHaveTextContent('project 1')
+ expect(trigger).toHaveTextContent('project 2')
+ expect(trigger).toHaveTextContent('+1')
+ expect(trigger).not.toHaveTextContent('project 3')
+ expect(trigger).not.toHaveTextContent('project-1')
+ })
+
+ test('fires onChange with the toggled id added', () => {
+ const onChange = vi.fn()
+ customRender(<ProjectMultiSelect projects={PROJECTS} selectedRefs={[]} onChange={onChange} />)
+
+ fireEvent.click(screen.getByRole('combobox'))
+ fireEvent.click(screen.getByText('production'))
+
+ expect(onChange).toHaveBeenCalledWith(['project-1'])
+ })
+
+ test('fires onChange with the toggled id removed', () => {
+ const onChange = vi.fn()
+ customRender(
+ <ProjectMultiSelect projects={PROJECTS} selectedRefs={['project-1']} onChange={onChange} />
+ )
+
+ fireEvent.click(screen.getByRole('combobox'))
+ fireEvent.click(screen.getByRole('option', { name: 'production' }))
+
+ expect(onChange).toHaveBeenCalledWith([])
+ })
+
+ test('does not render an error message by default', () => {
+ customRender(<ProjectMultiSelect projects={PROJECTS} selectedRefs={[]} onChange={vi.fn()} />)
+
+ expect(
+ screen.queryByText('Must select at least one project to authorize.')
+ ).not.toBeInTheDocument()
+ })
+
+ test('renders the error message when the error prop is set', () => {
+ customRender(
+ <ProjectMultiSelect
+ projects={PROJECTS}
+ selectedRefs={[]}
+ onChange={vi.fn()}
+ error="Must select at least one project to authorize."
+ />
+ )
+
+ expect(screen.getByText('Must select at least one project to authorize.')).toBeInTheDocument()
+ })
+
+ test('search filters the visible project rows', () => {
+ customRender(<ProjectMultiSelect projects={PROJECTS} selectedRefs={[]} onChange={vi.fn()} />)
+
+ fireEvent.click(screen.getByRole('combobox'))
+ expect(screen.getByText('production')).toBeInTheDocument()
+ expect(screen.getByText('staging')).toBeInTheDocument()
+
+ fireEvent.change(screen.getByPlaceholderText('Search projects'), {
+ target: { value: 'prod' },
+ })
+
+ expect(screen.getByText('production')).toBeInTheDocument()
+ expect(screen.queryByText('staging')).not.toBeInTheDocument()
+ })
+
+ test('has no select-all control', () => {
+ customRender(<ProjectMultiSelect projects={PROJECTS} selectedRefs={[]} onChange={vi.fn()} />)
+
+ fireEvent.click(screen.getByRole('combobox'))
+
+ expect(screen.queryByText(/select all/i)).not.toBeInTheDocument()
+ })
+
+ test('hides the counter until something is selected', () => {
+ customRender(<ProjectMultiSelect projects={PROJECTS} selectedRefs={[]} onChange={vi.fn()} />)
+
+ expect(screen.queryByText('0/10')).not.toBeInTheDocument()
+ })
+
+ test('hides the counter below eight selected', () => {
+ customRender(
+ <ProjectMultiSelect projects={MANY_PROJECTS} selectedRefs={refsUpTo(7)} onChange={vi.fn()} />
+ )
+
+ expect(screen.queryByText('7/10')).not.toBeInTheDocument()
+ })
+
+ test('shows the counter from eight selected onward', () => {
+ customRender(
+ <ProjectMultiSelect projects={MANY_PROJECTS} selectedRefs={refsUpTo(8)} onChange={vi.fn()} />
+ )
+
+ expect(screen.getByText('8/10')).toBeInTheDocument()
+ })
+
+ test('at nine selected the cap is not yet reached and a tenth can be added', () => {
+ const onChange = vi.fn()
+ customRender(
+ <ProjectMultiSelect projects={MANY_PROJECTS} selectedRefs={refsUpTo(9)} onChange={onChange} />
+ )
+
+ expect(screen.getByText('9/10')).toBeInTheDocument()
+ expect(screen.queryByText(CAP_HELPER_TEXT)).not.toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('combobox'))
+ fireEvent.click(screen.getByText('project 10'))
+
+ expect(onChange).toHaveBeenCalledWith(refsUpTo(10))
+ })
+
+ test('at the cap it shows 10/10 and the helper text', () => {
+ customRender(
+ <ProjectMultiSelect projects={MANY_PROJECTS} selectedRefs={refsUpTo(10)} onChange={vi.fn()} />
+ )
+
+ expect(screen.getByText('10/10')).toBeInTheDocument()
+ expect(screen.getByText(CAP_HELPER_TEXT)).toBeInTheDocument()
+ })
+
+ test('at the cap unselected options are disabled and cannot be selected', () => {
+ const onChange = vi.fn()
+ customRender(
+ <ProjectMultiSelect
+ projects={MANY_PROJECTS}
+ selectedRefs={refsUpTo(10)}
+ onChange={onChange}
+ />
+ )
+
+ fireEvent.click(screen.getByRole('combobox'))
+
+ const unselected = screen.getByText('project 11').closest('[role="option"]')
+ expect(unselected).toHaveAttribute('aria-disabled', 'true')
+
+ fireEvent.click(screen.getByText('project 11'))
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ test('the cap never blocks deselection, which re-enables the other options', () => {
+ const onChange = vi.fn()
+ const { rerender } = customRender(
+ <ProjectMultiSelect
+ projects={MANY_PROJECTS}
+ selectedRefs={refsUpTo(10)}
+ onChange={onChange}
+ />
+ )
+
+ fireEvent.click(screen.getByRole('combobox'))
+ fireEvent.click(screen.getByRole('option', { name: 'project 1' }))
+
+ expect(onChange).toHaveBeenCalledWith(refsUpTo(10).slice(1))
+
+ rerender(
+ <ProjectMultiSelect projects={MANY_PROJECTS} selectedRefs={refsUpTo(9)} onChange={onChange} />
+ )
+
+ expect(screen.queryByText(CAP_HELPER_TEXT)).not.toBeInTheDocument()
+ expect(screen.getByText('project 11').closest('[role="option"]')).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true'
+ )
+ })
+
+ test('the required-selection error still renders at the cap boundary', () => {
+ customRender(
+ <ProjectMultiSelect
+ projects={PROJECTS}
+ selectedRefs={[]}
+ onChange={vi.fn()}
+ error="Must select at least one project to authorize."
+ />
+ )
+
+ expect(screen.getByText('Must select at least one project to authorize.')).toBeInTheDocument()
+ expect(screen.queryByText(CAP_HELPER_TEXT)).not.toBeInTheDocument()
+ })
+})
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ProjectMultiSelect.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ProjectMultiSelect.tsx
new file mode 100644
index 00000000000..c597df299e0
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ProjectMultiSelect.tsx
@@ -0,0 +1,119 @@
+import { useId } from 'react'
+import { Checkbox, cn } from 'ui'
+import {
+ MultiSelector,
+ MultiSelectorContent,
+ MultiSelectorInput,
+ MultiSelectorItem,
+ MultiSelectorList,
+ MultiSelectorTrigger,
+} from 'ui-patterns/multi-select'
+
+import { CONSENT_COPY } from './OAuthAppsAuthorizeScreen.utils'
+import type { OAuthAppsAuthorizeOrganizationProject } from '@/data/oauth-apps/types'
+
+export const MAX_SELECTED_PROJECTS = 10
+
+export interface ProjectMultiSelectProps {
+ projects: OAuthAppsAuthorizeOrganizationProject[]
+ selectedRefs: string[]
+ onChange: (selectedRefs: string[]) => void
+ maxSelected?: number
+ error?: string
+ flaggedRefs?: string[]
+ unavailableRefs?: string[]
+ allProjectsSelected?: boolean
+ onAllProjectsChange?: (selected: boolean) => void
+}
+
+export const ProjectMultiSelect = ({
+ projects,
+ selectedRefs,
+ onChange,
+ maxSelected = MAX_SELECTED_PROJECTS,
+ error,
+ flaggedRefs = [],
+ unavailableRefs = [],
+ allProjectsSelected = false,
+ onAllProjectsChange,
+}: ProjectMultiSelectProps) => {
+ const labelId = useId()
+ const hasFlagged = flaggedRefs.length > 0
+ const atCap = selectedRefs.length >= maxSelected
+ const showCounter = selectedRefs.length >= maxSelected - 2
+
+ const handleValuesChange = (nextRefs: string[]) => {
+ if (nextRefs.length > maxSelected) return
+ onChange(nextRefs)
+ }
+
+ return (
+ <div className="flex w-full flex-col gap-2">
+ <div className="flex items-center justify-between gap-2">
+ <p
+ id={labelId}
+ className={cn('text-sm', hasFlagged ? 'text-destructive' : 'text-foreground')}
+ >
+ Projects
+ </p>
+ {!allProjectsSelected && showCounter && (
+ <p className="text-xs text-foreground-lighter">
+ {selectedRefs.length}/{maxSelected}
+ </p>
+ )}
+ </div>
+
+ <label className="flex cursor-pointer items-center gap-2 py-1 text-sm text-foreground">
+ <Checkbox
+ checked={allProjectsSelected}
+ onCheckedChange={(checked) => onAllProjectsChange?.(checked === true)}
+ />
+ {CONSENT_COPY.allProjectsOption}
+ </label>
+
+ {!allProjectsSelected && (
+ <>
+ <MultiSelector values={selectedRefs} onValuesChange={handleValuesChange}>
+ <MultiSelectorTrigger
+ aria-labelledby={labelId}
+ label="Select projects..."
+ badgeLimit={2}
+ deletableBadge
+ renderValue={(value) =>
+ projects.find((project) => project.ref === value)?.name ?? value
+ }
+ />
+ <MultiSelectorContent>
+ <MultiSelectorInput placeholder="Search projects" showResetIcon />
+ <MultiSelectorList emptyLabel="No projects found">
+ {projects.map((project) => (
+ <MultiSelectorItem
+ key={project.ref}
+ value={project.ref}
+ disabled={atCap && !selectedRefs.includes(project.ref)}
+ >
+ {project.name}
+ {unavailableRefs.includes(project.ref) && (
+ <span className="text-foreground-lighter"> - Unavailable</span>
+ )}
+ </MultiSelectorItem>
+ ))}
+ </MultiSelectorList>
+ </MultiSelectorContent>
+ </MultiSelector>
+
+ {hasFlagged && (
+ <p className="text-xs text-destructive">
+ {flaggedRefs.length} of {selectedRefs.length}{' '}
+ {selectedRefs.length === 1 ? 'project' : 'projects'} unavailable
+ </p>
+ )}
+ {atCap && (
+ <p className="text-xs text-foreground-lighter">{CONSENT_COPY.maxProjectsReached}</p>
+ )}
+ {error && <p className="text-xs text-foreground-light">{error}</p>}
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ScopeGroupCard.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ScopeGroupCard.test.tsx
new file mode 100644
index 00000000000..894c88967af
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ScopeGroupCard.test.tsx
@@ -0,0 +1,38 @@
+import { screen } from '@testing-library/react'
+import { describe, expect, test } from 'vitest'
+
+import { ScopeGroupCard } from './ScopeGroupCard'
+import type { OAuthScope } from '@/data/oauth-apps/types'
+import { customRender } from '@/tests/lib/custom-render'
+
+const SCOPE_GROUPS: OAuthScope[] = [
+ 'database:read',
+ 'database:write',
+ 'environment:read',
+ 'environment:write',
+ 'projects:read',
+ 'edge_functions:read',
+ 'storage:read',
+]
+
+describe('ScopeGroupCard', () => {
+ test('renders READ and READ-WRITE badge labels', () => {
+ customRender(<ScopeGroupCard scopes={SCOPE_GROUPS} />)
+
+ expect(screen.getByText('READ-WRITE')).toBeInTheDocument()
+ expect(screen.getByText('READ')).toBeInTheDocument()
+ })
+
+ test('renders a WRITE badge for a write-only group', () => {
+ customRender(<ScopeGroupCard scopes={['analytics:write']} />)
+
+ expect(screen.getByText('WRITE')).toBeInTheDocument()
+ })
+
+ test('renders no over-role annotation', () => {
+ customRender(<ScopeGroupCard scopes={SCOPE_GROUPS} />)
+
+ expect(screen.queryByText('Read-only for your role')).not.toBeInTheDocument()
+ expect(screen.queryByText('READ + WRITE')).not.toBeInTheDocument()
+ })
+})
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ScopeGroupCard.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ScopeGroupCard.tsx
new file mode 100644
index 00000000000..6eef35ee76e
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/ScopeGroupCard.tsx
@@ -0,0 +1,39 @@
+import { useMemo } from 'react'
+
+import {
+ formatPermissionName,
+ getScopeLevelLabel,
+ groupScopesByLevel,
+} from './OAuthAppsAuthorizeScreen.utils'
+import type { OAuthScope } from '@/data/oauth-apps/types'
+
+export interface ScopeGroupCardProps {
+ scopes: OAuthScope[]
+}
+
+type ScopeGroupLevel = 'read' | 'write' | 'read-write'
+type ScopeGroup = {
+ level: ScopeGroupLevel
+ permissions: string[]
+}
+
+export const ScopeGroupCard = ({ scopes }: ScopeGroupCardProps) => {
+ const scopeGroups = useMemo<ScopeGroup[]>(() => groupScopesByLevel(scopes), [scopes])
+
+ return (
+ <div className="divide-y rounded-md border bg-surface-75 px-4">
+ {scopeGroups.map((scopeGroup) => (
+ <div key={scopeGroup.level} className="flex flex-col gap-2 py-3">
+ <p className="font-mono text-[11px] uppercase tracking-wider text-foreground-light">
+ {getScopeLevelLabel(scopeGroup.level)}
+ </p>
+ <p className="text-xs font-medium text-foreground">
+ {scopeGroup.permissions
+ .map((permission) => formatPermissionName(permission))
+ .join(', ')}
+ </p>
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/index.ts b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/index.ts
new file mode 100644
index 00000000000..1afe8c5be44
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/index.ts
@@ -0,0 +1,12 @@
+export { AuthorizeSuccessScreen } from './AuthorizeSuccessScreen'
+export type { AuthorizeSuccessScreenProps } from './AuthorizeSuccessScreen'
+export { AuthorizingAsCard } from './AuthorizingAsCard'
+export type { AuthorizingAsCardProps } from './AuthorizingAsCard'
+export { OAuthAppsAuthorizeScreen } from './OAuthAppsAuthorizeScreen'
+export type { OAuthAppsAuthorizeScreenProps } from './OAuthAppsAuthorizeScreen'
+export { NoProjectsNotice } from './NoProjectsNotice'
+export type { NoProjectsNoticeProps } from './NoProjectsNotice'
+export { ProjectMultiSelect } from './ProjectMultiSelect'
+export type { ProjectMultiSelectProps } from './ProjectMultiSelect'
+export { ScopeGroupCard } from './ScopeGroupCard'
+export type { ScopeGroupCardProps } from './ScopeGroupCard'
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/Consent/useMemberOrganization.ts b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/useMemberOrganization.ts
new file mode 100644
index 00000000000..5a0c50f0f35
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/Consent/useMemberOrganization.ts
@@ -0,0 +1,154 @@
+import { useQueries } from '@tanstack/react-query'
+
+import { oauthAppsKeys } from '@/data/oauth-apps/keys'
+import { USE_MOCKS } from '@/data/oauth-apps/mocks'
+import { getOAuthAppsAuthorizeOrganizationProjects } from '@/data/oauth-apps/oauth-apps-authorize-organization-projects-query'
+import { useOAuthAppsAuthorizeOrganizationsQuery } from '@/data/oauth-apps/oauth-apps-authorize-organizations-query'
+import { OAuthAppsAuthorizeRequest } from '@/data/oauth-apps/types'
+
+export interface OAuthAppsAuthorizeScreenProps {
+ authId: string
+ request: OAuthAppsAuthorizeRequest
+ organizationSlug?: string
+ projectRef?: string | null
+}
+
+export const useMemberOrganization = ({
+ authId,
+ organizationSlug,
+ projectRef = null,
+ request,
+}: Omit<OAuthAppsAuthorizeScreenProps, 'navigate'>):
+ | { isPending: false; isError: true; error: Error; data: null }
+ | { isPending: true; isError: false; error: null; data: null }
+ | { isPending: false; isError: false; error: null; data: string } => {
+ const isProjectScopingModeEnabled = request.project_scoping_mode
+ const needsOrgResolution = isProjectScopingModeEnabled && !organizationSlug && projectRef !== null
+ const identityQuery = useOAuthAppsAuthorizeOrganizationsQuery({ id: authId })
+
+ const resolveOrgFromProjectQuery = useQueries({
+ queries: (identityQuery.data?.organizations ?? []).map((organization) => ({
+ queryKey: oauthAppsKeys.authorizeOrganizationProjects(authId, organization.slug),
+ queryFn: () =>
+ getOAuthAppsAuthorizeOrganizationProjects({ id: authId, slug: organization.slug }),
+ enabled: USE_MOCKS && needsOrgResolution && identityQuery.isSuccess,
+ })),
+ combine: (queries) => {
+ // When combine is called, this cannot be null/undefined as it's a condition for the query to be enabled
+ // TS doesn't know though
+ if (!identityQuery.data) {
+ return {
+ isPending: true,
+ isError: false,
+ }
+ }
+
+ const owners = identityQuery.data.organizations.filter((_, index) =>
+ (queries[index].data ?? []).some((project) => project.ref === projectRef)
+ )
+ return {
+ isPending: queries.some((query) => query.isPending),
+ isError: queries.some((query) => query.isError),
+ error: queries.find((query) => !!query.error)?.error,
+ data: owners.length === 1 ? owners[0].slug : undefined,
+ }
+ },
+ })
+
+ if (identityQuery.isPending) {
+ return {
+ isPending: true,
+ isError: false,
+ data: null,
+ error: null,
+ }
+ }
+
+ if (identityQuery.isError) {
+ return {
+ isPending: false,
+ isError: true,
+ data: null,
+ error: identityQuery.error,
+ }
+ }
+
+ // An organization slug was provided
+ if (organizationSlug != null) {
+ const organization = identityQuery.data?.organizations.find(
+ (org) => org.slug === organizationSlug
+ )
+
+ if (organization) {
+ return {
+ isPending: false,
+ isError: false,
+ data: organization.slug,
+ error: null,
+ }
+ }
+
+ return {
+ isPending: false,
+ isError: true,
+ data: null,
+ error: new Error(`You are not part of organization ${organizationSlug}`),
+ }
+ }
+
+ // No organization slug was provided, nor a project ref, fallback to the first user org if available
+ if (!needsOrgResolution) {
+ if (identityQuery.data.organizations.length > 0) {
+ return {
+ isPending: false,
+ isError: false,
+ data: identityQuery.data?.organizations[0].slug,
+ error: null,
+ }
+ }
+
+ return {
+ isPending: false,
+ isError: true,
+ data: null,
+ error: new Error('No organizations found'),
+ }
+ }
+
+ // A project ref was provided and the authorization request is scoped to projects
+ if (resolveOrgFromProjectQuery.isPending) {
+ return {
+ isPending: true,
+ isError: false,
+ data: null,
+ error: null,
+ }
+ }
+
+ if (resolveOrgFromProjectQuery.isError) {
+ return {
+ isPending: false,
+ isError: true,
+ data: null,
+ error: resolveOrgFromProjectQuery.error!,
+ }
+ }
+
+ const orgSlug = resolveOrgFromProjectQuery.data ?? identityQuery.data?.organizations[0]?.slug
+ const memberOrg = identityQuery.data?.organizations.find((org) => org.slug === orgSlug)
+ if (!memberOrg) {
+ return {
+ isPending: false,
+ isError: true,
+ data: null,
+ error: new Error('No organizations found'),
+ }
+ }
+
+ return {
+ isPending: false,
+ isError: false,
+ data: memberOrg.slug,
+ error: null,
+ }
+}
diff --git a/apps/studio/data/oauth-apps/mocks.ts b/apps/studio/data/oauth-apps/mocks.ts
index d809a743c30..cd80e7c1585 100644
--- a/apps/studio/data/oauth-apps/mocks.ts
+++ b/apps/studio/data/oauth-apps/mocks.ts
@@ -218,7 +218,7 @@ const MOCK_IDENTITIES: Record<string, OAuthAppsAuthorizeIdentity> = {
},
[OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation]: {
- organizations: [NORTHWIND_TRADERS_DEVELOPER, CONTOSO_LABS],
+ organizations: [NORTHWIND_TRADERS_READ_ONLY, CONTOSO_LABS],
},
[OAUTH_APPS_MOCK_SCENARIOS.vercelOptionalProjects]: {
@@ -226,7 +226,7 @@ const MOCK_IDENTITIES: Record<string, OAuthAppsAuthorizeIdentity> = {
},
[OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects]: {
- organizations: [NORTHWIND_TRADERS_READ_ONLY, CONTOSO_LABS, FABRIKAM_OWNER],
+ organizations: [NORTHWIND_TRADERS_DEVELOPER, CONTOSO_LABS, FABRIKAM_OWNER],
},
[OAUTH_APPS_MOCK_SCENARIOS.vercelReconsentAllProjects]: {
@@ -234,7 +234,7 @@ const MOCK_IDENTITIES: Record<string, OAuthAppsAuthorizeIdentity> = {
},
[OAUTH_APPS_MOCK_SCENARIOS.kemalBot]: {
- organizations: [NORTHWIND_TRADERS_DEVELOPER, CONTOSO_LABS],
+ organizations: [NORTHWIND_TRADERS_DEVELOPER, CONTOSO_LABS, FABRIKAM_OWNER],
},
[OAUTH_APPS_MOCK_SCENARIOS.kemalBotOrgWide]: {
@@ -314,7 +314,7 @@ const MOCK_APPS_BY_ID: Record<string, OAuthAppsAuthorizeRequest> = {
// The current member's org-level role, keyed by org slug — same reasoning as MOCK_APPS_BY_ID.
const MOCK_ORGANIZATIONS_BY_SLUG: Record<string, OAuthOrganizationRole> = {
- 'northwind-traders': NORTHWIND_TRADERS_READ_ONLY,
+ 'northwind-traders': NORTHWIND_TRADERS_DEVELOPER,
'tailspin-toys': TAILSPIN_TOYS_ADMIN,
'fabrikam-industries': FABRIKAM_OWNER,
'contoso-labs': CONTOSO_LABS,
@@ -549,8 +549,9 @@ function evaluateGrantEligibility(
organization: OAuthOrganizationRole
): OAuthAppsAuthorizePreflightResult {
if (request.grant_kind === 'organization_bound') {
- if (isOwnerOrAdmin(organization.default_role)) return { ok: true }
+ if (isOwnerOrAdmin(organization.default_role)) return { status: 'success' }
return {
+ status: 'error',
error_code: 'role_validation_failed',
message: `Your ${organization.default_role.name} role cannot install this app for the organization.`,
validation: { scope_target: 'organization', role: organization.default_role },
@@ -558,9 +559,11 @@ function evaluateGrantEligibility(
}
const failedScopes = request.scopes.filter(isWriteScope)
- if (failedScopes.length === 0 || !isReadOnlyRole(organization.default_role)) return { ok: true }
+ if (failedScopes.length === 0 || !isReadOnlyRole(organization.default_role))
+ return { status: 'success' }
return {
+ status: 'error',
error_code: 'role_validation_failed',
message: `Your ${organization.default_role.name} role cannot satisfy this app's scopes for all projects.`,
validation: {
@@ -577,7 +580,7 @@ export function getMockOAuthAppsPreflightValidation(
): OAuthAppsAuthorizePreflightResult {
const request = MOCK_APPS_BY_ID[appId]
const organization = MOCK_ORGANIZATIONS_BY_SLUG[slug]
- if (!request || !organization) return { ok: true }
+ if (!request || !organization) return { status: 'success' }
return evaluateGrantEligibility(request, organization)
}
@@ -607,6 +610,7 @@ export function getMockOAuthAppsAuthorizeApproveResult(
if (blocked.length === 0) return approved
return {
+ status: 'error',
error_code: 'role_validation_failed',
message: `Your role is read-only on ${blocked.length} of the selected projects.`,
validation: {
diff --git a/apps/studio/data/oauth-apps/types.test.ts b/apps/studio/data/oauth-apps/types.test.ts
index 0af62eee06a..dd81a8ef52e 100644
--- a/apps/studio/data/oauth-apps/types.test.ts
+++ b/apps/studio/data/oauth-apps/types.test.ts
@@ -95,6 +95,7 @@ describe('isRoleValidationFailure', () => {
test('recognises a role validation failure', () => {
expect(
isRoleValidationFailure({
+ status: 'error',
error_code: 'role_validation_failed',
message: 'nope',
validation: { scope_target: 'organization', role: READ_ONLY_ROLE },
@@ -118,6 +119,7 @@ describe('getFailedProjects', () => {
expect(
getFailedProjects({
+ status: 'error',
error_code: 'role_validation_failed',
message: 'nope',
validation: { scope_target: 'projects', failures: [failure] },
@@ -128,6 +130,7 @@ describe('getFailedProjects', () => {
test('is empty for an organization-level failure', () => {
expect(
getFailedProjects({
+ status: 'error',
error_code: 'role_validation_failed',
message: 'nope',
validation: { scope_target: 'organization', role: READ_ONLY_ROLE },
diff --git a/apps/studio/data/oauth-apps/types.ts b/apps/studio/data/oauth-apps/types.ts
index 4d811a3b37d..9f47d31a139 100644
--- a/apps/studio/data/oauth-apps/types.ts
+++ b/apps/studio/data/oauth-apps/types.ts
@@ -100,6 +100,7 @@ export type OAuthScopeValidationProjectFailure = Extract<
>['failures'][number]
export type OAuthAppsAuthorizeRoleValidationFailure = {
+ status: 'error'
error_code: 'role_validation_failed'
message: string
validation: OAuthScopeValidationResult
@@ -122,7 +123,7 @@ export function getFailedProjects(
return failure.validation.scope_target === 'projects' ? failure.validation.failures : []
}
-export type OAuthAppsAuthorizePreflightSuccess = { ok: true }
+export type OAuthAppsAuthorizePreflightSuccess = { status: 'success' }
export type OAuthAppsAuthorizePreflightResult =
| OAuthAppsAuthorizePreflightSuccess
diff --git a/apps/studio/pages/authorize.tsx b/apps/studio/pages/authorize.tsx
index 45921d5c34a..af05b04c76b 100644
--- a/apps/studio/pages/authorize.tsx
+++ b/apps/studio/pages/authorize.tsx
@@ -1,19 +1,53 @@
-import { useParams } from 'common'
+import { useFlag, useParams } from 'common'
import Head from 'next/head'
import { useRouter } from 'next/router'
import { ApiAuthorizationScreen } from '@/components/interfaces/ApiAuthorization/ApiAuthorization'
import { ApiAuthorizationLoadingScreen } from '@/components/interfaces/ApiAuthorization/ApiAuthorization.Loading'
+import { OAuthAppsAuthorizeScreen } from '@/components/interfaces/Organization/OAuthApps/Consent'
+import { OAUTH_APPS_MOCK_SCENARIOS, USE_MOCKS } from '@/data/oauth-apps/mocks'
+import { useOAuthAppsAuthorizeRequestQuery } from '@/data/oauth-apps/oauth-apps-authorize-request-query'
import { withAuth } from '@/hooks/misc/withAuth'
import { buildStudioPageTitle } from '@/lib/page-title'
import type { NextPageWithLayout } from '@/types'
const PAGE_TITLE = buildStudioPageTitle({ section: 'Authorize API Access', brand: 'Supabase' })
+const MOCK_SCENARIOS: Record<string, { authId: string; organizationSlug?: string }> = {
+ default: { authId: OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper },
+ reconsent: { authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent },
+ reconsent_all_projects: { authId: OAUTH_APPS_MOCK_SCENARIOS.vercelReconsentAllProjects },
+ role_validation: { authId: OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation },
+ empty_org: {
+ authId: OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper,
+ organizationSlug: 'contoso-labs',
+ },
+ dynamic_client: { authId: OAUTH_APPS_MOCK_SCENARIOS.dynamicMcpClient },
+ org_bound: { authId: OAUTH_APPS_MOCK_SCENARIOS.kemalBot },
+ org_bound_all: { authId: OAUTH_APPS_MOCK_SCENARIOS.kemalBotOrgWide },
+ user_bound_all: { authId: OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects },
+}
+
const APIAuthorizationPage: NextPageWithLayout = () => {
const router = useRouter()
const routerReady = router.isReady
- const { auth_id, organization_slug } = useParams()
+ const { auth_id, organization_slug, mock_scenario } = useParams()
+ const oauthAppScopedGrants = useFlag('OauthAppScopedGrants')
+ const isScopedOAuthFlowEnabled = oauthAppScopedGrants && USE_MOCKS
+
+ const mockScenario = USE_MOCKS
+ ? (MOCK_SCENARIOS[mock_scenario ?? 'default'] ?? MOCK_SCENARIOS.default)
+ : undefined
+ const authId = mockScenario?.authId ?? auth_id
+ const organizationSlug = organization_slug ?? mockScenario?.organizationSlug
+
+ const projectRefParam = router.query.project_ref
+ const projectRef = (Array.isArray(projectRefParam) ? projectRefParam[0] : projectRefParam) ?? null
+
+ const { data: request } = useOAuthAppsAuthorizeRequestQuery(
+ { id: authId },
+ { enabled: isScopedOAuthFlowEnabled }
+ )
if (!routerReady) {
return (
@@ -26,6 +60,34 @@ const APIAuthorizationPage: NextPageWithLayout = () => {
)
}
+ if (isScopedOAuthFlowEnabled) {
+ if (!authId || !request) {
+ return (
+ <>
+ <Head>
+ <title>{PAGE_TITLE}</title>
+ </Head>
+ <ApiAuthorizationLoadingScreen />
+ </>
+ )
+ }
+
+ return (
+ <>
+ <Head>
+ <title>{PAGE_TITLE}</title>
+ </Head>
+ <OAuthAppsAuthorizeScreen
+ authId={authId}
+ request={request}
+ organizationSlug={organizationSlug}
+ projectRef={projectRef}
+ navigate={(destination) => router.push(destination)}
+ />
+ </>
+ )
+ }
+
return (
<>
<Head>
diff --git a/apps/studio/tests/pages/authorize.test.tsx b/apps/studio/tests/pages/authorize.test.tsx
index 7561cce3406..9f01fef49c2 100644
--- a/apps/studio/tests/pages/authorize.test.tsx
+++ b/apps/studio/tests/pages/authorize.test.tsx
@@ -1,5 +1,5 @@
import { screen } from '@testing-library/react'
-import { describe, expect, test, vi } from 'vitest'
+import { afterEach, describe, expect, test, vi } from 'vitest'
import type { ProfileContextType } from '@/lib/profile'
import APIAuthorizationPage from '@/pages/authorize'
@@ -9,14 +9,27 @@ vi.mock('@/hooks/misc/withAuth', () => ({
withAuth: (Component: React.ComponentType) => Component,
}))
+const flags = vi.hoisted(() => ({ scopedGrants: false }))
+const params = vi.hoisted(() => ({ current: {} as Record<string, string | undefined> }))
+
+vi.mock('common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('common')>()
+ return {
+ ...actual,
+ useParams: () => params.current,
+ useFlag: () => flags.scopedGrants,
+ }
+})
+
const routerPushMock = vi.fn()
+const useRouterMock = vi.fn(() => ({
+ isReady: false,
+ push: routerPushMock,
+ query: {},
+}))
vi.mock('next/router', () => ({
- useRouter: () => ({
- isReady: false,
- push: routerPushMock,
- query: {},
- }),
+ useRouter: () => useRouterMock(),
}))
const DEFAULT_PROFILE_CONTEXT: ProfileContextType = {
@@ -41,10 +54,86 @@ const DEFAULT_PROFILE_CONTEXT: ProfileContextType = {
}
describe('APIAuthorizationPage', () => {
+ afterEach(() => {
+ flags.scopedGrants = false
+ params.current = {}
+ })
+
test('renders loading interstitial while router is not ready', () => {
customRender(<APIAuthorizationPage dehydratedState={{}} />, {
profileContext: DEFAULT_PROFILE_CONTEXT,
})
expect(screen.getByText('Loading...')).toBeInTheDocument()
})
+
+ test('renders the legacy component when the OauthAppScopedGrants flag is off', () => {
+ useRouterMock.mockReturnValue({ isReady: true, push: routerPushMock, query: {} })
+
+ customRender(<APIAuthorizationPage dehydratedState={{}} />, {
+ profileContext: DEFAULT_PROFILE_CONTEXT,
+ })
+
+ expect(screen.getByText('Missing authorization link')).toBeInTheDocument()
+ expect(screen.queryByText(/is connected/)).not.toBeInTheDocument()
+ })
+
+ test('preselects projects from repeated project_ref params', async () => {
+ flags.scopedGrants = true
+ useRouterMock.mockReturnValue({
+ isReady: true,
+ push: routerPushMock,
+ query: { project_ref: ['northwindstorefront1', 'northwindcms1'] },
+ })
+
+ customRender(<APIAuthorizationPage dehydratedState={{}} />, {
+ profileContext: DEFAULT_PROFILE_CONTEXT,
+ })
+
+ expect(await screen.findByText('northwind-storefront')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()
+ })
+
+ test('normalises a single project_ref param to a one-item preselection', async () => {
+ flags.scopedGrants = true
+ useRouterMock.mockReturnValue({
+ isReady: true,
+ push: routerPushMock,
+ query: { project_ref: 'northwindcms1' },
+ })
+
+ customRender(<APIAuthorizationPage dehydratedState={{}} />, {
+ profileContext: DEFAULT_PROFILE_CONTEXT,
+ })
+
+ expect(await screen.findByText('northwind-cms')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /Authorize Vercel/ })).toBeEnabled()
+ })
+
+ test('org_bound_all renders without a picker and covers every project', async () => {
+ flags.scopedGrants = true
+ params.current = { mock_scenario: 'org_bound_all' }
+ useRouterMock.mockReturnValue({ isReady: true, push: routerPushMock, query: {} })
+
+ customRender(<APIAuthorizationPage dehydratedState={{}} />, {
+ profileContext: DEFAULT_PROFILE_CONTEXT,
+ })
+
+ expect(await screen.findByText('All projects, including future ones')).toBeInTheDocument()
+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
+ expect(screen.getByText('Want this scoped to one member?')).toBeInTheDocument()
+ })
+
+ test('user_bound_all renders without a picker and covers every project', async () => {
+ flags.scopedGrants = true
+ params.current = { mock_scenario: 'user_bound_all' }
+ useRouterMock.mockReturnValue({ isReady: true, push: routerPushMock, query: {} })
+
+ customRender(<APIAuthorizationPage dehydratedState={{}} />, {
+ profileContext: DEFAULT_PROFILE_CONTEXT,
+ })
+
+ expect(await screen.findByText('All projects, including future ones')).toBeInTheDocument()
+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
+ expect(screen.queryByText('Want this scoped to one member?')).not.toBeInTheDocument()
+ })
})
diff --git a/knip.jsonc b/knip.jsonc
index 5baa43c1ad7..4d34cdb5830 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -65,13 +65,17 @@
// read are documentation of the valid values, not dead code. Scoped to
// this file so `enumMembers` keeps working everywhere else.
"data/database/constraints-query.ts": ["enumMembers"],
- // Data contracts and mock hooks for the OAuth authorization
- // interstitial, landed ahead of the UI that consumes them. `exports`
- // and `types` cover the contract types that only gain consumers in the
- // consent-screen PR.
- // TODO(PROD-625): drop every oauth-apps knip exception in the
- // consent-screen PR, once the interstitial route imports them.
- "data/oauth-apps/**": ["files", "exports", "types"],
+ // Org settings authorized-apps data layer, landed in #49476 ahead of the
+ // tables that consume it. Scoped to the remaining files rather than the whole
+ // folder so everything else here stays gated.
+ // TODO(FE-4330): remove — used from #50529, drop this entry in that PR.
+ "data/oauth-apps/oauth-apps-approvals-query.ts": ["files"],
+ "data/oauth-apps/oauth-apps-authorized-apps-query.ts": ["files"],
+ "data/oauth-apps/oauth-apps-grants-query.ts": ["files"],
+ "data/oauth-apps/oauth-apps-member-grants-query.ts": ["files"],
+ "data/oauth-apps/oauth-apps-preflight-validation-query.ts": ["files"],
+ "data/oauth-apps/oauth-apps-revoke-grant-mutation.ts": ["files"],
+ "data/oauth-apps/oauth-apps-revoke-mutation.ts": ["files"],
"hooks/misc/useTrackExperimentExposure.ts": ["files"],
// Staging-only pinned Postgres image + FDW request payload for creating
// Warehouse test projects by hand. Nothing imports it yet — it's kept