Skip to content

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

feat(studio): scoped oauth data layer (#49476)

kemal.earth0c2257fb3d6d
diff --git a/apps/studio/data/oauth-apps/keys.ts b/apps/studio/data/oauth-apps/keys.ts
new file mode 100644
index 00000000000..7fa7cd3de54
--- /dev/null
+++ b/apps/studio/data/oauth-apps/keys.ts
@@ -0,0 +1,25 @@
+export const oauthAppsKeys = {
+ authorizeRequest: (id: string | undefined) => ['oauth-apps', 'authorize', id] as const,
+ authorizeOrganizations: (id: string | undefined) =>
+ ['oauth-apps', 'authorize', id, 'organizations'] as const,
+ authorizeOrganizationProjects: (id: string | undefined, slug: string | undefined) =>
+ ['oauth-apps', 'authorize', id, 'organizations', slug, 'projects'] as const,
+ orgAppDetails: (slug: string | undefined, appId: string | undefined) =>
+ ['oauth-apps', 'organizations', slug, 'apps', appId, 'grant'] as const,
+ preflightValidation: (slug: string | undefined, appId: string | undefined) =>
+ ['oauth-apps', 'organizations', slug, 'apps', appId, 'preflight-validation'] as const,
+ // cursor omitted (rather than passed as `undefined`) so the cursor-less key is a true prefix
+ // of every paginated key — invalidating without a cursor clears every cached page.
+ approvals: (slug: string | undefined, cursor?: string) =>
+ cursor === undefined
+ ? (['oauth-apps', 'approvals', slug] as const)
+ : (['oauth-apps', 'approvals', slug, cursor] as const),
+ appMemberGrants: (slug: string | undefined, appId: string | undefined, cursor?: string) =>
+ cursor === undefined
+ ? (['oauth-apps', 'authorized', slug, appId, 'member-grants'] as const)
+ : (['oauth-apps', 'authorized', slug, appId, 'member-grants', cursor] as const),
+ grants: (cursor?: string) =>
+ cursor === undefined
+ ? (['oauth-apps', 'grants'] as const)
+ : (['oauth-apps', 'grants', cursor] as const),
+}
diff --git a/apps/studio/data/oauth-apps/mocks.ts b/apps/studio/data/oauth-apps/mocks.ts
new file mode 100644
index 00000000000..d809a743c30
--- /dev/null
+++ b/apps/studio/data/oauth-apps/mocks.ts
@@ -0,0 +1,622 @@
+import dayjs from 'dayjs'
+
+import type { OAuthAppsAuthorizeIdentity } from './oauth-apps-authorize-organizations-query'
+import type {
+ ListOAuthApprovalsResponse,
+ ListOrgAppGrantsResponse,
+ ListOwnGrantsResponse,
+ OAuthAppsAuthorizeApproveResult,
+ OAuthAppsAuthorizeOrganizationProject,
+ OAuthAppsAuthorizePreflightResult,
+ OAuthAppsAuthorizeRequest,
+ OAuthExistingGrant,
+ OAuthOrganizationRole,
+ OAuthOrgAppDetails,
+ OAuthScope,
+} from './types'
+import { isPreflightValidationFailure, isWriteScope } from './types'
+import type { OrganizationRole } from '@/data/organization-members/organization-roles-query'
+
+const ENABLE_MOCKS = true
+export const USE_MOCKS = ENABLE_MOCKS && process.env.NEXT_PUBLIC_ENVIRONMENT !== 'prod'
+
+export const OAUTH_APPS_MOCK_SCENARIOS = {
+ vercelDeveloper: 'mock-vercel-developer',
+ vercelReadOnly: 'mock-vercel-readonly',
+ vercelReconsent: 'mock-vercel-reconsent',
+ vercelOrgAdmin: 'mock-vercel-org-admin',
+ vercelManyProjects: 'mock-vercel-many-projects',
+ vercelRoleValidation: 'mock-vercel-role-validation',
+ vercelOptionalProjects: 'mock-vercel-optional-projects',
+ vercelAllProjects: 'mock-vercel-all-projects',
+ vercelReconsentAllProjects: 'mock-vercel-reconsent-all-projects',
+ kemalBot: 'mock-kemal-bot',
+ kemalBotOrgWide: 'mock-kemal-bot-org-wide',
+ dynamicMcpClient: 'mock-dynamic-mcp-client',
+} as const
+
+export const OWNER_ROLE: OrganizationRole = {
+ id: 1,
+ base_role_id: 1,
+ name: 'Owner',
+ description: null,
+ projects: [],
+}
+
+export const ADMINISTRATOR_ROLE: OrganizationRole = {
+ id: 2,
+ base_role_id: 2,
+ name: 'Administrator',
+ description: null,
+ projects: [],
+}
+
+export const DEVELOPER_ROLE: OrganizationRole = {
+ id: 3,
+ base_role_id: 3,
+ name: 'Developer',
+ description: null,
+ projects: [],
+}
+
+export const READ_ONLY_ROLE: OrganizationRole = {
+ id: 4,
+ base_role_id: 4,
+ name: 'Read-only',
+ description: null,
+ projects: [],
+}
+
+const VERCEL_SCOPES: OAuthScope[] = [
+ 'database:read',
+ 'database:write',
+ 'environment:read',
+ 'environment:write',
+ 'secrets:read',
+ 'secrets:write',
+ 'projects:read',
+ 'edge_functions:read',
+ 'storage:read',
+]
+
+const VERCEL_REQUEST: OAuthAppsAuthorizeRequest = {
+ app_id: 'vercel',
+ app_name: 'Vercel',
+ name: 'Vercel',
+ website: 'https://vercel.com',
+ domain: 'vercel.com',
+ redirect_uri: 'https://vercel.com/api/integrations/supabase/callback',
+ registration_type: 'manual',
+ expires_at: dayjs().add(1, 'month').toISOString(),
+ grant_kind: 'member_bound',
+ project_scoping_mode: true,
+ scopes: VERCEL_SCOPES,
+}
+
+const VERCEL_OPTIONAL_PROJECTS_REQUEST: OAuthAppsAuthorizeRequest = {
+ ...VERCEL_REQUEST,
+ app_id: 'vercel-optional',
+ project_scoping_mode: true,
+}
+
+const VERCEL_ALL_PROJECTS_REQUEST: OAuthAppsAuthorizeRequest = {
+ ...VERCEL_REQUEST,
+ app_id: 'vercel-org-wide',
+ project_scoping_mode: false,
+}
+
+const DYNAMIC_MCP_CLIENT_REQUEST: OAuthAppsAuthorizeRequest = {
+ ...VERCEL_REQUEST,
+ app_id: 'dynamic-mcp-client',
+ app_name: 'Northwind MCP',
+ name: 'Northwind MCP',
+ website: 'https://mcp.northwind.example',
+ domain: 'mcp.northwind.example',
+ redirect_uri: 'https://mcp.northwind.example/callback',
+ registration_type: 'dynamic',
+ // DCR (MCP) oauth apps are forced org-bound, unscoped.
+ grant_kind: 'organization_bound',
+ project_scoping_mode: false,
+}
+
+const KEMAL_BOT_REQUEST: OAuthAppsAuthorizeRequest = {
+ app_id: 'kemal-bot',
+ app_name: 'kemal-bot',
+ name: 'kemal-bot',
+ website: 'https://kemal.lol',
+ domain: 'kemal.lol',
+ redirect_uri: 'https://kemal.lol/hollerback',
+ registration_type: 'manual',
+ expires_at: dayjs().add(1, 'month').toISOString(),
+ grant_kind: 'organization_bound',
+ project_scoping_mode: true,
+ scopes: ['projects:read'],
+}
+
+const KEMAL_BOT_ORG_WIDE_REQUEST: OAuthAppsAuthorizeRequest = {
+ ...KEMAL_BOT_REQUEST,
+ app_id: 'kemal-bot-org-wide',
+ project_scoping_mode: false,
+}
+
+const MOCK_AUTHORIZE_REQUESTS: Record<string, OAuthAppsAuthorizeRequest> = {
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper]: VERCEL_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelReadOnly]: VERCEL_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent]: VERCEL_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelOrgAdmin]: VERCEL_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelManyProjects]: VERCEL_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation]: VERCEL_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelOptionalProjects]: VERCEL_OPTIONAL_PROJECTS_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects]: VERCEL_ALL_PROJECTS_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelReconsentAllProjects]: VERCEL_OPTIONAL_PROJECTS_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.kemalBot]: KEMAL_BOT_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.kemalBotOrgWide]: KEMAL_BOT_ORG_WIDE_REQUEST,
+ [OAUTH_APPS_MOCK_SCENARIOS.dynamicMcpClient]: DYNAMIC_MCP_CLIENT_REQUEST,
+}
+
+const NORTHWIND_TRADERS_DEVELOPER: OAuthOrganizationRole = {
+ slug: 'northwind-traders',
+ name: 'Northwind Traders',
+ default_role: DEVELOPER_ROLE,
+}
+
+const NORTHWIND_TRADERS_READ_ONLY: OAuthOrganizationRole = {
+ ...NORTHWIND_TRADERS_DEVELOPER,
+ default_role: READ_ONLY_ROLE,
+}
+
+const CONTOSO_LABS: OAuthOrganizationRole = {
+ slug: 'contoso-labs',
+ name: 'Contoso Labs',
+ default_role: OWNER_ROLE,
+}
+
+const TAILSPIN_TOYS_ADMIN: OAuthOrganizationRole = {
+ slug: 'tailspin-toys',
+ name: 'Tailspin Toys',
+ default_role: ADMINISTRATOR_ROLE,
+}
+
+const FABRIKAM_OWNER: OAuthOrganizationRole = {
+ slug: 'fabrikam-industries',
+ name: 'Fabrikam Industries',
+ default_role: OWNER_ROLE,
+}
+
+const WINGTIP_TOYS_DEVELOPER: OAuthOrganizationRole = {
+ slug: 'wingtip-toys',
+ name: 'Wingtip Toys',
+ default_role: DEVELOPER_ROLE,
+}
+
+const LITWARE_DEVELOPER: OAuthOrganizationRole = {
+ slug: 'litware-inc',
+ name: 'Litware Inc.',
+ default_role: DEVELOPER_ROLE,
+}
+
+const MOCK_IDENTITIES: Record<string, OAuthAppsAuthorizeIdentity> = {
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper]: {
+ email: '[email protected]',
+ organizations: [NORTHWIND_TRADERS_DEVELOPER, CONTOSO_LABS],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelReadOnly]: {
+ email: '[email protected]',
+ organizations: [NORTHWIND_TRADERS_READ_ONLY, CONTOSO_LABS],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelReconsent]: {
+ email: '[email protected]',
+ organizations: [TAILSPIN_TOYS_ADMIN, NORTHWIND_TRADERS_DEVELOPER],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelOrgAdmin]: {
+ email: '[email protected]',
+ organizations: [TAILSPIN_TOYS_ADMIN, FABRIKAM_OWNER, NORTHWIND_TRADERS_DEVELOPER],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelManyProjects]: {
+ email: '[email protected]',
+ organizations: [WINGTIP_TOYS_DEVELOPER, NORTHWIND_TRADERS_DEVELOPER],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation]: {
+ email: '[email protected]',
+ organizations: [NORTHWIND_TRADERS_DEVELOPER, CONTOSO_LABS],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelOptionalProjects]: {
+ email: '[email protected]',
+ organizations: [NORTHWIND_TRADERS_DEVELOPER, CONTOSO_LABS],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects]: {
+ email: '[email protected]',
+ organizations: [NORTHWIND_TRADERS_READ_ONLY, CONTOSO_LABS, FABRIKAM_OWNER],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.vercelReconsentAllProjects]: {
+ email: '[email protected]',
+ organizations: [TAILSPIN_TOYS_ADMIN, NORTHWIND_TRADERS_DEVELOPER],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.kemalBot]: {
+ email: '[email protected]',
+ organizations: [NORTHWIND_TRADERS_DEVELOPER, CONTOSO_LABS],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.kemalBotOrgWide]: {
+ email: '[email protected]',
+ organizations: [NORTHWIND_TRADERS_DEVELOPER, FABRIKAM_OWNER],
+ },
+ [OAUTH_APPS_MOCK_SCENARIOS.dynamicMcpClient]: {
+ email: '[email protected]',
+ organizations: [NORTHWIND_TRADERS_DEVELOPER, CONTOSO_LABS],
+ },
+}
+
+const MOCK_ORGANIZATION_PROJECTS: Record<string, OAuthAppsAuthorizeOrganizationProject[]> = {
+ 'northwind-traders': [
+ { ref: 'northwindstorefront1', name: 'northwind-storefront', role: ADMINISTRATOR_ROLE },
+ { ref: 'northwindcms1', name: 'northwind-cms', role: DEVELOPER_ROLE },
+ { ref: 'fabrikamapi1', name: 'fabrikam-api', role: READ_ONLY_ROLE },
+ { ref: 'fabrikamjobs1', name: 'fabrikam-jobs', role: READ_ONLY_ROLE },
+ ],
+ 'wingtip-toys': [
+ { ref: 'wingtipweb1', name: 'wingtip-web', role: ADMINISTRATOR_ROLE },
+ { ref: 'wingtipapi1', name: 'wingtip-api', role: DEVELOPER_ROLE },
+ { ref: 'wingtipadmin1', name: 'wingtip-admin', role: DEVELOPER_ROLE },
+ { ref: 'wingtipjobs1', name: 'wingtip-jobs', role: DEVELOPER_ROLE },
+ { ref: 'wingtipsearch1', name: 'wingtip-search', role: READ_ONLY_ROLE },
+ { ref: 'wingtipbilling1', name: 'wingtip-billing', role: ADMINISTRATOR_ROLE },
+ { ref: 'wingtipmail1', name: 'wingtip-mail', role: DEVELOPER_ROLE },
+ { ref: 'wingtipmedia1', name: 'wingtip-media', role: DEVELOPER_ROLE },
+ { ref: 'wingtipmetrics1', name: 'wingtip-metrics', role: READ_ONLY_ROLE },
+ { ref: 'wingtipstaging1', name: 'wingtip-staging', role: DEVELOPER_ROLE },
+ { ref: 'wingtippreview1', name: 'wingtip-preview', role: DEVELOPER_ROLE },
+ { ref: 'wingtipsandbox1', name: 'wingtip-sandbox', role: READ_ONLY_ROLE },
+ ],
+ 'fabrikam-industries': [
+ { ref: 'fabrikamledger1', name: 'fabrikam-ledger', role: ADMINISTRATOR_ROLE },
+ ],
+ 'tailspin-toys': [
+ { ref: 'tailspinshop1', name: 'tailspin-shop', role: ADMINISTRATOR_ROLE },
+ { ref: 'tailspinwarehouse1', name: 'tailspin-warehouse', role: DEVELOPER_ROLE },
+ ],
+ 'litware-inc': [{ ref: 'litwarecrm1', name: 'litware-crm', role: DEVELOPER_ROLE }],
+ 'contoso-labs': [],
+}
+
+const TAILSPIN_VERCEL_EXISTING_GRANT: OAuthExistingGrant = {
+ approved_scopes: ['database:read', 'database:write', 'projects:read'],
+ project_refs: ['tailspinshop1', 'tailspindeleted1'],
+ approved_at: '2026-08-14T09:12:00.000Z',
+}
+
+const TAILSPIN_VERCEL_OPTIONAL_EXISTING_GRANT: OAuthExistingGrant = {
+ approved_scopes: ['database:read', 'projects:read'],
+ project_refs: [],
+ approved_at: '2026-08-29T16:40:00.000Z',
+}
+
+const DEFAULT_ORG_APP_DETAILS: OAuthOrgAppDetails = {
+ existing_grant: null,
+}
+
+const MOCK_ORG_APP_DETAILS: Record<string, Record<string, OAuthOrgAppDetails>> = {
+ 'tailspin-toys': {
+ vercel: { existing_grant: TAILSPIN_VERCEL_EXISTING_GRANT },
+ 'vercel-optional': { existing_grant: TAILSPIN_VERCEL_OPTIONAL_EXISTING_GRANT },
+ },
+}
+
+// Real oauth_apps config, keyed by app_id — preflight-validation is org+app scoped, not tied to
+// an in-flight authorization request.
+const MOCK_APPS_BY_ID: Record<string, OAuthAppsAuthorizeRequest> = {
+ vercel: VERCEL_REQUEST,
+ 'vercel-optional': VERCEL_OPTIONAL_PROJECTS_REQUEST,
+ 'vercel-org-wide': VERCEL_ALL_PROJECTS_REQUEST,
+ 'dynamic-mcp-client': DYNAMIC_MCP_CLIENT_REQUEST,
+ 'kemal-bot': KEMAL_BOT_REQUEST,
+ 'kemal-bot-org-wide': KEMAL_BOT_ORG_WIDE_REQUEST,
+}
+
+// The current member's org-level role, keyed by org slug — same reasoning as MOCK_APPS_BY_ID.
+const MOCK_ORGANIZATIONS_BY_SLUG: Record<string, OAuthOrganizationRole> = {
+ 'northwind-traders': NORTHWIND_TRADERS_READ_ONLY,
+ 'tailspin-toys': TAILSPIN_TOYS_ADMIN,
+ 'fabrikam-industries': FABRIKAM_OWNER,
+ 'contoso-labs': CONTOSO_LABS,
+ 'wingtip-toys': WINGTIP_TOYS_DEVELOPER,
+ 'litware-inc': LITWARE_DEVELOPER,
+}
+
+const MOCK_APPROVALS: ListOAuthApprovalsResponse = {
+ data: [
+ {
+ app: {
+ id: 'vercel',
+ name: 'Vercel',
+ icon: null,
+ created_by: '',
+ },
+ grant_target: 'members',
+ org_grant: null,
+ },
+ {
+ app: {
+ id: 'dynamic-mcp-client',
+ name: 'Northwind MCP',
+ icon: null,
+ created_by: '',
+ },
+ grant_target: 'members',
+ org_grant: null,
+ },
+ {
+ app: {
+ id: 'contoso-analytics',
+ name: 'Contoso Analytics',
+ icon: null,
+ created_by: '',
+ },
+ grant_target: 'organization',
+ org_grant: {
+ grant_id: 'grant-contoso-analytics-org',
+ approved_scopes: ['analytics:read', 'projects:read'],
+ approved_at: '2025-11-03T14:20:00.000Z',
+ },
+ },
+ ],
+ pagination: { next_cursor: null },
+}
+
+const MOCK_APP_GRANTS: Record<string, ListOrgAppGrantsResponse> = {
+ vercel: {
+ data: [
+ {
+ grant_id: 'grant-vercel-admin',
+ kind: 'member_bound',
+ user: {
+ gotrue_id: 'b1d3e2f4-0000-4000-8000-000000000001',
+ email: '[email protected]',
+ },
+ projects: [
+ { ref: 'northwindstorefront1', name: 'northwind-storefront' },
+ { ref: 'northwindcms1', name: 'northwind-cms' },
+ ],
+ approved_scopes: ['database:read', 'database:write', 'projects:read'],
+ approved_at: '2026-08-18T09:12:00.000Z',
+ },
+ {
+ grant_id: 'grant-vercel-developer',
+ kind: 'member_bound',
+ user: {
+ gotrue_id: 'b1d3e2f4-0000-4000-8000-000000000002',
+ email: '[email protected]',
+ avatar_url: 'https://avatars.example/developer.png',
+ },
+ projects: [{ ref: 'northwindcms1', name: 'northwind-cms' }],
+ approved_scopes: ['projects:read'],
+ approved_at: '2026-08-16T11:30:00.000Z',
+ },
+ ],
+ pagination: { next_cursor: null },
+ },
+ 'dynamic-mcp-client': {
+ data: [
+ {
+ grant_id: 'grant-northwind-mcp-ops',
+ kind: 'member_bound',
+ user: {
+ gotrue_id: 'b1d3e2f4-0000-4000-8000-000000000003',
+ email: '[email protected]',
+ },
+ projects: [{ ref: 'northwindstorefront1', name: 'northwind-storefront' }],
+ approved_scopes: ['database:read', 'database:write'],
+ approved_at: '2026-09-01T08:45:00.000Z',
+ },
+ ],
+ pagination: { next_cursor: null },
+ },
+ 'contoso-analytics': {
+ data: [
+ {
+ grant_id: 'grant-contoso-analytics-org',
+ kind: 'organization_bound',
+ user: null,
+ projects: null,
+ approved_scopes: ['analytics:read', 'projects:read'],
+ approved_at: '2025-11-03T14:20:00.000Z',
+ },
+ ],
+ pagination: { next_cursor: null },
+ },
+}
+
+const MOCK_OWN_GRANTS: ListOwnGrantsResponse = {
+ data: [
+ {
+ grant_id: 'grant-vercel-admin',
+ app: { id: 'vercel', name: 'Vercel', icon: null },
+ organization: { slug: 'northwind-traders', name: 'Northwind Traders' },
+ projects: [
+ { ref: 'northwindstorefront1', name: 'northwind-storefront' },
+ { ref: 'northwindcms1', name: 'northwind-cms' },
+ ],
+ approved_scopes: ['database:read', 'database:write', 'projects:read'],
+ approved_at: '2026-08-18T09:12:00.000Z',
+ },
+ {
+ grant_id: 'grant-northwind-mcp-ops',
+ app: { id: 'dynamic-mcp-client', name: 'Northwind MCP', icon: null },
+ organization: { slug: 'northwind-traders', name: 'Northwind Traders' },
+ projects: [{ ref: 'northwindstorefront1', name: 'northwind-storefront' }],
+ approved_scopes: ['database:read', 'database:write'],
+ approved_at: '2026-09-01T08:45:00.000Z',
+ },
+ {
+ grant_id: 'kemal-bot-all-projects',
+ app: { id: 'kemal-bot', name: 'kemal-bot', icon: null },
+ organization: { slug: 'northwind-traders', name: 'Northwind Traders' },
+ // Targets all projects
+ projects: null,
+ approved_scopes: ['database:read', 'database:write'],
+ approved_at: '2026-09-20T14:30:00.000Z',
+ },
+ ],
+ pagination: { next_cursor: null },
+}
+
+// Fixture lists are small and static — cursor is accepted for real-endpoint parity but not
+// used to actually paginate the mock data.
+export function getMockOAuthApprovals(_cursor?: string): ListOAuthApprovalsResponse {
+ return MOCK_APPROVALS
+}
+
+export function getMockOAuthAppGrants(appId: string, _cursor?: string): ListOrgAppGrantsResponse {
+ return MOCK_APP_GRANTS[appId] ?? { data: [], pagination: { next_cursor: null } }
+}
+
+export function getMockOAuthOwnGrants(_cursor?: string): ListOwnGrantsResponse {
+ return MOCK_OWN_GRANTS
+}
+
+export function getMockOAuthAppsAuthorizeRequest(authId: string): OAuthAppsAuthorizeRequest {
+ const request = MOCK_AUTHORIZE_REQUESTS[authId]
+ if (!request) throw new Error(`No mock authorize request for id "${authId}"`)
+ return request
+}
+
+export function getMockOAuthAppsAuthorizeIdentity(authId: string): OAuthAppsAuthorizeIdentity {
+ const identity = MOCK_IDENTITIES[authId]
+ if (!identity) throw new Error(`No mock identity for id "${authId}"`)
+ return identity
+}
+
+export function getMockOAuthAppsAuthorizeOrganizationProjects(
+ slug: string
+): OAuthAppsAuthorizeOrganizationProject[] {
+ return MOCK_ORGANIZATION_PROJECTS[slug] ?? []
+}
+
+export function getMockOAuthOrgAppDetails(slug: string, appId: string): OAuthOrgAppDetails {
+ return MOCK_ORG_APP_DETAILS[slug]?.[appId] ?? DEFAULT_ORG_APP_DETAILS
+}
+
+function findMockOrganization(authId: string, slug: string): OAuthOrganizationRole | undefined {
+ return getMockOAuthAppsAuthorizeIdentity(authId).organizations.find(
+ (candidate) => candidate.slug === slug
+ )
+}
+
+const MOCK_OAUTH_STATE = 'mock_state_9f2c1b'
+
+function buildMockRedirectUrl(redirectUri: string, params: Record<string, string>) {
+ const url = new URL(redirectUri)
+ Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value))
+ return url.toString()
+}
+
+export function getMockOAuthAppsAuthorizeRedirect(
+ authId: string,
+ { approved }: { approved: boolean }
+) {
+ const request = getMockOAuthAppsAuthorizeRequest(authId)
+ const url = approved
+ ? buildMockRedirectUrl(request.redirect_uri, {
+ code: 'mock_authorization_code',
+ state: MOCK_OAUTH_STATE,
+ })
+ : buildMockRedirectUrl(request.redirect_uri, {
+ error: 'access_denied',
+ error_description: 'The user denied the authorization request',
+ state: MOCK_OAUTH_STATE,
+ })
+
+ return { url }
+}
+
+const ROLE_VALIDATED_SCENARIOS = new Set<string>([
+ OAUTH_APPS_MOCK_SCENARIOS.vercelRoleValidation,
+ OAUTH_APPS_MOCK_SCENARIOS.vercelAllProjects,
+ OAUTH_APPS_MOCK_SCENARIOS.kemalBotOrgWide,
+])
+
+function isReadOnlyRole(role: OrganizationRole) {
+ return role.id === READ_ONLY_ROLE.id
+}
+
+function isOwnerOrAdmin(role: OrganizationRole) {
+ return role.id === OWNER_ROLE.id || role.id === ADMINISTRATOR_ROLE.id
+}
+
+// Upfront org-level check shared by preflight-validation and the "all projects" branch of approve.
+// Never checks project-scoped roles (that's approve's job once project_refs are known).
+function evaluateGrantEligibility(
+ request: OAuthAppsAuthorizeRequest,
+ organization: OAuthOrganizationRole
+): OAuthAppsAuthorizePreflightResult {
+ if (request.grant_kind === 'organization_bound') {
+ if (isOwnerOrAdmin(organization.default_role)) return { ok: true }
+ return {
+ error_code: 'role_validation_failed',
+ message: `Your ${organization.default_role.name} role cannot install this app for the organization.`,
+ validation: { scope_target: 'organization', role: organization.default_role },
+ }
+ }
+
+ const failedScopes = request.scopes.filter(isWriteScope)
+ if (failedScopes.length === 0 || !isReadOnlyRole(organization.default_role)) return { ok: true }
+
+ return {
+ error_code: 'role_validation_failed',
+ message: `Your ${organization.default_role.name} role cannot satisfy this app's scopes for all projects.`,
+ validation: {
+ scope_target: 'all_projects',
+ role: organization.default_role,
+ failed_scopes: failedScopes,
+ },
+ }
+}
+
+export function getMockOAuthAppsPreflightValidation(
+ slug: string,
+ appId: string
+): OAuthAppsAuthorizePreflightResult {
+ const request = MOCK_APPS_BY_ID[appId]
+ const organization = MOCK_ORGANIZATIONS_BY_SLUG[slug]
+ if (!request || !organization) return { ok: true }
+
+ return evaluateGrantEligibility(request, organization)
+}
+
+export function getMockOAuthAppsAuthorizeApproveResult(
+ authId: string,
+ { slug, projectRefs }: { slug: string; projectRefs: string[] | undefined }
+): OAuthAppsAuthorizeApproveResult {
+ const approved = getMockOAuthAppsAuthorizeRedirect(authId, { approved: true })
+ if (!ROLE_VALIDATED_SCENARIOS.has(authId)) return approved
+
+ const request = getMockOAuthAppsAuthorizeRequest(authId)
+ const organization = findMockOrganization(authId, slug)
+ if (!organization) return approved
+
+ if (projectRefs === undefined || request.grant_kind === 'organization_bound') {
+ const result = evaluateGrantEligibility(request, organization)
+ return isPreflightValidationFailure(result) ? result : approved
+ }
+
+ const failedScopes = request.scopes.filter(isWriteScope)
+ if (failedScopes.length === 0) return approved
+
+ const blocked = getMockOAuthAppsAuthorizeOrganizationProjects(slug).filter(
+ (project) => projectRefs.includes(project.ref) && isReadOnlyRole(project.role)
+ )
+ if (blocked.length === 0) return approved
+
+ return {
+ error_code: 'role_validation_failed',
+ message: `Your role is read-only on ${blocked.length} of the selected projects.`,
+ validation: {
+ scope_target: 'projects',
+ failures: blocked.map(({ name, ref, role }) => ({
+ ref,
+ name,
+ role,
+ failed_scopes: failedScopes,
+ })),
+ },
+ }
+}
diff --git a/apps/studio/data/oauth-apps/oauth-apps-approvals-query.ts b/apps/studio/data/oauth-apps/oauth-apps-approvals-query.ts
new file mode 100644
index 00000000000..f440618196b
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-approvals-query.ts
@@ -0,0 +1,40 @@
+import { useQuery } from '@tanstack/react-query'
+
+import { oauthAppsKeys } from './keys'
+import { getMockOAuthApprovals, USE_MOCKS } from './mocks'
+import type { ListOAuthApprovalsResponse } from './types'
+import type { ResponseError, UseCustomQueryOptions } from '@/types'
+
+export type OAuthApprovalsVariables = {
+ slug?: string
+ cursor?: string
+}
+
+export type { ListOAuthApprovalsResponse, OAuthApprovalItem } from './types'
+
+export async function getOAuthApprovals({
+ slug,
+ cursor,
+}: OAuthApprovalsVariables): Promise<ListOAuthApprovalsResponse> {
+ if (!slug) throw new Error('Organization slug is required')
+ if (!USE_MOCKS) throw new Error('OAuth app approvals are not yet implemented')
+
+ return getMockOAuthApprovals(cursor)
+}
+
+export type OAuthApprovalsData = Awaited<ReturnType<typeof getOAuthApprovals>>
+export type OAuthApprovalsError = ResponseError
+
+export const useOAuthApprovalsQuery = <TData = OAuthApprovalsData>(
+ { slug, cursor }: OAuthApprovalsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<OAuthApprovalsData, OAuthApprovalsError, TData> = {}
+) =>
+ useQuery<OAuthApprovalsData, OAuthApprovalsError, TData>({
+ queryKey: oauthAppsKeys.approvals(slug, cursor),
+ queryFn: () => getOAuthApprovals({ slug, cursor }),
+ enabled: enabled && USE_MOCKS && Boolean(slug),
+ ...options,
+ })
diff --git a/apps/studio/data/oauth-apps/oauth-apps-authorize-approve-mutation.ts b/apps/studio/data/oauth-apps/oauth-apps-authorize-approve-mutation.ts
new file mode 100644
index 00000000000..d3da65fb547
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-authorize-approve-mutation.ts
@@ -0,0 +1,56 @@
+import { useMutation } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { getMockOAuthAppsAuthorizeApproveResult, USE_MOCKS } from './mocks'
+import type { OAuthAppsAuthorizeApproveResult, OAuthAuthorizeApproveRequest } from './types'
+import type { ResponseError, UseCustomMutationOptions } from '@/types'
+
+export type OAuthAppsAuthorizeApproveVariables = {
+ slug: string
+ auth_id: string
+ body: OAuthAuthorizeApproveRequest
+}
+
+export type OAuthAppsAuthorizeApproveResponse = OAuthAppsAuthorizeApproveResult
+
+export async function approveOAuthAppsAuthorize({
+ slug,
+ auth_id,
+ body,
+}: OAuthAppsAuthorizeApproveVariables): Promise<OAuthAppsAuthorizeApproveResult> {
+ if (!auth_id) throw new Error('Authorization request id is required')
+ if (!slug) throw new Error('Organization slug is required')
+ if (!USE_MOCKS) throw new Error('OAuth app authorization approval is not yet implemented')
+
+ return getMockOAuthAppsAuthorizeApproveResult(auth_id, { slug, projectRefs: body.project_refs })
+}
+
+type OAuthAppsAuthorizeApproveData = Awaited<ReturnType<typeof approveOAuthAppsAuthorize>>
+
+export const useOAuthAppsAuthorizeApproveMutation = ({
+ onError,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<
+ OAuthAppsAuthorizeApproveData,
+ ResponseError,
+ OAuthAppsAuthorizeApproveVariables
+ >,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<
+ OAuthAppsAuthorizeApproveData,
+ ResponseError,
+ OAuthAppsAuthorizeApproveVariables
+ >({
+ mutationFn: (vars) => approveOAuthAppsAuthorize(vars),
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to authorize access to OAuth app: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/oauth-apps/oauth-apps-authorize-deny-mutation.ts b/apps/studio/data/oauth-apps/oauth-apps-authorize-deny-mutation.ts
new file mode 100644
index 00000000000..e54431cd965
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-authorize-deny-mutation.ts
@@ -0,0 +1,47 @@
+import { useMutation } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { getMockOAuthAppsAuthorizeRedirect, USE_MOCKS } from './mocks'
+import type { OAuthAppsAuthorizeRedirect } from './types'
+import type { ResponseError, UseCustomMutationOptions } from '@/types'
+
+export type OAuthAppsAuthorizeDenyVariables = {
+ slug: string
+ auth_id: string
+}
+
+export type OAuthAppsAuthorizeDenyResponse = OAuthAppsAuthorizeRedirect
+
+export async function denyOAuthAppsAuthorize({ slug, auth_id }: OAuthAppsAuthorizeDenyVariables) {
+ if (!auth_id) throw new Error('Authorization request id is required')
+ if (!slug) throw new Error('Organization slug is required')
+ if (!USE_MOCKS) throw new Error('OAuth app authorization denial is not yet implemented')
+
+ return getMockOAuthAppsAuthorizeRedirect(auth_id, { approved: false })
+}
+
+type OAuthAppsAuthorizeDenyData = Awaited<ReturnType<typeof denyOAuthAppsAuthorize>>
+
+export const useOAuthAppsAuthorizeDenyMutation = ({
+ onError,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<
+ OAuthAppsAuthorizeDenyData,
+ ResponseError,
+ OAuthAppsAuthorizeDenyVariables
+ >,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<OAuthAppsAuthorizeDenyData, ResponseError, OAuthAppsAuthorizeDenyVariables>({
+ mutationFn: (vars) => denyOAuthAppsAuthorize(vars),
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to deny access to OAuth app: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/oauth-apps/oauth-apps-authorize-mutations.test.ts b/apps/studio/data/oauth-apps/oauth-apps-authorize-mutations.test.ts
new file mode 100644
index 00000000000..f53884948b3
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-authorize-mutations.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, test } from 'vitest'
+
+import { OAUTH_APPS_MOCK_SCENARIOS } from './mocks'
+import { approveOAuthAppsAuthorize } from './oauth-apps-authorize-approve-mutation'
+import { denyOAuthAppsAuthorize } from './oauth-apps-authorize-deny-mutation'
+import { isRoleValidationFailure } from './types'
+
+const AUTH_ID = OAUTH_APPS_MOCK_SCENARIOS.vercelDeveloper
+const SLUG = 'northwind-traders'
+const BODY = { project_refs: ['northwindstorefront1'] }
+
+async function approveExpectingRedirect(
+ variables: Parameters<typeof approveOAuthAppsAuthorize>[0]
+) {
+ const result = await approveOAuthAppsAuthorize(variables)
+ if (isRoleValidationFailure(result)) throw new Error('expected a redirect, got a role failure')
+ return result
+}
+
+describe('approveOAuthAppsAuthorize', () => {
+ test('returns a redirect url carrying both code and state', async () => {
+ const { url } = await approveExpectingRedirect({ slug: SLUG, auth_id: AUTH_ID, body: BODY })
+
+ const params = new URL(url).searchParams
+ expect(params.get('code')).toBeTruthy()
+ expect(params.get('state')).toBeTruthy()
+ expect(params.get('error')).toBeNull()
+ })
+
+ test('accepts a body without project_refs', async () => {
+ const { url } = await approveExpectingRedirect({ slug: SLUG, auth_id: AUTH_ID, body: {} })
+
+ expect(new URL(url).searchParams.get('code')).toBeTruthy()
+ })
+
+ test('requires an authorization request id', async () => {
+ await expect(
+ approveOAuthAppsAuthorize({ slug: SLUG, auth_id: '', body: BODY })
+ ).rejects.toThrow('Authorization request id is required')
+ })
+
+ test('requires an organization slug', async () => {
+ await expect(
+ approveOAuthAppsAuthorize({ slug: '', auth_id: AUTH_ID, body: BODY })
+ ).rejects.toThrow('Organization slug is required')
+ })
+
+ test('does not enforce a selection cap', async () => {
+ const manyRefs = Array.from({ length: 25 }, (_, index) => `ref-${index}`)
+
+ const { url } = await approveExpectingRedirect({
+ slug: SLUG,
+ auth_id: AUTH_ID,
+ body: { project_refs: manyRefs },
+ })
+
+ expect(url).toBeTruthy()
+ })
+})
+
+describe('denyOAuthAppsAuthorize', () => {
+ test('returns a redirect url carrying access_denied and state', async () => {
+ const { url } = await denyOAuthAppsAuthorize({ slug: SLUG, auth_id: AUTH_ID })
+
+ const params = new URL(url).searchParams
+ expect(params.get('error')).toBe('access_denied')
+ expect(params.get('state')).toBeTruthy()
+ expect(params.get('code')).toBeNull()
+ })
+
+ test('requires an authorization request id', async () => {
+ await expect(denyOAuthAppsAuthorize({ slug: SLUG, auth_id: '' })).rejects.toThrow(
+ 'Authorization request id is required'
+ )
+ })
+
+ test('requires an organization slug', async () => {
+ await expect(denyOAuthAppsAuthorize({ slug: '', auth_id: AUTH_ID })).rejects.toThrow(
+ 'Organization slug is required'
+ )
+ })
+})
diff --git a/apps/studio/data/oauth-apps/oauth-apps-authorize-organization-projects-query.ts b/apps/studio/data/oauth-apps/oauth-apps-authorize-organization-projects-query.ts
new file mode 100644
index 00000000000..8881f59a2b1
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-authorize-organization-projects-query.ts
@@ -0,0 +1,53 @@
+import { useQuery } from '@tanstack/react-query'
+
+import { oauthAppsKeys } from './keys'
+import { getMockOAuthAppsAuthorizeOrganizationProjects, USE_MOCKS } from './mocks'
+import type { ResponseError, UseCustomQueryOptions } from '@/types'
+
+export type OAuthAppsAuthorizeOrganizationProjectsVariables = {
+ id?: string
+ slug?: string
+}
+
+export type { OAuthAppsAuthorizeOrganizationProject } from './types'
+
+export async function getOAuthAppsAuthorizeOrganizationProjects({
+ id,
+ slug,
+}: OAuthAppsAuthorizeOrganizationProjectsVariables) {
+ if (!id) throw new Error('Authorization request id is required')
+ if (!slug) throw new Error('Organization slug is required')
+ if (!USE_MOCKS)
+ throw new Error('OAuth app authorization organization projects are not yet implemented')
+
+ return getMockOAuthAppsAuthorizeOrganizationProjects(slug)
+}
+
+export type OAuthAppsAuthorizeOrganizationProjectsData = Awaited<
+ ReturnType<typeof getOAuthAppsAuthorizeOrganizationProjects>
+>
+export type OAuthAppsAuthorizeOrganizationProjectsError = ResponseError
+
+export const useOAuthAppsAuthorizeOrganizationProjectsQuery = <
+ TData = OAuthAppsAuthorizeOrganizationProjectsData,
+>(
+ { id, slug }: OAuthAppsAuthorizeOrganizationProjectsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<
+ OAuthAppsAuthorizeOrganizationProjectsData,
+ OAuthAppsAuthorizeOrganizationProjectsError,
+ TData
+ > = {}
+) =>
+ useQuery<
+ OAuthAppsAuthorizeOrganizationProjectsData,
+ OAuthAppsAuthorizeOrganizationProjectsError,
+ TData
+ >({
+ queryKey: oauthAppsKeys.authorizeOrganizationProjects(id, slug),
+ queryFn: () => getOAuthAppsAuthorizeOrganizationProjects({ id, slug }),
+ enabled: enabled && USE_MOCKS && Boolean(id) && Boolean(slug),
+ ...options,
+ })
diff --git a/apps/studio/data/oauth-apps/oauth-apps-authorize-organizations-query.ts b/apps/studio/data/oauth-apps/oauth-apps-authorize-organizations-query.ts
new file mode 100644
index 00000000000..c41bf4992f3
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-authorize-organizations-query.ts
@@ -0,0 +1,49 @@
+import { useQuery } from '@tanstack/react-query'
+
+import { oauthAppsKeys } from './keys'
+import { getMockOAuthAppsAuthorizeIdentity, USE_MOCKS } from './mocks'
+import type { OAuthOrganizationRole } from './types'
+import type { ResponseError, UseCustomQueryOptions } from '@/types'
+
+export type OAuthAppsAuthorizeOrganizationsVariables = {
+ id?: string
+}
+
+export type OAuthAppsAuthorizeIdentity = {
+ email: string
+ organizations: OAuthOrganizationRole[]
+}
+
+export async function getOAuthAppsAuthorizeIdentity({
+ id,
+}: OAuthAppsAuthorizeOrganizationsVariables) {
+ if (!id) throw new Error('Authorization request id is required')
+ if (!USE_MOCKS) throw new Error('OAuth app authorization identity is not yet implemented')
+
+ return getMockOAuthAppsAuthorizeIdentity(id)
+}
+
+export type OAuthAppsAuthorizeOrganizationsData = Awaited<
+ ReturnType<typeof getOAuthAppsAuthorizeIdentity>
+>
+export type OAuthAppsAuthorizeOrganizationsError = ResponseError
+
+export const useOAuthAppsAuthorizeOrganizationsQuery = <
+ TData = OAuthAppsAuthorizeOrganizationsData,
+>(
+ { id }: OAuthAppsAuthorizeOrganizationsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<
+ OAuthAppsAuthorizeOrganizationsData,
+ OAuthAppsAuthorizeOrganizationsError,
+ TData
+ > = {}
+) =>
+ useQuery<OAuthAppsAuthorizeOrganizationsData, OAuthAppsAuthorizeOrganizationsError, TData>({
+ queryKey: oauthAppsKeys.authorizeOrganizations(id),
+ queryFn: () => getOAuthAppsAuthorizeIdentity({ id }),
+ enabled: enabled && USE_MOCKS && Boolean(id),
+ ...options,
+ })
diff --git a/apps/studio/data/oauth-apps/oauth-apps-authorize-request-query.ts b/apps/studio/data/oauth-apps/oauth-apps-authorize-request-query.ts
new file mode 100644
index 00000000000..a231073e086
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-authorize-request-query.ts
@@ -0,0 +1,42 @@
+import { useQuery } from '@tanstack/react-query'
+
+import { oauthAppsKeys } from './keys'
+import { getMockOAuthAppsAuthorizeRequest, USE_MOCKS } from './mocks'
+import type { OAuthAppsAuthorizeRequest } from './types'
+import type { ResponseError, UseCustomQueryOptions } from '@/types'
+
+export type OAuthAppsAuthorizeRequestVariables = {
+ id?: string
+}
+
+export type { OAuthAppsAuthorizeRequest } from './types'
+
+export async function getOAuthAppsAuthorizeRequest({
+ id,
+}: OAuthAppsAuthorizeRequestVariables): Promise<OAuthAppsAuthorizeRequest> {
+ if (!id) throw new Error('Authorization request id is required')
+ if (!USE_MOCKS) throw new Error('OAuth app authorization request is not yet implemented')
+
+ return getMockOAuthAppsAuthorizeRequest(id)
+}
+
+export type OAuthAppsAuthorizeRequestData = Awaited<ReturnType<typeof getOAuthAppsAuthorizeRequest>>
+export type OAuthAppsAuthorizeRequestError = ResponseError
+
+export const useOAuthAppsAuthorizeRequestQuery = <TData = OAuthAppsAuthorizeRequestData>(
+ { id }: OAuthAppsAuthorizeRequestVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<
+ OAuthAppsAuthorizeRequestData,
+ OAuthAppsAuthorizeRequestError,
+ TData
+ > = {}
+) =>
+ useQuery<OAuthAppsAuthorizeRequestData, OAuthAppsAuthorizeRequestError, TData>({
+ queryKey: oauthAppsKeys.authorizeRequest(id),
+ queryFn: () => getOAuthAppsAuthorizeRequest({ id }),
+ enabled: enabled && USE_MOCKS && Boolean(id),
+ ...options,
+ })
diff --git a/apps/studio/data/oauth-apps/oauth-apps-grants-query.ts b/apps/studio/data/oauth-apps/oauth-apps-grants-query.ts
new file mode 100644
index 00000000000..f5f300fc160
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-grants-query.ts
@@ -0,0 +1,37 @@
+import { useQuery } from '@tanstack/react-query'
+
+import { oauthAppsKeys } from './keys'
+import { getMockOAuthOwnGrants, USE_MOCKS } from './mocks'
+import type { ListOwnGrantsResponse } from './types'
+import type { ResponseError, UseCustomQueryOptions } from '@/types'
+
+export type OAuthGrantsVariables = {
+ cursor?: string
+}
+
+export type { ListOwnGrantsResponse, MemberOauthGrantItem, OAuthGrantProject } from './types'
+
+export async function getOAuthGrants({
+ cursor,
+}: OAuthGrantsVariables = {}): Promise<ListOwnGrantsResponse> {
+ if (!USE_MOCKS) throw new Error('OAuth grants are not yet implemented')
+
+ return getMockOAuthOwnGrants(cursor)
+}
+
+export type OAuthGrantsData = Awaited<ReturnType<typeof getOAuthGrants>>
+export type OAuthGrantsError = ResponseError
+
+export const useOAuthGrantsQuery = <TData = OAuthGrantsData>(
+ { cursor }: OAuthGrantsVariables = {},
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<OAuthGrantsData, OAuthGrantsError, TData> = {}
+) =>
+ useQuery<OAuthGrantsData, OAuthGrantsError, TData>({
+ queryKey: oauthAppsKeys.grants(cursor),
+ queryFn: () => getOAuthGrants({ cursor }),
+ enabled: enabled && USE_MOCKS,
+ ...options,
+ })
diff --git a/apps/studio/data/oauth-apps/oauth-apps-member-grants-query.ts b/apps/studio/data/oauth-apps/oauth-apps-member-grants-query.ts
new file mode 100644
index 00000000000..6cef0997500
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-member-grants-query.ts
@@ -0,0 +1,43 @@
+import { useQuery } from '@tanstack/react-query'
+
+import { oauthAppsKeys } from './keys'
+import { getMockOAuthAppGrants, USE_MOCKS } from './mocks'
+import type { ListOrgAppGrantsResponse } from './types'
+import type { ResponseError, UseCustomQueryOptions } from '@/types'
+
+export type OAuthAppMemberGrantsVariables = {
+ slug?: string
+ appId?: string
+ cursor?: string
+}
+
+export type { ListOrgAppGrantsResponse, OAuthGrantItem, OAuthGrantProject } from './types'
+
+export async function getOAuthAppMemberGrants({
+ slug,
+ appId,
+ cursor,
+}: OAuthAppMemberGrantsVariables): Promise<ListOrgAppGrantsResponse> {
+ if (!slug) throw new Error('Organization slug is required')
+ if (!appId) throw new Error('App id is required')
+ if (!USE_MOCKS) throw new Error('OAuth app member grants are not yet implemented')
+
+ return getMockOAuthAppGrants(appId, cursor)
+}
+
+export type OAuthAppMemberGrantsData = Awaited<ReturnType<typeof getOAuthAppMemberGrants>>
+export type OAuthAppMemberGrantsError = ResponseError
+
+export const useOAuthAppMemberGrantsQuery = <TData = OAuthAppMemberGrantsData>(
+ { slug, appId, cursor }: OAuthAppMemberGrantsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<OAuthAppMemberGrantsData, OAuthAppMemberGrantsError, TData> = {}
+) =>
+ useQuery<OAuthAppMemberGrantsData, OAuthAppMemberGrantsError, TData>({
+ queryKey: oauthAppsKeys.appMemberGrants(slug, appId, cursor),
+ queryFn: () => getOAuthAppMemberGrants({ slug, appId, cursor }),
+ enabled: enabled && USE_MOCKS && Boolean(slug) && Boolean(appId),
+ ...options,
+ })
diff --git a/apps/studio/data/oauth-apps/oauth-apps-org-app-details-query.ts b/apps/studio/data/oauth-apps/oauth-apps-org-app-details-query.ts
new file mode 100644
index 00000000000..169ae55359e
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-org-app-details-query.ts
@@ -0,0 +1,41 @@
+import { useQuery } from '@tanstack/react-query'
+
+import { oauthAppsKeys } from './keys'
+import { getMockOAuthOrgAppDetails, USE_MOCKS } from './mocks'
+import type { OAuthOrgAppDetails } from './types'
+import type { ResponseError, UseCustomQueryOptions } from '@/types'
+
+export type OAuthOrgAppDetailsVariables = {
+ slug?: string
+ appId?: string
+}
+
+export type { OAuthOrgAppDetails } from './types'
+
+export async function getOAuthOrgAppDetails({
+ slug,
+ appId,
+}: OAuthOrgAppDetailsVariables): Promise<OAuthOrgAppDetails> {
+ if (!slug) throw new Error('Organization slug is required')
+ if (!appId) throw new Error('App id is required')
+ if (!USE_MOCKS) throw new Error('OAuth org app details are not yet implemented')
+
+ return getMockOAuthOrgAppDetails(slug, appId)
+}
+
+export type OAuthOrgAppDetailsData = Awaited<ReturnType<typeof getOAuthOrgAppDetails>>
+export type OAuthOrgAppDetailsError = ResponseError
+
+export const useOAuthOrgAppDetailsQuery = <TData = OAuthOrgAppDetailsData>(
+ { slug, appId }: OAuthOrgAppDetailsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<OAuthOrgAppDetailsData, OAuthOrgAppDetailsError, TData> = {}
+) =>
+ useQuery<OAuthOrgAppDetailsData, OAuthOrgAppDetailsError, TData>({
+ queryKey: oauthAppsKeys.orgAppDetails(slug, appId),
+ queryFn: () => getOAuthOrgAppDetails({ slug, appId }),
+ enabled: enabled && USE_MOCKS && Boolean(slug) && Boolean(appId),
+ ...options,
+ })
diff --git a/apps/studio/data/oauth-apps/oauth-apps-preflight-validation-query.ts b/apps/studio/data/oauth-apps/oauth-apps-preflight-validation-query.ts
new file mode 100644
index 00000000000..5bf8f6a2e68
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-preflight-validation-query.ts
@@ -0,0 +1,47 @@
+import { useQuery } from '@tanstack/react-query'
+
+import { oauthAppsKeys } from './keys'
+import { getMockOAuthAppsPreflightValidation, USE_MOCKS } from './mocks'
+import type { OAuthAppsAuthorizePreflightResult } from './types'
+import type { ResponseError, UseCustomQueryOptions } from '@/types'
+
+export type OAuthAppsPreflightValidationVariables = {
+ slug?: string
+ appId?: string
+}
+
+export type { OAuthAppsAuthorizePreflightResult } from './types'
+
+export async function getOAuthAppsPreflightValidation({
+ slug,
+ appId,
+}: OAuthAppsPreflightValidationVariables): Promise<OAuthAppsAuthorizePreflightResult> {
+ if (!slug) throw new Error('Organization slug is required')
+ if (!appId) throw new Error('App id is required')
+ if (!USE_MOCKS) throw new Error('OAuth app preflight validation is not yet implemented')
+
+ return getMockOAuthAppsPreflightValidation(slug, appId)
+}
+
+export type OAuthAppsPreflightValidationData = Awaited<
+ ReturnType<typeof getOAuthAppsPreflightValidation>
+>
+export type OAuthAppsPreflightValidationError = ResponseError
+
+export const useOAuthAppsPreflightValidationQuery = <TData = OAuthAppsPreflightValidationData>(
+ { slug, appId }: OAuthAppsPreflightValidationVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<
+ OAuthAppsPreflightValidationData,
+ OAuthAppsPreflightValidationError,
+ TData
+ > = {}
+) =>
+ useQuery<OAuthAppsPreflightValidationData, OAuthAppsPreflightValidationError, TData>({
+ queryKey: oauthAppsKeys.preflightValidation(slug, appId),
+ queryFn: () => getOAuthAppsPreflightValidation({ slug, appId }),
+ enabled: enabled && USE_MOCKS && Boolean(slug) && Boolean(appId),
+ ...options,
+ })
diff --git a/apps/studio/data/oauth-apps/oauth-apps-revoke-grant-mutation.ts b/apps/studio/data/oauth-apps/oauth-apps-revoke-grant-mutation.ts
new file mode 100644
index 00000000000..e7fe1faa1b4
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-revoke-grant-mutation.ts
@@ -0,0 +1,48 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { oauthAppsKeys } from './keys'
+import { USE_MOCKS } from './mocks'
+import type { ResponseError, UseCustomMutationOptions } from '@/types'
+
+export type OAuthGrantRevokeVariables = {
+ slug: string
+ grantId: string
+}
+
+export async function revokeOAuthGrant({ slug, grantId }: OAuthGrantRevokeVariables) {
+ if (!slug) throw new Error('Organization slug is required')
+ if (!grantId) throw new Error('Grant id is required')
+ if (!USE_MOCKS) throw new Error('OAuth grant revocation is not yet implemented')
+
+ // 204 on success — no response body.
+}
+
+type OAuthGrantRevokeData = Awaited<ReturnType<typeof revokeOAuthGrant>>
+
+export const useOAuthGrantRevokeMutation = ({
+ onError,
+ onSuccess,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<OAuthGrantRevokeData, ResponseError, OAuthGrantRevokeVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<OAuthGrantRevokeData, ResponseError, OAuthGrantRevokeVariables>({
+ mutationFn: (vars) => revokeOAuthGrant(vars),
+ async onSuccess(data, variables, context) {
+ await queryClient.invalidateQueries({ queryKey: oauthAppsKeys.grants() })
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to revoke OAuth grant: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/oauth-apps/oauth-apps-revoke-mutation.ts b/apps/studio/data/oauth-apps/oauth-apps-revoke-mutation.ts
new file mode 100644
index 00000000000..72f80a5b592
--- /dev/null
+++ b/apps/studio/data/oauth-apps/oauth-apps-revoke-mutation.ts
@@ -0,0 +1,57 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { oauthAppsKeys } from './keys'
+import { USE_MOCKS } from './mocks'
+import type { ResponseError, UseCustomMutationOptions } from '@/types'
+
+export type OAuthAppRevokeVariables = {
+ slug: string
+ appId: string
+}
+
+export async function revokeOAuthApp({ slug, appId }: OAuthAppRevokeVariables) {
+ if (!slug) throw new Error('Organization slug is required')
+ if (!appId) throw new Error('App id is required')
+ if (!USE_MOCKS) throw new Error('OAuth app revocation is not yet implemented')
+
+ return { id: appId }
+}
+
+type OAuthAppRevokeData = Awaited<ReturnType<typeof revokeOAuthApp>>
+
+export const useOAuthAppRevokeMutation = ({
+ onError,
+ onSuccess,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<OAuthAppRevokeData, ResponseError, OAuthAppRevokeVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<OAuthAppRevokeData, ResponseError, OAuthAppRevokeVariables>({
+ mutationFn: (vars) => revokeOAuthApp(vars),
+ async onSuccess(data, variables, context) {
+ // Revoking an app deletes every row for (app_id, organization_id), both kinds — the
+ // org's approvals overview, this app's grant list, and any member's own-grants view are
+ // all stale.
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: oauthAppsKeys.approvals(variables.slug) }),
+ queryClient.invalidateQueries({
+ queryKey: oauthAppsKeys.appMemberGrants(variables.slug, variables.appId),
+ }),
+ queryClient.invalidateQueries({ queryKey: oauthAppsKeys.grants() }),
+ ])
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to revoke OAuth app: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/oauth-apps/types.test.ts b/apps/studio/data/oauth-apps/types.test.ts
new file mode 100644
index 00000000000..0af62eee06a
--- /dev/null
+++ b/apps/studio/data/oauth-apps/types.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, test } from 'vitest'
+
+import { DEVELOPER_ROLE, READ_ONLY_ROLE } from './mocks'
+import type { OAuthAppsAuthorizeOrganizationProject, OAuthExistingGrant } from './types'
+import { getFailedProjects, getPreselectedProjectRefs, isRoleValidationFailure } from './types'
+
+const project = (ref: string): OAuthAppsAuthorizeOrganizationProject => ({
+ ref,
+ name: ref,
+ role: DEVELOPER_ROLE,
+})
+
+const grant = (refs: string[]): OAuthExistingGrant => ({
+ approved_scopes: ['projects:read'],
+ project_refs: refs,
+ approved_at: '2026-08-14T09:12:00.000Z',
+})
+
+describe('getPreselectedProjectRefs', () => {
+ const live = ['alpha', 'bravo', 'charlie', 'delta'].map(project)
+
+ test('preselects the project_ref query param when it resolves against live projects', () => {
+ expect(
+ getPreselectedProjectRefs({ existingGrant: null, projectRef: 'alpha', liveProjects: live })
+ ).toEqual(['alpha'])
+ })
+
+ test('drops a project_ref that does not resolve against live projects', () => {
+ expect(
+ getPreselectedProjectRefs({ existingGrant: null, projectRef: 'ghost', liveProjects: live })
+ ).toEqual([])
+ })
+
+ test('returns nothing when there is neither a grant nor a project_ref', () => {
+ expect(
+ getPreselectedProjectRefs({ existingGrant: null, projectRef: null, liveProjects: live })
+ ).toEqual([])
+ })
+
+ test('existing-grant refs win over the project_ref query param', () => {
+ expect(
+ getPreselectedProjectRefs({
+ existingGrant: grant(['charlie', 'delta']),
+ projectRef: 'alpha',
+ liveProjects: live,
+ })
+ ).toEqual(['charlie', 'delta'])
+ })
+
+ test('filters stale refs out of the existing grant', () => {
+ expect(
+ getPreselectedProjectRefs({
+ existingGrant: grant(['alpha', 'ghost']),
+ projectRef: null,
+ liveProjects: live,
+ })
+ ).toEqual(['alpha'])
+ })
+
+ test('falls back to the project_ref when the existing grant carries no refs', () => {
+ expect(
+ getPreselectedProjectRefs({
+ existingGrant: grant([]),
+ projectRef: 'bravo',
+ liveProjects: live,
+ })
+ ).toEqual(['bravo'])
+ })
+
+ test('does not cap the number of preselected refs', () => {
+ const manyProjects = Array.from({ length: 15 }, (_, index) => project(`ref-${index}`))
+ const manyRefs = manyProjects.map((entry) => entry.ref)
+
+ expect(
+ getPreselectedProjectRefs({
+ existingGrant: grant(manyRefs),
+ projectRef: null,
+ liveProjects: manyProjects,
+ })
+ ).toEqual(manyRefs)
+ })
+
+ test('returns nothing when there are no live projects', () => {
+ expect(
+ getPreselectedProjectRefs({
+ existingGrant: grant(['alpha']),
+ projectRef: 'alpha',
+ liveProjects: [],
+ })
+ ).toEqual([])
+ })
+})
+
+describe('isRoleValidationFailure', () => {
+ test('recognises a role validation failure', () => {
+ expect(
+ isRoleValidationFailure({
+ error_code: 'role_validation_failed',
+ message: 'nope',
+ validation: { scope_target: 'organization', role: READ_ONLY_ROLE },
+ })
+ ).toBe(true)
+ })
+
+ test('treats a redirect as a success', () => {
+ expect(isRoleValidationFailure({ url: 'https://vercel.com/callback?code=abc' })).toBe(false)
+ })
+})
+
+describe('getFailedProjects', () => {
+ test('returns the failures of a projects-level failure', () => {
+ const failure = {
+ ref: 'alpha',
+ name: 'alpha',
+ role: READ_ONLY_ROLE,
+ failed_scopes: ['database:write' as const],
+ }
+
+ expect(
+ getFailedProjects({
+ error_code: 'role_validation_failed',
+ message: 'nope',
+ validation: { scope_target: 'projects', failures: [failure] },
+ })
+ ).toEqual([failure])
+ })
+
+ test('is empty for an organization-level failure', () => {
+ expect(
+ getFailedProjects({
+ error_code: 'role_validation_failed',
+ message: 'nope',
+ validation: { scope_target: 'organization', role: READ_ONLY_ROLE },
+ })
+ ).toEqual([])
+ })
+
+ test('is empty when there is no failure', () => {
+ expect(getFailedProjects(null)).toEqual([])
+ expect(getFailedProjects(undefined)).toEqual([])
+ })
+})
diff --git a/apps/studio/data/oauth-apps/types.ts b/apps/studio/data/oauth-apps/types.ts
new file mode 100644
index 00000000000..4d811a3b37d
--- /dev/null
+++ b/apps/studio/data/oauth-apps/types.ts
@@ -0,0 +1,190 @@
+import type { components } from 'api-types'
+
+import type { OrganizationRole } from '@/data/organization-members/organization-roles-query'
+
+type LiveAuthorizeRequest = components['schemas']['GetOAuthAuthorizationResponse_Output']
+
+export type OAuthAppsAuthorizeLiveFields = Pick<
+ LiveAuthorizeRequest,
+ 'name' | 'website' | 'domain' | 'icon' | 'redirect_uri' | 'registration_type' | 'expires_at'
+>
+
+export type OAuthScope = NonNullable<LiveAuthorizeRequest['scopes']>[number]
+
+export function isWriteScope(scope: OAuthScope): boolean {
+ return scope.endsWith(':write')
+}
+
+export type OAuthGrantKind = 'organization_bound' | 'member_bound'
+
+export type OAuthAppsAuthorizeRequest = OAuthAppsAuthorizeLiveFields & {
+ app_id: string
+ app_name: string
+ grant_kind: OAuthGrantKind
+ project_scoping_mode: boolean
+ scopes: OAuthScope[]
+}
+
+export type OAuthOrganizationRole = {
+ slug: string
+ name: string
+ default_role: OrganizationRole
+}
+
+export type OAuthAppsAuthorizeOrganizationProject = {
+ ref: string
+ name: string
+ role: OrganizationRole
+}
+
+export type OAuthExistingGrant = {
+ approved_scopes: OAuthScope[] | null
+ project_refs: string[]
+ approved_at: string
+}
+
+export type OAuthOrgAppDetails = {
+ existing_grant: OAuthExistingGrant | null
+}
+
+export function getPreselectedProjectRefs({
+ existingGrant,
+ projectRef,
+ liveProjects,
+}: {
+ existingGrant: OAuthExistingGrant | null
+ projectRef: string | null
+ liveProjects: OAuthAppsAuthorizeOrganizationProject[]
+}): string[] {
+ const liveRefs = new Set(liveProjects.map((project) => project.ref))
+ const candidates = existingGrant?.project_refs.length
+ ? existingGrant.project_refs
+ : projectRef
+ ? [projectRef]
+ : []
+ return candidates.filter((ref) => liveRefs.has(ref))
+}
+
+export type OAuthAuthorizeApproveRequest = {
+ // not allowed when project_scoping_mode is false.
+ // when project_scoping_mode is true, if omitted, this means all projects
+ project_refs?: string[]
+}
+
+export type OAuthAppsAuthorizeRedirect =
+ components['schemas']['ApproveAuthorizationResponse_Output']
+
+export type OAuthScopeValidationResult =
+ | {
+ scope_target: 'organization'
+ role: OrganizationRole
+ }
+ | {
+ scope_target: 'all_projects'
+ role: OrganizationRole
+ failed_scopes: OAuthScope[]
+ }
+ | {
+ scope_target: 'projects'
+ failures: Array<{
+ ref: string
+ name: string
+ role: OrganizationRole
+ failed_scopes: OAuthScope[]
+ }>
+ }
+
+export type OAuthScopeValidationProjectFailure = Extract<
+ OAuthScopeValidationResult,
+ { scope_target: 'projects' }
+>['failures'][number]
+
+export type OAuthAppsAuthorizeRoleValidationFailure = {
+ error_code: 'role_validation_failed'
+ message: string
+ validation: OAuthScopeValidationResult
+}
+
+export type OAuthAppsAuthorizeApproveResult =
+ | OAuthAppsAuthorizeRedirect
+ | OAuthAppsAuthorizeRoleValidationFailure
+
+export function isRoleValidationFailure(
+ result: OAuthAppsAuthorizeApproveResult
+): result is OAuthAppsAuthorizeRoleValidationFailure {
+ return 'error_code' in result && result.error_code === 'role_validation_failed'
+}
+
+export function getFailedProjects(
+ failure: OAuthAppsAuthorizeRoleValidationFailure | null | undefined
+): OAuthScopeValidationProjectFailure[] {
+ if (!failure) return []
+ return failure.validation.scope_target === 'projects' ? failure.validation.failures : []
+}
+
+export type OAuthAppsAuthorizePreflightSuccess = { ok: true }
+
+export type OAuthAppsAuthorizePreflightResult =
+ | OAuthAppsAuthorizePreflightSuccess
+ | OAuthAppsAuthorizeRoleValidationFailure
+
+export function isPreflightValidationFailure(
+ result: OAuthAppsAuthorizePreflightResult
+): result is OAuthAppsAuthorizeRoleValidationFailure {
+ return 'error_code' in result && result.error_code === 'role_validation_failed'
+}
+
+export type OAuthApprovalTarget = 'organization' | 'members' | 'organization_and_members'
+
+export type OAuthApprovalItem = {
+ app: {
+ id: string
+ name: string
+ created_by: string
+ icon: string | null
+ }
+ grant_target: OAuthApprovalTarget
+ org_grant: {
+ grant_id: string
+ approved_scopes: string[]
+ approved_at: string
+ } | null
+}
+
+export type ListOAuthApprovalsResponse = {
+ data: OAuthApprovalItem[]
+ pagination: { next_cursor: string | null }
+}
+
+export type OAuthGrantProject = {
+ ref: string
+ name: string
+}
+
+export type OAuthGrantItem = {
+ grant_id: string
+ kind: OAuthGrantKind
+ user: { gotrue_id: string; email: string; avatar_url?: string } | null
+ projects: OAuthGrantProject[] | null
+ approved_scopes: string[]
+ approved_at: string
+}
+
+export type ListOrgAppGrantsResponse = {
+ data: OAuthGrantItem[]
+ pagination: { next_cursor: string | null }
+}
+
+export type MemberOauthGrantItem = {
+ grant_id: string
+ app: { id: string; name: string; icon: string | null }
+ organization: { slug: string; name: string }
+ projects: OAuthGrantProject[] | null
+ approved_scopes: string[]
+ approved_at: string
+}
+
+export type ListOwnGrantsResponse = {
+ data: MemberOauthGrantItem[]
+ pagination: { next_cursor: string | null }
+}
diff --git a/knip.jsonc b/knip.jsonc
index 7a79952a7e0..5baa43c1ad7 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -65,6 +65,13 @@
// read are documentation of the valid values, not dead code. Scoped to
// this file so `enumMembers` keeps working everywhere else.
"data/database/constraints-query.ts": ["enumMembers"],
+ // Data contracts and mock hooks for the OAuth authorization
+ // interstitial, landed ahead of the UI that consumes them. `exports`
+ // and `types` cover the contract types that only gain consumers in the
+ // consent-screen PR.
+ // TODO(PROD-625): drop every oauth-apps knip exception in the
+ // consent-screen PR, once the interstitial route imports them.
+ "data/oauth-apps/**": ["files", "exports", "types"],
"hooks/misc/useTrackExperimentExposure.ts": ["files"],
// Staging-only pinned Postgres image + FDW request payload for creating
// Warehouse test projects by hand. Nothing imports it yet — it's kept