Files
Danny White 9052601faf fix(studio): validate direct database access permissions (#54506)
## Problem

Direct database access requires Database management read access, but
OAuth app settings currently allow saving an invalid combination. The
consent screen’s readiness checks then fail.

## Solution

Show an inline error when direct database access lacks Database
management read access, and prevent saving through the button, keyboard
shortcut, or form submission. Both controls stay editable, and neither
changes the other automatically.

| After |
| --- |
| <img width="1280" height="1103" alt="OAuth Apps Organization Settings
Office Supabase (1)"
src="https://github.com/user-attachments/assets/6cfd203b-d320-46da-b7b5-9ede2e9d814c"
/> |
| _Immediate inline error, cleared as soon as it’s corrected._ |
| <img width="1280" height="1103" alt="OAuth Apps Organization Settings
Office Supabase"
src="https://github.com/user-attachments/assets/f2637d92-c149-4d1a-9d83-130e0f54ce66"
/> |
| _Follow-up footer pattern if that error (or any inline error) is
ignored._ |

## Review instructions

1. Open the [staging
preview](https://studio-staging-git-dnywh-trusted-partner-permis-56807c-supabase.vercel.app/dashboard)
→ Organization → OAuth Apps. Edit an organisation-bound app, or select
**Publish OAuth app**. If your organisation is not a Trusted Partner,
use the DevTools steps below first.
2. Select Direct database access, then set Database management to No
access or Write. Check that the inline error explains that “Database
management” requires at least read access and Confirm stays enabled.
Click Confirm: saving should be blocked and “Fix the errors above to
continue.” should appear in red above the footer actions.
3. Select Database management Read only or Read and write. Check that
the inline and footer errors clear. Confirm should remain enabled.
4. Repeat in the opposite order, or remove Direct database access.
Neither control should change automatically.


<details>
<summary>Review without a Trusted Partner organisation (Chrome
DevTools)</summary>

1. In the Studio dev toolbar’s **Flags** tab, enable
`enableScopedOAuthPublish` if needed.
2. Open Chrome DevTools → **Network**, then open **Publish OAuth app**
or edit an existing app.
3. Select the **GET** request whose URL ends in
`/platform/organizations/YOUR_ORG_SLUG`, without `/oauth/apps` after it.
Its response contains your organisation’s name and slug.
4. Right-click the request → **Override content**. Choose a local folder
and click **Allow**. Add `"is_trusted_partner": true` to the top-level
JSON object, or change the existing value to `true`. Keep every other
field and save with **Cmd/Ctrl+S**.
5. Reload with DevTools open and reopen the app form. For a new app,
choose **An owner, once for the whole organization** under
**Authorization**. Fill in the required name, website and callback URL
so other validation does not interfere.
6. Under **Application permissions**, select **Direct database access →
Read only** while **Database management** has **No access**. Check that
the inline error appears and **Confirm** stays enabled. Click
**Confirm** and check that saving is blocked, with “Fix the errors above
to continue.” in red above the footer actions.
7. Set **Database management → Read only** or **Read and write**. Check
that the inline and footer errors clear, while **Confirm** remains
enabled. Change it to **Write** and check that the error returns.
Neither permission should change automatically.
8. Set **Direct database access → No access**. Check that the inline and
footer errors clear. Cancel the form without saving.
9. Turn off **Sources → Overrides → Enable Local Overrides** and reload
when finished.

The override only changes the response in your browser. It does not
grant backend Trusted Partner eligibility, so use it to review the UI
validation. Saving an app with direct database access requires a
genuinely eligible organisation.

</details>
2026-12-03 13:39:50 +07:00

211 lines
6.3 KiB
TypeScript

import { OAuthScope } from '@supabase/shared-types/out/constants'
import { getMcpClientIconSrc } from 'ui-patterns/McpUrlBuilder'
export const hasDirectDatabaseAccess = (scopes: readonly string[]) =>
scopes.includes(OAuthScope.DATABASE_TOKEN_ACCESS_READ) ||
scopes.includes(OAuthScope.DATABASE_TOKEN_ACCESS_WRITE)
export const isDatabaseManagementReadRequired = (scopes: readonly string[]) =>
hasDirectDatabaseAccess(scopes) && !scopes.includes(OAuthScope.DATABASE_READ)
export function getDatabaseTokenAccess(scopes: readonly string[] | undefined) {
if (scopes?.includes(OAuthScope.DATABASE_TOKEN_ACCESS_WRITE)) return 'write'
if (scopes?.includes(OAuthScope.DATABASE_TOKEN_ACCESS_READ)) return 'read'
}
export type TrustedOAuthPartner = {
/** Substrings matched against the requester name (case-insensitive). */
nameMatchers: readonly string[]
displayName: string
icon: string
hasDistinctDarkIcon: boolean
/** Exact host or parent host for redirect_uri (subdomains allowed). */
redirectHosts: readonly string[]
}
/**
* High-traffic MCP / OAuth partners with curated Connect logos.
* Logos resolve from allowlisted redirect_uri hosts, or from a trusted name when
* redirect_uri is localhost / loopback (common for local MCP clients).
* Never from self-asserted name alone on a remote host.
*/
export const TRUSTED_OAUTH_PARTNERS: readonly TrustedOAuthPartner[] = [
{
nameMatchers: ['claude'],
displayName: 'Claude',
icon: 'claude',
hasDistinctDarkIcon: false,
redirectHosts: ['claude.ai', 'anthropic.com'],
},
{
nameMatchers: ['cursor'],
displayName: 'Cursor',
icon: 'cursor',
hasDistinctDarkIcon: true,
redirectHosts: ['cursor.com', 'cursor.sh'],
},
{
nameMatchers: ['chatgpt', 'openai'],
displayName: 'ChatGPT',
icon: 'openai',
hasDistinctDarkIcon: true,
redirectHosts: ['chatgpt.com', 'openai.com'],
},
{
nameMatchers: ['perplexity'],
displayName: 'Perplexity',
icon: 'perplexity',
hasDistinctDarkIcon: true,
redirectHosts: ['perplexity.ai'],
},
]
const LOCAL_REDIRECT_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])
export function getRedirectHostname(redirectUri: string | null | undefined): string | null {
if (!redirectUri) return null
try {
const { hostname } = new URL(redirectUri)
return hostname.toLowerCase() || null
} catch {
return null
}
}
export function isLocalRedirectHost(hostname: string | null | undefined): boolean {
if (!hostname) return false
const host = hostname.toLowerCase()
return LOCAL_REDIRECT_HOSTS.has(host) || host.endsWith('.localhost')
}
export function hostMatchesAllowlist(hostname: string, allowedHosts: readonly string[]): boolean {
const host = hostname.toLowerCase()
return allowedHosts.some((allowed) => {
const entry = allowed.toLowerCase()
return host === entry || host.endsWith(`.${entry}`)
})
}
export function findTrustedPartnerByRedirectUri(
redirectUri: string | null | undefined
): TrustedOAuthPartner | null {
const hostname = getRedirectHostname(redirectUri)
if (!hostname || isLocalRedirectHost(hostname)) return null
return (
TRUSTED_OAUTH_PARTNERS.find((partner) =>
hostMatchesAllowlist(hostname, partner.redirectHosts)
) ?? null
)
}
export function findTrustedPartnerByName(
name: string | null | undefined
): TrustedOAuthPartner | null {
if (!name) return null
const searchable = name.toLowerCase()
return (
TRUSTED_OAUTH_PARTNERS.find((partner) =>
partner.nameMatchers.some((matcher) => searchable.includes(matcher))
) ?? null
)
}
function curatedLogoForPartner(
partner: TrustedOAuthPartner,
useDarkVariant: boolean
): { src: string; isKnownClient: boolean } | null {
const customLogoUrl = getMcpClientIconSrc({
icon: partner.icon,
useDarkVariant,
hasDistinctDarkIcon: partner.hasDistinctDarkIcon,
})
if (!customLogoUrl) return null
return { src: customLogoUrl, isKnownClient: true }
}
export function getRequesterLogo({
icon,
name,
redirectUri,
useDarkVariant,
}: {
icon: string | null
name?: string | null
redirectUri: string | null | undefined
useDarkVariant: boolean
}): { src: string; isKnownClient: boolean } {
const byRedirect = findTrustedPartnerByRedirectUri(redirectUri)
if (byRedirect) {
const curated = curatedLogoForPartner(byRedirect, useDarkVariant)
if (curated) return curated
}
// Local MCP clients (Claude Desktop, Cursor, etc.) use loopback redirects.
// Name match is enough there — remote hosts still require the allowlist.
const hostname = getRedirectHostname(redirectUri)
if (hostname && isLocalRedirectHost(hostname) && name) {
const byName = findTrustedPartnerByName(name)
if (byName) {
const curated = curatedLogoForPartner(byName, useDarkVariant)
if (curated) return curated
}
}
return { src: icon || '', isKnownClient: false }
}
export type OAuthImpersonationWarning = {
/** Trusted partner label used in the caution copy. */
brandDisplayName: string
redirectHost: string
}
/**
* Warn when the requester name looks like a known partner but redirect_uri is a
* remote host outside that partner's allowlist. Localhost redirects are skipped
* (common for local MCP clients). Missing or malformed redirect URIs are skipped.
*/
export function getOAuthImpersonationWarning({
name,
redirectUri,
}: {
name: string | null | undefined
redirectUri: string | null | undefined
}): OAuthImpersonationWarning | null {
const namedPartner = findTrustedPartnerByName(name)
if (!namedPartner) return null
const hostname = getRedirectHostname(redirectUri)
if (!hostname || isLocalRedirectHost(hostname)) return null
if (hostMatchesAllowlist(hostname, namedPartner.redirectHosts)) {
return null
}
return {
brandDisplayName: namedPartner.displayName,
redirectHost: hostname,
}
}
type SortOrder = 'asc' | 'desc'
export const parseSort = <C extends string>(sort: string): [C, SortOrder] => {
return sort.split(':') as [C, SortOrder]
}
export const toggleSort = <S extends string>(
currentSort: S,
column: string,
setSort: (sort: S) => void
) => {
const [currentColumn, currentOrder] = parseSort(currentSort)
if (currentColumn === column) {
setSort(`${column}:${currentOrder === 'asc' ? 'desc' : 'asc'}` as S)
} else {
setSort(`${column}:asc` as S)
}
}