Skip to content

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

feat: Add a config drift page in Studio (#48906)

Ivan Vasilove10f7cc80881
diff --git a/apps/studio/components/interfaces/App/GitHubConfigDriftBanner.tsx b/apps/studio/components/interfaces/App/GitHubConfigDriftBanner.tsx
new file mode 100644
index 00000000000..88b11d93818
--- /dev/null
+++ b/apps/studio/components/interfaces/App/GitHubConfigDriftBanner.tsx
@@ -0,0 +1,32 @@
+import { useParams } from 'common'
+import { AnimatePresence } from 'framer-motion'
+import Link from 'next/link'
+
+import { HeaderBanner } from '../Organization/HeaderBanner'
+import { useSelectedGitHubConfigDrift } from '@/hooks/misc/useGitHubConfigDrift'
+
+export function GitHubConfigDriftBanner() {
+ const { ref } = useParams()
+ const { hasConfigurationIssues, summary } = useSelectedGitHubConfigDrift()
+
+ const driftCount = summary.driftedFields.length
+ const settingsLabel = `${driftCount} managed ${driftCount === 1 ? 'setting differs' : 'settings differ'}`
+
+ return (
+ <AnimatePresence initial={false}>
+ {hasConfigurationIssues && ref && (
+ <HeaderBanner
+ key="github-config-drift-banner"
+ variant="warning"
+ title="Code configuration needs attention"
+ description={
+ <>
+ Current environment values are active; {settingsLabel}.{' '}
+ <Link href={`/project/${ref}/settings/code-configuration`}>Review configuration</Link>
+ </>
+ }
+ />
+ )}
+ </AnimatePresence>
+ )
+}
diff --git a/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.test.tsx b/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.test.tsx
new file mode 100644
index 00000000000..36c6f00a3ec
--- /dev/null
+++ b/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.test.tsx
@@ -0,0 +1,285 @@
+import { screen } from '@testing-library/react'
+import { apiV1Components, apiV2Components, platformComponents } from 'api-types'
+import { HttpResponse } from 'msw'
+import { describe, expect, test, vi } from 'vitest'
+
+import { ConfigurationDriftPage } from './ConfigurationDriftPage'
+import type { ProfileContextType } from '@/lib/profile'
+import { createMockOrganizationResponse } from '@/tests/helpers'
+import { customRender } from '@/tests/lib/custom-render'
+import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
+
+type ProjectDetailResponse = platformComponents['schemas']['ProjectDetailResponse']
+type OrganizationResponse = platformComponents['schemas']['OrganizationResponse']
+type ListGitHubConnectionsResponse = platformComponents['schemas']['ListGitHubConnectionsResponse']
+type GetGitHubConnectionConfigResponse =
+ platformComponents['schemas']['GetGitHubConnectionConfigResponse']
+type BranchResponse = apiV1Components['schemas']['BranchResponse']
+type V2ProjectConfigResponse = apiV2Components['schemas']['V2ProjectConfigResponse']
+
+const PROJECT_REF = 'default'
+const ORGANIZATION_ID = 1
+const CONNECTION_ID = 42
+
+const 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,
+}
+
+vi.mock('common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('common')>()
+ return {
+ ...actual,
+ useIsLoggedIn: () => true,
+ useParams: () => ({ ref: PROJECT_REF }),
+ }
+})
+
+vi.mock('@/lib/constants', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/lib/constants')>()
+ return {
+ ...actual,
+ IS_PLATFORM: true,
+ }
+})
+
+const PROJECT: ProjectDetailResponse = {
+ cloud_provider: 'AWS',
+ db_host: `db.${PROJECT_REF}.supabase.co`,
+ high_availability: false,
+ id: 1,
+ inserted_at: '2025-01-01T00:00:00Z',
+ integration_source: null,
+ is_branch_enabled: true,
+ is_physical_backups_enabled: false,
+ name: 'Test project',
+ organization_id: ORGANIZATION_ID,
+ ref: PROJECT_REF,
+ region: 'us-east-1',
+ restUrl: `https://${PROJECT_REF}.supabase.co`,
+ status: 'ACTIVE_HEALTHY',
+ subscription_id: 'subscription-1',
+ updated_at: '2025-01-01T00:00:00Z',
+}
+
+const BRANCH: BranchResponse = {
+ created_at: '2025-01-01T00:00:00Z',
+ id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ is_default: true,
+ name: 'main',
+ parent_project_ref: PROJECT_REF,
+ persistent: true,
+ project_ref: PROJECT_REF,
+ status: 'MIGRATIONS_PASSED',
+ updated_at: '2025-01-01T00:00:00Z',
+ with_data: false,
+}
+
+const CONNECTION: ListGitHubConnectionsResponse['connections'][number] = {
+ branch_limit: 0,
+ id: CONNECTION_ID,
+ inserted_at: '2025-01-01T00:00:00Z',
+ installation_id: 1,
+ new_branch_per_pr: false,
+ project: { id: 1, name: 'Test project', ref: PROJECT_REF },
+ repository: { id: 1, name: 'acme/repo' },
+ supabase_changes_only: false,
+ updated_at: '2025-01-01T00:00:00Z',
+ user: null,
+ workdir: '',
+}
+
+function createProjectConfigResponse(auth: Record<string, unknown>): V2ProjectConfigResponse {
+ return {
+ data: {
+ id: PROJECT_REF,
+ type: 'project_config',
+ attributes: {
+ api: {
+ db_extra_search_path: 'public',
+ db_pool: null,
+ db_pool_acquisition_timeout: 10,
+ db_schema: 'public',
+ max_rows: 1000,
+ },
+ auth,
+ database: {
+ network_restrictions: {
+ allowed_cidrs: [],
+ entitlement: 'disallowed',
+ status: 'stored',
+ },
+ postgres_settings: {},
+ ssl_enforced: true,
+ },
+ pooler: {
+ default_pool_size: 15,
+ ignore_startup_parameters: '',
+ max_client_conn: 200,
+ pool_mode: 'transaction',
+ query_wait_timeout: 120,
+ reserve_pool_size: 0,
+ server_idle_timeout: 0,
+ server_lifetime: 3600,
+ },
+ realtime: {
+ connection_pool: 20,
+ max_bytes_per_second: 100_000,
+ max_channels_per_client: 100,
+ max_concurrent_users: 200,
+ max_events_per_second: 100,
+ max_joins_per_second: 100,
+ max_payload_size_in_kb: 1000,
+ max_presence_events_per_second: 100,
+ postgres_changes_pool: null,
+ presence_enabled: true,
+ private_only: false,
+ suspend: false,
+ },
+ storage: {
+ capabilities: { iceberg_catalog: false, list_v2: true },
+ database_pool_mode: 'transaction',
+ features: {
+ iceberg_catalog: { enabled: false, max_catalogs: 0, max_namespaces: 0, max_tables: 0 },
+ image_transformation: { enabled: true },
+ purge_cache: { enabled: false },
+ s3_protocol: { enabled: false },
+ vector_buckets: { enabled: false, max_buckets: 0, max_indexes: 0 },
+ },
+ file_size_limit: 52_428_800,
+ migration_version: '0',
+ upstream_target: 'main',
+ },
+ },
+ },
+ }
+}
+
+function mockProject() {
+ addAPIMock({ method: 'get', path: '/platform/projects/:ref', response: PROJECT })
+ addAPIMock({
+ method: 'get',
+ path: '/platform/organizations',
+ response: () =>
+ HttpResponse.json<OrganizationResponse[]>([
+ createMockOrganizationResponse({ id: ORGANIZATION_ID }),
+ ]),
+ })
+}
+
+function mockConnectedProject() {
+ mockProject()
+ addAPIMock({
+ method: 'get',
+ path: '/v1/projects/:ref/branches',
+ response: () => HttpResponse.json<BranchResponse[]>([BRANCH]),
+ })
+ addAPIMock({
+ method: 'get',
+ path: '/platform/integrations/github/connections',
+ response: () => HttpResponse.json<ListGitHubConnectionsResponse>({ connections: [CONNECTION] }),
+ })
+}
+
+function mockProjectConfig(auth: Record<string, unknown>) {
+ addAPIMock({
+ method: 'get',
+ path: '/v2/projects/:ref/config',
+ response: () => HttpResponse.json<V2ProjectConfigResponse>(createProjectConfigResponse(auth)),
+ })
+}
+
+function mockGitHubConfig(config: Record<string, unknown>) {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/integrations/github/connections/:connection_id/config',
+ response: () =>
+ HttpResponse.json<GetGitHubConnectionConfigResponse>({
+ config,
+ path: 'supabase/config.toml',
+ ref: null,
+ sha: 'abc123',
+ }),
+ })
+}
+
+describe('ConfigurationDriftPage', () => {
+ test('prompts to connect GitHub when the project has no connection', async () => {
+ mockProject()
+ addAPIMock({
+ method: 'get',
+ path: '/v1/projects/:ref/branches',
+ response: () => HttpResponse.json<BranchResponse[]>([]),
+ })
+ addAPIMock({
+ method: 'get',
+ path: '/platform/integrations/github/connections',
+ response: () => HttpResponse.json<ListGitHubConnectionsResponse>({ connections: [] }),
+ })
+
+ customRender(<ConfigurationDriftPage />, { profileContext: PROFILE_CONTEXT })
+
+ expect(await screen.findByText(/Connect a GitHub repo/)).toBeInTheDocument()
+ })
+
+ test('shows an error state when a query fails', async () => {
+ mockProject()
+ addAPIMock({
+ method: 'get',
+ path: '/v1/projects/:ref/branches',
+ response: () =>
+ HttpResponse.json<APIErrorBody>({ message: 'Boom from the backend' }, { status: 500 }),
+ })
+ addAPIMock({
+ method: 'get',
+ path: '/platform/integrations/github/connections',
+ response: () => HttpResponse.json<ListGitHubConnectionsResponse>({ connections: [] }),
+ })
+
+ customRender(<ConfigurationDriftPage />, { profileContext: PROFILE_CONTEXT })
+
+ expect(await screen.findByText('Could not check configuration drift')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Refresh' })).toBeInTheDocument()
+ })
+
+ test('shows a success state when all comparable settings match', async () => {
+ mockConnectedProject()
+ mockProjectConfig({ disable_signup: false })
+ mockGitHubConfig({ auth: { enable_signup: true } })
+
+ customRender(<ConfigurationDriftPage />, { profileContext: PROFILE_CONTEXT })
+
+ expect(await screen.findByText('All compared settings match')).toBeInTheDocument()
+ })
+
+ test('renders a drift row when the dashboard and config.toml disagree', async () => {
+ mockConnectedProject()
+ mockProjectConfig({ disable_signup: false })
+ mockGitHubConfig({ auth: { enable_signup: false } })
+
+ customRender(<ConfigurationDriftPage />, { profileContext: PROFILE_CONTEXT })
+
+ expect(await screen.findByText('New user signups')).toBeInTheDocument()
+ expect(screen.getByText('1 setting differs')).toBeInTheDocument()
+ expect(screen.getByRole('link', { name: /Open setting/ })).toHaveAttribute(
+ 'href',
+ `/project/${PROJECT_REF}/auth/providers`
+ )
+ })
+})
diff --git a/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.tsx b/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.tsx
new file mode 100644
index 00000000000..435a18cdfb5
--- /dev/null
+++ b/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.tsx
@@ -0,0 +1,348 @@
+import { useParams } from 'common'
+import { ArrowRight, CheckCircle2, FileWarning, Github, Minus, Plus } from 'lucide-react'
+import Link from 'next/link'
+import { Button, Card, Skeleton } from 'ui'
+import { CollapsibleCardSection } from 'ui-patterns/CollapsibleCardSection'
+import { EmptyStatePresentational } from 'ui-patterns/EmptyStatePresentational'
+
+import {
+ createConfigurationDriftRows,
+ groupUnmanagedConfigFields,
+ type ConfigurationDriftRow,
+ type UnmanagedConfigSectionGroup,
+} from './ConfigurationDriftPage.utils'
+import { AlertError } from '@/components/ui/AlertError'
+import { useSelectedGitHubConfigDrift } from '@/hooks/misc/useGitHubConfigDrift'
+
+export function ConfigurationDriftPageSkeleton() {
+ return (
+ <div className="space-y-6" aria-label="Loading configuration drift" aria-busy="true">
+ <div className="space-y-3 rounded-lg border border-border bg-surface-100 px-4 py-3">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex min-w-0 items-center gap-3">
+ <Skeleton className="h-8 w-8 shrink-0 rounded-md" />
+ <Skeleton className="h-4 w-44 max-w-[60vw]" />
+ </div>
+ <div className="flex w-full items-center gap-2 sm:w-auto">
+ <Skeleton className="h-7 flex-1 rounded-md sm:w-28 sm:flex-none" />
+ <Skeleton className="h-7 flex-1 rounded-md sm:w-20 sm:flex-none" />
+ </div>
+ </div>
+
+ <div className="grid gap-3 border-t border-border pt-3 sm:grid-cols-2 lg:grid-cols-3">
+ {['w-28', 'w-44', 'w-52'].map((width) => (
+ <div key={width} className="space-y-2">
+ <Skeleton className="h-3 w-20" />
+ <Skeleton className={`h-3 ${width}`} />
+ </div>
+ ))}
+ </div>
+
+ <div className="border-t border-border pt-3">
+ <Skeleton className="h-3 w-40" />
+ <Skeleton className="mt-2 h-3 w-72 max-w-full" />
+ <div className="mt-3 overflow-hidden rounded-md border border-border">
+ <div className="flex items-center gap-2 bg-surface-100 px-3 py-2.5">
+ <Skeleton className="h-5 w-5 rounded-full" />
+ <Skeleton className="h-3 w-32" />
+ </div>
+ <div className="space-y-2 border-t border-border bg-[#0d0d0d] px-4 py-4">
+ <Skeleton className="h-3 w-24" />
+ <Skeleton className="h-3 w-52 max-w-full" />
+ <Skeleton className="h-3 w-40 max-w-full" />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <Card className="overflow-hidden">
+ <div className="flex min-h-[77px] items-start gap-3 border-b border-border px-4 py-4 sm:px-5">
+ <Skeleton className="mt-0.5 h-5 w-5 shrink-0 rounded" />
+ <div className="flex-1 space-y-2">
+ <Skeleton className="h-4 w-48 max-w-full" />
+ <Skeleton className="h-3 w-[460px] max-w-full" />
+ </div>
+ </div>
+
+ <div className="border-b border-border bg-surface-100 px-4 py-3 sm:px-5">
+ <Skeleton className="h-3 w-32" />
+ </div>
+
+ <div className="px-4 py-4 sm:px-5">
+ <div className="flex items-start justify-between gap-4">
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-36" />
+ <Skeleton className="h-3 w-52 max-w-[55vw]" />
+ </div>
+ <Skeleton className="h-7 w-24 shrink-0 rounded-md" />
+ </div>
+ <div className="mt-4 grid gap-3 md:grid-cols-2">
+ {[0, 1].map((panel) => (
+ <div
+ key={panel}
+ className="min-h-[84px] space-y-3 rounded-md border border-border p-3"
+ >
+ <Skeleton className="h-3 w-28" />
+ <Skeleton className="h-3 w-4/5" />
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-2 border-t border-border bg-surface-100 px-4 py-4 sm:flex-row sm:px-5">
+ <Skeleton className="h-[58px] flex-1 rounded-md" />
+ <Skeleton className="h-[58px] flex-1 rounded-md" />
+ </div>
+ </Card>
+ </div>
+ )
+}
+
+function ConfigurationValuePanel({
+ label,
+ values,
+ kind,
+}: {
+ label: string
+ values: string[]
+ kind: 'dashboard' | 'config'
+}) {
+ const Icon = kind === 'dashboard' ? Minus : Plus
+
+ return (
+ <div className="min-w-0 rounded-md border border-border bg-surface-100 p-3">
+ <div className="mb-2 flex items-center gap-2 text-xs font-medium text-foreground-light">
+ <Icon
+ className={kind === 'dashboard' ? 'h-3.5 w-3.5 text-warning' : 'h-3.5 w-3.5 text-brand'}
+ />
+ <span>{label}</span>
+ </div>
+ <ul className="space-y-1.5">
+ {values.map((value) => (
+ <li key={value} className="break-all font-mono text-xs leading-5 text-foreground">
+ {value}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )
+}
+
+function ConfigurationDriftItem({ row }: { row: ConfigurationDriftRow }) {
+ const valueDiff = row.valueDiff
+ const listDifferenceCount =
+ valueDiff.kind === 'list'
+ ? Number(valueDiff.onlyInDashboard.length > 0) + Number(valueDiff.onlyInConfig.length > 0)
+ : 0
+
+ return (
+ <article className="border-t border-border px-4 py-4 first:border-t-0 sm:px-5">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
+ <div className="flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-1">
+ <h3 className="text-sm font-medium text-foreground">{row.settingLabel}</h3>
+ <code className="text-code-inline max-w-full truncate text-xs" title={row.configPath}>
+ {row.configPath}
+ </code>
+ <span className="text-xs text-warning">Drift</span>
+ </div>
+ <Button
+ asChild
+ type="button"
+ variant="default"
+ size="tiny"
+ className="w-full shrink-0 sm:w-auto"
+ icon={<ArrowRight className="h-3.5 w-3.5" />}
+ >
+ <Link href={row.settingHref}>Open setting</Link>
+ </Button>
+ </div>
+
+ {valueDiff.kind === 'list' ? (
+ <div
+ className={`mt-4 grid gap-3 ${listDifferenceCount > 1 ? 'md:grid-cols-2' : 'grid-cols-1'}`}
+ >
+ {valueDiff.onlyInDashboard.length > 0 && (
+ <ConfigurationValuePanel
+ label="Only in current environment"
+ values={valueDiff.onlyInDashboard}
+ kind="dashboard"
+ />
+ )}
+ {valueDiff.onlyInConfig.length > 0 && (
+ <ConfigurationValuePanel
+ label="Only in config.toml"
+ values={valueDiff.onlyInConfig}
+ kind="config"
+ />
+ )}
+ </div>
+ ) : (
+ <div className="mt-4 grid gap-3 md:grid-cols-2">
+ <div className="min-w-0 rounded-md border border-border bg-surface-100 p-3">
+ <p className="mb-2 text-xs font-medium text-foreground-light">
+ Current environment · active
+ </p>
+ <pre className="whitespace-pre-wrap break-all font-mono text-xs leading-5 text-foreground">
+ {valueDiff.dashboardValue}
+ </pre>
+ </div>
+ <div className="min-w-0 rounded-md border border-border bg-surface-100 p-3">
+ <p className="mb-2 text-xs font-medium text-foreground-light">config.toml · intended</p>
+ <pre className="whitespace-pre-wrap break-all font-mono text-xs leading-5 text-foreground">
+ {valueDiff.configValue}
+ </pre>
+ </div>
+ </div>
+ )}
+ </article>
+ )
+}
+
+export function ConfigurationDriftResults({ rows }: { rows: ConfigurationDriftRow[] }) {
+ const driftCount = rows.length
+ const issueSummary = `${driftCount} ${driftCount === 1 ? 'setting differs' : 'settings differ'}`
+
+ return (
+ <Card className="overflow-hidden">
+ <div className="flex items-start gap-3 border-b border-border px-4 py-4 sm:px-5">
+ <div className="flex items-start gap-3">
+ <FileWarning className="mt-0.5 h-5 w-5 shrink-0 -translate-x-0.5 text-warning" />
+ <div className="min-w-0">
+ <h2 className="text-sm font-medium">{issueSummary}</h2>
+ <p className="mt-1 text-sm text-foreground-light">
+ Current environment values differ from config.toml. Update the setting to resolve.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div>
+ {rows.map((row) => (
+ <ConfigurationDriftItem key={row.configPath} row={row} />
+ ))}
+ </div>
+ </Card>
+ )
+}
+
+function UnmanagedConfigSection({ groups }: { groups: UnmanagedConfigSectionGroup[] }) {
+ const fieldCount = groups.reduce((count, group) => count + group.rows.length, 0)
+ if (fieldCount === 0) return null
+
+ return (
+ <Card className="px-4 py-4 sm:px-5">
+ <CollapsibleCardSection
+ title={`Not tracked in config.toml (${fieldCount})`}
+ description="These settings aren't declared in config.toml, so they can't drift — shown here for visibility only."
+ >
+ <div className="space-y-4">
+ {groups.map((group) => (
+ <div key={group.section}>
+ <h3 className="mb-2 text-xs font-medium uppercase tracking-wide text-foreground-muted">
+ {group.sectionLabel}
+ </h3>
+ <ul className="divide-y divide-border rounded-md border border-border">
+ {group.rows.map((row) => (
+ <li
+ key={row.configPath}
+ className="flex items-center justify-between gap-4 px-3 py-2 text-sm"
+ >
+ <span className="text-foreground-light">{row.label}</span>
+ <code
+ className="max-w-[60%] truncate text-xs text-foreground-muted"
+ title={row.value}
+ >
+ {row.value}
+ </code>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ </CollapsibleCardSection>
+ </Card>
+ )
+}
+
+export function ConfigurationDriftPage() {
+ const { ref: projectRef = '' } = useParams()
+ const { summary, unmanagedFields, isReady, isPending, isFetching, isError, error, refetch } =
+ useSelectedGitHubConfigDrift()
+ const driftRows = createConfigurationDriftRows(summary.driftedFields, projectRef)
+ const comparableSettingCount = summary.managedCount + driftRows.length
+ const unmanagedGroups = groupUnmanagedConfigFields(unmanagedFields)
+
+ if (isPending) {
+ return <ConfigurationDriftPageSkeleton />
+ }
+
+ if (isError) {
+ return (
+ <AlertError
+ projectRef={projectRef}
+ subject="Could not check configuration drift"
+ description="Refresh to compare the supported settings with the selected GitHub branch again."
+ error={error}
+ additionalActions={
+ <Button variant="default" size="small" loading={isFetching} onClick={() => refetch()}>
+ Refresh
+ </Button>
+ }
+ />
+ )
+ }
+
+ if (!isReady) {
+ return (
+ <EmptyStatePresentational
+ icon={Github}
+ title="Github integration required"
+ description={
+ <p className="mt-1 text-sm text-foreground-light">
+ This feature requires a GitHub integration to enable the project to be managed by a
+ config.toml file.
+ </p>
+ }
+ >
+ <Link href={`/project/${projectRef}/settings/integrations`}>
+ <Button size="tiny" variant="primary" icon={<Plus size={14} />}>
+ Connect a GitHub repo
+ </Button>
+ </Link>
+ </EmptyStatePresentational>
+ )
+ }
+
+ return (
+ <main className="space-y-6">
+ {comparableSettingCount === 0 ? (
+ <Card className="flex min-h-44 items-center justify-center px-6 text-center">
+ <div className="max-w-lg">
+ <Github className="mx-auto mb-3 h-6 w-6 text-foreground-muted" />
+ <h2 className="text-sm font-medium">No comparable settings found</h2>
+ <p className="mt-1 text-sm text-foreground-light">
+ This branch does not define any supported, non-secret settings that can be compared
+ with the current environment.
+ </p>
+ </div>
+ </Card>
+ ) : driftRows.length === 0 ? (
+ <Card className="flex min-h-44 items-center justify-center px-6 text-center">
+ <div className="max-w-lg">
+ <CheckCircle2 className="mx-auto mb-3 h-6 w-6 text-brand" />
+ <h2 className="text-sm font-medium">All compared settings match</h2>
+ <p className="mt-1 text-sm text-foreground-light">
+ The current environment matches all {summary.managedCount} comparable settings in this
+ branch.
+ </p>
+ </div>
+ </Card>
+ ) : (
+ <ConfigurationDriftResults rows={driftRows} />
+ )}
+
+ <UnmanagedConfigSection groups={unmanagedGroups} />
+ </main>
+ )
+}
diff --git a/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.utils.test.ts b/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.utils.test.ts
new file mode 100644
index 00000000000..ca08b0e8d5c
--- /dev/null
+++ b/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.utils.test.ts
@@ -0,0 +1,183 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ createConfigurationDriftRows,
+ groupUnmanagedConfigFields,
+} from './ConfigurationDriftPage.utils'
+import type { GitHubConfigDriftField, UnmanagedConfigField } from './github-config-drift'
+
+const PROJECT_REF = 'abcdefgh'
+
+function driftField(overrides: Partial<GitHubConfigDriftField>): GitHubConfigDriftField {
+ return {
+ section: 'api',
+ configPath: 'api.max_rows',
+ settingHref: (projectRef) => `/project/${projectRef}/settings/api`,
+ dashboardValue: 1000,
+ githubValue: 500,
+ ...overrides,
+ }
+}
+
+function unmanagedField(overrides: Partial<UnmanagedConfigField>): UnmanagedConfigField {
+ return {
+ section: 'api',
+ configPath: 'api.max_rows',
+ dashboardValue: 1000,
+ ...overrides,
+ }
+}
+
+describe('createConfigurationDriftRows', () => {
+ it('resolves the setting href against the project ref and marks the row as drifted', () => {
+ const [row] = createConfigurationDriftRows([driftField({})], PROJECT_REF)
+
+ expect(row.status).toBe('drifted')
+ expect(row.settingHref).toBe('/project/abcdefgh/settings/api')
+ })
+
+ it('uses the hand-written label for a known config path', () => {
+ const [row] = createConfigurationDriftRows(
+ [driftField({ configPath: 'auth.enable_signup' })],
+ PROJECT_REF
+ )
+
+ expect(row.settingLabel).toBe('New user signups')
+ })
+
+ it('labels an external auth provider field as "<provider> · <key>"', () => {
+ const [row] = createConfigurationDriftRows(
+ [driftField({ configPath: 'auth.external.google.client_id' })],
+ PROJECT_REF
+ )
+
+ expect(row.settingLabel).toBe('Google · Client ID')
+ })
+
+ it('falls back to a title-cased last path segment for an unrecognized config path', () => {
+ const [row] = createConfigurationDriftRows(
+ [driftField({ configPath: 'some.unknown_setting' })],
+ PROJECT_REF
+ )
+
+ expect(row.settingLabel).toBe('Unknown Setting')
+ })
+
+ it('builds a scalar diff, formatting booleans and empty values for display', () => {
+ const [row] = createConfigurationDriftRows(
+ [
+ driftField({
+ configPath: 'auth.enable_signup',
+ dashboardValue: true,
+ githubValue: false,
+ }),
+ ],
+ PROJECT_REF
+ )
+
+ expect(row.valueDiff).toEqual({
+ kind: 'scalar',
+ dashboardValue: 'Enabled',
+ configValue: 'Disabled',
+ })
+ })
+
+ it('formats a missing scalar value as "Not set"', () => {
+ const [row] = createConfigurationDriftRows(
+ [driftField({ configPath: 'auth.site_url', dashboardValue: '', githubValue: undefined })],
+ PROJECT_REF
+ )
+
+ expect(row.valueDiff).toEqual({
+ kind: 'scalar',
+ dashboardValue: 'Not set',
+ configValue: 'Not set',
+ })
+ })
+
+ it('builds a list diff for redirect URLs, normalizing and comparing entries', () => {
+ const [row] = createConfigurationDriftRows(
+ [
+ driftField({
+ configPath: 'auth.additional_redirect_urls',
+ dashboardValue: ['https://a.com', 'https://b.com'],
+ githubValue: [' https://a.com ', 'https://c.com'],
+ }),
+ ],
+ PROJECT_REF
+ )
+
+ expect(row.valueDiff).toEqual({
+ kind: 'list',
+ onlyInDashboard: ['https://b.com'],
+ onlyInConfig: ['https://c.com'],
+ })
+ })
+
+ it('reports no diff entries when redirect URL lists are equal after normalization', () => {
+ const [row] = createConfigurationDriftRows(
+ [
+ driftField({
+ configPath: 'auth.additional_redirect_urls',
+ dashboardValue: ['https://a.com'],
+ githubValue: ['https://a.com', 'https://a.com'],
+ }),
+ ],
+ PROJECT_REF
+ )
+
+ expect(row.valueDiff).toEqual({ kind: 'list', onlyInDashboard: [], onlyInConfig: [] })
+ })
+})
+
+describe('groupUnmanagedConfigFields', () => {
+ it('returns an empty array when there are no unmanaged fields', () => {
+ expect(groupUnmanagedConfigFields([])).toEqual([])
+ })
+
+ it('groups fields from the same section into a single group', () => {
+ const groups = groupUnmanagedConfigFields([
+ unmanagedField({ configPath: 'api.max_rows', dashboardValue: 1000 }),
+ unmanagedField({ configPath: 'api.enabled', dashboardValue: true }),
+ ])
+
+ expect(groups).toHaveLength(1)
+ expect(groups[0]).toEqual({
+ section: 'api',
+ sectionLabel: 'API',
+ rows: [
+ { configPath: 'api.max_rows', label: 'Max rows', value: '1000' },
+ { configPath: 'api.enabled', label: 'API enabled', value: 'Enabled' },
+ ],
+ })
+ })
+
+ it('orders groups by CONFIG_SECTIONS order, not by input order', () => {
+ const groups = groupUnmanagedConfigFields([
+ unmanagedField({ section: 'storage', configPath: 'storage.enabled', dashboardValue: true }),
+ unmanagedField({ section: 'api', configPath: 'api.enabled', dashboardValue: true }),
+ ])
+
+ expect(groups.map((group) => group.section)).toEqual(['api', 'storage'])
+ })
+
+ it('formats an empty-value field as "Not set"', () => {
+ const groups = groupUnmanagedConfigFields([
+ unmanagedField({ configPath: 'auth.site_url', section: 'auth', dashboardValue: undefined }),
+ ])
+
+ expect(groups[0].rows[0].value).toBe('Not set')
+ })
+
+ it('joins a normalized redirect URL list with newlines', () => {
+ const groups = groupUnmanagedConfigFields([
+ unmanagedField({
+ section: 'auth',
+ configPath: 'auth.additional_redirect_urls',
+ dashboardValue: ['https://b.com', ' https://a.com ', 'https://a.com'],
+ }),
+ ])
+
+ expect(groups[0].rows[0].value).toBe('https://a.com\nhttps://b.com')
+ })
+})
diff --git a/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.utils.ts b/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.utils.ts
new file mode 100644
index 00000000000..f032e33a5f2
--- /dev/null
+++ b/apps/studio/components/interfaces/ConfigDrift/ConfigurationDriftPage.utils.ts
@@ -0,0 +1,297 @@
+import {
+ type GitHubConfigDriftField,
+ type UnmanagedConfigField,
+} from '@/components/interfaces/ConfigDrift/github-config-drift'
+import {
+ CONFIG_SECTIONS,
+ normalizeRedirectUrls,
+ type ConfigSection,
+} from '@/components/interfaces/ConfigDrift/github-config-field-registry'
+
+/** Keyed by config.toml path — the single identifier a drifted or unmanaged field carries. */
+const FIELD_LABELS: Record<string, string> = {
+ 'auth.enable_signup': 'New user signups',
+ 'auth.enable_anonymous_sign_ins': 'Anonymous sign-ins',
+ 'auth.enable_manual_linking': 'Manual account linking',
+ 'auth.site_url': 'Site URL',
+ 'auth.additional_redirect_urls': 'Redirect URLs',
+ 'auth.email.enable_signup': 'Email signups',
+ 'auth.sms.enable_signup': 'Phone signups',
+ 'auth.email.enable_confirmations': 'Email confirmations',
+ 'auth.email.double_confirm_changes': 'Secure email change',
+ 'auth.email.otp_length': 'Email OTP length',
+ 'auth.email.otp_expiry': 'Email OTP expiry',
+ 'auth.minimum_password_length': 'Minimum password length',
+ 'auth.password_requirements': 'Password requirements',
+ 'auth.sms.provider': 'SMS provider',
+ 'auth.sms.enable_confirmations': 'SMS confirmations',
+ 'auth.sms.otp_expiry': 'SMS OTP expiry',
+ 'auth.sms.otp_length': 'SMS OTP length',
+ 'auth.sms.template': 'SMS template',
+ 'api.max_rows': 'Max rows',
+ 'storage.file_size_limit': 'File size limit',
+ 'api.enabled': 'API enabled',
+ 'api.port': 'API port',
+ 'api.schemas': 'Exposed schemas',
+ 'api.extra_search_path': 'Extra search path',
+ 'api.tls.enabled': 'Enforce TLS',
+ 'db.port': 'Database port',
+ 'db.shadow_port': 'Shadow database port',
+ 'db.major_version': 'Postgres major version',
+ 'db.pooler.enabled': 'Connection pooler enabled',
+ 'db.pooler.port': 'Pooler port',
+ 'db.pooler.pool_mode': 'Pool mode',
+ 'db.pooler.default_pool_size': 'Default pool size',
+ 'db.pooler.max_client_conn': 'Max client connections',
+ 'db.migrations.enabled': 'Migrations enabled',
+ 'db.migrations.schema_paths': 'Migration schema paths',
+ 'db.seed.enabled': 'Seed enabled',
+ 'db.seed.sql_paths': 'Seed file paths',
+ 'db.network_restrictions.enabled': 'Network restrictions enabled',
+ 'db.network_restrictions.allowed_cidrs': 'Allowed CIDRs (IPv4)',
+ 'db.network_restrictions.allowed_cidrs_v6': 'Allowed CIDRs (IPv6)',
+ 'realtime.enabled': 'Realtime enabled',
+ 'studio.enabled': 'Studio enabled',
+ 'studio.port': 'Studio port',
+ 'studio.api_url': 'Studio API URL',
+ 'inbucket.enabled': 'Inbucket enabled',
+ 'inbucket.port': 'Inbucket port',
+ 'storage.enabled': 'Storage enabled',
+ 'storage.s3_protocol.enabled': 'S3 protocol enabled',
+ 'storage.analytics.enabled': 'Storage analytics enabled',
+ 'storage.analytics.max_namespaces': 'Max analytics namespaces',
+ 'storage.analytics.max_tables': 'Max analytics tables',
+ 'storage.analytics.max_catalogs': 'Max analytics catalogs',
+ 'storage.vector.enabled': 'Storage vector enabled',
+ 'storage.vector.max_buckets': 'Max vector buckets',
+ 'storage.vector.max_indexes': 'Max vector indexes',
+ 'auth.enabled': 'Auth enabled',
+ 'auth.jwt_expiry': 'JWT expiry',
+ 'auth.enable_refresh_token_rotation': 'Refresh token rotation',
+ 'auth.refresh_token_reuse_interval': 'Refresh token reuse interval',
+ 'auth.rate_limit.email_sent': 'Email rate limit',
+ 'auth.rate_limit.sms_sent': 'SMS rate limit',
+ 'auth.rate_limit.anonymous_users': 'Anonymous sign-in rate limit',
+ 'auth.rate_limit.token_refresh': 'Token refresh rate limit',
+ 'auth.rate_limit.sign_in_sign_ups': 'Sign-in/sign-up rate limit',
+ 'auth.rate_limit.token_verifications': 'Token verification rate limit',
+ 'auth.rate_limit.web3': 'Web3 rate limit',
+ 'auth.email.secure_password_change': 'Secure email change',
+ 'auth.email.max_frequency': 'Email send frequency limit',
+ 'auth.sms.max_frequency': 'SMS send frequency limit',
+ 'auth.sms.twilio.enabled': 'Twilio enabled',
+ 'auth.mfa.max_enrolled_factors': 'Max enrolled MFA factors',
+ 'auth.mfa.totp.enroll_enabled': 'TOTP enrollment',
+ 'auth.mfa.totp.verify_enabled': 'TOTP verification',
+ 'auth.mfa.phone.enroll_enabled': 'Phone MFA enrollment',
+ 'auth.mfa.phone.verify_enabled': 'Phone MFA verification',
+ 'auth.mfa.phone.otp_length': 'Phone MFA OTP length',
+ 'auth.mfa.phone.template': 'Phone MFA template',
+ 'auth.mfa.phone.max_frequency': 'Phone MFA send frequency limit',
+ 'auth.web3.solana.enabled': 'Solana Web3 enabled',
+ 'auth.oauth_server.enabled': 'OAuth server enabled',
+ 'auth.oauth_server.authorization_url_path': 'OAuth authorization URL path',
+ 'auth.oauth_server.allow_dynamic_registration': 'Allow dynamic client registration',
+ 'edge_runtime.enabled': 'Edge runtime enabled',
+ 'edge_runtime.policy': 'Edge runtime policy',
+ 'edge_runtime.inspector_port': 'Edge runtime inspector port',
+ 'edge_runtime.deno_version': 'Deno version',
+ 'analytics.enabled': 'Analytics enabled',
+ 'analytics.port': 'Analytics port',
+ 'analytics.backend': 'Analytics backend',
+ 'experimental.orioledb_version': 'OrioleDB version',
+ 'experimental.s3_host': 'S3 host',
+ 'experimental.s3_region': 'S3 region',
+ 'experimental.s3_access_key': 'S3 access key',
+ 'experimental.s3_secret_key': 'S3 secret key',
+}
+
+/** config.toml path of the redirect URL list, which renders as an added/removed diff, not a scalar. */
+const REDIRECT_URLS_CONFIG_PATH = 'auth.additional_redirect_urls'
+
+const CONFIG_KEY_LABELS: Record<string, string> = {
+ client_id: 'Client ID',
+ email_optional: 'Email optional',
+ enabled: 'Enabled',
+ redirect_uri: 'Redirect URI',
+ skip_nonce_check: 'Skip nonce check',
+ url: 'URL',
+}
+
+const PROVIDER_LABELS: Record<string, string> = {
+ apple: 'Apple',
+ azure: 'Azure',
+ bitbucket: 'Bitbucket',
+ discord: 'Discord',
+ facebook: 'Facebook',
+ figma: 'Figma',
+ github: 'GitHub',
+ gitlab: 'GitLab',
+ google: 'Google',
+ kakao: 'Kakao',
+ keycloak: 'Keycloak',
+ linkedin_oidc: 'LinkedIn (OIDC)',
+ notion: 'Notion',
+ slack_oidc: 'Slack (OIDC)',
+ spotify: 'Spotify',
+ twitch: 'Twitch',
+ workos: 'WorkOS',
+ zoom: 'Zoom',
+}
+
+const CONFIG_SECTION_LABELS: Record<ConfigSection, string> = {
+ api: 'API',
+ auth: 'Auth',
+ db: 'Database',
+ storage: 'Storage',
+ realtime: 'Realtime',
+ studio: 'Studio',
+ inbucket: 'Inbucket',
+ functions: 'Edge Functions',
+ edge_runtime: 'Edge Runtime',
+ analytics: 'Analytics',
+ remotes: 'Remotes',
+ experimental: 'Experimental',
+}
+
+interface ConfigurationIssueRowMeta {
+ settingLabel: string
+ settingHref: string
+ valueDiff: ConfigurationDriftValueDiff
+}
+
+export type ConfigurationDriftRow = Omit<GitHubConfigDriftField, 'settingHref'> &
+ ConfigurationIssueRowMeta & { status: 'drifted' }
+
+type ConfigurationDriftValueDiff =
+ | {
+ kind: 'list'
+ onlyInDashboard: string[]
+ onlyInConfig: string[]
+ }
+ | {
+ kind: 'scalar'
+ dashboardValue: string
+ configValue: string
+ }
+
+interface UnmanagedConfigRow {
+ configPath: string
+ label: string
+ value: string
+}
+
+export interface UnmanagedConfigSectionGroup {
+ section: ConfigSection
+ sectionLabel: string
+ rows: UnmanagedConfigRow[]
+}
+
+export function createConfigurationDriftRows(
+ fields: GitHubConfigDriftField[],
+ projectRef: string
+): ConfigurationDriftRow[] {
+ return fields.map((field) => ({
+ ...field,
+ status: 'drifted' as const,
+ settingLabel: getConfigFieldLabel(field.configPath),
+ settingHref: field.settingHref(projectRef),
+ valueDiff: createConfigurationDriftValueDiff(field),
+ }))
+}
+
+export function groupUnmanagedConfigFields(
+ fields: readonly UnmanagedConfigField[]
+): UnmanagedConfigSectionGroup[] {
+ const bySection = new Map<ConfigSection, UnmanagedConfigRow[]>()
+
+ for (const field of fields) {
+ const rows = bySection.get(field.section) ?? []
+ rows.push({
+ configPath: field.configPath,
+ label: getConfigFieldLabel(field.configPath),
+ value: formatConfigFieldValue(field.configPath, field.dashboardValue),
+ })
+ bySection.set(field.section, rows)
+ }
+
+ return CONFIG_SECTIONS.filter((section) => bySection.has(section)).map((section) => ({
+ section,
+ sectionLabel: CONFIG_SECTION_LABELS[section],
+ rows: bySection.get(section)!,
+ }))
+}
+
+function formatConfigFieldValue(configPath: string, value: unknown): string {
+ const normalizedValue =
+ configPath === REDIRECT_URLS_CONFIG_PATH ? normalizeRedirectUrls(value) : value
+
+ if (normalizedValue === undefined || normalizedValue === null || normalizedValue === '') {
+ return 'Not set'
+ }
+ if (Array.isArray(normalizedValue)) {
+ return normalizedValue.length === 0
+ ? 'Not set'
+ : normalizedValue.map((item) => formatScalarValue(item)).join('\n')
+ }
+
+ return formatScalarValue(normalizedValue)
+}
+
+function createConfigurationDriftValueDiff(
+ field: GitHubConfigDriftField
+): ConfigurationDriftValueDiff {
+ if (field.configPath === REDIRECT_URLS_CONFIG_PATH) {
+ const dashboardUrls = normalizeRedirectUrls(field.dashboardValue)
+ const configUrls = normalizeRedirectUrls(field.githubValue)
+ const dashboardUrlSet = new Set(dashboardUrls)
+ const configUrlSet = new Set(configUrls)
+
+ return {
+ kind: 'list',
+ onlyInDashboard: dashboardUrls.filter((url) => !configUrlSet.has(url)),
+ onlyInConfig: configUrls.filter((url) => !dashboardUrlSet.has(url)),
+ }
+ }
+
+ return {
+ kind: 'scalar',
+ dashboardValue: formatConfigFieldValue(field.configPath, field.dashboardValue),
+ configValue: formatConfigFieldValue(field.configPath, field.githubValue),
+ }
+}
+
+/**
+ * Prefers a hand-written label, then the `auth.external.<provider>.<key>` shape, and otherwise
+ * title-cases the last path segment — never the whole path, which would leave the dots in.
+ */
+function getConfigFieldLabel(configPath: string): string {
+ const staticLabel = FIELD_LABELS[configPath]
+ if (staticLabel) return staticLabel
+
+ const [, section, provider, configKey] = configPath.split('.')
+ if (section === 'external' && provider && configKey) {
+ return `${formatProviderLabel(provider)} · ${CONFIG_KEY_LABELS[configKey] ?? titleCase(configKey)}`
+ }
+
+ return titleCase(configPath.split('.').at(-1) ?? configPath)
+}
+
+function formatScalarValue(value: unknown): string {
+ if (typeof value === 'string') return value || 'Not set'
+ if (typeof value === 'boolean') return value ? 'Enabled' : 'Disabled'
+ if (typeof value === 'number') return String(value)
+ return JSON.stringify(value, null, 2) ?? 'Not set'
+}
+
+function formatProviderLabel(provider: string): string {
+ return PROVIDER_LABELS[provider] ?? titleCase(provider)
+}
+
+function titleCase(value: string): string {
+ return value
+ .split('_')
+ .filter(Boolean)
+ .map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1).toLowerCase()}`)
+ .join(' ')
+}
diff --git a/apps/studio/components/interfaces/ConfigDrift/github-config-convert.test.ts b/apps/studio/components/interfaces/ConfigDrift/github-config-convert.test.ts
new file mode 100644
index 00000000000..1109e66367d
--- /dev/null
+++ b/apps/studio/components/interfaces/ConfigDrift/github-config-convert.test.ts
@@ -0,0 +1,177 @@
+import { describe, expect, it } from 'vitest'
+
+import { convertProjectConfigToGitHubConfig } from './github-config-convert'
+
+describe('convertProjectConfigToGitHubConfig', () => {
+ it('returns an empty object when no dashboard config is provided', () => {
+ expect(convertProjectConfigToGitHubConfig()).toEqual({})
+ })
+
+ it('maps registered fields onto their nested config.toml path', () => {
+ const result = convertProjectConfigToGitHubConfig({
+ auth: {
+ site_url: 'https://example.com',
+ disable_signup: false,
+ mailer_otp_length: 6,
+ },
+ api: {
+ max_rows: 1000,
+ },
+ })
+
+ expect(result).toEqual({
+ auth: {
+ site_url: 'https://example.com',
+ enable_signup: true,
+ email: { otp_length: 6 },
+ },
+ api: { max_rows: 1000 },
+ })
+ })
+
+ it('inverts booleans that config.toml expresses the opposite way', () => {
+ const result = convertProjectConfigToGitHubConfig({
+ auth: { disable_signup: true },
+ })
+
+ expect(result).toEqual({ auth: { enable_signup: false } })
+ })
+
+ it('omits fields it has no conversion mapping for, secret-named or not', () => {
+ const result = convertProjectConfigToGitHubConfig({
+ auth: {
+ sms_twilio_auth_token: 'super-secret',
+ some_unregistered_field: 'value',
+ },
+ })
+
+ expect(result).toEqual({})
+ })
+
+ it('skips sections that are absent from the dashboard config', () => {
+ const result = convertProjectConfigToGitHubConfig({ database: { some_field: 'x' } })
+ expect(result).toEqual({})
+ })
+
+ describe('auth.additional_redirect_urls', () => {
+ it('splits the comma-separated list, then dedupes, trims and sorts it', () => {
+ const result = convertProjectConfigToGitHubConfig({
+ auth: { uri_allow_list: 'https://b.com, https://a.com ,https://b.com' },
+ })
+
+ expect(result).toEqual({
+ auth: { additional_redirect_urls: ['https://a.com', 'https://b.com'] },
+ })
+ })
+
+ it('maps an empty list to an empty array, not to an absent field', () => {
+ const result = convertProjectConfigToGitHubConfig({ auth: { uri_allow_list: '' } })
+
+ expect(result).toEqual({ auth: { additional_redirect_urls: [] } })
+ })
+
+ it('omits the field when the dashboard has no list at all', () => {
+ const result = convertProjectConfigToGitHubConfig({ auth: { site_url: 'https://a.com' } })
+
+ expect(result).toEqual({ auth: { site_url: 'https://a.com' } })
+ })
+ })
+
+ it('leaves order-sensitive comma lists in their original order', () => {
+ // Only the redirect allow-list is a set — `extra_search_path` order is meaningful to Postgres.
+ const result = convertProjectConfigToGitHubConfig({
+ api: { db_extra_search_path: 'public, extensions, auth' },
+ })
+
+ expect(result).toEqual({ api: { extra_search_path: ['public', 'extensions', 'auth'] } })
+ })
+
+ describe('db.network_restrictions', () => {
+ it('derives enabled from status and splits allowed CIDRs by type', () => {
+ const result = convertProjectConfigToGitHubConfig({
+ database: {
+ network_restrictions: {
+ status: 'applied',
+ allowed_cidrs: [
+ { type: 'v4', address: '10.0.0.0/24' },
+ { type: 'v6', address: '::1/128' },
+ ],
+ },
+ },
+ })
+
+ expect(result).toEqual({
+ db: {
+ network_restrictions: {
+ enabled: true,
+ allowed_cidrs: ['10.0.0.0/24'],
+ allowed_cidrs_v6: ['::1/128'],
+ },
+ },
+ })
+ })
+ })
+
+ describe('db.pooler', () => {
+ it('maps the top-level dashboard pooler section under db.pooler', () => {
+ const result = convertProjectConfigToGitHubConfig({
+ pooler: { pool_mode: 'transaction', default_pool_size: 20, max_client_conn: 100 },
+ })
+
+ expect(result).toEqual({
+ db: { pooler: { pool_mode: 'transaction', default_pool_size: 20, max_client_conn: 100 } },
+ })
+ })
+ })
+
+ describe('storage', () => {
+ it('maps file_size_limit and renames feature flags onto their config.toml fields', () => {
+ const result = convertProjectConfigToGitHubConfig({
+ storage: {
+ file_size_limit: 52428800,
+ features: {
+ s3_protocol: { enabled: true },
+ iceberg_catalog: {
+ enabled: true,
+ max_namespaces: 10,
+ max_tables: 100,
+ max_catalogs: 5,
+ },
+ vector_buckets: { enabled: false, max_buckets: 2, max_indexes: 4 },
+ },
+ },
+ })
+
+ expect(result).toEqual({
+ storage: {
+ file_size_limit: 52428800,
+ s3_protocol: { enabled: true },
+ analytics: { enabled: true, max_namespaces: 10, max_tables: 100, max_catalogs: 5 },
+ vector: { enabled: false, max_buckets: 2, max_indexes: 4 },
+ },
+ })
+ })
+ })
+
+ describe('auth.password_requirements', () => {
+ it('maps NO_REQUIRED_CHARS and null to an empty string', () => {
+ expect(
+ convertProjectConfigToGitHubConfig({
+ auth: { password_required_characters: 'NO_REQUIRED_CHARS' },
+ })
+ ).toEqual({ auth: { password_requirements: '' } })
+
+ expect(
+ convertProjectConfigToGitHubConfig({ auth: { password_required_characters: null } })
+ ).toEqual({ auth: { password_requirements: '' } })
+ })
+
+ it('passes through any other value unchanged', () => {
+ const result = convertProjectConfigToGitHubConfig({
+ auth: { password_required_characters: 'abcdefgABCDEFG01234' },
+ })
+
+ expect(result).toEqual({ auth: { password_requirements: 'abcdefgABCDEFG01234' } })
+ })
+ })
+})
diff --git a/apps/studio/components/interfaces/ConfigDrift/github-config-convert.ts b/apps/studio/components/interfaces/ConfigDrift/github-config-convert.ts
new file mode 100644
index 00000000000..98682237699
--- /dev/null
+++ b/apps/studio/components/interfaces/ConfigDrift/github-config-convert.ts
@@ -0,0 +1,350 @@
+import {
+ EXTERNAL_AUTH_PROVIDERS,
+ EXTERNAL_AUTH_PROVIDERS_WITH_URL,
+ normalizeRedirectUrls,
+ type ConfigDriftDashboardConfig,
+} from './github-config-field-registry'
+import { type GitHubConfigToml } from './github-config.types'
+
+/**
+ * Reshapes a project's dashboard config (sections keyed by section name, fields in their
+ * dashboard-native naming, e.g. from `GET /v1/projects/:ref/config`) into the nested, dotted-path
+ * shape of a parsed config.toml.
+ *
+ * Not every dashboard field has a config.toml counterpart — untracked fields are simply never read
+ * here. See the comments throughout for renames/inversions/unit conversions and for fields that
+ * were deliberately left out because config.toml has no equivalent.
+ */
+export function convertProjectConfigToGitHubConfig(
+ dashboardConfig?: ConfigDriftDashboardConfig
+): GitHubConfigToml {
+ if (!dashboardConfig) return {}
+
+ const database = dashboardConfig.database
+
+ const config: GitHubConfigToml = {
+ db: {
+ network_restrictions: convertNetworkRestrictions(database?.network_restrictions),
+ pooler: convertPooler(dashboardConfig.pooler),
+ },
+ api: convertApi(dashboardConfig.api),
+ auth: convertAuth(dashboardConfig.auth),
+ storage: convertStorage(dashboardConfig.storage),
+ // realtime: gitHubConfigTomlSchema only models `realtime.enabled`, and the dashboard's realtime
+ // section (private_only, max_concurrent_users, max_events_per_second, ...) never provides one —
+ // there is nothing to map.
+ }
+ // database.ssl_enforced: dashboard-only security toggle, not managed via config.toml
+ // database.postgres_settings: user-set Postgres GUC overrides, applied directly to the database
+ // rather than declared in config.toml
+
+ return pruneUndefined(config) ?? {}
+}
+
+/**
+ * Every convertX helper always returns every field it knows about, most of them `undefined` when
+ * the source dashboard config didn't have that value. Recursively drop `undefined` leaves and the
+ * empty objects left behind, so callers only see the fields that actually had a value.
+ */
+function pruneUndefined<T>(value: T): T | undefined {
+ if (value === undefined || Array.isArray(value) || typeof value !== 'object' || value === null) {
+ return value === undefined ? undefined : value
+ }
+
+ const result: Record<string, unknown> = {}
+ for (const [key, nestedValue] of Object.entries(value)) {
+ const pruned = pruneUndefined(nestedValue)
+ if (pruned !== undefined) result[key] = pruned
+ }
+
+ return Object.keys(result).length > 0 ? (result as T) : undefined
+}
+
+function convertNetworkRestrictions(
+ value: unknown
+): NonNullable<NonNullable<GitHubConfigToml['db']>['network_restrictions']> | undefined {
+ const restrictions = asRecord(value)
+ if (!restrictions) return undefined
+
+ const cidrs = Array.isArray(restrictions.allowed_cidrs) ? restrictions.allowed_cidrs : undefined
+ const addressesOfType = (type: string) =>
+ cidrs
+ ?.map((cidr) => asRecord(cidr))
+ .filter((cidr): cidr is Record<string, unknown> => cidr?.type === type)
+ .map((cidr) => asString(cidr.address))
+ .filter((address): address is string => address !== undefined)
+
+ return {
+ // dashboard has no single boolean — derived from `status === 'applied'`. `entitlement` (plan
+ // gating) and `status` (rollout state) have no config.toml equivalent.
+ enabled: restrictions.status === undefined ? undefined : restrictions.status === 'applied',
+ allowed_cidrs: addressesOfType('v4'),
+ allowed_cidrs_v6: addressesOfType('v6'),
+ }
+}
+
+function convertPooler(
+ value: unknown
+): NonNullable<NonNullable<GitHubConfigToml['db']>['pooler']> | undefined {
+ // dashboard's "pooler" is a top-level section; config.toml nests it under `db.pooler`
+ const pooler = asRecord(value)
+ if (!pooler) return undefined
+
+ return {
+ pool_mode: asString(pooler.pool_mode),
+ default_pool_size: asNumber(pooler.default_pool_size),
+ max_client_conn: asNumber(pooler.max_client_conn),
+ // ignore_startup_parameters, server_idle_timeout, server_lifetime, query_wait_timeout,
+ // reserve_pool_size: Supavisor-only settings, no config.toml field.
+ }
+}
+
+function convertApi(value: unknown): GitHubConfigToml['api'] {
+ const api = asRecord(value)
+ if (!api) return undefined
+
+ return {
+ max_rows: asNumber(api.max_rows),
+ schemas: splitCommaList(api.db_schema),
+ extra_search_path: splitCommaList(api.db_extra_search_path),
+ // db_pool, db_pool_acquisition_timeout: no config.toml field.
+ }
+}
+
+function convertAuth(value: unknown): GitHubConfigToml['auth'] {
+ const auth = asRecord(value)
+ if (!auth) return undefined
+
+ return {
+ site_url: asString(auth.site_url),
+ // uri_allow_list is a comma-separated string on the dashboard; config.toml wants a string[]
+ additional_redirect_urls: convertRedirectUrls(auth.uri_allow_list),
+ jwt_expiry: asNumber(auth.jwt_exp),
+ // disable_signup -> enable_signup (inverted boolean)
+ enable_signup: invertBoolean(auth.disable_signup),
+ enable_manual_linking: asBoolean(auth.security_manual_linking_enabled),
+ // refresh_token_rotation_enabled -> enable_refresh_token_rotation (renamed)
+ enable_refresh_token_rotation: asBoolean(auth.refresh_token_rotation_enabled),
+ // security_refresh_token_reuse_interval -> refresh_token_reuse_interval (renamed)
+ refresh_token_reuse_interval: asNumber(auth.security_refresh_token_reuse_interval),
+ minimum_password_length: asNumber(auth.password_min_length),
+ password_requirements: normalizePasswordRequirements(auth.password_required_characters),
+ enable_anonymous_sign_ins: asBoolean(auth.external_anonymous_users_enabled),
+ rate_limit: convertAuthRateLimit(auth),
+ email: convertAuthEmail(auth),
+ sms: convertAuthSms(auth),
+ mfa: convertAuthMfa(auth),
+ external: convertAuthExternalProviders(auth),
+ // external_web3_solana_enabled -> web3.solana.enabled; external_web3_ethereum_enabled has no
+ // config.toml field (schema only models solana)
+ web3: { solana: { enabled: asBoolean(auth.external_web3_solana_enabled) } },
+ oauth_server: {
+ enabled: asBoolean(auth.oauth_server_enabled),
+ allow_dynamic_registration: asBoolean(auth.oauth_server_allow_dynamic_registration),
+ // oauth_server_authorization_path -> authorization_url_path (renamed)
+ authorization_url_path: asString(auth.oauth_server_authorization_path),
+ },
+ // api_max_request_duration, db_max_pool_size(_unit), security_update_password_require_*,
+ // audit_log_disable_postgres, sessions_*, hook_*_enabled/uri (secrets are always excluded
+ // regardless), nimbus_oauth_client_id, mailer_allow_unverified_email_sign_ins,
+ // mailer_notifications_*, password_hibp_enabled, saml_*, security_sb_forwarded_for_enabled,
+ // security_captcha_*, sms_test_otp(_valid_until), index_worker_ensure_user_search_indexes_exist,
+ // custom_oauth_enabled/max_providers, mailer_subjects_custom_contents,
+ // mailer_templates_custom_contents: none of these have a gitHubConfigTomlSchema field.
+ }
+}
+
+function normalizePasswordRequirements(value: unknown): string | undefined {
+ if (value === null || value === 'NO_REQUIRED_CHARS') return ''
+ return asString(value)
+}
+
+function convertAuthRateLimit(
+ auth: Record<string, unknown>
+): NonNullable<GitHubConfigToml['auth']>['rate_limit'] {
+ return {
+ email_sent: asNumber(auth.rate_limit_email_sent),
+ sms_sent: asNumber(auth.rate_limit_sms_sent),
+ anonymous_users: asNumber(auth.rate_limit_anonymous_users),
+ token_refresh: asNumber(auth.rate_limit_token_refresh),
+ web3: asNumber(auth.rate_limit_web3),
+ // Confirmed against the Auth service source (supabase/auth#2090): the dashboard's
+ // RATE_LIMIT_VERIFY backs "rate limit for token verifications" and RATE_LIMIT_OTP backs
+ // "rate limit for sign ups and sign ins", despite the naming mismatch.
+ token_verifications: asNumber(auth.rate_limit_verify),
+ sign_in_sign_ups: asNumber(auth.rate_limit_otp),
+ }
+}
+
+function convertAuthEmail(
+ auth: Record<string, unknown>
+): NonNullable<GitHubConfigToml['auth']>['email'] {
+ return {
+ enable_signup: asBoolean(auth.external_email_enabled),
+ // mailer_autoconfirm -> enable_confirmations (inverted boolean)
+ enable_confirmations: invertBoolean(auth.mailer_autoconfirm),
+ double_confirm_changes: asBoolean(auth.mailer_secure_email_change_enabled),
+ otp_length: asNumber(auth.mailer_otp_length),
+ otp_expiry: asNumber(auth.mailer_otp_exp),
+ // smtp_max_frequency is seconds on the dashboard vs. a duration string ("1m") in config.toml —
+ // needs a number -> duration-string conversion, not done here. smtp_pass is a secret, excluded.
+ // template subjects/content: dashboard stores literal subject/HTML, config.toml stores
+ // `{ subject, content_path }` where content_path is a file path — not convertible without
+ // writing the HTML to disk.
+ }
+}
+
+function convertAuthSms(
+ auth: Record<string, unknown>
+): NonNullable<GitHubConfigToml['auth']>['sms'] {
+ return {
+ provider: asString(auth.sms_provider),
+ // sms_autoconfirm -> enable_confirmations (inverted boolean)
+ enable_confirmations: invertBoolean(auth.sms_autoconfirm),
+ otp_expiry: asNumber(auth.sms_otp_exp),
+ otp_length: asNumber(auth.sms_otp_length),
+ template: asString(auth.sms_template),
+ // sms_max_frequency is seconds on the dashboard vs. a duration string in config.toml — needs
+ // conversion, not done here.
+ twilio: {
+ account_sid: asStringOrNull(auth.sms_twilio_account_sid),
+ message_service_sid: asStringOrNull(auth.sms_twilio_message_service_sid),
+ content_sid: asStringOrNull(auth.sms_twilio_content_sid),
+ // auth_token is a secret, excluded
+ },
+ twilio_verify: {
+ account_sid: asStringOrNull(auth.sms_twilio_verify_account_sid),
+ message_service_sid: asStringOrNull(auth.sms_twilio_verify_message_service_sid),
+ // auth_token is a secret, excluded
+ },
+ messagebird: { originator: asStringOrNull(auth.sms_messagebird_originator) },
+ textlocal: { sender: asStringOrNull(auth.sms_textlocal_sender) },
+ vonage: { from: asStringOrNull(auth.sms_vonage_from) },
+ }
+}
+
+function convertAuthMfa(
+ auth: Record<string, unknown>
+): NonNullable<GitHubConfigToml['auth']>['mfa'] {
+ return {
+ max_enrolled_factors: asNumber(auth.mfa_max_enrolled_factors),
+ totp: {
+ enroll_enabled: asBoolean(auth.mfa_totp_enroll_enabled),
+ verify_enabled: asBoolean(auth.mfa_totp_verify_enabled),
+ },
+ phone: {
+ enroll_enabled: asBoolean(auth.mfa_phone_enroll_enabled),
+ verify_enabled: asBoolean(auth.mfa_phone_verify_enabled),
+ otp_length: asNumber(auth.mfa_phone_otp_length),
+ template: asString(auth.mfa_phone_template),
+ // mfa_phone_max_frequency is seconds on the dashboard vs. a duration string in config.toml —
+ // needs conversion, not done here.
+ },
+ // mfa_allow_low_aal, mfa_web_authn_enroll_enabled, mfa_web_authn_verify_enabled,
+ // passkey_enabled, webauthn_rp_*: no config.toml field.
+ }
+}
+
+function convertAuthExternalProviders(
+ auth: Record<string, unknown>
+): NonNullable<GitHubConfigToml['auth']>['external'] {
+ const providers: Record<string, Record<string, unknown>> = {}
+
+ for (const provider of EXTERNAL_AUTH_PROVIDERS) {
+ providers[provider] = {
+ enabled: asBoolean(auth[`external_${provider}_enabled`]),
+ client_id: asStringOrNull(auth[`external_${provider}_client_id`]),
+ email_optional: asBoolean(auth[`external_${provider}_email_optional`]),
+ skip_nonce_check: asBoolean(auth[`external_${provider}_skip_nonce_check`]),
+ ...(EXTERNAL_AUTH_PROVIDERS_WITH_URL.has(provider)
+ ? { url: asStringOrNull(auth[`external_${provider}_url`]) }
+ : {}),
+ }
+ }
+
+ // external_apple_additional_client_ids, external_google_additional_client_ids,
+ // external_google_skip_nonce_check: dashboard-only extensions with no config.toml field.
+
+ return providers
+}
+
+function convertStorage(value: unknown): GitHubConfigToml['storage'] {
+ const storage = asRecord(value)
+ if (!storage) return undefined
+
+ const features = asRecord(storage.features)
+ const s3Protocol = asRecord(features?.s3_protocol)
+ // features.iceberg_catalog -> analytics (renamed)
+ const icebergCatalog = asRecord(features?.iceberg_catalog)
+ // features.vector_buckets -> vector (renamed)
+ const vectorBuckets = asRecord(features?.vector_buckets)
+
+ return {
+ file_size_limit: asNumber(storage.file_size_limit),
+ s3_protocol: { enabled: asBoolean(s3Protocol?.enabled) },
+ analytics: {
+ enabled: asBoolean(icebergCatalog?.enabled),
+ max_namespaces: asNumber(icebergCatalog?.max_namespaces),
+ max_tables: asNumber(icebergCatalog?.max_tables),
+ max_catalogs: asNumber(icebergCatalog?.max_catalogs),
+ },
+ vector: {
+ enabled: asBoolean(vectorBuckets?.enabled),
+ max_buckets: asNumber(vectorBuckets?.max_buckets),
+ max_indexes: asNumber(vectorBuckets?.max_indexes),
+ },
+ // features.image_transformation.enabled, features.purge_cache.enabled: no config.toml field.
+ // capabilities.list_v2, capabilities.iceberg_catalog: read-only capability flags, not settings.
+ // upstream_target, migration_version: internal infra bookkeeping.
+ }
+}
+
+function asRecord(value: unknown): Record<string, unknown> | undefined {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : undefined
+}
+
+function asString(value: unknown): string | undefined {
+ return typeof value === 'string' ? value : undefined
+}
+
+function asStringOrNull(value: unknown): string | null | undefined {
+ return value === null ? null : asString(value)
+}
+
+function asNumber(value: unknown): number | undefined {
+ return typeof value === 'number' ? value : undefined
+}
+
+function asBoolean(value: unknown): boolean | undefined {
+ return typeof value === 'boolean' ? value : undefined
+}
+
+function invertBoolean(value: unknown): boolean | undefined {
+ const bool = asBoolean(value)
+ return bool === undefined ? undefined : !bool
+}
+
+/**
+ * Unlike the other comma-separated lists (`api.schemas`, `api.extra_search_path`) whose order is
+ * meaningful, a redirect allow-list is a set. Dedupe and sort it here so a list that differs from
+ * config.toml only in ordering isn't reported as drift — `getConfigFieldState` compares with
+ * `JSON.stringify`, which is order-sensitive.
+ */
+function convertRedirectUrls(value: unknown): string[] | undefined {
+ const urls = splitCommaList(value)
+ if (urls === undefined) return undefined
+
+ return normalizeRedirectUrls(urls)
+}
+
+function splitCommaList(value: unknown): string[] | undefined {
+ const raw = asString(value)
+ if (raw === undefined) return undefined
+ if (raw.trim() === '') return []
+ return raw
+ .split(',')
+ .map((entry) => entry.trim())
+ .filter(Boolean)
+}
diff --git a/apps/studio/components/interfaces/ConfigDrift/github-config-drift.test.ts b/apps/studio/components/interfaces/ConfigDrift/github-config-drift.test.ts
new file mode 100644
index 00000000000..276acb239b4
--- /dev/null
+++ b/apps/studio/components/interfaces/ConfigDrift/github-config-drift.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it } from 'vitest'
+
+import { getConfigDriftSummary } from './github-config-drift'
+
+describe('getConfigDriftSummary', () => {
+ it('counts a matching field as managed', () => {
+ const summary = getConfigDriftSummary({
+ dashboardConfig: { api: { max_rows: 1000 } },
+ githubConfig: { api: { max_rows: 1000 } },
+ })
+
+ expect(summary).toEqual({ managedCount: 1, driftedFields: [], unmanagedFields: [] })
+ })
+
+ it('reports a differing field as drifted, keeping raw (non-normalized) display values', () => {
+ const summary = getConfigDriftSummary({
+ dashboardConfig: { auth: { enable_signup: false } },
+ githubConfig: { auth: { enable_signup: true } },
+ })
+
+ expect(summary.managedCount).toBe(0)
+ expect(summary.driftedFields).toEqual([
+ {
+ section: 'auth',
+ configPath: 'auth.enable_signup',
+ settingHref: expect.any(Function),
+ dashboardValue: false,
+ githubValue: true,
+ },
+ ])
+ })
+
+ it('excludes a secret field even when dashboard and config.toml values match', () => {
+ const summary = getConfigDriftSummary({
+ dashboardConfig: { auth: { jwt_secret: 'shh' } },
+ githubConfig: { auth: { jwt_secret: 'shh' } },
+ })
+
+ expect(summary).toEqual({ managedCount: 0, driftedFields: [], unmanagedFields: [] })
+ })
+
+ it('reports a field absent from config.toml as unmanaged', () => {
+ const summary = getConfigDriftSummary({
+ dashboardConfig: { auth: { site_url: 'https://example.com' } },
+ githubConfig: { auth: {} },
+ })
+
+ expect(summary).toEqual({
+ managedCount: 0,
+ driftedFields: [],
+ unmanagedFields: [
+ { section: 'auth', configPath: 'auth.site_url', dashboardValue: 'https://example.com' },
+ ],
+ })
+ })
+
+ it('falls back to the hosted default when config.toml is code-owned and silent on the field', () => {
+ const atDefault = getConfigDriftSummary({
+ dashboardConfig: { auth: { site_url: 'http://localhost:3000' } },
+ githubConfig: { auth: {}, config_source: 'code' },
+ })
+ expect(atDefault).toEqual({
+ managedCount: 0,
+ driftedFields: [],
+ unmanagedFields: [
+ { section: 'auth', configPath: 'auth.site_url', dashboardValue: 'http://localhost:3000' },
+ ],
+ })
+
+ const drifted = getConfigDriftSummary({
+ dashboardConfig: { auth: { site_url: 'https://example.com' } },
+ githubConfig: { auth: {}, config_source: 'code' },
+ })
+ expect(drifted.driftedFields).toHaveLength(1)
+ expect(drifted.driftedFields[0].githubValue).toBe('http://localhost:3000')
+ })
+
+ describe('auth.additional_redirect_urls', () => {
+ it('counts an identical list as managed', () => {
+ const summary = getConfigDriftSummary({
+ dashboardConfig: { auth: { additional_redirect_urls: ['https://a.com', 'https://b.com'] } },
+ githubConfig: { auth: { additional_redirect_urls: ['https://a.com', 'https://b.com'] } },
+ })
+
+ expect(summary).toEqual({ managedCount: 1, driftedFields: [], unmanagedFields: [] })
+ })
+
+ it('counts a list that differs only in order as managed', () => {
+ const summary = getConfigDriftSummary({
+ // `convertProjectConfigToGitHubConfig` sorts the dashboard list and `normalizeGithubValue`
+ // sorts the config.toml one, so ordering can never register as drift.
+ dashboardConfig: { auth: { additional_redirect_urls: ['https://a.com', 'https://b.com'] } },
+ githubConfig: { auth: { additional_redirect_urls: ['https://b.com', 'https://a.com'] } },
+ })
+
+ expect(summary).toEqual({ managedCount: 1, driftedFields: [], unmanagedFields: [] })
+ })
+
+ it('ignores duplicate and untrimmed entries in config.toml', () => {
+ const summary = getConfigDriftSummary({
+ dashboardConfig: { auth: { additional_redirect_urls: ['https://a.com'] } },
+ githubConfig: {
+ auth: { additional_redirect_urls: [' https://a.com ', 'https://a.com', ''] },
+ },
+ })
+
+ expect(summary.managedCount).toBe(1)
+ expect(summary.driftedFields).toEqual([])
+ })
+
+ it('reports a list the dashboard adds to as drifted, keeping the raw dashboard list', () => {
+ const summary = getConfigDriftSummary({
+ dashboardConfig: { auth: { additional_redirect_urls: ['https://a.com', 'https://b.com'] } },
+ githubConfig: { auth: { additional_redirect_urls: ['https://a.com'] } },
+ })
+
+ expect(summary.driftedFields).toEqual([
+ {
+ section: 'auth',
+ configPath: 'auth.additional_redirect_urls',
+ settingHref: expect.any(Function),
+ dashboardValue: ['https://a.com', 'https://b.com'],
+ githubValue: ['https://a.com'],
+ },
+ ])
+ })
+
+ it('compares against the empty hosted default when code-owned config.toml is silent', () => {
+ const atDefault = getConfigDriftSummary({
+ dashboardConfig: { auth: { additional_redirect_urls: [] } },
+ githubConfig: { auth: {}, config_source: 'code' },
+ })
+ expect(atDefault.managedCount).toBe(0)
+ expect(atDefault.driftedFields).toEqual([])
+
+ const drifted = getConfigDriftSummary({
+ dashboardConfig: { auth: { additional_redirect_urls: ['https://a.com'] } },
+ githubConfig: { auth: {}, config_source: 'code' },
+ })
+ expect(drifted.driftedFields).toHaveLength(1)
+ expect(drifted.driftedFields[0].githubValue).toEqual([])
+ })
+ })
+})
diff --git a/apps/studio/components/interfaces/ConfigDrift/github-config-drift.ts b/apps/studio/components/interfaces/ConfigDrift/github-config-drift.ts
new file mode 100644
index 00000000000..7ede8c279ae
--- /dev/null
+++ b/apps/studio/components/interfaces/ConfigDrift/github-config-drift.ts
@@ -0,0 +1,141 @@
+import {
+ CONFIG_SECTIONS,
+ getConfigValue,
+ getFieldDefinition,
+ getSectionFieldEntries,
+ isSecretConfigField,
+ type ConfigSection,
+} from './github-config-field-registry'
+import { gitHubConfigTomlSchema, type GitHubConfigToml } from './github-config.types'
+
+// This file should be temporary and will be removed once we publish a "@supabase/config" package.
+
+type GitHubConfigFieldStatus = 'unmanaged' | 'managed' | 'drifted'
+
+interface GitHubConfigFieldState {
+ status: GitHubConfigFieldStatus
+ configPath?: string
+ settingHref?: (projectRef: string) => string
+ githubValue?: unknown
+}
+
+export interface GitHubConfigDriftField {
+ section: ConfigSection
+ configPath: string
+ settingHref: (projectRef: string) => string
+ dashboardValue: unknown
+ githubValue: unknown
+}
+
+export interface UnmanagedConfigField {
+ section: ConfigSection
+ configPath: string
+ dashboardValue: unknown
+}
+
+interface GitHubConfigDriftSummary {
+ managedCount: number
+ driftedFields: GitHubConfigDriftField[]
+ unmanagedFields: UnmanagedConfigField[]
+}
+
+function getConfigFieldState({
+ configPath,
+ dashboardConfig,
+ githubConfig,
+}: {
+ configPath: string
+ dashboardConfig: GitHubConfigToml
+ githubConfig?: GitHubConfigToml
+}): GitHubConfigFieldState {
+ const definition = getFieldDefinition(configPath)
+ if (!definition || !githubConfig || isSecretConfigField(definition.configPath)) {
+ return { status: 'unmanaged' }
+ }
+
+ const normalizedDashboardValue = getConfigValue(dashboardConfig, definition.configPath)
+
+ let githubValue = getConfigValue(githubConfig, definition.configPath)
+ if (githubValue === undefined) {
+ const isCodeOwned = getConfigValue(githubConfig, 'config_source') === 'code'
+ if (!isCodeOwned || definition.hostedDefault === undefined) return { status: 'unmanaged' }
+
+ const normalizedDefaultValue =
+ definition.normalizeGithubValue?.(definition.hostedDefault) ?? definition.hostedDefault
+ if (valuesMatch(normalizedDashboardValue, normalizedDefaultValue)) {
+ return { status: 'unmanaged' }
+ }
+
+ githubValue = definition.hostedDefault
+ }
+
+ const normalizedGithubValue = definition.normalizeGithubValue?.(githubValue) ?? githubValue
+ return {
+ status: valuesMatch(normalizedDashboardValue, normalizedGithubValue) ? 'managed' : 'drifted',
+ configPath: definition.configPath,
+ settingHref: definition.settingHref,
+ githubValue,
+ }
+}
+
+export function getConfigDriftSummary({
+ dashboardConfig,
+ githubConfig,
+}: {
+ dashboardConfig?: GitHubConfigToml
+ githubConfig?: GitHubConfigToml
+}): GitHubConfigDriftSummary {
+ if (!dashboardConfig || !githubConfig) {
+ return { managedCount: 0, driftedFields: [], unmanagedFields: [] }
+ }
+
+ const githubConfigResult = gitHubConfigTomlSchema.safeParse(githubConfig)
+ const dashboardConfigResult = gitHubConfigTomlSchema.safeParse(dashboardConfig)
+ if (!githubConfigResult.success || !dashboardConfigResult.success) {
+ return { managedCount: 0, driftedFields: [], unmanagedFields: [] }
+ }
+ const cleanedGithubConfig = githubConfigResult.data
+ const cleanedDashboardConfig = dashboardConfigResult.data
+
+ let managedCount = 0
+ const driftedFields: GitHubConfigDriftField[] = []
+ const unmanagedFields: UnmanagedConfigField[] = []
+
+ for (const section of CONFIG_SECTIONS) {
+ const sectionConfig = cleanedDashboardConfig[section]
+ if (!sectionConfig) continue
+
+ for (const { configPath, rawValue } of getSectionFieldEntries(section, sectionConfig)) {
+ if (isSecretConfigField(configPath)) continue
+
+ const state = getConfigFieldState({
+ configPath,
+ dashboardConfig: cleanedDashboardConfig,
+ githubConfig: cleanedGithubConfig,
+ })
+
+ if (state.status === 'managed') {
+ managedCount += 1
+ continue
+ }
+ if (state.status === 'unmanaged' || !state.configPath || !state.settingHref) {
+ unmanagedFields.push({ section, configPath, dashboardValue: rawValue })
+ continue
+ }
+
+ driftedFields.push({
+ section,
+ configPath: state.configPath,
+ settingHref: state.settingHref,
+ dashboardValue: rawValue,
+ githubValue: state.githubValue,
+ })
+ }
+ }
+
+ return { managedCount, driftedFields, unmanagedFields }
+}
+
+function valuesMatch(left: unknown, right: unknown): boolean {
+ return JSON.stringify(left) === JSON.stringify(right)
+}
diff --git a/apps/studio/components/interfaces/ConfigDrift/github-config-field-registry.ts b/apps/studio/components/interfaces/ConfigDrift/github-config-field-registry.ts
new file mode 100644
index 00000000000..a6e55240320
--- /dev/null
+++ b/apps/studio/components/interfaces/ConfigDrift/github-config-field-registry.ts
@@ -0,0 +1,555 @@
+import { type GitHubConfigToml } from './github-config.types'
+import { StorageSizeUnits } from '@/components/interfaces/Storage/StorageSettings/StorageSettings.constants'
+import { convertToBytes } from '@/components/interfaces/Storage/StorageSettings/StorageSettings.utils'
+
+// This file should be temporary and will be removed once we publish a "@supabase/config" package.
+
+// Every top-level config.toml section, excluding `project_id` which is a scalar, not a section.
+export const CONFIG_SECTIONS = [
+ 'api',
+ 'auth',
+ 'db',
+ 'storage',
+ 'realtime',
+ 'studio',
+ 'inbucket',
+ 'functions',
+ 'edge_runtime',
+ 'analytics',
+ 'remotes',
+ 'experimental',
+] as const satisfies readonly Exclude<keyof GitHubConfigToml, 'project_id'>[]
+export type ConfigSection = (typeof CONFIG_SECTIONS)[number]
+
+// The v2 project config API's own top-level section names — distinct from `CONFIG_SECTIONS`,
+// which mirrors config.toml's naming (e.g. `pooler` here nests under config.toml's `db.pooler`).
+const DASHBOARD_CONFIG_SECTIONS = [
+ 'api',
+ 'auth',
+ 'database',
+ 'pooler',
+ 'realtime',
+ 'storage',
+] as const
+type DashboardConfigSection = (typeof DASHBOARD_CONFIG_SECTIONS)[number]
+
+export type ConfigDriftDashboardConfig = Partial<
+ Record<DashboardConfigSection, Record<string, unknown>>
+>
+
+interface ConfigFieldDefinition {
+ settingHref: (projectRef: string) => string
+ /** Value to compare against when the field is absent from a code-owned config.toml. */
+ hostedDefault?: unknown
+ normalizeGithubValue?: (value: unknown) => unknown
+}
+
+export type ResolvedConfigFieldDefinition = ConfigFieldDefinition & { configPath: string }
+
+// external_<provider>_enabled/client_id/email_optional/skip_nonce_check is the dashboard's flat
+// naming for every OAuth provider; a handful of self-hosted providers also expose `_url`.
+// external_<provider>_secret is always a secret and is never read here.
+export const EXTERNAL_AUTH_PROVIDERS = [
+ 'apple',
+ 'azure',
+ 'bitbucket',
+ 'discord',
+ 'facebook',
+ 'figma',
+ 'github',
+ 'gitlab',
+ 'google',
+ 'kakao',
+ 'keycloak',
+ 'linkedin_oidc',
+ 'notion',
+ 'slack',
+ 'slack_oidc',
+ 'spotify',
+ 'twitch',
+ 'twitter',
+ 'x',
+ 'workos',
+ 'zoom',
+] as const
+
+export const EXTERNAL_AUTH_PROVIDERS_WITH_URL = new Set(['azure', 'gitlab', 'keycloak', 'workos'])
+
+const toAuthUrlConfigHref = (projectRef: string) => `/project/${projectRef}/auth/url-configuration`
+const toAuthProvidersHref = (projectRef: string) => `/project/${projectRef}/auth/providers`
+const toApiSettingsHref = (projectRef: string) => `/project/${projectRef}/settings/api`
+const toStorageSettingsHref = (projectRef: string) =>
+ `/project/${projectRef}/storage/files/settings`
+const toProjectHref = (projectRef: string) => `/project/${projectRef}`
+
+/**
+ * Every trackable field across every section, keyed by its config.toml dotted path — the same shape
+ * `getConfigValue`/`setConfigValue` address, and the single identifier a field is known by once the
+ * dashboard config has been run through `convertProjectConfigToGitHubConfig`.
+ */
+const CONFIG_FIELD_REGISTRY: Record<string, ConfigFieldDefinition> = {
+ 'auth.enable_signup': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.enable_anonymous_sign_ins': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.enable_manual_linking': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.site_url': {
+ settingHref: toAuthUrlConfigHref,
+ hostedDefault: 'http://localhost:3000',
+ },
+ 'auth.additional_redirect_urls': {
+ settingHref: toAuthUrlConfigHref,
+ hostedDefault: [],
+ normalizeGithubValue: normalizeRedirectUrls,
+ },
+ 'auth.email.enable_signup': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.enable_signup': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.email.enable_confirmations': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.email.double_confirm_changes': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.email.otp_length': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.email.otp_expiry': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.minimum_password_length': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.password_requirements': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.provider': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.enable_confirmations': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.otp_expiry': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.otp_length': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.template': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.twilio.account_sid': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.twilio.message_service_sid': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.twilio.content_sid': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.twilio_verify.account_sid': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.twilio_verify.message_service_sid': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.messagebird.originator': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.textlocal.sender': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'auth.sms.vonage.from': {
+ settingHref: toAuthProvidersHref,
+ },
+ 'api.max_rows': {
+ settingHref: toApiSettingsHref,
+ },
+ 'storage.file_size_limit': {
+ settingHref: toStorageSettingsHref,
+ normalizeGithubValue: parseFileSizeToBytes,
+ },
+ 'api.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'api.port': {
+ settingHref: toProjectHref,
+ },
+ 'api.schemas': {
+ settingHref: toProjectHref,
+ },
+ 'api.extra_search_path': {
+ settingHref: toProjectHref,
+ },
+ 'api.tls.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'db.port': {
+ settingHref: toProjectHref,
+ },
+ 'db.shadow_port': {
+ settingHref: toProjectHref,
+ },
+ 'db.major_version': {
+ settingHref: toProjectHref,
+ },
+ 'db.pooler.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'db.pooler.port': {
+ settingHref: toProjectHref,
+ },
+ 'db.pooler.pool_mode': {
+ settingHref: toProjectHref,
+ },
+ 'db.pooler.default_pool_size': {
+ settingHref: toProjectHref,
+ },
+ 'db.pooler.max_client_conn': {
+ settingHref: toProjectHref,
+ },
+ 'db.migrations.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'db.migrations.schema_paths': {
+ settingHref: toProjectHref,
+ },
+ 'db.seed.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'db.seed.sql_paths': {
+ settingHref: toProjectHref,
+ },
+ 'db.network_restrictions.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'db.network_restrictions.allowed_cidrs': {
+ settingHref: toProjectHref,
+ },
+ 'db.network_restrictions.allowed_cidrs_v6': {
+ settingHref: toProjectHref,
+ },
+ 'realtime.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'studio.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'studio.port': {
+ settingHref: toProjectHref,
+ },
+ 'studio.api_url': {
+ settingHref: toProjectHref,
+ },
+ 'inbucket.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'inbucket.port': {
+ settingHref: toProjectHref,
+ },
+ 'storage.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'storage.s3_protocol.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'storage.analytics.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'storage.analytics.max_namespaces': {
+ settingHref: toProjectHref,
+ },
+ 'storage.analytics.max_tables': {
+ settingHref: toProjectHref,
+ },
+ 'storage.analytics.max_catalogs': {
+ settingHref: toProjectHref,
+ },
+ 'storage.vector.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'storage.vector.max_buckets': {
+ settingHref: toProjectHref,
+ },
+ 'storage.vector.max_indexes': {
+ settingHref: toProjectHref,
+ },
+ 'auth.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'auth.jwt_expiry': {
+ settingHref: toProjectHref,
+ },
+ 'auth.enable_refresh_token_rotation': {
+ settingHref: toProjectHref,
+ },
+ 'auth.refresh_token_reuse_interval': {
+ settingHref: toProjectHref,
+ },
+ 'auth.rate_limit.email_sent': {
+ settingHref: toProjectHref,
+ },
+ 'auth.rate_limit.sms_sent': {
+ settingHref: toProjectHref,
+ },
+ 'auth.rate_limit.anonymous_users': {
+ settingHref: toProjectHref,
+ },
+ 'auth.rate_limit.token_refresh': {
+ settingHref: toProjectHref,
+ },
+ 'auth.rate_limit.sign_in_sign_ups': {
+ settingHref: toProjectHref,
+ },
+ 'auth.rate_limit.token_verifications': {
+ settingHref: toProjectHref,
+ },
+ 'auth.rate_limit.web3': {
+ settingHref: toProjectHref,
+ },
+ 'auth.email.secure_password_change': {
+ settingHref: toProjectHref,
+ },
+ 'auth.email.max_frequency': {
+ settingHref: toProjectHref,
+ },
+ 'auth.sms.max_frequency': {
+ settingHref: toProjectHref,
+ },
+ 'auth.sms.twilio.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'auth.mfa.max_enrolled_factors': {
+ settingHref: toProjectHref,
+ },
+ 'auth.mfa.totp.enroll_enabled': {
+ settingHref: toProjectHref,
+ },
+ 'auth.mfa.totp.verify_enabled': {
+ settingHref: toProjectHref,
+ },
+ 'auth.mfa.phone.enroll_enabled': {
+ settingHref: toProjectHref,
+ },
+ 'auth.mfa.phone.verify_enabled': {
+ settingHref: toProjectHref,
+ },
+ 'auth.mfa.phone.otp_length': {
+ settingHref: toProjectHref,
+ },
+ 'auth.mfa.phone.template': {
+ settingHref: toProjectHref,
+ },
+ 'auth.mfa.phone.max_frequency': {
+ settingHref: toProjectHref,
+ },
+ 'auth.web3.solana.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'auth.oauth_server.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'auth.oauth_server.authorization_url_path': {
+ settingHref: toProjectHref,
+ },
+ 'auth.oauth_server.allow_dynamic_registration': {
+ settingHref: toProjectHref,
+ },
+ 'edge_runtime.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'edge_runtime.policy': {
+ settingHref: toProjectHref,
+ },
+ 'edge_runtime.inspector_port': {
+ settingHref: toProjectHref,
+ },
+ 'edge_runtime.deno_version': {
+ settingHref: toProjectHref,
+ },
+ 'analytics.enabled': {
+ settingHref: toProjectHref,
+ },
+ 'analytics.port': {
+ settingHref: toProjectHref,
+ },
+ 'analytics.backend': {
+ settingHref: toProjectHref,
+ },
+ 'experimental.orioledb_version': {
+ settingHref: toProjectHref,
+ },
+ 'experimental.s3_host': {
+ settingHref: toProjectHref,
+ },
+ 'experimental.s3_region': {
+ settingHref: toProjectHref,
+ },
+ 'experimental.s3_access_key': {
+ settingHref: toProjectHref,
+ },
+ 'experimental.s3_secret_key': {
+ settingHref: toProjectHref,
+ },
+}
+
+for (const provider of EXTERNAL_AUTH_PROVIDERS) {
+ for (const field of ['enabled', 'client_id', 'email_optional', 'skip_nonce_check']) {
+ CONFIG_FIELD_REGISTRY[`auth.external.${provider}.${field}`] = {
+ settingHref: toAuthProvidersHref,
+ }
+ }
+ if (EXTERNAL_AUTH_PROVIDERS_WITH_URL.has(provider)) {
+ CONFIG_FIELD_REGISTRY[`auth.external.${provider}.url`] = { settingHref: toAuthProvidersHref }
+ }
+}
+
+/**
+ * config.toml paths whose values are secrets — never tracked, compared, or displayed.
+ * A `*` segment matches any key at that position (e.g. every vault entry, every OAuth provider).
+ */
+const SECRET_CONFIG_FIELDS = [
+ 'studio.openai_api_key',
+ 'db.root_key',
+ 'db.vault.*',
+ 'auth.publishable_key',
+ 'auth.secret_key',
+ 'auth.jwt_secret',
+ 'auth.email.smtp.pass',
+ 'auth.captcha.secret',
+ 'auth.hook.mfa_verification_attempt.secrets',
+ 'auth.hook.password_verification_attempt.secrets',
+ 'auth.hook.custom_access_token.secrets',
+ 'auth.hook.send_sms.secrets',
+ 'auth.hook.send_email.secrets',
+ 'auth.hook.before_user_created.secrets',
+ 'auth.sms.twilio.auth_token',
+ 'auth.sms.twilio_verify.auth_token',
+ 'auth.sms.messagebird.access_key',
+ 'auth.sms.textlocal.api_key',
+ 'auth.sms.vonage.api_secret',
+ 'auth.external.*.secret',
+ 'edge_runtime.secrets.*',
+ 'experimental.s3_access_key',
+ 'experimental.s3_secret_key',
+] as const
+
+export function isSecretConfigField(configPath: string): boolean {
+ const pathSegments = configPath.split('.')
+
+ return SECRET_CONFIG_FIELDS.some((secretPath) => {
+ const secretSegments = secretPath.split('.')
+ const isPrefixPattern = secretSegments[secretSegments.length - 1] === '*'
+ if (isPrefixPattern) {
+ if (pathSegments.length < secretSegments.length) return false
+ } else if (secretSegments.length !== pathSegments.length) {
+ return false
+ }
+ return secretSegments.every((segment, i) => segment === '*' || segment === pathSegments[i])
+ })
+}
+
+export function getFieldDefinition(configPath: string): ResolvedConfigFieldDefinition | undefined {
+ const definition = CONFIG_FIELD_REGISTRY[configPath]
+ if (!definition) return undefined
+ return { ...definition, configPath }
+}
+
+/**
+ * A config section can nest fields arbitrarily deep (e.g. `storage.analytics.max_namespaces`),
+ * mirroring how deep `gitHubConfigTomlSchema` itself nests. Recurse through plain objects — but not
+ * arrays, which are leaf values — to produce one section-prefixed dotted path per leaf, matching how
+ * `CONFIG_FIELD_REGISTRY` is keyed.
+ */
+export function getSectionFieldEntries(
+ section: ConfigSection,
+ sectionConfig: Record<string, unknown>
+): Array<{ configPath: string; rawValue: unknown }> {
+ const entries: Array<{ configPath: string; rawValue: unknown }> = []
+
+ function walk(value: unknown, path: string[]) {
+ if (isRecord(value)) {
+ for (const [key, nestedValue] of Object.entries(value)) walk(nestedValue, [...path, key])
+ return
+ }
+
+ entries.push({
+ configPath: path.join('.'),
+ rawValue: value,
+ })
+ }
+
+ for (const [key, value] of Object.entries(sectionConfig)) walk(value, [section, key])
+
+ return entries
+}
+
+export function getConfigValue(config: Record<string, unknown>, configPath: string): unknown {
+ let value: unknown = config
+
+ for (const segment of configPath.split('.')) {
+ if (!isRecord(value) || !Object.prototype.hasOwnProperty.call(value, segment)) {
+ return undefined
+ }
+ value = value[segment]
+ }
+
+ return value
+}
+
+/**
+ * A redirect allow-list is a set, not a sequence: accepts either a comma-separated string or an
+ * array, and returns trimmed, deduped, sorted entries so two lists holding the same URLs compare
+ * equal regardless of how they were written.
+ */
+export function normalizeRedirectUrls(value: unknown): string[] {
+ const urls = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : []
+
+ return Array.from(
+ new Set(urls.filter((url): url is string => typeof url === 'string').map((url) => url.trim()))
+ )
+ .filter(Boolean)
+ .sort()
+}
+
+const FILE_SIZE_PATTERN = /^(\d+(?:\.\d+)?)\s*(B|KB|KIB|MB|MIB|GB|GIB)?$/i
+const FILE_SIZE_UNIT_ALIASES: Record<string, StorageSizeUnits> = {
+ B: StorageSizeUnits.BYTES,
+ KB: StorageSizeUnits.KB,
+ KIB: StorageSizeUnits.KB,
+ MB: StorageSizeUnits.MB,
+ MIB: StorageSizeUnits.MB,
+ GB: StorageSizeUnits.GB,
+ GIB: StorageSizeUnits.GB,
+}
+
+/**
+ * config.toml declares storage.file_size_limit as a human string (e.g. "50MiB"); the v2 project
+ * config returns the same setting in bytes. Parse the former so both sides compare as bytes.
+ */
+function parseFileSizeToBytes(value: unknown): unknown {
+ if (typeof value === 'number') return value
+ if (typeof value !== 'string') return value
+
+ const match = FILE_SIZE_PATTERN.exec(value.trim())
+ if (!match) return value
+
+ const [, amount, unitSuffix] = match
+ const unit = unitSuffix
+ ? FILE_SIZE_UNIT_ALIASES[unitSuffix.toUpperCase()]
+ : StorageSizeUnits.BYTES
+ if (!unit) return value
+
+ return convertToBytes(Number(amount), unit)
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
diff --git a/apps/studio/components/interfaces/ConfigDrift/github-config.types.ts b/apps/studio/components/interfaces/ConfigDrift/github-config.types.ts
new file mode 100644
index 00000000000..b943e9ba334
--- /dev/null
+++ b/apps/studio/components/interfaces/ConfigDrift/github-config.types.ts
@@ -0,0 +1,261 @@
+import { z } from 'zod'
+
+// This file should be temporary and will be removed once we publish a "@supabase/config" package.
+
+// Mirrors the shape produced by parsing a project's `supabase/config.toml`.
+// Every field is optional since config.toml sections are all opt-in, and
+// objects allow unknown keys since users can add custom sections/providers.
+export const gitHubConfigTomlSchema = z.object({
+ project_id: z.string().optional(),
+ // `code` when the config is owned by the repository, which is what lets drift detection fall back
+ // to a field's hosted default when config.toml is silent on it.
+ config_source: z.string().optional(),
+ api: z
+ .object({
+ enabled: z.boolean().optional(),
+ port: z.number().optional(),
+ schemas: z.array(z.string()).optional(),
+ extra_search_path: z.array(z.string()).optional(),
+ max_rows: z.number().optional(),
+ tls: z.object({ enabled: z.boolean().optional() }).passthrough().optional(),
+ })
+ .passthrough()
+ .optional(),
+ db: z
+ .object({
+ port: z.number().optional(),
+ shadow_port: z.number().optional(),
+ major_version: z.number().optional(),
+ pooler: z
+ .object({
+ enabled: z.boolean().optional(),
+ port: z.number().optional(),
+ pool_mode: z.string().optional(),
+ default_pool_size: z.number().optional(),
+ max_client_conn: z.number().optional(),
+ })
+ .passthrough()
+ .optional(),
+ migrations: z
+ .object({
+ enabled: z.boolean().optional(),
+ schema_paths: z.array(z.string()).optional(),
+ })
+ .passthrough()
+ .optional(),
+ seed: z
+ .object({
+ enabled: z.boolean().optional(),
+ sql_paths: z.array(z.string()).optional(),
+ })
+ .passthrough()
+ .optional(),
+ network_restrictions: z
+ .object({
+ enabled: z.boolean().optional(),
+ allowed_cidrs: z.array(z.string()).optional(),
+ allowed_cidrs_v6: z.array(z.string()).optional(),
+ })
+ .passthrough()
+ .optional(),
+ })
+ .passthrough()
+ .optional(),
+ realtime: z.object({ enabled: z.boolean().optional() }).passthrough().optional(),
+ studio: z
+ .object({
+ enabled: z.boolean().optional(),
+ port: z.number().optional(),
+ api_url: z.string().optional(),
+ openai_api_key: z.string().optional(),
+ })
+ .passthrough()
+ .optional(),
+ inbucket: z
+ .object({ enabled: z.boolean().optional(), port: z.number().optional() })
+ .passthrough()
+ .optional(),
+ storage: z
+ .object({
+ enabled: z.boolean().optional(),
+ file_size_limit: z.union([z.string(), z.number()]).optional(),
+ s3_protocol: z.object({ enabled: z.boolean().optional() }).passthrough().optional(),
+ analytics: z
+ .object({
+ enabled: z.boolean().optional(),
+ max_namespaces: z.number().optional(),
+ max_tables: z.number().optional(),
+ max_catalogs: z.number().optional(),
+ })
+ .passthrough()
+ .optional(),
+ vector: z
+ .object({
+ enabled: z.boolean().optional(),
+ max_buckets: z.number().optional(),
+ max_indexes: z.number().optional(),
+ })
+ .passthrough()
+ .optional(),
+ })
+ .passthrough()
+ .optional(),
+ auth: z
+ .object({
+ enabled: z.boolean().optional(),
+ site_url: z.string().nullable().optional(),
+ additional_redirect_urls: z.array(z.string()).optional(),
+ jwt_expiry: z.number().optional(),
+ enable_refresh_token_rotation: z.boolean().optional(),
+ refresh_token_reuse_interval: z.number().optional(),
+ enable_signup: z.boolean().optional(),
+ enable_anonymous_sign_ins: z.boolean().optional(),
+ enable_manual_linking: z.boolean().optional(),
+ minimum_password_length: z.number().optional(),
+ password_requirements: z.string().nullable().optional(),
+ rate_limit: z
+ .object({
+ email_sent: z.number().optional(),
+ sms_sent: z.number().optional(),
+ anonymous_users: z.number().optional(),
+ token_refresh: z.number().optional(),
+ sign_in_sign_ups: z.number().optional(),
+ token_verifications: z.number().optional(),
+ web3: z.number().optional(),
+ })
+ .passthrough()
+ .optional(),
+ email: z
+ .object({
+ enable_signup: z.boolean().optional(),
+ double_confirm_changes: z.boolean().optional(),
+ enable_confirmations: z.boolean().optional(),
+ secure_password_change: z.boolean().optional(),
+ max_frequency: z.string().optional(),
+ otp_length: z.number().optional(),
+ otp_expiry: z.number().optional(),
+ template: z
+ .record(
+ z.string(),
+ z
+ .object({ subject: z.string().optional(), content_path: z.string().optional() })
+ .passthrough()
+ )
+ .optional(),
+ })
+ .passthrough()
+ .optional(),
+ sms: z
+ .object({
+ enable_signup: z.boolean().optional(),
+ enable_confirmations: z.boolean().optional(),
+ template: z.string().nullable().optional(),
+ max_frequency: z.string().optional(),
+ provider: z.string().nullable().optional(),
+ twilio: z
+ .object({
+ enabled: z.boolean().optional(),
+ account_sid: z.string().nullable().optional(),
+ message_service_sid: z.string().nullable().optional(),
+ auth_token: z.string().optional(),
+ })
+ .passthrough()
+ .optional(),
+ })
+ .passthrough()
+ .optional(),
+ mfa: z
+ .object({
+ max_enrolled_factors: z.number().optional(),
+ totp: z
+ .object({
+ enroll_enabled: z.boolean().optional(),
+ verify_enabled: z.boolean().optional(),
+ })
+ .passthrough()
+ .optional(),
+ phone: z
+ .object({
+ enroll_enabled: z.boolean().optional(),
+ verify_enabled: z.boolean().optional(),
+ otp_length: z.number().optional(),
+ template: z.string().optional(),
+ max_frequency: z.string().optional(),
+ })
+ .passthrough()
+ .optional(),
+ })
+ .passthrough()
+ .optional(),
+ external: z
+ .record(
+ z.string(),
+ z
+ .object({
+ enabled: z.boolean().optional(),
+ client_id: z.string().nullable().optional(),
+ secret: z.string().nullable().optional(),
+ redirect_uri: z.string().nullable().optional(),
+ url: z.string().nullable().optional(),
+ skip_nonce_check: z.boolean().optional(),
+ email_optional: z.boolean().optional(),
+ })
+ .passthrough()
+ )
+ .optional(),
+ web3: z
+ .object({
+ solana: z.object({ enabled: z.boolean().optional() }).passthrough().optional(),
+ })
+ .passthrough()
+ .optional(),
+ third_party: z
+ .record(z.string(), z.object({ enabled: z.boolean().optional() }).passthrough())
+ .optional(),
+ oauth_server: z
+ .object({
+ enabled: z.boolean().optional(),
+ authorization_url_path: z.string().optional(),
+ allow_dynamic_registration: z.boolean().optional(),
+ })
+ .passthrough()
+ .optional(),
+ })
+ .passthrough()
+ .optional(),
+ functions: z
+ .record(z.string(), z.object({ verify_jwt: z.boolean().optional() }).passthrough())
+ .optional(),
+ edge_runtime: z
+ .object({
+ enabled: z.boolean().optional(),
+ policy: z.string().optional(),
+ inspector_port: z.number().optional(),
+ deno_version: z.number().optional(),
+ })
+ .passthrough()
+ .optional(),
+ analytics: z
+ .object({
+ enabled: z.boolean().optional(),
+ port: z.number().optional(),
+ backend: z.string().optional(),
+ })
+ .passthrough()
+ .optional(),
+ remotes: z
+ .record(z.string(), z.object({ project_id: z.string().optional() }).passthrough())
+ .optional(),
+ experimental: z
+ .object({
+ orioledb_version: z.string().optional(),
+ s3_host: z.string().optional(),
+ s3_region: z.string().optional(),
+ s3_access_key: z.string().optional(),
+ s3_secret_key: z.string().optional(),
+ })
+ .passthrough()
+ .optional(),
+})
+
+export type GitHubConfigToml = z.infer<typeof gitHubConfigTomlSchema>
diff --git a/apps/studio/components/layouts/DefaultLayout.tsx b/apps/studio/components/layouts/DefaultLayout.tsx
index 734493bb7bb..a5d920e4b97 100644
--- a/apps/studio/components/layouts/DefaultLayout.tsx
+++ b/apps/studio/components/layouts/DefaultLayout.tsx
@@ -1,4 +1,4 @@
-import { useBreakpoint, useParams } from 'common'
+import { useBreakpoint, useFlag, useParams } from 'common'
import { useRouter } from 'next/router'
import { PropsWithChildren, useEffect, useState } from 'react'
import { ResizablePanel, ResizablePanelGroup, SidebarProvider, usePanelRef } from 'ui'
@@ -16,6 +16,7 @@ import {
} from './ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { ProjectContextProvider } from './ProjectLayout/ProjectContext'
import { AppBannerWrapper } from '@/components/interfaces/App/AppBannerWrapper'
+import { GitHubConfigDriftBanner } from '@/components/interfaces/App/GitHubConfigDriftBanner'
import { Sidebar } from '@/components/interfaces/Sidebar'
import { useSyncScopedIntrospection } from '@/data/scoped-introspection'
import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganization'
@@ -54,6 +55,7 @@ export const DefaultLayout = ({
const appSnap = useAppStateSnapshot()
const { isMaximised, activeSidebar } = useSidebarManagerSnapshot()
const { lastVisitedOrganization } = useLastVisitedOrganization()
+ const showConfigDrift = useFlag('ConfigDrift') && IS_PLATFORM
const [isMounted, setIsMounted] = useState(false)
@@ -106,6 +108,7 @@ export const DefaultLayout = ({
/>
)}
<LayoutHeader headerTitle={headerTitle} backToDashboardURL={backToDashboardURL} />
+ {showConfigDrift && ref && <GitHubConfigDriftBanner />}
</div>
{/* Main Content Area */}
<div className="flex flex-1 w-full overflow-y-hidden">
diff --git a/apps/studio/components/layouts/ProjectSettingsLayout/ProjectSettings.Commands.tsx b/apps/studio/components/layouts/ProjectSettingsLayout/ProjectSettings.Commands.tsx
index 9a992684534..9755bce0b57 100644
--- a/apps/studio/components/layouts/ProjectSettingsLayout/ProjectSettings.Commands.tsx
+++ b/apps/studio/components/layouts/ProjectSettingsLayout/ProjectSettings.Commands.tsx
@@ -1,4 +1,4 @@
-import { useParams } from 'common'
+import { useFlag, useParams } from 'common'
import { useRouter } from 'next/router'
import type { CommandOptions, ICommand } from 'ui-patterns/CommandMenu'
import { useRegisterCommands, useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'
@@ -7,12 +7,14 @@ import { IRouteCommand } from 'ui-patterns/CommandMenu/internal/types'
import { COMMAND_MENU_SECTIONS } from '@/components/interfaces/App/CommandMenu/CommandMenu.utils'
import { useIsPlatformWebhooksEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
+import { IS_PLATFORM } from '@/lib/constants'
export function useProjectSettingsGotoCommands(options?: CommandOptions) {
const router = useRouter()
const setIsOpen = useSetCommandMenuOpen()
let { ref, slug } = useParams()
const platformWebhooksEnabled = useIsPlatformWebhooksEnabled()
+ const showConfigDrift = useFlag('ConfigDrift')
ref ||= '_'
const hasOrgSlug = typeof slug === 'string' && slug.length > 0 && slug !== '_'
@@ -47,6 +49,16 @@ export function useProjectSettingsGotoCommands(options?: CommandOptions) {
route: `/project/${ref}/settings/general`,
defaultHidden: true,
},
+ ...(IS_PLATFORM && showConfigDrift
+ ? [
+ {
+ id: 'nav-project-settings-code-configuration',
+ name: 'Code configuration',
+ route: `/project/${ref}/settings/code-configuration`,
+ defaultHidden: true,
+ } as IRouteCommand,
+ ]
+ : []),
{
id: 'nav-project-settings-database',
name: 'Database Settings',
@@ -191,6 +203,6 @@ export function useProjectSettingsGotoCommands(options?: CommandOptions) {
]
: []),
],
- { ...options, deps: [platformWebhooksEnabled, showLogDrains, ref, slug] }
+ { ...options, deps: [platformWebhooksEnabled, showLogDrains, showConfigDrift, ref, slug] }
)
}
diff --git a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx
index 30e693dcf53..5c5b68c8b63 100644
--- a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx
+++ b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx
@@ -14,6 +14,7 @@ export const useGenerateSettingsMenu = () => {
const { data: project, isPending } = useSelectedProjectQuery()
const { data: organization } = useSelectedOrganizationQuery()
const showDashboardPreferences = useFlag('dashboardPreferences')
+ const showConfigDrift = useFlag('ConfigDrift') && IS_PLATFORM
const platformWebhooksEnabled = useIsPlatformWebhooksEnabled()
@@ -107,6 +108,16 @@ export const useGenerateSettingsMenu = () => {
items: [],
shortcutId: SHORTCUT_IDS.NAV_PROJECT_SETTINGS_GENERAL,
},
+ ...(showConfigDrift
+ ? [
+ {
+ name: 'Code configuration',
+ key: 'code-configuration',
+ url: `/project/${ref}/settings/code-configuration`,
+ items: [],
+ },
+ ]
+ : []),
{
name: 'Infrastructure',
key: 'infrastructure',
diff --git a/apps/studio/data/config/github-config-query.ts b/apps/studio/data/config/github-config-query.ts
new file mode 100644
index 00000000000..5123a1e1517
--- /dev/null
+++ b/apps/studio/data/config/github-config-query.ts
@@ -0,0 +1,69 @@
+import { useQuery } from '@tanstack/react-query'
+import type { components } from 'api-types'
+import { z } from 'zod'
+
+import { gitHubConfigTomlSchema } from '@/components/interfaces/ConfigDrift/github-config.types'
+import { get, handleError } from '@/data/fetchers'
+import type { UseCustomQueryOptions } from '@/types'
+
+export type GitHubConfigVariables = {
+ connectionId?: number
+ branch?: string
+}
+
+type GithubConfigQueryResponse = components['schemas']['GetGitHubConnectionConfigResponse'] & {
+ config: z.infer<typeof gitHubConfigTomlSchema>
+}
+
+export const githubConfigKeys = {
+ all: ['github-config'] as const,
+ connection: (connectionId?: number, branch?: string) =>
+ [...githubConfigKeys.all, connectionId, branch] as const,
+}
+
+export async function getGitHubConfig(
+ { connectionId, branch }: GitHubConfigVariables,
+ signal?: AbortSignal
+) {
+ if (!connectionId) throw new Error('connectionId is required')
+
+ const { data, error } = await get(
+ '/platform/integrations/github/connections/{connection_id}/config',
+ {
+ params: {
+ path: { connection_id: connectionId },
+ query: { ref: branch },
+ },
+ signal,
+ }
+ )
+
+ if (error) return handleError(error)
+ const parsed = gitHubConfigTomlSchema.safeParse(data.config)
+ if (parsed.error) {
+ return handleError(
+ new Error(`Invalid response from Github config API: ${parsed.error.message}`)
+ )
+ }
+
+ return {
+ ...data,
+ config: parsed.data,
+ }
+}
+
+export const useGitHubConfigQuery = <TData = GithubConfigQueryResponse>(
+ variables: GitHubConfigVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<GithubConfigQueryResponse, Error, TData> = {}
+) =>
+ useQuery<GithubConfigQueryResponse, Error, TData>({
+ // eslint-disable-next-line @tanstack/query/exhaustive-deps
+ queryKey: githubConfigKeys.connection(variables.connectionId, variables.branch),
+ queryFn: ({ signal }) => getGitHubConfig(variables, signal),
+ enabled: enabled && typeof variables.connectionId !== 'undefined',
+ staleTime: 30_000,
+ ...options,
+ })
diff --git a/apps/studio/data/config/keys.ts b/apps/studio/data/config/keys.ts
index f72e9876f05..d19301cd08d 100644
--- a/apps/studio/data/config/keys.ts
+++ b/apps/studio/data/config/keys.ts
@@ -29,4 +29,6 @@ export const configKeys = {
deploymentMode: () => ['deployment-mode'] as const,
postgresConfig: (projectRef: string | undefined) =>
['projects', projectRef, 'postgres-config'] as const,
+ // used for entire project state, includes all configs, matches `config.toml` schema
+ projectConfig: (projectRef: string | undefined) => ['projects', projectRef, 'config'] as const,
}
diff --git a/apps/studio/data/config/project-config-query.ts b/apps/studio/data/config/project-config-query.ts
new file mode 100644
index 00000000000..e847a2986b7
--- /dev/null
+++ b/apps/studio/data/config/project-config-query.ts
@@ -0,0 +1,41 @@
+import { queryOptions } from '@tanstack/react-query'
+
+import { configKeys } from './keys'
+import { get, handleError } from '@/data/fetchers'
+import { IS_PLATFORM } from '@/lib/constants'
+import type { ResponseError } from '@/types'
+
+export type ProjectConfigV2Variables = {
+ projectRef?: string
+}
+
+export async function getProjectConfig(
+ { projectRef }: ProjectConfigV2Variables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) throw new Error('Project ref is required')
+
+ // [Alpha] GET /v2/projects/{ref}/config — the project's effective service config
+ // (database, pooler, auth, api, realtime, storage).
+ const { data, error } = await get('/v2/projects/{ref}/config', {
+ params: { path: { ref: projectRef } },
+ signal,
+ })
+
+ if (error) handleError(error)
+ return (data || { data: undefined }).data
+}
+
+export type ProjectConfigV2Data = Awaited<ReturnType<typeof getProjectConfig>>
+export type ProjectConfigV2Error = ResponseError
+
+export const projectConfigV2QueryOptions = (
+ { projectRef }: ProjectConfigV2Variables,
+ { enabled = true }: { enabled?: boolean } = { enabled: true }
+) => {
+ return queryOptions({
+ queryKey: configKeys.projectConfig(projectRef),
+ queryFn: ({ signal }) => getProjectConfig({ projectRef }, signal),
+ enabled: enabled && IS_PLATFORM && typeof projectRef !== 'undefined',
+ })
+}
diff --git a/apps/studio/data/integrations/github-connections-query.ts b/apps/studio/data/integrations/github-connections-query.ts
index cb22cf1916b..fcf606ef3a3 100644
--- a/apps/studio/data/integrations/github-connections-query.ts
+++ b/apps/studio/data/integrations/github-connections-query.ts
@@ -1,5 +1,4 @@
import { useQuery } from '@tanstack/react-query'
-import { useMemo } from 'react'
import { integrationKeys } from './keys'
import { get, handleError } from '@/data/fetchers'
@@ -52,14 +51,11 @@ export const useGitHubConnectionsQuery = <TData = GitHubConnectionsData>(
export const useProjectGitHubConnectionQuery = ({ ref }: { ref?: string }) => {
const { data: organization } = useSelectedOrganizationQuery()
- const { data: connections, ...props } = useGitHubConnectionsQuery(
+ return useGitHubConnectionsQuery(
{ organizationId: organization?.id },
- { enabled: !!ref && !!organization?.id }
+ {
+ enabled: !!ref && !!organization?.id,
+ select: (data) => data?.find((c) => c.project.ref === ref),
+ }
)
-
- const existingConnection = useMemo(
- () => connections?.find((c) => c.project.ref === ref),
- [connections, ref]
- )
- return { data: existingConnection, ...props }
}
diff --git a/apps/studio/hooks/misc/useGitHubConfigDrift.test.ts b/apps/studio/hooks/misc/useGitHubConfigDrift.test.ts
new file mode 100644
index 00000000000..65b4507f306
--- /dev/null
+++ b/apps/studio/hooks/misc/useGitHubConfigDrift.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest'
+
+import { getGitBranchName } from './useGitHubConfigDrift'
+import type { Branch } from '@/data/branches/branches-query'
+
+function branch(overrides: Partial<Branch>): Branch {
+ return {
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ id: 'branch-id',
+ is_default: false,
+ name: 'feature/foo',
+ parent_project_ref: 'parent-ref',
+ persistent: false,
+ project_ref: 'project-ref',
+ status: 'MIGRATIONS_PASSED',
+ with_data: false,
+ ...overrides,
+ }
+}
+
+describe('getGitBranchName', () => {
+ it('returns undefined when there is no branch', () => {
+ expect(getGitBranchName(undefined)).toBeUndefined()
+ })
+
+ it('prefers the trimmed git_branch when set', () => {
+ expect(getGitBranchName(branch({ git_branch: ' main ', name: 'feature/foo' }))).toBe('main')
+ })
+
+ it('falls back to the trimmed branch name when git_branch is unset', () => {
+ expect(getGitBranchName(branch({ git_branch: undefined, name: ' feature/foo ' }))).toBe(
+ 'feature/foo'
+ )
+ })
+
+ it('falls back to the branch name when git_branch is blank', () => {
+ expect(getGitBranchName(branch({ git_branch: ' ', name: 'feature/foo' }))).toBe('feature/foo')
+ })
+
+ it('returns undefined for the default branch when git_branch is unset', () => {
+ expect(getGitBranchName(branch({ git_branch: undefined, is_default: true }))).toBeUndefined()
+ })
+
+ it('still prefers git_branch for the default branch when it is set', () => {
+ expect(getGitBranchName(branch({ git_branch: 'main', is_default: true }))).toBe('main')
+ })
+})
diff --git a/apps/studio/hooks/misc/useGitHubConfigDrift.ts b/apps/studio/hooks/misc/useGitHubConfigDrift.ts
new file mode 100644
index 00000000000..f1df911284a
--- /dev/null
+++ b/apps/studio/hooks/misc/useGitHubConfigDrift.ts
@@ -0,0 +1,93 @@
+import { useQuery } from '@tanstack/react-query'
+import { useParams } from 'common'
+import { useCallback, useMemo } from 'react'
+
+import { convertProjectConfigToGitHubConfig } from '@/components/interfaces/ConfigDrift/github-config-convert'
+import { getConfigDriftSummary } from '@/components/interfaces/ConfigDrift/github-config-drift'
+import type { Branch } from '@/data/branches/branches-query'
+import { useBranchesQuery } from '@/data/branches/branches-query'
+import { useGitHubConfigQuery } from '@/data/config/github-config-query'
+import { projectConfigV2QueryOptions } from '@/data/config/project-config-query'
+import { useProjectGitHubConnectionQuery } from '@/data/integrations/github-connections-query'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import { IS_PLATFORM } from '@/lib/constants'
+
+export function getGitBranchName(branch?: Branch): string | undefined {
+ return branch?.git_branch?.trim() || (branch?.is_default ? undefined : branch?.name?.trim())
+}
+
+export function useSelectedGitHubConfigDrift() {
+ const { ref: projectRef } = useParams()
+ const projectQuery = useSelectedProjectQuery()
+ const project = projectQuery.data
+ const parentProjectRef = project?.parentRef ?? projectRef
+ const shouldLoad = IS_PLATFORM && Boolean(projectRef) && Boolean(project)
+
+ const branchesQuery = useBranchesQuery({ projectRef: parentProjectRef }, { enabled: shouldLoad })
+ const connectionQuery = useProjectGitHubConnectionQuery({ ref: parentProjectRef })
+ const connection = connectionQuery.data
+ const hasConnection = connection !== undefined
+ const branches = branchesQuery.data ?? []
+ const selectedBranch = branches.find((branch) => branch.project_ref === projectRef)
+ const gitBranch = getGitBranchName(selectedBranch)
+ const queriesEnabled =
+ shouldLoad && branchesQuery.isSuccess && connectionQuery.isSuccess && hasConnection
+
+ const projectConfigQuery = useQuery({
+ ...projectConfigV2QueryOptions({ projectRef }),
+ enabled: queriesEnabled,
+ staleTime: 30_000,
+ })
+ const githubConfigQuery = useGitHubConfigQuery(
+ { connectionId: connection?.id, branch: gitBranch },
+ { enabled: queriesEnabled }
+ )
+
+ const { refetch: branchesRefetch } = branchesQuery
+ const { refetch: connectionRefetch } = connectionQuery
+ const { refetch: projectConfigRefetch } = projectConfigQuery
+ const { refetch: githubConfigRefetch } = githubConfigQuery
+
+ const refetch = useCallback(
+ () =>
+ Promise.all([
+ branchesRefetch(),
+ connectionRefetch(),
+ projectConfigRefetch(),
+ githubConfigRefetch(),
+ ]),
+ [branchesRefetch, connectionRefetch, projectConfigRefetch, githubConfigRefetch]
+ )
+
+ const summary = useMemo(() => {
+ const dashboardConfig = convertProjectConfigToGitHubConfig(projectConfigQuery.data?.attributes)
+
+ return getConfigDriftSummary({
+ dashboardConfig: dashboardConfig,
+ githubConfig: githubConfigQuery.data?.config,
+ })
+ }, [projectConfigQuery.data?.attributes, githubConfigQuery.data?.config])
+
+ const activeQueries = [
+ projectQuery,
+ ...(shouldLoad ? [branchesQuery, connectionQuery] : []),
+ ...(shouldLoad && hasConnection ? [projectConfigQuery, githubConfigQuery] : []),
+ ]
+
+ const isReady =
+ shouldLoad && hasConnection && projectConfigQuery.isSuccess && githubConfigQuery.isSuccess
+ const issueCount = summary.driftedFields.length
+
+ return {
+ requestedGitBranch: gitBranch,
+ isReady,
+ isPending: activeQueries.some((query) => query.isPending),
+ isFetching: activeQueries.some((query) => query.isFetching),
+ isError: activeQueries.some((query) => query.isError),
+ error: activeQueries.find((query) => query.error)?.error,
+ hasConfigurationIssues: isReady && issueCount > 0,
+ unmanagedFields: summary.unmanagedFields,
+ summary,
+ refetch,
+ }
+}
diff --git a/apps/studio/pages/project/[ref]/settings/code-configuration.tsx b/apps/studio/pages/project/[ref]/settings/code-configuration.tsx
new file mode 100644
index 00000000000..f7f039546a8
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/settings/code-configuration.tsx
@@ -0,0 +1,46 @@
+import { PageContainer } from 'ui-patterns/PageContainer'
+import {
+ PageHeader,
+ PageHeaderDescription,
+ PageHeaderMeta,
+ PageHeaderSummary,
+ PageHeaderTitle,
+} from 'ui-patterns/PageHeader'
+import { PageSection, PageSectionContent } from 'ui-patterns/PageSection'
+
+import { ConfigurationDriftPage } from '@/components/interfaces/ConfigDrift/ConfigurationDriftPage'
+import { DefaultLayout } from '@/components/layouts/DefaultLayout'
+import SettingsLayout from '@/components/layouts/ProjectSettingsLayout/SettingsLayout'
+import type { NextPageWithLayout } from '@/types'
+
+const ConfigurationDriftPageEntry: NextPageWithLayout = () => {
+ return (
+ <>
+ <PageHeader size="small">
+ <PageHeaderMeta>
+ <PageHeaderSummary>
+ <PageHeaderTitle>Code configuration</PageHeaderTitle>
+ <PageHeaderDescription>
+ Compare the live project configuration with supabase/config.toml on this branch
+ </PageHeaderDescription>
+ </PageHeaderSummary>
+ </PageHeaderMeta>
+ </PageHeader>
+ <PageContainer size="small">
+ <PageSection>
+ <PageSectionContent>
+ <ConfigurationDriftPage />
+ </PageSectionContent>
+ </PageSection>
+ </PageContainer>
+ </>
+ )
+}
+
+ConfigurationDriftPageEntry.getLayout = (page) => (
+ <DefaultLayout>
+ <SettingsLayout title="Code configuration">{page}</SettingsLayout>
+ </DefaultLayout>
+)
+
+export default ConfigurationDriftPageEntry
diff --git a/apps/studio/routeTree.gen.ts b/apps/studio/routeTree.gen.ts
index c49f7edcbd9..350cfbc6ccd 100644
--- a/apps/studio/routeTree.gen.ts
+++ b/apps/studio/routeTree.gen.ts
@@ -108,6 +108,7 @@ import { Route as ProjectRefSettingsLogDrainsRouteImport } from './routes/projec
import { Route as ProjectRefSettingsIntegrationsRouteImport } from './routes/project/$ref/settings/integrations'
import { Route as ProjectRefSettingsGeneralRouteImport } from './routes/project/$ref/settings/general'
import { Route as ProjectRefSettingsDashboardRouteImport } from './routes/project/$ref/settings/dashboard'
+import { Route as ProjectRefSettingsCodeConfigurationRouteImport } from './routes/project/$ref/settings/code-configuration'
import { Route as ProjectRefSettingsApiKeysRouteImport } from './routes/project/$ref/settings/api-keys'
import { Route as ProjectRefSettingsApiRouteImport } from './routes/project/$ref/settings/api'
import { Route as ProjectRefSettingsAddonsRouteImport } from './routes/project/$ref/settings/addons'
@@ -836,6 +837,12 @@ const ProjectRefSettingsDashboardRoute =
path: '/dashboard',
getParentRoute: () => ProjectRefSettingsRoute,
} as any)
+const ProjectRefSettingsCodeConfigurationRoute =
+ ProjectRefSettingsCodeConfigurationRouteImport.update({
+ id: '/code-configuration',
+ path: '/code-configuration',
+ getParentRoute: () => ProjectRefSettingsRoute,
+ } as any)
const ProjectRefSettingsApiKeysRoute =
ProjectRefSettingsApiKeysRouteImport.update({
id: '/api-keys',
@@ -2254,6 +2261,7 @@ export interface FileRoutesByFullPath {
'/project/$ref/settings/addons': typeof ProjectRefSettingsAddonsRoute
'/project/$ref/settings/api': typeof ProjectRefSettingsApiRoute
'/project/$ref/settings/api-keys': typeof ProjectRefSettingsApiKeysRouteWithChildren
+ '/project/$ref/settings/code-configuration': typeof ProjectRefSettingsCodeConfigurationRoute
'/project/$ref/settings/dashboard': typeof ProjectRefSettingsDashboardRoute
'/project/$ref/settings/general': typeof ProjectRefSettingsGeneralRoute
'/project/$ref/settings/integrations': typeof ProjectRefSettingsIntegrationsRoute
@@ -2555,6 +2563,7 @@ export interface FileRoutesByTo {
'/project/$ref/realtime/settings': typeof ProjectRefRealtimeSettingsRoute
'/project/$ref/settings/addons': typeof ProjectRefSettingsAddonsRoute
'/project/$ref/settings/api': typeof ProjectRefSettingsApiRoute
+ '/project/$ref/settings/code-configuration': typeof ProjectRefSettingsCodeConfigurationRoute
'/project/$ref/settings/dashboard': typeof ProjectRefSettingsDashboardRoute
'/project/$ref/settings/general': typeof ProjectRefSettingsGeneralRoute
'/project/$ref/settings/integrations': typeof ProjectRefSettingsIntegrationsRoute
@@ -2873,6 +2882,7 @@ export interface FileRoutesById {
'/project/$ref/settings/addons': typeof ProjectRefSettingsAddonsRoute
'/project/$ref/settings/api': typeof ProjectRefSettingsApiRoute
'/project/$ref/settings/api-keys': typeof ProjectRefSettingsApiKeysRouteWithChildren
+ '/project/$ref/settings/code-configuration': typeof ProjectRefSettingsCodeConfigurationRoute
'/project/$ref/settings/dashboard': typeof ProjectRefSettingsDashboardRoute
'/project/$ref/settings/general': typeof ProjectRefSettingsGeneralRoute
'/project/$ref/settings/integrations': typeof ProjectRefSettingsIntegrationsRoute
@@ -3190,6 +3200,7 @@ export interface FileRouteTypes {
| '/project/$ref/settings/addons'
| '/project/$ref/settings/api'
| '/project/$ref/settings/api-keys'
+ | '/project/$ref/settings/code-configuration'
| '/project/$ref/settings/dashboard'
| '/project/$ref/settings/general'
| '/project/$ref/settings/integrations'
@@ -3491,6 +3502,7 @@ export interface FileRouteTypes {
| '/project/$ref/realtime/settings'
| '/project/$ref/settings/addons'
| '/project/$ref/settings/api'
+ | '/project/$ref/settings/code-configuration'
| '/project/$ref/settings/dashboard'
| '/project/$ref/settings/general'
| '/project/$ref/settings/integrations'
@@ -3808,6 +3820,7 @@ export interface FileRouteTypes {
| '/project/$ref/settings/addons'
| '/project/$ref/settings/api'
| '/project/$ref/settings/api-keys'
+ | '/project/$ref/settings/code-configuration'
| '/project/$ref/settings/dashboard'
| '/project/$ref/settings/general'
| '/project/$ref/settings/integrations'
@@ -4775,6 +4788,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ProjectRefSettingsDashboardRouteImport
parentRoute: typeof ProjectRefSettingsRoute
}
+ '/project/$ref/settings/code-configuration': {
+ id: '/project/$ref/settings/code-configuration'
+ path: '/code-configuration'
+ fullPath: '/project/$ref/settings/code-configuration'
+ preLoaderRoute: typeof ProjectRefSettingsCodeConfigurationRouteImport
+ parentRoute: typeof ProjectRefSettingsRoute
+ }
'/project/$ref/settings/api-keys': {
id: '/project/$ref/settings/api-keys'
path: '/api-keys'
@@ -6820,6 +6840,7 @@ interface ProjectRefSettingsRouteChildren {
ProjectRefSettingsAddonsRoute: typeof ProjectRefSettingsAddonsRoute
ProjectRefSettingsApiRoute: typeof ProjectRefSettingsApiRoute
ProjectRefSettingsApiKeysRoute: typeof ProjectRefSettingsApiKeysRouteWithChildren
+ ProjectRefSettingsCodeConfigurationRoute: typeof ProjectRefSettingsCodeConfigurationRoute
ProjectRefSettingsDashboardRoute: typeof ProjectRefSettingsDashboardRoute
ProjectRefSettingsGeneralRoute: typeof ProjectRefSettingsGeneralRoute
ProjectRefSettingsIntegrationsRoute: typeof ProjectRefSettingsIntegrationsRoute
@@ -6837,6 +6858,8 @@ const ProjectRefSettingsRouteChildren: ProjectRefSettingsRouteChildren = {
ProjectRefSettingsAddonsRoute: ProjectRefSettingsAddonsRoute,
ProjectRefSettingsApiRoute: ProjectRefSettingsApiRoute,
ProjectRefSettingsApiKeysRoute: ProjectRefSettingsApiKeysRouteWithChildren,
+ ProjectRefSettingsCodeConfigurationRoute:
+ ProjectRefSettingsCodeConfigurationRoute,
ProjectRefSettingsDashboardRoute: ProjectRefSettingsDashboardRoute,
ProjectRefSettingsGeneralRoute: ProjectRefSettingsGeneralRoute,
ProjectRefSettingsIntegrationsRoute: ProjectRefSettingsIntegrationsRoute,
diff --git a/apps/studio/routes/project/$ref/settings/code-configuration.tsx b/apps/studio/routes/project/$ref/settings/code-configuration.tsx
new file mode 100644
index 00000000000..1c0127cfbfc
--- /dev/null
+++ b/apps/studio/routes/project/$ref/settings/code-configuration.tsx
@@ -0,0 +1,12 @@
+import { createFileRoute } from '@tanstack/react-router'
+
+import ConfigurationDriftPage from '@/pages/project/[ref]/settings/code-configuration'
+
+export const Route = createFileRoute('/project/$ref/settings/code-configuration')({
+ component: CodeConfigurationRoute,
+ staticData: { settingsLayoutTitle: 'Code configuration' },
+})
+
+function CodeConfigurationRoute() {
+ return <ConfigurationDriftPage dehydratedState={undefined} />
+}