The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): scoped pat root branch (#48384)
Gildas Garciacddb430310c1
diff --git a/apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts b/apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.tsnew file mode 100644index 00000000000..20932566e42--- /dev/null+++ b/apps/studio/app/api/scoped-access-token-permissions/MCPToolScopeMappings.ts@@ -0,0 +1,174 @@+import { constants, permissions } from '@supabase/shared-types'++import { McpMap } from '@/data/scoped-access-tokens/permission-scope-map-query'++const { OAuthScope } = constants++// Manually extracted from platform mcp controller code+const MCPToolOAuthScopeMapping = {+ apply_migration: [OAuthScope.DATABASE_WRITE],+ create_branch: [OAuthScope.ENVIRONMENT_WRITE],+ create_project: [OAuthScope.PROJECTS_WRITE],+ delete_branch: [OAuthScope.ENVIRONMENT_WRITE],+ deploy_edge_function: [OAuthScope.EDGE_FUNCTIONS_WRITE],+ execute_sql: [OAuthScope.DATABASE_READ, OAuthScope.DATABASE_WRITE],+ generate_typescript_types: [OAuthScope.DATABASE_READ],+ get_security_advisors: [OAuthScope.DATABASE_READ],+ get_performance_advisors: [OAuthScope.DATABASE_READ],+ get_edge_function: [OAuthScope.EDGE_FUNCTIONS_READ],+ get_logs: [OAuthScope.ANALYTICS_READ],+ get_organization: [OAuthScope.ORGANIZATIONS_READ],+ get_project: [OAuthScope.PROJECTS_READ],+ get_project_url: [OAuthScope.PROJECTS_READ],+ get_publishable_keys: [OAuthScope.SECRETS_READ],+ get_storage_config: [OAuthScope.STORAGE_READ],+ list_branches: [OAuthScope.ENVIRONMENT_READ],+ list_edge_functions: [OAuthScope.EDGE_FUNCTIONS_READ],+ list_migrations: [OAuthScope.DATABASE_READ],+ list_organizations: [OAuthScope.ORGANIZATIONS_READ],+ list_projects: [OAuthScope.PROJECTS_READ],+ list_storage_buckets: [OAuthScope.STORAGE_READ],+ merge_branch: [OAuthScope.ENVIRONMENT_WRITE],+ pause_project: [OAuthScope.PROJECTS_WRITE],+ rebase_branch: [OAuthScope.ENVIRONMENT_WRITE],+ reset_branch: [OAuthScope.ENVIRONMENT_WRITE],+ restore_project: [OAuthScope.PROJECTS_WRITE],+ update_storage_config: [OAuthScope.STORAGE_WRITE],+}++type ExtractIds<T> = {+ [K in keyof T]: {+ [P in keyof T[K]]: T[K][P] extends { id: infer I } ? I : never+ }+}+const FGA_PERMISSIONS = Object.fromEntries(+ Object.entries(permissions.FgaPermissions).map(([group, permissions]) => [+ group,+ Object.fromEntries(Object.entries(permissions).map(([key, { id }]) => [key, id])),+ ])+) as ExtractIds<typeof permissions.FgaPermissions>++// Duplicated from platform (packages/api-core/src/lib/permissions/fga-permissions.ts)+// Ideally, this could be exported from @supabase/shared-types+export const legacyOauthScopeToFgaPermissionMap: Record<string, string[]> = {+ 'analytics:read': [+ FGA_PERMISSIONS.PROJECT.ANALYTICS_LOGS_READ,+ FGA_PERMISSIONS.PROJECT.ANALYTICS_USAGE_READ,+ ],+ 'analytics:write': [],+ 'analytics_config:read': [FGA_PERMISSIONS.PROJECT.ANALYTICS_CONFIG_READ],+ 'analytics_config:write': [FGA_PERMISSIONS.PROJECT.ANALYTICS_CONFIG_WRITE],+ 'auth:read': [FGA_PERMISSIONS.PROJECT.AUTH_CONFIG_READ],+ // Note(Hieu) Auth:write scope grants access to all auth config endpoints.+ // However, one endpoint requires minimum administrator role, so this oauth scope must also include the FGA PROJECT.ADMIN_WRITE permission+ 'auth:write': [FGA_PERMISSIONS.PROJECT.ADMIN_WRITE, FGA_PERMISSIONS.PROJECT.AUTH_CONFIG_WRITE],+ 'database:read': [+ FGA_PERMISSIONS.USER.SNIPPETS_READ,+ FGA_PERMISSIONS.PROJECT.ADVISORS_READ,+ FGA_PERMISSIONS.PROJECT.BACKUPS_READ,+ FGA_PERMISSIONS.PROJECT.DATABASE_READ,+ FGA_PERMISSIONS.PROJECT.DATABASE_CONFIG_READ,+ FGA_PERMISSIONS.PROJECT.DATABASE_JIT_READ,+ FGA_PERMISSIONS.PROJECT.DATABASE_MIGRATIONS_READ,+ FGA_PERMISSIONS.PROJECT.DATABASE_POOLING_CONFIG_READ,+ FGA_PERMISSIONS.PROJECT.DATABASE_READONLY_CONFIG_READ,+ FGA_PERMISSIONS.PROJECT.DATABASE_SSL_CONFIG_READ,+ FGA_PERMISSIONS.PROJECT.SNIPPETS_READ,+ ],+ 'database:write': [+ FGA_PERMISSIONS.PROJECT.ADMIN_WRITE,+ FGA_PERMISSIONS.PROJECT.BACKUPS_WRITE,+ // Note(Hieu): Include database read permission here to align with the project query endpoint.+ // RLS and FGA guard this endpoint with database read first, then perform an additional check for write queries.+ // The OAuth guard requires database write directly, which causes a discrepancy error if we don't include read here.+ FGA_PERMISSIONS.PROJECT.DATABASE_READ,+ FGA_PERMISSIONS.PROJECT.DATABASE_WRITE,+ FGA_PERMISSIONS.PROJECT.DATABASE_CONFIG_WRITE,+ FGA_PERMISSIONS.PROJECT.DATABASE_MIGRATIONS_WRITE,+ FGA_PERMISSIONS.PROJECT.DATABASE_POOLING_CONFIG_WRITE,+ FGA_PERMISSIONS.PROJECT.DATABASE_READONLY_CONFIG_WRITE,+ FGA_PERMISSIONS.PROJECT.DATABASE_SSL_CONFIG_WRITE,+ FGA_PERMISSIONS.PROJECT.DATABASE_WEBHOOKS_CONFIG_WRITE,+ ],+ 'domains:read': [+ FGA_PERMISSIONS.PROJECT.CUSTOM_DOMAIN_READ,+ FGA_PERMISSIONS.PROJECT.VANITY_SUBDOMAIN_READ,+ ],+ 'domains:write': [+ FGA_PERMISSIONS.PROJECT.CUSTOM_DOMAIN_WRITE,+ FGA_PERMISSIONS.PROJECT.VANITY_SUBDOMAIN_WRITE,+ ],+ 'edge_functions:read': [FGA_PERMISSIONS.PROJECT.EDGE_FUNCTIONS_READ],+ 'edge_functions:write': [FGA_PERMISSIONS.PROJECT.EDGE_FUNCTIONS_WRITE],+ 'environment:read': [+ FGA_PERMISSIONS.PROJECT.ACTION_RUNS_READ,+ FGA_PERMISSIONS.PROJECT.BRANCHING_DEVELOPMENT_READ,+ FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_READ,+ ],+ 'environment:write': [+ FGA_PERMISSIONS.PROJECT.ACTION_RUNS_WRITE,+ FGA_PERMISSIONS.PROJECT.BRANCHING_DEVELOPMENT_CREATE,+ FGA_PERMISSIONS.PROJECT.BRANCHING_DEVELOPMENT_DELETE,+ FGA_PERMISSIONS.PROJECT.BRANCHING_DEVELOPMENT_WRITE,+ FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_CREATE,+ FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_DELETE,+ FGA_PERMISSIONS.PROJECT.BRANCHING_PRODUCTION_WRITE,+ ],+ 'organizations:read': [+ FGA_PERMISSIONS.USER.ORGANIZATIONS_READ,+ FGA_PERMISSIONS.ORGANIZATION.ADMIN_READ,+ FGA_PERMISSIONS.ORGANIZATION.MEMBERS_READ,+ ],+ 'organizations:write': [],+ 'projects:read': [+ FGA_PERMISSIONS.USER.PROJECTS_READ,+ FGA_PERMISSIONS.ORGANIZATION.PROJECTS_READ,+ FGA_PERMISSIONS.PROJECT.ADMIN_READ,+ FGA_PERMISSIONS.PROJECT.DATABASE_NETWORK_BANS_READ,+ FGA_PERMISSIONS.PROJECT.DATABASE_NETWORK_RESTRICTIONS_READ,+ ],+ 'projects:write': [+ FGA_PERMISSIONS.ORGANIZATION.ADMIN_WRITE,+ FGA_PERMISSIONS.ORGANIZATION.PROJECTS_CREATE,+ FGA_PERMISSIONS.PROJECT.ADMIN_WRITE,+ FGA_PERMISSIONS.PROJECT.DATABASE_NETWORK_BANS_WRITE,+ FGA_PERMISSIONS.PROJECT.DATABASE_NETWORK_RESTRICTIONS_WRITE,+ ],+ 'rest:read': [FGA_PERMISSIONS.PROJECT.DATA_API_CONFIG_READ],+ 'rest:write': [FGA_PERMISSIONS.PROJECT.DATA_API_CONFIG_WRITE],+ 'secrets:read': [+ FGA_PERMISSIONS.PROJECT.API_GATEWAY_KEYS_READ,+ FGA_PERMISSIONS.PROJECT.AUTH_SIGNING_KEYS_READ,+ FGA_PERMISSIONS.PROJECT.EDGE_FUNCTIONS_SECRETS_READ,+ ],+ 'secrets:write': [+ FGA_PERMISSIONS.PROJECT.API_GATEWAY_KEYS_WRITE,+ FGA_PERMISSIONS.PROJECT.AUTH_SIGNING_KEYS_WRITE,+ FGA_PERMISSIONS.PROJECT.EDGE_FUNCTIONS_SECRETS_WRITE,+ ],+ 'storage:read': [+ FGA_PERMISSIONS.PROJECT.STORAGE_READ,+ FGA_PERMISSIONS.PROJECT.STORAGE_CONFIG_READ,+ ],+ 'storage:write': [+ FGA_PERMISSIONS.PROJECT.STORAGE_WRITE,+ FGA_PERMISSIONS.PROJECT.STORAGE_CONFIG_WRITE,+ ],+}++/*+ * Build a map of MCP tools/FGA permissions by mapping their OAuth Scopes to the FGA permissions:+ * {+ * apply_migration: ["project_admin_write", ...]+ * }+ * The code is duplicated from platform until we find a better way to share those mappings+ */+export const MCPToolScopeMappings = Object.entries(MCPToolOAuthScopeMapping).reduce(+ (acc, [mcpTool, oAuthScopes]) => {+ acc[mcpTool] = oAuthScopes.flatMap(+ (oAuthScope) => legacyOauthScopeToFgaPermissionMap[oAuthScope]+ )+ return acc+ },+ {} as McpMap+)diff --git a/apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts b/apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.tsnew file mode 100644index 00000000000..367d6b3917f--- /dev/null+++ b/apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.test.ts@@ -0,0 +1,53 @@+import { describe, expect, test } from 'vitest'++import { getEndpointsAndMCPToolsForAPI } from './buildAPIPermissionScopeMap'++describe('getEndpointsAndMCPToolsForAPI', () => {+ const openAPISpecs = {+ paths: {+ '/v1/projects/{ref}/database/migrations': {+ get: {+ 'x-fga-permissions': [['database_migrations_read']],+ },+ post: {+ 'x-fga-permissions': [['database_migrations_write']],+ },+ },+ '/v1/projects/{ref}/database/migrations/{version}': {+ patch: {+ 'x-fga-permissions': [['database_migrations_write']],+ },+ },+ },+ }++ const mcp_tools = {+ list_migrations: ['database_migrations_read'],+ apply_migration: ['database_migrations_write', 'database_write'],+ }++ test('returns an object with permissions as keys and endpoints and mcp_tools as values', () => {+ const permissionScopeMap = getEndpointsAndMCPToolsForAPI(openAPISpecs, mcp_tools)++ expect(permissionScopeMap).toEqual({+ scopes: {+ database_migrations_read: {+ endpoints: ['GET /v1/projects/{ref}/database/migrations'],+ mcp_tools: ['list_migrations'],+ },+ database_migrations_write: {+ endpoints: [+ 'POST /v1/projects/{ref}/database/migrations',+ 'PATCH /v1/projects/{ref}/database/migrations/{version}',+ ],+ mcp_tools: ['apply_migration'],+ },+ },+ endpoints: {+ 'GET /v1/projects/{ref}/database/migrations': ['database_migrations_read'],+ 'POST /v1/projects/{ref}/database/migrations': ['database_migrations_write'],+ 'PATCH /v1/projects/{ref}/database/migrations/{version}': ['database_migrations_write'],+ },+ })+ })+})diff --git a/apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts b/apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.tsnew file mode 100644index 00000000000..57c7ffc70f0--- /dev/null+++ b/apps/studio/app/api/scoped-access-token-permissions/buildAPIPermissionScopeMap.ts@@ -0,0 +1,153 @@+import lodash from 'lodash'+import z from 'zod'++// We don't have an OpenAPI that describes mcp tools security requirements so+// we have this hard coded file that must be updated when they change+import { MCPToolScopeMappings } from './MCPToolScopeMappings'+import {+ EndpointMap,+ McpMap,+ PermissionScopeMap,+ ScopeMap,+} from '@/data/scoped-access-tokens/permission-scope-map-query'+import { InternalServerError } from '@/lib/api/apiHelpers'++// Default lodash merge does not correctly merge arrays so this custom merger fixes it+function mergeArrays(objValue: unknown, srcValue: unknown) {+ if (Array.isArray(objValue) && Array.isArray(srcValue)) {+ return objValue.concat(srcValue)+ }+}++/*+ * Builds the permissions/endpoint mapping by fetching the OpenAPI specs for our v1 and v2 APIs.+ * @throws InternalServerError when it can't fetch the OpenAPI specs+ */+export const buildAPIPermissionScopeMap = async (): Promise<PermissionScopeMap> => {+ // Get the permissions map for the API v1+ const apiV1SpecsJSON = await fetchAPIPermissionScope('v1')+ const apiV1Specs = API_SPECS_SCHEMA.parse(apiV1SpecsJSON)+ const permissionScopeMapV1 = getEndpointsAndMCPToolsForAPI(apiV1Specs, MCPToolScopeMappings)++ // Get the permissions map for the API v2+ const apiV2SpecsJSON = await fetchAPIPermissionScope('v2')+ const apiV2Specs = API_SPECS_SCHEMA.parse(apiV2SpecsJSON)+ const permissionScopeMapV2 = getEndpointsAndMCPToolsForAPI(apiV2Specs, MCPToolScopeMappings)++ const permissionScope = lodash.mergeWith(+ { mcp_tools: MCPToolScopeMappings },+ permissionScopeMapV1,+ permissionScopeMapV2,+ mergeArrays+ )++ return permissionScope+}++// OPEN API specs look like this (only kept the parts we're interested in):+// {+// "paths": {+// "/v2/projects/{ref}/analytics/log-drains": {+// "get": {+// "x-fga-permissions": [+// [+// "analytics_config_read"+// ]+// ]+// }+// }+// }+// }+export const getEndpointsAndMCPToolsForAPI = (+ apiSpecs: z.output<typeof API_SPECS_SCHEMA>,+ mcp_tools: McpMap+): Omit<PermissionScopeMap, 'mcp_tools'> => {+ const scopes: ScopeMap = {}+ const endpoints: EndpointMap = {}++ // Loop over each API path to assign endpoints to their scopes and+ // scopes to their endpoints+ Object.entries(apiSpecs.paths).forEach(([path, methods]) => {+ // Loop over each API path method (get, post, etc.)+ Object.entries(methods).forEach(([method, methodSpecs]) => {+ const endpoint = `${method.toUpperCase()} ${path}`+ if (methodSpecs['x-fga-permissions'] == null) return++ methodSpecs['x-fga-permissions'].forEach((permissions) => {+ permissions?.forEach((permission) => {+ // Initialize scope object if needed+ scopes[permission] = scopes[permission] || { endpoints: [], mcp_tools: [] }++ // Initialize endpoints array if needed+ endpoints[endpoint] = endpoints[endpoint] || []++ if (!scopes[permission].endpoints.includes(endpoint)) {+ scopes[permission].endpoints.push(endpoint)+ }+ if (!endpoints[endpoint].includes(permission)) {+ endpoints[endpoint].push(permission)+ }+ })+ })+ })+ })++ // Assign the mcp tools to their scopes+ Object.entries(mcp_tools).forEach(([mcpTool, toolScopes]) => {+ toolScopes.forEach((toolScope) => {+ if (scopes[toolScope] && !scopes[toolScope].mcp_tools.includes(mcpTool)) {+ scopes[toolScope].mcp_tools.push(mcpTool)+ }+ })+ })++ return { scopes, endpoints }+}++const NEXT_PUBLIC_API_DOMAIN = process.env.NEXT_PUBLIC_API_DOMAIN || 'https://api.supabase.com'++const fetchAPIPermissionScope = async (version: 'v1' | 'v2') => {+ try {+ const response = await fetch(`${NEXT_PUBLIC_API_DOMAIN}/api/${version}-json`, {+ method: 'get',+ headers: {+ 'Content-Type': 'application/json',+ },+ })+ if (response.ok) {+ return response.json()+ }+ const responseText = await response.text()++ const retryAfter = response.headers.get('Retry-After') ?? undefined+ throw new InternalServerError(`API v${version} responded with ${response.status}`, {+ status: response.status,+ body: responseText,+ ...(retryAfter !== undefined && { retryAfter }),+ })+ } catch (error: unknown) {+ if (error instanceof InternalServerError) {+ throw error+ }++ if (error instanceof Error) {+ throw new InternalServerError(error.message)+ }+ }+}++// Simplified OPEN API specs schemas that only defines what we care about for scoped tokens++const OPEN_API_PATH_METHOD_SCHEMA = z.object({+ 'x-fga-permissions': z.array(z.string().array().optional()).optional(),+})++const API_SPECS_SCHEMA = z.object({+ paths: z.record(+ z.string(),+ z.record(+ z.enum(['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'trace']),+ OPEN_API_PATH_METHOD_SCHEMA+ )+ ),+})diff --git a/apps/studio/app/api/scoped-access-token-permissions/route.ts b/apps/studio/app/api/scoped-access-token-permissions/route.tsnew file mode 100644index 00000000000..998ee654f79--- /dev/null+++ b/apps/studio/app/api/scoped-access-token-permissions/route.ts@@ -0,0 +1,66 @@+import { IS_PLATFORM } from 'common'+import { NextResponse } from 'next/server'++import { buildAPIPermissionScopeMap } from './buildAPIPermissionScopeMap'+import { InternalServerError } from '@/lib/api/apiHelpers'++/**+ * Cache on CDN for 5 minutes+ * Allow serving stale content for 1 minute while revalidating+ */+const CACHE_CONTROL_SETTINGS = 'public, s-maxage=300, stale-while-revalidate=60'++export async function OPTIONS() {+ if (!IS_PLATFORM) return new Response(null, { status: 404 })+ return new Response(null, {+ status: 204,+ headers: {+ Allow: 'GET, HEAD, OPTIONS',+ },+ })+}++export async function HEAD() {+ if (!IS_PLATFORM) return new Response(null, { status: 404 })+ return new Response(null, {+ status: 200,+ headers: { 'Cache-Control': CACHE_CONTROL_SETTINGS },+ })+}++/*+ * This route allows us to not add all permissions mappings to the client bundle.+ * Ideally, this should be provided by the management API, including MCP tools.+ */+export async function GET() {+ if (!IS_PLATFORM) return new Response(null, { status: 404 })++ try {+ const permissionsScopes = await buildAPIPermissionScopeMap()+ return NextResponse.json(permissionsScopes, {+ headers: { 'Cache-Control': CACHE_CONTROL_SETTINGS },+ })+ } catch (error) {+ let errorCode = 500+ const headers = new Headers()++ if (error instanceof InternalServerError) {+ if (typeof error.details?.status === 'number') errorCode = error.details.status+ if (errorCode === 420) errorCode = 429+ if (errorCode === 429 && typeof error.details?.retryAfter === 'string') {+ headers.set('Retry-After', error.details.retryAfter)+ }+ console.error('Failed to fetch scoped token permission scope map: %O', {+ message: error.message,+ details: error.details,+ })+ } else {+ console.error('Unexpected error fetching scoped token permission scope map: %O', error)+ }++ return NextResponse.json(+ { error: 'Unable to fetch scoped token permission scope map at this time' },+ { status: errorCode, headers }+ )+ }+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.tsnew file mode 100644index 00000000000..7bd9bee642e--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from 'vitest'++import {+ computeOverallRisk,+ countConfigured,+ getCatalogEntry,+ selectionToScopes,+ type PermissionSelection,+} from './AccessToken.permissions'+import {+ getEnabledEndpoints,+ getEnabledMcpTools,+} from '@/data/scoped-access-tokens/permission-scope-map-query'++describe('selectionToScopes', () => {+ it('ignores none and returns read scope for read mode', () => {+ const selection: PermissionSelection = { 'project:database': 'read', 'project:backups': 'none' }+ expect(selectionToScopes(selection)).toEqual(['database_read'])+ })++ it('returns read + write scopes for readwrite mode', () => {+ const selection: PermissionSelection = { 'project:database': 'readwrite' }+ expect(selectionToScopes(selection).sort()).toEqual(['database_read', 'database_write'])+ })++ it('dedupes and skips unknown keys', () => {+ const selection: PermissionSelection = {+ 'project:database': 'read',+ 'not:a-real-key': 'readwrite',+ }+ expect(selectionToScopes(selection)).toEqual(['database_read'])+ })++ it('read-only resources have no write scopes', () => {+ const advisors = getCatalogEntry('project:advisors')+ expect(advisors?.writable).toBe(false)+ expect(selectionToScopes({ 'project:advisors': 'readwrite' })).toEqual(['advisors_read'])+ })+})++describe('computeOverallRisk', () => {+ it('is Minimal with no capabilities', () => {+ expect(computeOverallRisk({}, 'project').level).toBe('Minimal')+ })++ it('account-level read-only is still Elevated', () => {+ const risk = computeOverallRisk({ 'project:advisors': 'read' }, 'account')+ expect(risk.level).toBe('Elevated')+ expect(risk.tone).toBe('medium')+ })++ it('account-level with any write is High', () => {+ const risk = computeOverallRisk({ 'project:realtime_config': 'readwrite' }, 'account')+ expect(risk.level).toBe('High')+ })++ it('project high-risk write is High', () => {+ expect(computeOverallRisk({ 'project:database': 'readwrite' }, 'project').level).toBe('High')+ })++ it('project medium write is Medium', () => {+ expect(computeOverallRisk({ 'project:realtime_config': 'readwrite' }, 'project').level).toBe(+ 'Medium'+ )+ })++ it('read-only project is Low', () => {+ expect(computeOverallRisk({ 'project:database': 'read' }, 'project').level).toBe('Low')+ })+})++describe('countConfigured', () => {+ it('counts only non-none modes', () => {+ expect(countConfigured({ a: 'read', b: 'none', c: 'readwrite' })).toBe(2)+ })+})++describe('permission scope map (dual-scope enforcement)', () => {+ it('enables a dual-scope MCP tool only when all required scopes are granted', () => {+ // execute_sql requires both database_read and database_write+ expect(+ getEnabledMcpTools({+ // Only scope one is granted+ grantedScopes: ['database_read'],+ permissionScopeMap: {+ scopes: {},+ endpoints: {},+ mcp_tools: {+ execute_sql: ['database_read', 'database_write'],+ },+ },+ })+ ).not.toContain('execute_sql')+ expect(+ getEnabledMcpTools({+ // Both scopes are granted+ grantedScopes: ['database_read', 'database_write'],+ permissionScopeMap: {+ scopes: {},+ endpoints: {},+ mcp_tools: {+ execute_sql: ['database_read', 'database_write'],+ },+ },+ })+ ).toContain('execute_sql')+ })++ it('only lists endpoints whose every required scope is granted', () => {+ const endpoints = getEnabledEndpoints({+ grantedScopes: ['database_read', 'database_write'],+ permissionScopeMap: {+ scopes: {},+ endpoints: {+ 'GET /api/valid_read': ['database_read'],+ 'POST /api/valid_write': ['database_write'],+ 'PUT /api/valid_both': ['database_read', 'database_write'],+ 'PUT /api/invalid': ['project_write'],+ 'PUT /api/incomplete': ['database_read', 'project_write'],+ },+ mcp_tools: {},+ },+ })+ expect(endpoints).toEqual([+ { raw: 'GET /api/valid_read', method: 'GET', path: '/api/valid_read' },+ { raw: 'POST /api/valid_write', method: 'POST', path: '/api/valid_write' },+ { raw: 'PUT /api/valid_both', method: 'PUT', path: '/api/valid_both' },+ ])+ })+})diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.tsnew file mode 100644index 00000000000..be204f9d45b--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts@@ -0,0 +1,643 @@+import { permissions } from '@supabase/shared-types'++import type { ScopedAccessTokenPermission } from './AccessToken.constants'++/**+ * Data model for the scoped access-token creation flow.+ *+ * The real permission scopes come from `@supabase/shared-types` (`FgaPermissions`). Those scopes+ * carry no category or risk metadata, so this file layers editable presentation data on top:+ * - PERMISSION_CATEGORIES groups every scope into one of five UI categories.+ * - RESOURCE_METADATA assigns each resource a display name, description, category and risk.+ *+ * TODO(product): the risk levels, reasons and "Allows" copy below are proposed defaults — review+ * and adjust. Where a resource has no explicit metadata entry we fall back to a heuristic.+ */++const FGA = permissions.FgaPermissions++export type PermissionMode = 'none' | 'read' | 'readwrite'+export type RiskLevel = 'low' | 'medium' | 'high'+export type PermissionCategoryKey = 'account' | 'project' | 'database' | 'appsvc' | 'infra'++export interface PermissionCategory {+ key: PermissionCategoryKey+ name: string+ description: string+}++/** Display order matches the accordion, where every category starts collapsed. */+export const PERMISSION_CATEGORIES: PermissionCategory[] = [+ {+ key: 'project',+ name: 'Project',+ description: 'Core project visibility, settings, and diagnostics.',+ },+ {+ key: 'database',+ name: 'Database',+ description: 'SQL access, migrations, backups, and data operations.',+ },+ {+ key: 'appsvc',+ name: 'Application Services',+ description: 'Auth, storage, realtime, edge functions, and service configuration.',+ },+ {+ key: 'infra',+ name: 'Infrastructure & Delivery',+ description: 'Branch automation, domains, add-ons, and network.',+ },+ {+ key: 'account',+ name: 'Account & Organization',+ description: 'Account-wide and organization-level access that spans projects.',+ },+]++interface ResourceMeta {+ category: PermissionCategoryKey+ name: string+ description: string+ risk: RiskLevel+ riskReason: string+ allowsRead?: string[]+ allowsWrite?: string[]+}++/**+ * Per-resource presentation metadata, keyed by the derived `scope:resource` key (see+ * AccessToken.constants → ACCESS_TOKEN_RESOURCES). Every resource returned from FgaPermissions+ * should have an entry; RESOURCE_METADATA_FALLBACK covers anything that slips through.+ */+const RESOURCE_METADATA: Record<string, ResourceMeta> = {+ // --- Account & Organization ---+ 'user:organizations': {+ category: 'account',+ name: 'Organizations',+ description: 'Organizations you belong to.',+ risk: 'medium',+ riskReason: 'Read-write can create new organizations under your account.',+ allowsRead: ['List your organizations'],+ allowsWrite: ['Create organizations'],+ },+ 'user:projects': {+ category: 'account',+ name: 'Projects (account-wide)',+ description: 'Projects across all your organizations.',+ risk: 'low',+ riskReason: 'Read-only listing of the projects you can access.',+ allowsRead: ['List your projects'],+ },+ 'user:snippets': {+ category: 'account',+ name: 'SQL Snippets (account-wide)',+ description: 'Saved SQL snippets across your account.',+ risk: 'low',+ riskReason: 'Read-only access to your saved snippets.',+ allowsRead: ['Read your SQL snippets'],+ },+ 'organization:admin': {+ category: 'account',+ name: 'Organization Settings',+ description: 'Organization settings and project transfers.',+ risk: 'high',+ riskReason: 'Read-write grants elevated access to organization settings and project transfers.',+ allowsRead: ['Read organization settings'],+ allowsWrite: ['Manage organization settings', 'Transfer projects'],+ },+ 'organization:members': {+ category: 'account',+ name: 'Organization Members',+ description: 'Members and roles within the organization.',+ risk: 'high',+ riskReason: 'Read-write can add or remove members and change roles across your organization.',+ allowsRead: ['Read organization members'],+ allowsWrite: ['Add or remove members', 'Change member roles'],+ },+ 'organization:projects': {+ category: 'account',+ name: 'Organization Projects',+ description: 'Projects within the organization.',+ risk: 'medium',+ riskReason: 'Read-write can create new projects in the organization.',+ allowsRead: ['List organization projects'],+ allowsWrite: ['Create organization projects'],+ },++ // --- Project ---+ 'project:admin': {+ category: 'project',+ name: 'Project Settings',+ description: 'Project metadata and settings.',+ risk: 'high',+ riskReason: 'Read-write grants elevated access to change project settings and configuration.',+ allowsRead: ['Read project metadata'],+ allowsWrite: ['Update project settings'],+ },+ 'project:action_runs': {+ category: 'project',+ name: 'Action Runs',+ description: 'Project action run status and logs.',+ risk: 'medium',+ riskReason: 'Read-write can trigger action runs that execute project workflows.',+ allowsRead: ['Read action run status', 'Read run logs'],+ allowsWrite: ['Trigger action runs'],+ },+ 'project:advisors': {+ category: 'project',+ name: 'Advisors',+ description: 'Security and performance advisor results.',+ risk: 'low',+ riskReason: 'Read-only access to advisor findings — no changes possible.',+ allowsRead: ['Read security advisors', 'Read performance advisors'],+ },+ 'project:analytics_logs': {+ category: 'project',+ name: 'Logs',+ description: 'Operational logs and log analytics.',+ risk: 'low',+ riskReason: 'Read-only access to project logs.',+ allowsRead: ['Read project logs'],+ },+ 'project:analytics_usage': {+ category: 'project',+ name: 'Usage Analytics',+ description: 'Project usage and analytics data.',+ risk: 'low',+ riskReason: 'Read-only access to usage analytics.',+ allowsRead: ['Read usage analytics'],+ },+ 'project:snippets': {+ category: 'project',+ name: 'SQL Snippets',+ description: 'Saved SQL snippets for the project.',+ risk: 'low',+ riskReason: 'Read-write can create and edit saved SQL snippets.',+ allowsRead: ['Read project SQL snippets'],+ allowsWrite: ['Manage project SQL snippets'],+ },++ // --- Database ---+ 'project:database': {+ category: 'database',+ name: 'Database',+ description: 'Database access and data operations.',+ risk: 'high',+ riskReason:+ 'Read-write lets this token run arbitrary SQL, so it can modify or delete any data in your database.',+ allowsRead: ['Read tables and schema', 'Run read-only queries'],+ allowsWrite: ['Run arbitrary SQL'],+ },+ 'project:database_migrations': {+ category: 'database',+ name: 'Migrations',+ description: 'Database migration history and application.',+ risk: 'high',+ riskReason:+ 'Read-write can apply schema changes that alter or drop tables across your database.',+ allowsRead: ['Read migration history'],+ allowsWrite: ['Apply migrations'],+ },+ 'project:backups': {+ category: 'database',+ name: 'Backups',+ description: 'Database backups, restore points, and restore.',+ risk: 'high',+ riskReason:+ 'Read-write can trigger restores that overwrite current data with an earlier snapshot.',+ allowsRead: ['Read backups and restore points'],+ allowsWrite: ['Trigger restores'],+ },+ 'project:database_config': {+ category: 'database',+ name: 'Database Config',+ description: 'Database configuration.',+ risk: 'medium',+ riskReason: 'Read-write can change database configuration.',+ allowsRead: ['Read database configuration'],+ allowsWrite: ['Update database configuration'],+ },+ 'project:database_jit': {+ category: 'database',+ name: 'Database JIT',+ description: 'Just-in-time database access settings.',+ risk: 'medium',+ riskReason: 'Read-write can change just-in-time database access settings.',+ allowsRead: ['Read JIT settings'],+ allowsWrite: ['Manage JIT settings'],+ },+ 'project:database_pooling_config': {+ category: 'database',+ name: 'Connection Pooling',+ description: 'Database connection pooling.',+ risk: 'medium',+ riskReason: 'Read-write can change connection pooling behavior.',+ allowsRead: ['Read pooling configuration'],+ allowsWrite: ['Update pooling configuration'],+ },+ 'project:database_readonly_config': {+ category: 'database',+ name: 'Read-only Mode',+ description: 'Database read-only mode.',+ risk: 'medium',+ riskReason: 'Read-write can toggle the database into or out of read-only mode.',+ allowsRead: ['Read read-only mode status'],+ allowsWrite: ['Toggle read-only mode'],+ },+ 'project:database_ssl_config': {+ category: 'database',+ name: 'SSL Enforcement',+ description: 'Database SSL configuration.',+ risk: 'medium',+ riskReason: 'Read-write can change SSL enforcement for database connections.',+ allowsRead: ['Read SSL configuration'],+ allowsWrite: ['Manage SSL enforcement'],+ },+ 'project:database_webhooks_config': {+ category: 'database',+ name: 'Database Webhooks',+ description: 'Webhooks triggered from the database.',+ risk: 'medium',+ riskReason: 'Read-write can change database webhook configuration.',+ allowsRead: ['Read webhook configuration'],+ allowsWrite: ['Manage database webhooks'],+ },+ 'project:database_network_bans': {+ category: 'database',+ name: 'Network Bans',+ description: 'Banned IPs for the database.',+ risk: 'medium',+ riskReason: 'Read-write can ban or unban IP addresses from reaching the database.',+ allowsRead: ['Read banned IPs'],+ allowsWrite: ['Manage banned IPs'],+ },+ 'project:database_network_restrictions': {+ category: 'database',+ name: 'Network Restrictions',+ description: 'Network restrictions for the database.',+ risk: 'high',+ riskReason: 'Read-write can change which networks are allowed to reach the database.',+ allowsRead: ['Read network restrictions'],+ allowsWrite: ['Manage network restrictions'],+ },++ // --- Application Services ---+ 'project:auth_config': {+ category: 'appsvc',+ name: 'Auth Config',+ description: 'Authentication provider and settings.',+ risk: 'high',+ riskReason:+ 'Read-write can change authentication providers and settings, affecting how users sign in.',+ allowsRead: ['Read auth configuration'],+ allowsWrite: ['Update auth providers and settings'],+ },+ 'project:auth_signing_keys': {+ category: 'appsvc',+ name: 'Auth Signing Keys',+ description: 'Authentication signing keys.',+ risk: 'high',+ riskReason: 'Read-write can rotate signing keys, invalidating existing sessions and tokens.',+ allowsRead: ['Read signing keys'],+ allowsWrite: ['Manage signing keys'],+ },+ 'project:api_gateway_keys': {+ category: 'appsvc',+ name: 'API Keys',+ description: 'Project API keys.',+ risk: 'high',+ riskReason: 'Read exposes API keys; read-write grants elevated access to create new keys.',+ allowsRead: ['Read project API keys'],+ allowsWrite: ['Create and revoke API keys'],+ },+ 'project:edge_functions': {+ category: 'appsvc',+ name: 'Edge Functions',+ description: 'Edge functions.',+ risk: 'medium',+ riskReason: 'Read-write can deploy or delete edge functions.',+ allowsRead: ['Read edge functions'],+ allowsWrite: ['Deploy and delete edge functions'],+ },+ 'project:edge_functions_secrets': {+ category: 'appsvc',+ name: 'Edge Function Secrets',+ description: 'Secrets available to edge functions.',+ risk: 'high',+ riskReason: 'Read exposes function secrets; read-write can set new secret values.',+ allowsRead: ['Read edge function secrets'],+ allowsWrite: ['Set edge function secrets'],+ },+ 'project:realtime_config': {+ category: 'appsvc',+ name: 'Realtime Config',+ description: 'Realtime configuration.',+ risk: 'medium',+ riskReason: 'Read-write can change realtime settings and shut down active connections.',+ allowsRead: ['Read realtime configuration'],+ allowsWrite: ['Update realtime settings'],+ },+ 'project:storage': {+ category: 'appsvc',+ name: 'Storage',+ description: 'File storage buckets and objects.',+ risk: 'medium',+ riskReason: 'Read-write can modify or delete stored files.',+ allowsRead: ['Read storage buckets and objects'],+ allowsWrite: ['Manage storage buckets and objects'],+ },+ 'project:storage_config': {+ category: 'appsvc',+ name: 'Storage Config',+ description: 'Storage bucket configuration.',+ risk: 'medium',+ riskReason: 'Read-write can change storage configuration.',+ allowsRead: ['Read storage configuration'],+ allowsWrite: ['Update storage configuration'],+ },+ 'project:data_api_config': {+ category: 'appsvc',+ name: 'Data API Config',+ description: 'PostgREST behavior and settings.',+ risk: 'medium',+ riskReason: 'Read-write can change how the auto-generated Data API behaves.',+ allowsRead: ['Read Data API configuration'],+ allowsWrite: ['Update Data API configuration'],+ },++ // --- Infrastructure & Delivery ---+ 'project:branching_development': {+ category: 'infra',+ name: 'Development Branches',+ description: 'Development branch automation.',+ risk: 'low',+ riskReason: 'Branch automation for development workflows — limited blast radius.',+ allowsRead: ['Read development branches'],+ allowsWrite: ['Create, update, and delete development branches'],+ },+ 'project:branching_production': {+ category: 'infra',+ name: 'Production Branches',+ description: 'Production branch automation.',+ risk: 'high',+ riskReason:+ 'Read-write grants elevated access to create, merge, or delete production branches.',+ allowsRead: ['Read production branches'],+ allowsWrite: ['Create, merge, and delete production branches'],+ },+ 'project:custom_domain': {+ category: 'infra',+ name: 'Custom Domains',+ description: 'Custom hostnames.',+ risk: 'medium',+ riskReason: 'Read-write can change custom hostnames, affecting how your project is reached.',+ allowsRead: ['Read custom domain configuration'],+ allowsWrite: ['Set custom hostnames'],+ },+ 'project:vanity_subdomain': {+ category: 'infra',+ name: 'Vanity Subdomain',+ description: 'Project vanity subdomain.',+ risk: 'medium',+ riskReason: 'Read-write can change the project vanity subdomain.',+ allowsRead: ['Read vanity subdomain'],+ allowsWrite: ['Manage vanity subdomain'],+ },+ 'project:infra_addons': {+ category: 'infra',+ name: 'Add-ons',+ description: 'Infrastructure add-ons.',+ risk: 'medium',+ riskReason: 'Read-write can enable or change paid infrastructure add-ons.',+ allowsRead: ['Read infrastructure add-ons'],+ allowsWrite: ['Manage infrastructure add-ons'],+ },+ 'project:infra_disk_config': {+ category: 'infra',+ name: 'Disk Config',+ description: 'Disk configuration.',+ risk: 'medium',+ riskReason: 'Read-write can change disk size and configuration, which may incur cost.',+ allowsRead: ['Read disk configuration'],+ allowsWrite: ['Manage disk configuration'],+ },+ 'project:read_replicas': {+ category: 'infra',+ name: 'Read Replicas',+ description: 'Read replica configuration.',+ risk: 'medium',+ riskReason: 'Read-write can provision or remove read replicas, which may incur cost.',+ allowsRead: ['Read read-replica configuration'],+ allowsWrite: ['Manage read replicas'],+ },+}++const RESOURCE_METADATA_FALLBACK = (+ resourceKey: string,+ title: string,+ hasWrite: boolean+): ResourceMeta => ({+ category: resourceKey.startsWith('project:') ? 'project' : 'account',+ name: title.replace(/^(Read|Manage|Create|Delete)\s+/i, ''),+ description: title,+ risk: hasWrite ? 'medium' : 'low',+ riskReason: hasWrite+ ? 'Read-write can modify this resource.'+ : 'Read-only access to this resource.',+})++export interface PermissionCatalogEntry {+ /** Derived resource key, e.g. "project:database" */+ key: string+ category: PermissionCategoryKey+ name: string+ description: string+ risk: RiskLevel+ riskReason: string+ allowsRead: string[]+ allowsWrite: string[]+ /** Whether a Read-write mode is offered (false => read-only resource). */+ writable: boolean+ /** FGA scope ids granted at Read (and above). */+ readScopes: ScopedAccessTokenPermission[]+ /** Additional FGA scope ids granted at Read-write (write / create / delete). */+ writeScopes: ScopedAccessTokenPermission[]+}++const getAction = (key: string): 'read' | 'write' | 'create' | 'delete' => {+ if (key.endsWith('_WRITE')) return 'write'+ if (key.endsWith('_CREATE')) return 'create'+ if (key.endsWith('_DELETE')) return 'delete'+ return 'read'+}++const getResource = (key: string): string =>+ key.replace(/_(READ|WRITE|CREATE|DELETE)$/, '').toLowerCase()++/**+ * Builds the permission catalog from the real FgaPermissions. Each unique `scope:resource` becomes+ * one row; its read scope maps to Read mode and its write/create/delete scopes to Read-write mode.+ */+const buildCatalog = (): PermissionCatalogEntry[] => {+ const byResource = new Map<+ string,+ { title: string; readScopes: string[]; writeScopes: string[] }+ >()++ for (const [scope, scopePerms] of Object.entries(FGA)) {+ for (const [permKey, perm] of Object.entries(scopePerms)) {+ const resourceKey = `${scope.toLowerCase()}:${getResource(permKey)}`+ const action = getAction(permKey)+ if (!byResource.has(resourceKey)) {+ byResource.set(resourceKey, { title: perm.title, readScopes: [], writeScopes: [] })+ }+ const entry = byResource.get(resourceKey)!+ if (action === 'read') entry.readScopes.push(perm.id)+ else entry.writeScopes.push(perm.id)+ }+ }++ const catalog: PermissionCatalogEntry[] = []+ for (const [key, { title, readScopes, writeScopes }] of byResource.entries()) {+ const meta =+ RESOURCE_METADATA[key] ?? RESOURCE_METADATA_FALLBACK(key, title, writeScopes.length > 0)+ catalog.push({+ key,+ category: meta.category,+ name: meta.name,+ description: meta.description,+ risk: meta.risk,+ riskReason: meta.riskReason,+ allowsRead: meta.allowsRead ?? [`Read ${meta.name.toLowerCase()}`],+ allowsWrite:+ meta.allowsWrite ?? (writeScopes.length > 0 ? [`Modify ${meta.name.toLowerCase()}`] : []),+ writable: writeScopes.length > 0,+ readScopes: readScopes as ScopedAccessTokenPermission[],+ writeScopes: writeScopes as ScopedAccessTokenPermission[],+ })+ }+ return catalog+}++export const PERMISSION_CATALOG = buildCatalog()++const CATALOG_BY_KEY = new Map(PERMISSION_CATALOG.map((entry) => [entry.key, entry]))++export const getCatalogEntry = (key: string) => CATALOG_BY_KEY.get(key)++export interface CategoryWithEntries extends PermissionCategory {+ entries: PermissionCatalogEntry[]+}++/** Catalog grouped by category, in category display order, dropping empty categories. */+export const PERMISSION_CATALOG_BY_CATEGORY: CategoryWithEntries[] = PERMISSION_CATEGORIES.map(+ (category) => ({+ ...category,+ entries: PERMISSION_CATALOG.filter((entry) => entry.category === category.key),+ })+).filter((category) => category.entries.length > 0)++/** Map of resource key -> selected mode. Absent keys are treated as 'none'. */+export type PermissionSelection = Record<string, PermissionMode>++/** Flattens a selection into the concrete FGA scope ids to send to the API. */+export const selectionToScopes = (+ selection: PermissionSelection+): ScopedAccessTokenPermission[] => {+ const scopes: ScopedAccessTokenPermission[] = []+ for (const [key, mode] of Object.entries(selection)) {+ if (mode === 'none') continue+ const entry = CATALOG_BY_KEY.get(key)+ if (!entry) continue+ scopes.push(...entry.readScopes)+ if (mode === 'readwrite') scopes.push(...entry.writeScopes)+ }+ return Array.from(new Set(scopes))+}++/** Reverses `selectionToScopes`: derives a selection from a token's granted FGA scope ids. */+export const scopesToSelection = (grantedScopes: string[]): PermissionSelection => {+ const granted = new Set(grantedScopes)+ const selection: PermissionSelection = {}+ for (const entry of PERMISSION_CATALOG) {+ const hasWrite =+ entry.writeScopes.length > 0 && entry.writeScopes.every((scope) => granted.has(scope))+ const hasRead =+ entry.readScopes.length > 0 && entry.readScopes.every((scope) => granted.has(scope))+ if (hasWrite) selection[entry.key] = 'readwrite'+ else if (hasRead) selection[entry.key] = 'read'+ }+ return selection+}++export const countConfiguredInCategory = (+ selection: PermissionSelection,+ categoryKey: PermissionCategoryKey+): number =>+ PERMISSION_CATALOG.filter(+ (entry) => entry.category === categoryKey && (selection[entry.key] ?? 'none') !== 'none'+ ).length++export const countConfigured = (selection: PermissionSelection): number =>+ Object.values(selection).filter((mode) => mode !== 'none').length++export const RISK_LEVEL_LABEL: Record<RiskLevel, string> = {+ low: 'Low risk',+ medium: 'Medium risk',+ high: 'High risk',+}++export type ResourceAccessMode = 'project' | 'organization' | 'account'++export interface OverallRisk {+ /** Minimal | Low | Medium | Elevated | High */+ level: string+ text: string+ tone: 'default' | 'low' | 'medium' | 'high'+}++/**+ * Computes the overall token risk from the selected capabilities and the resource-access breadth.+ * Account-level tokens are never below "Elevated", even when read-only.+ */+export const computeOverallRisk = (+ selection: PermissionSelection,+ resourceAccess: ResourceAccessMode+): OverallRisk => {+ const active = Object.entries(selection).filter(([, mode]) => mode !== 'none')+ if (active.length === 0) {+ return { level: 'Minimal', text: 'Minimal — no capabilities', tone: 'default' }+ }++ const anyWrite = active.some(([, mode]) => mode === 'readwrite')+ const anyHighWrite = active.some(+ ([key, mode]) => mode === 'readwrite' && CATALOG_BY_KEY.get(key)?.risk === 'high'+ )++ const scopeWord =+ resourceAccess === 'account'+ ? 'account-wide'+ : resourceAccess === 'organization'+ ? 'organization-wide'+ : 'single-project'+ const accessWord = anyWrite ? 'read-write' : 'read-only'++ let level: string+ let tone: OverallRisk['tone']+ if (resourceAccess === 'account') {+ level = anyWrite ? 'High' : 'Elevated'+ tone = anyWrite ? 'high' : 'medium'+ } else if (anyHighWrite) {+ level = 'High'+ tone = 'high'+ } else if (anyWrite) {+ level = 'Medium'+ tone = 'medium'+ } else {+ level = 'Low'+ tone = 'low'+ }++ return { level, text: `${level} — ${scopeWord} ${accessWord} access`, tone }+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx b/apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsxindex e18648d1cc6..72de6b84163 100644--- a/apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx@@ -1,4 +1,4 @@-import { MoreVertical, Trash } from 'lucide-react'+import { Key, MoreVertical, Trash } from 'lucide-react'import { parseAsStringLiteral, useQueryState } from 'nuqs'import { useMemo, useState } from 'react'import { toast } from 'sonner'@@ -21,38 +21,59 @@ import { filterAndSortTokens, handleSortChange } from './AccessToken.utils'import { RowLoading } from './AccessTokenTable/RowLoading'import { TableContainer } from './AccessTokenTable/TableContainer'import { ExpiresCell, LastUsedCell, TokenNameCell } from './AccessTokenTable/TokenCells'+import { useMergedAccessTokens, type MergedAccessToken } from './hooks/useMergedAccessTokens'+import { ViewTokenSheet } from './Scoped/ViewTokenSheet'import { AlertError } from '@/components/ui/AlertError'import { useAccessTokenDeleteMutation } from '@/data/access-tokens/access-tokens-delete-mutation'-import { AccessToken, useAccessTokensQuery } from '@/data/access-tokens/access-tokens-query'+import { useScopedAccessTokenDeleteMutation } from '@/data/scoped-access-tokens/scoped-access-tokens-delete-mutation'import { useTrack } from '@/lib/telemetry/track'export interface AccessTokenListProps {searchString?: string- onDeleteSuccess: (id: number) => void+ scopedTokensEnabled?: boolean+ onDeleteSuccess: (id: number | string) => void}-export const AccessTokenList = ({ searchString = '', onDeleteSuccess }: AccessTokenListProps) => {+export const AccessTokenList = ({+ searchString = '',+ scopedTokensEnabled,+ onDeleteSuccess,+}: AccessTokenListProps) => {const track = useTrack()- const [isOpen, setIsOpen] = useState(false)- const [token, setToken] = useState<AccessToken | undefined>(undefined)+ const [tokenToShow, setTokenToShow] = useState<MergedAccessToken | undefined>(undefined)+ const [tokenToDelete, setTokenToDelete] = useState<MergedAccessToken | undefined>(undefined)const [sort, setSort] = useQueryState('sort',parseAsStringLiteral<AccessTokenSort>(ACCESS_TOKEN_SORT_VALUES).withDefault('created_at:desc'))- const { data: tokens, error, isPending: isLoading, isError } = useAccessTokensQuery()+ const { tokens, error, isLoading, isError } = useMergedAccessTokens({ scopedTokensEnabled })- const { mutate: deleteToken } = useAccessTokenDeleteMutation({- onSuccess: (_, vars) => {- track('access_token_removed', { tokenType: 'classic' })- onDeleteSuccess(vars.id)- toast.success('Successfully deleted access token')- setIsOpen(false)- },- onError: (error) => {- toast.error(`Failed to delete access token: ${error.message}`)- },- })+ const { mutate: deleteClassicToken, isPending: isPendingClassicToken } =+ useAccessTokenDeleteMutation({+ onSuccess: (_, vars) => {+ track('access_token_removed', { tokenType: 'classic' })+ onDeleteSuccess(vars.id)+ toast.success('Successfully deleted access token')+ setTokenToDelete(undefined)+ },+ onError: (error) => {+ toast.error(`Failed to delete access token: ${error.message}`)+ },+ })++ const { mutate: deleteScopedToken, isPending: isPendingScopedToken } =+ useScopedAccessTokenDeleteMutation({+ onSuccess: (_, vars) => {+ track('access_token_removed', { tokenType: 'scoped' })+ onDeleteSuccess(vars.id)+ toast.success('Successfully deleted access token')+ setTokenToDelete(undefined)+ },+ onError: (error) => {+ toast.error(`Failed to delete access token: ${error.message}`)+ },+ })const onSortChange = (column: AccessTokenSortColumn) => {handleSortChange(sort, column, setSort)@@ -65,6 +86,12 @@ export const AccessTokenList = ({ searchString = '', onDeleteSuccess }: AccessToconst empty = filteredTokens?.length === 0 && !isLoading+ const handleConfirmDelete = () => {+ if (!tokenToDelete) return+ if (tokenToDelete.kind === 'classic') deleteClassicToken({ id: tokenToDelete.id as number })+ else deleteScopedToken({ id: tokenToDelete.id as string })+ }+if (isError) {return (<TableContainer sort={sort} onSortChange={onSortChange}>@@ -110,7 +137,12 @@ export const AccessTokenList = ({ searchString = '', onDeleteSuccess }: AccessTo<TableContainer sort={sort} onSortChange={onSortChange}>{filteredTokens?.map((x) => (<TableRow key={x.token_alias}>- <TokenNameCell name={x.name} tokenAlias={x.token_alias} />+ <TokenNameCell+ name={x.name}+ tokenAlias={x.token_alias}+ isClassic={x.kind === 'classic'}+ scopedTokensEnabled={scopedTokensEnabled}+ /><LastUsedCell lastUsedAt={x.last_used_at} /><ExpiresCell expiresAt={x.expires_at} /><TableCell>@@ -119,19 +151,19 @@ export const AccessTokenList = ({ searchString = '', onDeleteSuccess }: AccessTo<DropdownMenuTrigger asChild><Buttonvariant="default"- title="More options"+ aria-label="More options"className="w-7"icon={<MoreVertical />}/></DropdownMenuTrigger><DropdownMenuContent side="bottom" align="end" className="w-40">- <DropdownMenuItem- className="gap-x-2"- onClick={() => {- setToken(x)- setIsOpen(true)- }}- >+ {x.kind === 'scoped' && (+ <DropdownMenuItem className="gap-x-2" onClick={() => setTokenToShow(x)}>+ <Key size={12} />+ <p>View permissions</p>+ </DropdownMenuItem>+ )}+ <DropdownMenuItem className="gap-x-2" onClick={() => setTokenToDelete(x)}><Trash size={12} /><p>Delete token</p></DropdownMenuItem>@@ -144,20 +176,26 @@ export const AccessTokenList = ({ searchString = '', onDeleteSuccess }: AccessTo</TableContainer><ConfirmationModal- visible={isOpen}+ visible={tokenToDelete != null}variant="destructive"title="Confirm to delete"confirmLabel="Delete"confirmLabelLoading="Deleting"- onCancel={() => setIsOpen(false)}- onConfirm={() => {- if (token) deleteToken({ id: token.id })- }}+ onCancel={() => setTokenToDelete(undefined)}+ onConfirm={handleConfirmDelete}+ loading={isPendingClassicToken || isPendingScopedToken}><p className="py-4 text-sm text-foreground-light">- This action cannot be undone. Are you sure you want to delete "{token?.name}" token?+ This action cannot be undone. Are you sure you want to delete "{tokenToDelete?.name}"+ token?</p></ConfirmationModal>++ <ViewTokenSheet+ visible={tokenToShow != null}+ onClose={() => setTokenToShow(undefined)}+ tokenId={tokenToShow ? String(tokenToShow.id) : undefined}+ /></>)}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/AccessTokenTable/TokenCells.tsx b/apps/studio/components/interfaces/Account/AccessTokens/AccessTokenTable/TokenCells.tsxindex 1e21f753636..6826a5340c8 100644--- a/apps/studio/components/interfaces/Account/AccessTokens/AccessTokenTable/TokenCells.tsx+++ b/apps/studio/components/interfaces/Account/AccessTokens/AccessTokenTable/TokenCells.tsx@@ -1,17 +1,27 @@import dayjs from 'dayjs'+import { Badge, TableCell } from 'ui'import { TimestampInfo } from 'ui-patterns/TimestampInfo'-import { TableCell } from 'ui/src/components/shadcn/ui/table'interface TokenNameCellProps {name: stringtokenAlias: string+ isClassic: boolean+ scopedTokensEnabled?: boolean}-export const TokenNameCell = ({ name, tokenAlias }: TokenNameCellProps) => (+export const TokenNameCell = ({+ name,+ tokenAlias,+ isClassic,+ scopedTokensEnabled,+}: TokenNameCellProps) => (<TableCell className="w-auto max-w-96">- <p className="truncate" title={name}>- {name}- </p>+ <div className="flex items-center gap-x-2">+ <p className="truncate" title={name}>+ {name}+ </p>+ {isClassic && scopedTokensEnabled && <Badge variant="default">Legacy</Badge>}+ </div><pclassName="font-mono text-foreground-lighter truncate text-xs mt-1 max-w-32 sm:max-w-48 lg:max-w-full"title={tokenAlias}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/MigrationAdmonition.tsx b/apps/studio/components/interfaces/Account/AccessTokens/MigrationAdmonition.tsxnew file mode 100644index 00000000000..cdf1f0d1cbf--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/MigrationAdmonition.tsx@@ -0,0 +1,47 @@+import { LOCAL_STORAGE_KEYS } from 'common'+import Link from 'next/link'+import { Badge, Button } from 'ui'+import { Admonition } from 'ui-patterns/Admonition'++import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'+import { DOCS_URL } from '@/lib/constants'++export const MigrationAdmonition = () => {+ const [isDismissed, setIsDismissed] = useLocalStorageQuery(+ LOCAL_STORAGE_KEYS.SCOPED_TOKENS_MIGRATION_ADMONITION_DISMISSED,+ false+ )++ if (isDismissed) return null++ return (+ <Admonition+ type="default"+ title="We're moving to scoped access tokens"+ className="relative mb-5"+ actions={+ <>+ {/* Awaiting correct documentation link */}+ <Button asChild variant="default" size="tiny">+ <Link href={`${DOCS_URL}/guides/api`} target="_blank" rel="noreferrer">+ Learn more+ </Link>+ </Button>+ <Button variant="text" onClick={() => setIsDismissed(true)} aria-label="Close">+ Dismiss+ </Button>+ </>+ }+ >+ <div className="flex flex-col gap-y-1.5">+ <p className="text-sm text-foreground-light">+ We recommend granting each new token the minimum access its integration needs.+ </p>+ <span className="text-sm text-foreground-light">+ Pre-existing tokens are marked with a <Badge>Legacy</Badge> badge and will continue to+ work until expiry or deletion.+ </span>+ </div>+ </Admonition>+ )+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsxnew file mode 100644index 00000000000..e4a79d3ee59--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx@@ -0,0 +1,144 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { ChevronRight } from 'lucide-react'+import { useEffect, useRef, useState } from 'react'+import { useForm, useWatch } from 'react-hook-form'+import { toast } from 'sonner'+import { Button, Form, ScrollArea, Separator, SheetClose, SheetFooter } from 'ui'+import { Admonition } from 'ui-patterns/Admonition'++import { countConfigured, PermissionMode } from '../../AccessToken.permissions'+import { DEFAULT_EXPIRY, TokenFormSchema, TokenFormValues } from './NewScopedTokenForm.utils'+import { NewScopedTokenFormReview } from './NewScopedTokenFormReview'+import { PermissionsAccordion } from './PermissionsAccordion'+import { ResourceAccessStep } from './ResourceAccessStep'+import { StepIndicator } from './StepIndicator'+import { TokenDetails } from './TokenDetails'+import { useGetEnabledEndpointsForCapability } from '@/data/scoped-access-tokens/permission-scope-map-query'++const FORM_ID = 'scoped-token-form'++const DEFAULT_VALUES: TokenFormValues = {+ tokenName: '',+ expiresAt: DEFAULT_EXPIRY,+ customExpiryDate: undefined,+ resourceAccess: 'project',+ organizationSlugs: [],+ projectRefs: [],+ accountConfirmed: false,+ permissions: {},+}++export const NewScopedTokenForm = ({+ isPending,+ onCreateToken,+ onCancel,+}: {+ isPending: boolean+ onCreateToken: (values: TokenFormValues) => void+ onCancel: () => void+}) => {+ const form = useForm<TokenFormValues>({+ resolver: zodResolver(TokenFormSchema),+ validate: ({ formValues }) => {+ if (formValues.resourceAccess === 'account') {+ if (!formValues.accountConfirmed) return 'Confirm account-level access to continue.'+ }+ return true+ },+ defaultValues: DEFAULT_VALUES,+ mode: 'onChange',+ })+ const [step, setStep] = useState<'form' | 'review'>('form')+ const [formValues, setFormValues] = useState<TokenFormValues>(DEFAULT_VALUES)+ const [showMissingPermissionsWarning, setShowMissingPermissionsWarning] = useState(false)+ const resourceSectionRef = useRef<HTMLDivElement>(null)+ const selection = useWatch({ control: form.control, name: 'permissions' })+ const configuredCount = useWatch({+ control: form.control,+ name: 'permissions',+ compute: (selection) => countConfigured(selection),+ })++ const { data: permissionScopeMap, isError } = useGetEnabledEndpointsForCapability()++ useEffect(() => {+ if (isError) {+ toast.error('Something went wrong, try again')+ onCancel()+ }+ }, [onCancel, isError])++ const handleReviewAccess = async (values: TokenFormValues) => {+ if (configuredCount === 0) {+ setShowMissingPermissionsWarning(true)+ return+ }+ setFormValues(values)+ setStep('review')+ }++ const handlePermissionChange = (key: string, mode: PermissionMode) => {+ form.setValue('permissions', { ...selection, [key]: mode })+ if (mode !== 'none') setShowMissingPermissionsWarning(false)+ }++ return (+ <>+ <ScrollArea className="flex-1">+ {step === 'form' ? (+ <Form {...form}>+ <form id={FORM_ID} onSubmit={form.handleSubmit(handleReviewAccess)}>+ <TokenDetails control={form.control} setValue={form.setValue} />+ <Separator />+ <div ref={resourceSectionRef}>+ <ResourceAccessStep control={form.control} setValue={form.setValue} />+ </div>+ <Separator />+ <PermissionsAccordion+ selection={selection}+ onChange={handlePermissionChange}+ permissionScopeMap={permissionScopeMap}+ />+ {showMissingPermissionsWarning && (+ <div className="space-y-3 px-5 sm:px-6 pb-6">+ <Admonition+ ref={(node) => {+ node?.scrollIntoView()+ }}+ type="warning"+ title="No permissions selected"+ description="This token won't be able to do anything until you grant at least one permission."+ />+ </div>+ )}+ </form>+ </Form>+ ) : (+ <NewScopedTokenFormReview values={formValues} permissionScopeMap={permissionScopeMap} />+ )}+ </ScrollArea>+ <SheetFooter className="mt-auto flex w-full items-center justify-between! border-t py-4 px-5 sm:px-6">+ <StepIndicator step={step === 'form' ? 1 : 2} total={2} label="Configure" />+ <div className="flex gap-2">+ {step === 'review' && (+ <Button variant="default" disabled={isPending} onClick={() => setStep('form')}>+ Back+ </Button>+ )}+ <SheetClose asChild disabled={isPending}>+ <Button variant="default">Cancel</Button>+ </SheetClose>+ {step === 'form' ? (+ <Button type="submit" form={FORM_ID} iconRight={<ChevronRight />}>+ Review access+ </Button>+ ) : (+ <Button loading={isPending} onClick={() => onCreateToken(formValues)}>+ Create token+ </Button>+ )}+ </div>+ </SheetFooter>+ </>+ )+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.utils.ts b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.utils.tsnew file mode 100644index 00000000000..5adb798be82--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.utils.ts@@ -0,0 +1,100 @@+import dayjs from 'dayjs'+import { z } from 'zod'++import type { PermissionMode } from '../../AccessToken.permissions'++export const EXPIRY_PRESETS = ['24h', '7d', '30d', '90d', 'custom'] as const+export type ExpiryPreset = (typeof EXPIRY_PRESETS)[number]++export const DEFAULT_EXPIRY: ExpiryPreset = '7d'++export interface ExpiryOption {+ value: ExpiryPreset+ label: string+ recommended?: boolean+}++export const EXPIRY_OPTIONS: ExpiryOption[] = [+ { value: '24h', label: '24 hours' },+ { value: '7d', label: '7 days', recommended: true },+ { value: '30d', label: '30 days' },+ { value: '90d', label: '90 days' },+ { value: 'custom', label: 'Custom' },+]++/** Resolves the final ISO expiry date for a preset, or `undefined` when the caller supplies a custom date. */+export const getExpiryDate = (preset: ExpiryPreset): string | undefined => {+ switch (preset) {+ case '24h':+ return dayjs().add(24, 'hours').toISOString()+ case '7d':+ return dayjs().add(7, 'days').toISOString()+ case '30d':+ return dayjs().add(30, 'days').toISOString()+ case '90d':+ return dayjs().add(90, 'days').toISOString()+ default:+ return undefined+ }+}++/** The default custom date sits ~7 days out, matching the recommended preset. */+export const getDefaultCustomExpiryDate = (): string =>+ dayjs().add(7, 'days').endOf('day').toISOString()++export const RESOURCE_ACCESS_MODES = ['project', 'organization', 'account'] as const++/**+ * The form schema is intentionally permissive: resource-selection and permission-count validation+ * happen imperatively on step transitions so errors only surface after an attempt (never+ * preemptively), and can be scrolled into view. Zod only guards always-required basics.+ */+export const TokenFormSchema = z+ .object({+ tokenName: z.string().trim().min(1, 'Please enter a name for the token'),+ expiresAt: z.enum(EXPIRY_PRESETS),+ customExpiryDate: z.string().datetime().optional(),+ resourceAccess: z.enum(RESOURCE_ACCESS_MODES),+ organizationSlugs: z.string().array().optional().default([]),+ projectRefs: z.string().array().optional().default([]),+ accountConfirmed: z.boolean().optional(),+ permissions: z.record(z.string(), z.enum(['none', 'read', 'readwrite'])),+ })+ .superRefine((data, ctx) => {+ if (data.expiresAt === 'custom' && !data.customExpiryDate) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Required',+ path: ['customExpiryDate'],+ })+ }++ if (data.resourceAccess === 'project') {+ if (data.organizationSlugs.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Please select an organization to continue.',+ path: ['organizationSlugs'],+ })+ }+ if (data.projectRefs.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Please select a project to continue.',+ path: ['projectRefs'],+ })+ }+ }++ if (data.resourceAccess === 'organization' && data.organizationSlugs.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Please select an organization to continue.',+ path: ['organizationSlugs'],+ })+ }+ })++export type TokenFormValues = Omit<z.infer<typeof TokenFormSchema>, 'permissions'> & {+ permissions: Record<string, PermissionMode>+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsxnew file mode 100644index 00000000000..285cb009a9a--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx@@ -0,0 +1,274 @@+import dayjs from 'dayjs'+import { useMemo } from 'react'+import { Badge, cn } from 'ui'+import { Admonition } from 'ui-patterns/Admonition'++import {+ computeOverallRisk,+ PERMISSION_CATALOG_BY_CATEGORY,+ selectionToScopes,+ type OverallRisk,+ type PermissionCatalogEntry,+ type PermissionMode,+ type RiskLevel,+} from '../../AccessToken.permissions'+import { useOrgAndProjectData } from '../../hooks/useOrgAndProjectData'+import { EXPIRY_OPTIONS, type TokenFormValues } from './NewScopedTokenForm.utils'+import {+ getEnabledEndpointsForCapability,+ getEnabledMcpTools,+ PermissionScopeMap,+} from '@/data/scoped-access-tokens/permission-scope-map-query'++interface ReviewStepProps {+ values: TokenFormValues+ permissionScopeMap: PermissionScopeMap | undefined+}++const RISK_TONE_VARIANT: Record<+ OverallRisk['tone'],+ 'default' | 'success' | 'warning' | 'destructive'+> = {+ default: 'default',+ low: 'success',+ medium: 'warning',+ high: 'destructive',+}++const modeLabel = (mode: PermissionMode) =>+ mode === 'readwrite' ? 'Read-write' : mode === 'read' ? 'Read' : 'None'++const RISK_DOT_CLASS: Record<RiskLevel, string> = {+ low: 'bg-brand-600',+ medium: 'bg-warning-600',+ high: 'bg-destructive-600',+}++export const NewScopedTokenFormReview = ({ values, permissionScopeMap }: ReviewStepProps) => {+ const { organizations, projects } = useOrgAndProjectData()+ const selection = values.permissions+ const grantedScopes = useMemo(() => selectionToScopes(selection), [selection])+ const risk = useMemo(+ () => computeOverallRisk(selection, values.resourceAccess),+ [selection, values.resourceAccess]+ )++ const resourceSummary = useMemo(() => {+ if (values.resourceAccess === 'project') {+ const selectedProjects = projects.filter((p) => values.projectRefs.includes(p.ref))+ return {+ title: 'Project',+ items: selectedProjects.length > 0 ? selectedProjects.map((p) => p.name) : ['-'],+ }+ }+ if (values.resourceAccess === 'organization') {+ const selectedOrganizations = organizations.filter((o) =>+ values.organizationSlugs.includes(o.slug)+ )+ return {+ title: 'Organization',+ items: selectedOrganizations.length > 0 ? selectedOrganizations.map((o) => o.name) : ['-'],+ }+ }+ return { title: 'Account', items: ['Account-level access'] }+ }, [values, projects, organizations])++ const expiresSummary = useMemo(() => {+ if (values.expiresAt === 'custom') {+ return values.customExpiryDate+ ? dayjs(values.customExpiryDate).format('DD MMM, YYYY')+ : 'Custom — no date set'+ }+ return EXPIRY_OPTIONS.find((o) => o.value === values.expiresAt)?.label ?? values.expiresAt+ }, [values])++ const activeByCategory = useMemo(+ () =>+ PERMISSION_CATALOG_BY_CATEGORY.map((category) => ({+ ...category,+ entries: category.entries+ .map((entry) => ({ entry, mode: selection[entry.key] ?? 'none' }))+ .filter(({ mode }) => mode !== 'none'),+ })).filter((category) => category.entries.length > 0),+ [selection]+ )++ const hasCapabilities = grantedScopes.length > 0++ const mcpTools = useMemo(+ () => getEnabledMcpTools({ grantedScopes, permissionScopeMap }),+ [grantedScopes, permissionScopeMap]+ )++ const capabilityGroups = useMemo(() => {+ const groups: { entry: PermissionCatalogEntry; mode: PermissionMode; endpoints: string[][] }[] =+ []+ for (const category of activeByCategory) {+ for (const { entry, mode } of category.entries) {+ const capabilityScopes =+ mode === 'readwrite' ? [...entry.readScopes, ...entry.writeScopes] : entry.readScopes+ const endpoints = getEnabledEndpointsForCapability({+ capabilityScopes,+ allGrantedScopes: grantedScopes,+ permissionScopeMap,+ })+ if (endpoints.length > 0) {+ groups.push({ entry, mode, endpoints: endpoints.map((e) => [e.method, e.path]) })+ }+ }+ }+ return groups+ }, [activeByCategory, grantedScopes, permissionScopeMap])++ const rows: [string, React.ReactNode][] = [+ ['Name', values.tokenName || <span className="text-foreground-lighter">Untitled token</span>],+ ['Expires', expiresSummary],+ [+ 'Resource access',+ <div key="resource-access" className="space-y-2">+ <p className="text-[11px] font-mono uppercase tracking-wide text-foreground-lighter">+ {resourceSummary.title}+ </p>+ <div className="divide-y">+ {resourceSummary.items.map((item) => (+ <p key={item} className="py-2 text-sm text-foreground">+ {item}+ </p>+ ))}+ </div>+ </div>,+ ],+ [+ 'Capabilities',+ hasCapabilities ? (+ <div className="space-y-4">+ {activeByCategory.map((category) => (+ <div key={category.key} className="space-y-2">+ <p className="text-[11px] font-mono uppercase tracking-wide text-foreground-lighter">+ {category.name}+ </p>+ <div className="divide-y">+ {category.entries.map(({ entry, mode }) => (+ <div+ key={entry.key}+ className="flex items-center justify-between gap-2 text-sm py-2"+ >+ <span className="flex items-center gap-2">+ <span+ className={cn(+ 'h-1.5 w-1.5 shrink-0 rounded-full',+ RISK_DOT_CLASS[entry.risk]+ )}+ />+ <span className="text-foreground text-wrap">{entry.name}</span>+ </span>+ <span className="text-foreground-lighter text-xs font-mono uppercase font-normal text-right">+ {modeLabel(mode)}+ </span>+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ ) : (+ <span className="text-foreground-lighter">No capabilities selected</span>+ ),+ ],+ [+ 'Risk level',+ <span key="risk" className="flex flex-wrap items-center gap-2">+ <span className="flex">+ <Badge variant={RISK_TONE_VARIANT[risk.tone]}>{risk.level} Risk</Badge>+ </span>+ <span className="text-sm text-foreground leading-px">+ {risk.text.replace(`${risk.level} — `, '')}+ </span>+ </span>,+ ],+ ]++ return (+ <div className="space-y-6 px-5 sm:px-6 py-6">+ {hasCapabilities ? (+ <Admonition+ type="warning"+ title="Token access can't be edited after creation"+ description="Once created, a token's access can't be edited. To change it, revoke this token and create a new one."+ />+ ) : (+ <Admonition+ type="warning"+ title="This token has no capabilities"+ description="Go back and grant at least one permission before creating it."+ />+ )}+ <div className="flex flex-col gap-3">+ <h3 className="text-sm">Token summary</h3>+ <dl className="divide-y rounded-md border bg-surface-300">+ {rows.map(([key, value]) => (+ <div key={key} className="grid grid-cols-3 gap-4 px-4 py-3">+ <dt className="text-sm text-foreground-lighter">{key}</dt>+ <dd className="col-span-2 text-sm text-foreground">{value}</dd>+ </div>+ ))}+ </dl>+ </div>++ {hasCapabilities && (+ <>+ <div className="flex flex-col gap-3">+ <h3 className="text-sm">Management API endpoints enabled</h3>+ {capabilityGroups.length === 0 ? (+ <p className="text-xs text-foreground-light">+ No Management API endpoints are enabled by the selected capabilities.+ </p>+ ) : (+ capabilityGroups.map(({ entry, mode, endpoints }) => (+ <div key={entry.key} className="rounded-md border">+ <div className="flex items-center justify-between border-b bg-surface-100 px-3 py-2">+ <span className="text-xs text-foreground">{entry.name}</span>+ <span className="text-[11px] font-mono uppercase text-foreground-lighter">+ {mode === 'readwrite' ? 'Read-write' : 'Read'}+ </span>+ </div>+ <div className="divide-y">+ {endpoints.map(([method, path]) => (+ <div+ key={`${method} ${path}`}+ className="flex items-center gap-2 px-3 py-1.5 font-mono text-xs"+ >+ <span className="w-14 shrink-0 text-foreground-light">{method}</span>+ <span className="text-foreground">{path}</span>+ </div>+ ))}+ </div>+ </div>+ ))+ )}+ </div>++ <div className="flex flex-col gap-3">+ <h3 className="text-sm">MCP tools</h3>+ {mcpTools.length === 0 ? (+ <p className="text-xs text-foreground-light">+ No MCP tools are enabled by the selected capabilities.+ </p>+ ) : (+ <div className="flex flex-wrap gap-2">+ {mcpTools.map((tool) => (+ <span+ key={tool}+ className="rounded border bg-surface-100 px-2 py-1 font-mono text-xs text-foreground-light"+ >+ {tool}+ </span>+ ))}+ </div>+ )}+ </div>+ </>+ )}+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenSuccess.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenSuccess.tsxnew file mode 100644index 00000000000..5023f82b78b--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenSuccess.tsx@@ -0,0 +1,65 @@+import { useState } from 'react'+import { toast } from 'sonner'+import { Button, Checkbox, ScrollArea, SheetFooter } from 'ui'+import { Admonition } from 'ui-patterns/Admonition'+import { Input } from 'ui-patterns/DataInputs/Input'++interface TokenSuccessProps {+ tokenName: string+ tokenValue: string+ onClose: () => void+}++export const NewScopedTokenSuccess = ({ tokenName, tokenValue, onClose }: TokenSuccessProps) => {+ const [keyCopied, setKeyCopied] = useState(false)++ return (+ <>+ <ScrollArea className="flex-1">+ <div className="space-y-4 px-5 sm:px-6 py-6">+ <div className="space-y-1">+ <h3 className="text-sm text-foreground">Token created</h3>+ <p className="text-xs text-foreground-light">+ Copy your new token{tokenName ? ` "${tokenName}"` : ''} and store it somewhere safe.+ </p>+ </div>++ <Input+ copy+ readOnly+ size="small"+ className="input-mono w-full"+ id="scoped-access-token-value"+ value={tokenValue}+ onChange={() => {}}+ aria-label={`${tokenName} token`}+ onCopy={() => toast.success('Token copied to clipboard')}+ />++ <Admonition+ type="warning"+ title="This is the only time the token is shown"+ description="You won't be able to see this token value again. If you lose it, revoke the token and create a new one."+ >+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}+ <label className="flex items-center gap-3 cursor-pointer py-2">+ <Checkbox+ id="key-copied"+ checked={keyCopied}+ onCheckedChange={(v) => setKeyCopied(Boolean(v))}+ />+ <span className="text-sm text-warning cursor-pointer select-none">+ I have copied the key and stored it securely+ </span>+ </label>+ </Admonition>+ </div>+ </ScrollArea>+ <SheetFooter className="mt-auto flex w-full items-center justify-between! border-t py-4">+ <Button className="ml-auto" disabled={!keyCopied} onClick={onClose}>+ Done+ </Button>+ </SheetFooter>+ </>+ )+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsxnew file mode 100644index 00000000000..43de879e201--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsx@@ -0,0 +1,54 @@+import { Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from 'ui'++import type { PermissionCatalogEntry, PermissionMode } from '../../AccessToken.permissions'+import { RiskMarker } from './RiskMarker'+import { PermissionScopeMap } from '@/data/scoped-access-tokens/permission-scope-map-query'++interface PermissionRowProps {+ entry: PermissionCatalogEntry+ mode: PermissionMode+ onChange: (mode: PermissionMode) => void+ permissionScopeMap: PermissionScopeMap | undefined+}++export const PermissionRow = ({+ entry,+ mode,+ onChange,+ permissionScopeMap,+}: PermissionRowProps) => {+ return (+ <div className="flex items-center justify-between gap-4 py-4">+ <div className="min-w-0 flex flex-col gap-1">+ <span className="flex items-start md:items-center gap-2 flex-col-reverse md:flex-row">+ <Label htmlFor={`${entry.key}-permissions`}>+ <span className="text-sm text-foreground">+ {entry.name} <span className="sr-only">permissions</span>+ </span>+ </Label>+ <RiskMarker entry={entry} permissionScopeMap={permissionScopeMap} />+ </span>+ <p id={`${entry.key}-permissions-description`} className="text-xs text-foreground-lighter">+ {entry.description}+ </p>+ </div>++ <div className="flex shrink-0 items-center gap-2">+ <Select value={mode} onValueChange={(value) => onChange(value as PermissionMode)}>+ <SelectTrigger+ className="w-36 shrink-0"+ id={`${entry.key}-permissions`}+ aria-describedby={`${entry.key}-permissions-description`}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="none">None</SelectItem>+ <SelectItem value="read">Read</SelectItem>+ {entry.writable && <SelectItem value="readwrite">Read-write</SelectItem>}+ </SelectContent>+ </Select>+ </div>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionsAccordion.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionsAccordion.tsxnew file mode 100644index 00000000000..ebae7ae16c9--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionsAccordion.tsx@@ -0,0 +1,86 @@+import { useState } from 'react'+import { Accordion, AccordionContent, AccordionItem, AccordionTrigger, cn } from 'ui'++import {+ countConfiguredInCategory,+ PERMISSION_CATALOG_BY_CATEGORY,+ type PermissionMode,+ type PermissionSelection,+} from '../../AccessToken.permissions'+import { PermissionRow } from './PermissionRow'+import { PermissionScopeMap } from '@/data/scoped-access-tokens/permission-scope-map-query'++interface PermissionsAccordionProps {+ selection: PermissionSelection+ onChange: (key: string, mode: PermissionMode) => void+ permissionScopeMap: PermissionScopeMap | undefined+}++export const PermissionsAccordion = ({+ selection,+ onChange,+ permissionScopeMap,+}: PermissionsAccordionProps) => {+ const [openCategories, setOpenCategories] = useState<string[]>([])++ return (+ <div className="space-y-3 px-5 sm:px-6 py-6">+ <div>+ <h3 className="text-sm text-foreground">Permissions</h3>+ <p className="text-foreground-lighter text-sm">+ Grant the minimum access this token needs. Everything defaults to None.+ </p>+ </div>++ <Accordion+ type="multiple"+ value={openCategories}+ onValueChange={setOpenCategories}+ className="mt-2"+ >+ {PERMISSION_CATALOG_BY_CATEGORY.map((category, index) => {+ const configuredCount = countConfiguredInCategory(selection, category.key)+ return (+ <AccordionItem+ key={category.key}+ value={category.key}+ className={cn('border', {+ 'border-b-0': index < PERMISSION_CATALOG_BY_CATEGORY.length - 1,+ 'rounded-t-md': index === 0,+ 'rounded-b-md': index === PERMISSION_CATALOG_BY_CATEGORY.length - 1,+ })}+ >+ <AccordionTrigger className="bg-surface-300 first:rounded-t last:rounded-b px-4 py-3 hover:no-underline transition">+ <div className="flex flex-1 items-center justify-between gap-2 pr-2">+ <div className="flex flex-col gap-1">+ <span className="text-sm font-medium">{category.name}</span>+ <span className="text-xs text-foreground-lighter">{category.description}</span>+ </div>+ {configuredCount > 0 && (+ <span className="text-xs text-primary font-medium">+ {configuredCount} configured+ </span>+ )}+ </div>+ </AccordionTrigger>+ <AccordionContent className="*:pb-0">+ <div className="divide-y first:border-t">+ {category.entries.map((entry) => (+ <div className="px-4" key={entry.key}>+ <PermissionRow+ entry={entry}+ mode={selection[entry.key] ?? 'none'}+ onChange={(mode) => onChange(entry.key, mode)}+ permissionScopeMap={permissionScopeMap}+ />+ </div>+ ))}+ </div>+ </AccordionContent>+ </AccordionItem>+ )+ })}+ </Accordion>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.tsxnew file mode 100644index 00000000000..587ac573ec4--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.tsx@@ -0,0 +1,367 @@+import { AnimatePresence, motion, useReducedMotion } from 'framer-motion'+import { useMemo } from 'react'+import type { Control, UseFormSetValue } from 'react-hook-form'+import {+ Badge,+ Checkbox,+ cn,+ FormControl,+ FormField,+ Label,+ RadioGroupStacked,+ RadioGroupStackedItem,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ useWatch,+} from 'ui'+import { Admonition } from 'ui-patterns/Admonition'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import {+ MultiSelector,+ MultiSelectorContent,+ MultiSelectorInput,+ MultiSelectorItem,+ MultiSelectorList,+ MultiSelectorTrigger,+} from 'ui-patterns/multi-select'++import type { ResourceAccessMode } from '../../AccessToken.permissions'+import { useOrgAndProjectData } from '../../hooks/useOrgAndProjectData'+import type { TokenFormValues } from './NewScopedTokenForm.utils'+import { ProjectInfoInfinite } from '@/data/projects/projects-infinite-query'+import { Organization } from '@/types'++interface ResourceAccessStepProps {+ control: Control<TokenFormValues>+ setValue: UseFormSetValue<TokenFormValues>++ /** Inline error surfaced only after an attempt to advance. */+ error?: string+}++const CARD_OPTIONS: {+ value: Exclude<ResourceAccessMode, 'account'>+ name: string+ description: string+ recommended?: boolean+}[] = [+ {+ value: 'project',+ name: 'Project',+ description: 'Access selected projects only.',+ recommended: true,+ },+ {+ value: 'organization',+ name: 'Organization',+ description: 'Access all projects in selected organizations.',+ },+]++export const ResourceAccessStep = ({ control, setValue, error }: ResourceAccessStepProps) => {+ const { organizations, projects } = useOrgAndProjectData()+ const organizationsBySlug = useMemo(+ () =>+ organizations.reduce(+ (acc, organization) => {+ acc[organization.slug] = organization+ return acc+ },+ {} as Record<string, Organization>+ ),+ [organizations]+ )+ const projectsByRef = useMemo(+ () =>+ projects.reduce(+ (acc, project) => {+ acc[project.ref] = project+ return acc+ },+ {} as Record<string, ProjectInfoInfinite>+ ),+ [projects]+ )++ const resourceAccess = useWatch({ control, name: 'resourceAccess' })+ const organizationSlugs = useWatch({ control, name: 'organizationSlugs', defaultValue: [] })+ const accountConfirmed = useWatch({ control, name: 'accountConfirmed' })++ const isAccount = resourceAccess === 'account'+ const prefersReducedMotion = useReducedMotion()++ const projectsForOrg = useMemo(+ () => projects.filter((project) => organizationSlugs.includes(project.organization_slug)),+ [projects, organizationSlugs]+ )++ const enableAccountLevel = () => {+ setValue('resourceAccess', 'account', { shouldValidate: true })+ setValue('organizationSlugs', [])+ setValue('projectRefs', [])+ }++ const switchBackToSingleProject = () => {+ setValue('resourceAccess', 'project', { shouldValidate: true })+ setValue('accountConfirmed', false)+ }++ const exitTransition = prefersReducedMotion+ ? { opacity: 0 }+ : { opacity: 0, scale: 0.97, filter: 'blur(4px)' }+ const enterTransition = prefersReducedMotion ? false : { opacity: 0, y: 16 }+ const formBackdropAnimate = isAccount+ ? {+ opacity: 0.5,+ scale: prefersReducedMotion ? 1 : 0.98,+ filter: prefersReducedMotion ? 'none' : 'blur(4px)',+ }+ : { opacity: 1, scale: 1, filter: 'none' }++ return (+ <section className="relative space-y-4 px-5 sm:px-6 py-6">+ <motion.div+ className={cn('space-y-4', isAccount && 'pointer-events-none')}+ animate={formBackdropAnimate}+ transition={{ duration: 0.2, ease: 'easeOut' }}+ aria-hidden={isAccount}+ inert={isAccount}+ >+ <FormField+ control={control}+ name="resourceAccess"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Resource access"+ description={+ <p className="text-foreground-lighter text-sm">+ Need access to every organization and project?{' '}+ <button+ type="button"+ className="text-foreground-light underline hover:text-foreground transition-colors"+ onClick={enableAccountLevel}+ tabIndex={isAccount ? -1 : 0}+ >+ Advanced options+ </button>+ </p>+ }+ id="resourceAccess"+ >+ <FormControl>+ <RadioGroupStacked+ value={resourceAccess}+ onValueChange={(value) => {+ field.onChange(value)+ // Reset dependent selections when switching modes.+ setValue('projectRefs', [])+ if (value !== 'account') setValue('accountConfirmed', false)+ }}+ >+ {CARD_OPTIONS.map((option) => (+ <RadioGroupStackedItem+ key={option.value}+ id={option.value}+ value={option.value}+ className="w-full"+ label={+ <div className="flex flex-col gap-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-foreground">{option.name}</span>+ {option.recommended && <Badge variant="success">Recommended</Badge>}+ </div>+ <span className="text-foreground-light">{option.description}</span>+ </div>+ }+ />+ ))}+ </RadioGroupStacked>+ </FormControl>+ </FormItemLayout>+ )}+ />++ {resourceAccess === 'project' && (+ <>+ <FormField+ control={control}+ name="organizationSlugs"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label={<span className="sr-only">Organization</span>}+ id="organizationSlugs"+ >+ <FormControl>+ <Select+ value={field.value.length > 0 ? field.value[0] : ''}+ onValueChange={(value) => {+ field.onChange([value])+ setValue('projectRefs', [])+ }}+ >+ <SelectTrigger id="organizationSlugs" ref={field.ref}>+ <SelectValue placeholder="Select an organization" asChild>+ <span>{organizationsBySlug[field.value[0]]?.name}</span>+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {organizations.map((org) => (+ <SelectItem key={org.slug} value={org.slug}>+ {org.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FormControl>+ </FormItemLayout>+ )}+ />+ <FormField+ control={control}+ name="projectRefs"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label={<span className="sr-only">Projects</span>}+ id="projectRefs"+ >+ <MultiSelector+ onValuesChange={field.onChange}+ values={field.value}+ disabled={!organizationSlugs}+ className="w-full"+ >+ <MultiSelectorTrigger+ id="projectRefs"+ mode="combobox"+ label={+ organizationSlugs.length > 0+ ? 'Select projects'+ : 'Select an organization first'+ }+ badgeLimit="wrap"+ showIcon={true}+ deletableBadge+ ref={field.ref}+ renderValue={(value) => projectsByRef[value]?.name}+ className="min-w-auto"+ />+ <MultiSelectorContent>+ <MultiSelectorInput placeholder="Search organizations" showResetIcon />+ <MultiSelectorList>+ {projectsForOrg.map((project) => (+ <MultiSelectorItem key={project.ref} value={project.ref}>+ {project.name}+ </MultiSelectorItem>+ ))}+ </MultiSelectorList>+ </MultiSelectorContent>+ </MultiSelector>+ </FormItemLayout>+ )}+ />+ </>+ )}+ {resourceAccess === 'organization' && (+ <FormField+ control={control}+ name="organizationSlugs"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label={<span className="sr-only">Organizations</span>}+ id="organizationSlugs"+ >+ <MultiSelector onValuesChange={field.onChange} values={field.value}>+ <MultiSelectorTrigger+ id="organizationSlugs"+ mode="combobox"+ label="Select organizations"+ badgeLimit="wrap"+ showIcon={false}+ deletableBadge+ className="w-full"+ ref={field.ref}+ renderValue={(value) => organizationsBySlug[value]?.name}+ />+ <MultiSelectorContent>+ <MultiSelectorInput placeholder="Search organizations" showResetIcon />+ <MultiSelectorList>+ {organizations.map((organization) => (+ <MultiSelectorItem key={organization.slug} value={organization.slug}>+ {organization.name}+ </MultiSelectorItem>+ ))}+ </MultiSelectorList>+ </MultiSelectorContent>+ </MultiSelector>+ </FormItemLayout>+ )}+ />+ )}+ </motion.div>++ <AnimatePresence>+ {isAccount && (+ <motion.div+ key="account"+ className="absolute inset-x-5 bottom-6 space-y-4 sm:inset-x-6"+ initial={enterTransition}+ animate={{ opacity: 1, y: 0 }}+ exit={exitTransition}+ transition={{ duration: 0.2, ease: 'easeOut' }}+ >+ <Admonition+ type="warning"+ title="Account-level access is broad."+ description={+ <div className="space-y-3">+ <p>+ This token can reach every organization and project you have access to. Prefer a+ single project or organization unless you specifically need account-wide access.+ </p>+ <div className="flex items-start gap-2">+ <FormField+ control={control}+ name="accountConfirmed"+ render={({ field }) => (+ <>+ <Checkbox+ id="accountConfirmed"+ checked={accountConfirmed ?? false}+ onCheckedChange={(checked) => field.onChange(checked)}+ />+ <Label+ htmlFor="accountConfirmed"+ className="text-xs text-foreground-light"+ >+ I understand this token is not limited to one project or organization.+ </Label>+ </>+ )}+ />+ </div>+ <button+ type="button"+ className="text-xs text-foreground-light underline hover:text-foreground transition-colors"+ onClick={switchBackToSingleProject}+ tabIndex={0}+ >+ Switch back+ </button>+ </div>+ }+ />+ </motion.div>+ )}+ </AnimatePresence>++ {error && <p className="text-xs text-destructive">{error}</p>}+ </section>+ )+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsxnew file mode 100644index 00000000000..a9e5bdf292c--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx@@ -0,0 +1,88 @@+import { Badge, cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'++import {+ RISK_LEVEL_LABEL,+ type PermissionCatalogEntry,+ type RiskLevel,+} from '../../AccessToken.permissions'+import {+ getMcpToolsForScopes,+ PermissionScopeMap,+} from '@/data/scoped-access-tokens/permission-scope-map-query'++const RISK_VARIANT: Record<RiskLevel, 'success' | 'warning' | 'destructive'> = {+ low: 'success',+ medium: 'warning',+ high: 'destructive',+}++interface RiskMarkerProps {+ entry: PermissionCatalogEntry+ /** When false, renders the dot + label without the explanatory tooltip (used in the review list). */+ withTooltip?: boolean+ className?: string+ permissionScopeMap: PermissionScopeMap | undefined+}++export const RiskMarker = ({+ entry,+ withTooltip = true,+ className,+ permissionScopeMap,+}: RiskMarkerProps) => {+ const marker = (+ <Badge+ variant={RISK_VARIANT[entry.risk]}+ className={cn(withTooltip && 'cursor-help', className)}+ >+ {RISK_LEVEL_LABEL[entry.risk]}+ </Badge>+ )++ if (!withTooltip) return marker++ const mcpTools = getMcpToolsForScopes({+ scopeIds: [...entry.readScopes, ...entry.writeScopes],+ permissionScopeMap,+ })++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span tabIndex={0}>{marker}</span>+ </TooltipTrigger>+ <TooltipContent side="top" align="center" className="w-72 space-y-2 p-3">+ <Badge variant={RISK_VARIANT[entry.risk]}>{RISK_LEVEL_LABEL[entry.risk]}</Badge>+ <p className="text-xs text-foreground-light">{entry.riskReason}</p>+ {(entry.allowsRead.length > 0 || entry.allowsWrite.length > 0) && (+ <div className="flex flex-col gap-5 mt-5">+ {entry.allowsRead.length > 0 && (+ <span className="text-xs text-foreground-light">+ <h3 className="text-foreground-muted text-[11px] uppercase font-mono tracking-wide font-normal mb-0.5">+ Read:{' '}+ </h3>+ {entry.allowsRead.join(', ')}+ </span>+ )}+ {entry.allowsWrite.length > 0 && (+ <span className="text-xs text-foreground-light">+ <h3 className="text-foreground-muted text-[11px] uppercase font-mono tracking-wide font-normal mb-0.5">+ Write:{' '}+ </h3>+ {entry.allowsWrite.join(', ')}+ </span>+ )}+ </div>+ )}+ {mcpTools.length > 0 && (+ <div className="space-y-1">+ <p className="text-[11px] font-mono uppercase tracking-wide text-foreground-lighter">+ MCP tools+ </p>+ <p className="font-mono text-xs text-foreground-light">{mcpTools.join(', ')}</p>+ </div>+ )}+ </TooltipContent>+ </Tooltip>+ )+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/StepIndicator.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/StepIndicator.tsxnew file mode 100644index 00000000000..5f371fb08ad--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/StepIndicator.tsx@@ -0,0 +1,30 @@+import { cn } from 'ui'++interface StepIndicatorProps {+ /** 1-indexed current step. */+ step: number+ total: number+ label: string+}++export const StepIndicator = ({ step, total, label }: StepIndicatorProps) => (+ <div className="flex items-center gap-2 text-xs text-foreground-light">+ <div className="flex items-center gap-1">+ {Array.from({ length: total }).map((_, index) => (+ <span+ key={index}+ className={cn(+ 'h-1.5 w-1.5 rounded-full transition-colors',+ index < step ? 'bg-primary' : 'bg-border-stronger'+ )}+ />+ ))}+ </div>+ <span className="text-foreground-lighter">+ <span className="text-foreground">+ Step {step} of {total}+ </span>{' '}+ · {label}+ </span>+ </div>+)diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/TokenDetails.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/TokenDetails.tsxnew file mode 100644index 00000000000..d4261710611--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/TokenDetails.tsx@@ -0,0 +1,134 @@+import dayjs from 'dayjs'+import type { Control, UseFormSetValue } from 'react-hook-form'+import {+ Badge,+ Calendar,+ FormControl,+ FormField,+ FormMessage,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ useWatch,+} from 'ui'+import {+ DatePicker,+ DatePickerButton,+ DatePickerContent,+ DatePickerTrigger,+} from 'ui-patterns/DatePicker'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'++import {+ EXPIRY_OPTIONS,+ getDefaultCustomExpiryDate,+ type TokenFormValues,+} from './NewScopedTokenForm.utils'++interface TokenDetailsProps {+ control: Control<TokenFormValues>+ setValue: UseFormSetValue<TokenFormValues>+}++export const TokenDetails = ({ control, setValue }: TokenDetailsProps) => {+ const customExpiryDate = useWatch({ control, name: 'customExpiryDate' })++ const handleExpiryChange = (value: string) => {+ setValue('expiresAt', value as TokenFormValues['expiresAt'], { shouldValidate: true })+ if (value === 'custom') {+ if (!customExpiryDate) {+ const iso = getDefaultCustomExpiryDate()+ setValue('customExpiryDate', iso, { shouldValidate: true })+ }+ } else {+ setValue('customExpiryDate', undefined, { shouldValidate: true })+ }+ }++ return (+ <section className="space-y-4 px-5 sm:px-6 py-6">+ <h3 className="text-sm text-foreground sr-only">Token details</h3>++ <FormField+ key="tokenName"+ name="tokenName"+ control={control}+ render={({ field }) => (+ <FormItemLayout name="tokenName" label="Name" layout="flex-row-reverse">+ <FormControl>+ <Input id="tokenName" {...field} placeholder="e.g. CI deploy token" />+ </FormControl>+ </FormItemLayout>+ )}+ />++ <FormField+ key="expiresAt"+ name="expiresAt"+ control={control}+ render={({ field }) => (+ <FormItemLayout name="expiresAt" label="Expires in" layout="flex-row-reverse">+ <div className="flex gap-2 w-full">+ <FormControl className="grow">+ <Select value={field.value} onValueChange={handleExpiryChange}>+ <SelectTrigger>+ <SelectValue placeholder="Select an expiry" />+ </SelectTrigger>+ <SelectContent>+ {EXPIRY_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ <span className="flex items-center gap-2">+ {option.label}+ {option.recommended && <Badge variant="success">Recommended</Badge>}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FormControl>++ {field.value === 'custom' && (+ <FormField+ key="customExpiryDate"+ name="customExpiryDate"+ control={control}+ render={({ field, fieldState }) => {+ const value = field.value ? new Date(field.value) : undefined+ return (+ <div className="shrink">+ <DatePicker>+ <DatePickerTrigger asChild>+ <DatePickerButton ref={field.ref} block isInvalid={fieldState.invalid}>+ {value ? dayjs(value).format('DD MMM, YYYY') : 'Pick a date'}+ </DatePickerButton>+ </DatePickerTrigger>+ <DatePickerContent align="end">+ <Calendar+ mode="single"+ selected={value}+ onSelect={(date) =>+ field.onChange(+ date ? dayjs(date).endOf('day').toISOString() : undefined+ )+ }+ initialFocus+ disabled={{ before: dayjs().startOf('day').toDate() }}+ />+ </DatePickerContent>+ </DatePicker>+ <FormMessage />+ </div>+ )+ }}+ />+ )}+ </div>+ </FormItemLayout>+ )}+ />+ </section>+ )+}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenButton.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenButton.tsxdeleted file mode 100644index 8e25f29e8a9..00000000000--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenButton.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { useState } from 'react'-import { Button } from 'ui'--import { NewScopedTokenSheet } from './NewScopedTokenSheet'-import { type NewScopedAccessToken } from '@/data/scoped-access-tokens/scoped-access-token-create-mutation'--export interface NewScopedTokenButtonProps {- onCreateToken: (token: NewScopedAccessToken) => void-}--export const NewScopedTokenButton = ({ onCreateToken }: NewScopedTokenButtonProps) => {- const [visible, setVisible] = useState(false)-- return (- <>- <Button- variant="primary"- onClick={() => {- setVisible(true)- }}- >- Generate new token- </Button>-- <NewScopedTokenSheet- visible={visible}- onOpenChange={setVisible}- tokenScope={undefined}- onCreateToken={onCreateToken}- />- </>- )-}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsxnew file mode 100644index 00000000000..7e26582a7af--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.test.tsx@@ -0,0 +1,282 @@+import { fireEvent, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { platformComponents as components } from 'api-types'+import { HttpResponse } from 'msw'+import { beforeEach, describe, expect, test } from 'vitest'++import { NewScopedTokenSheet } from './NewScopedTokenSheet'+import type { ProfileContextType } from '@/lib/profile'+import { createMockOrganizationResponse, createMockProject } from '@/tests/helpers'+import { customRender } from '@/tests/lib/custom-render'+import { addAPIMock } from '@/tests/lib/msw'++type OrganizationResponse = components['schemas']['OrganizationResponse']+type ProjectsResponse = components['schemas']['ListProjectsPaginatedResponse']+type CreateTokenResponse = components['schemas']['CreateScopedAccessTokenResponse']++const user = userEvent.setup({+ writeToClipboard: true,+})++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,+}++const mockOrganizations = () =>+ addAPIMock({+ method: 'get',+ path: '/platform/organizations',+ response: () =>+ HttpResponse.json<OrganizationResponse[]>([+ createMockOrganizationResponse({ slug: 'acme-prod', name: 'Acme Production' }),+ ]),+ })++const mockProjects = () =>+ addAPIMock({+ method: 'get',+ path: '/platform/projects',+ response: () =>+ HttpResponse.json<ProjectsResponse>({+ pagination: { count: 1, limit: 100, offset: 0 },+ projects: [+ {+ ...createMockProject({+ id: 1,+ ref: 'project-1',+ name: 'Project 1',+ organization_id: 1,+ }),+ organization_slug: 'acme-prod',+ preview_branch_refs: [],+ },+ ],+ }),+ })++const mockPermissionsMap = () =>+ addAPIMock({+ method: 'get',+ // @ts-expect-error Studio API is missing from types+ path: '/scoped-access-token-permissions',+ response: () =>+ HttpResponse.json({+ scopes: {},+ endpoints: {},+ mcp_tools: {},+ }),+ })++const mockCreateToken = () =>+ addAPIMock({+ method: 'post',+ path: '/platform/profile/scoped-access-tokens',+ response: () =>+ HttpResponse.json<CreateTokenResponse>({+ created_at: '',+ expires_at: null,+ id: 'plop',+ last_used_at: null,+ name: 'test',+ token: 'a_token_value',+ token_alias: '',+ permissions: [],+ }),+ })++/**+ * Permission categories render collapsed, so a category has to be expanded before its+ * rows are in the DOM.+ */+const expandPermissionCategory = async (name: string) =>+ fireEvent.click(await screen.findByRole('button', { name: new RegExp(`^${name}`) }))++describe('NewScopedTokenSheet', () => {+ beforeEach(() => {+ mockPermissionsMap()+ mockOrganizations()+ mockProjects()+ mockCreateToken()+ })+ test('requires a token name', async () => {+ customRender(<NewScopedTokenSheet />, { profileContext: PROFILE_CONTEXT })+ fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))+ await screen.findByRole('dialog')+ fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ expect(await screen.findByText('Please enter a name for the token'))+ })+ // Project scope tests+ test('requires an organization when scope is Project', async () => {+ customRender(<NewScopedTokenSheet />, { profileContext: PROFILE_CONTEXT })+ fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))+ await screen.findByRole('dialog')+ await user.type(await screen.findByLabelText('Name'), 'test')+ fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ expect(await screen.findByText('Please select an organization to continue.'))+ })+ test('requires a project when scope is Project', async () => {+ customRender(<NewScopedTokenSheet />, { profileContext: PROFILE_CONTEXT })+ fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))+ await screen.findByRole('dialog')+ await user.type(await screen.findByLabelText('Name'), 'test')+ fireEvent.click(await screen.findByRole('combobox', { name: 'Organization' }))+ fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ expect(await screen.findByText('Please select a project to continue.'))+ })+ test('requires permissions when scope is Project', async () => {+ customRender(<NewScopedTokenSheet />, { profileContext: PROFILE_CONTEXT })+ fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))+ await screen.findByRole('dialog')+ await user.type(await screen.findByLabelText('Name'), 'test')+ fireEvent.click(await screen.findByRole('combobox', { name: 'Organization' }))+ fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))+ fireEvent.click(await screen.findByRole('combobox', { name: 'Projects' }))+ fireEvent.click(await screen.findByRole('option', { name: 'Project 1' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ expect(await screen.findByText('No permissions selected', { selector: '[role="alert"] *' }))+ })+ test('creates the token when scope is Project', async () => {+ customRender(<NewScopedTokenSheet />, { profileContext: PROFILE_CONTEXT })+ fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))+ await screen.findByRole('dialog')+ await user.type(await screen.findByLabelText('Name'), 'test')+ fireEvent.click(await screen.findByRole('combobox', { name: 'Organization' }))+ fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))+ fireEvent.click(await screen.findByRole('combobox', { name: 'Projects' }))+ fireEvent.click(await screen.findByRole('option', { name: 'Project 1' }))+ await expandPermissionCategory('Project')+ fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))+ fireEvent.click(await screen.findByRole('option', { name: 'Read' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ // Review screen+ await screen.findByText('Low Risk')+ await screen.findByText('single-project read-only access')+ fireEvent.click(await screen.findByRole('button', { name: 'Create token' }))+ // If we can click this checkbox, the token was created+ // Must be a real click, which focuses the button: nothing holds focus once the form+ // unmounts, and copyToClipboard bails out when the document has no focus+ await user.click(await screen.findByRole('button', { name: 'Copy' }))+ await waitFor(async () =>+ expect(await window.navigator.clipboard.readText()).toEqual('a_token_value')+ )+ fireEvent.click(await screen.findByLabelText('I have copied the key and stored it securely'))+ fireEvent.click(await screen.findByRole('button', { name: 'Done' }))+ // Dialog has been closed+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ })++ // Organization scope tests+ test('requires an organization when scope is Organization', async () => {+ customRender(<NewScopedTokenSheet />, { profileContext: PROFILE_CONTEXT })+ fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))+ await screen.findByRole('dialog')+ await user.type(await screen.findByLabelText('Name'), 'test')+ await user.click(await screen.findByRole('radio', { name: /Organization/ }))+ fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ expect(await screen.findByText('Please select an organization to continue.'))+ })+ test('requires permissions when scope is Organization', async () => {+ customRender(<NewScopedTokenSheet />, { profileContext: PROFILE_CONTEXT })+ fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))+ await screen.findByRole('dialog')+ await user.type(await screen.findByLabelText('Name'), 'test')+ await user.click(await screen.findByRole('radio', { name: /Organization/ }))+ fireEvent.click(await screen.findByRole('combobox', { name: 'Organizations' }))+ fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ expect(await screen.findByText('No permissions selected', { selector: '[role="alert"] *' }))+ })+ test('creates the token when scope is Organization', async () => {+ customRender(<NewScopedTokenSheet />, { profileContext: PROFILE_CONTEXT })+ fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))+ await screen.findByRole('dialog')+ await user.type(await screen.findByLabelText('Name'), 'test')+ await user.click(await screen.findByRole('radio', { name: /Organization/ }))+ fireEvent.click(await screen.findByRole('combobox', { name: 'Organizations' }))+ fireEvent.click(await screen.findByRole('option', { name: 'Acme Production' }))+ await expandPermissionCategory('Project')+ fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))+ fireEvent.click(await screen.findByRole('option', { name: 'Read' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ // Review screen+ await screen.findByText('Low Risk')+ await screen.findByText('organization-wide read-only access')+ fireEvent.click(await screen.findByRole('button', { name: 'Create token' }))+ // If we can click this checkbox, the token was created+ // Must be a real click, which focuses the button: nothing holds focus once the form+ // unmounts, and copyToClipboard bails out when the document has no focus+ await user.click(await screen.findByRole('button', { name: 'Copy' }))+ await waitFor(async () =>+ expect(await window.navigator.clipboard.readText()).toEqual('a_token_value')+ )+ fireEvent.click(await screen.findByLabelText('I have copied the key and stored it securely'))+ fireEvent.click(await screen.findByRole('button', { name: 'Done' }))+ // Dialog has been closed+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ })++ // Account scope tests+ test('requires permissions when scope is Account', async () => {+ customRender(<NewScopedTokenSheet />, { profileContext: PROFILE_CONTEXT })+ fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))+ await screen.findByRole('dialog')+ await user.type(await screen.findByLabelText('Name'), 'test')+ await user.click(await screen.findByText('Advanced options'))+ await user.click(+ await screen.findByText(+ 'I understand this token is not limited to one project or organization.'+ )+ )+ fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ expect(await screen.findByText('No permissions selected', { selector: '[role="alert"] *' }))+ })+ test('creates the token when scope is Account', async () => {+ customRender(<NewScopedTokenSheet />, { profileContext: PROFILE_CONTEXT })+ fireEvent.click(await screen.findByRole('button', { name: 'Generate new token' }))+ await screen.findByRole('dialog')+ await user.type(await screen.findByLabelText('Name'), 'test')+ await user.click(await screen.findByText('Advanced options'))+ await user.click(+ await screen.findByText(+ 'I understand this token is not limited to one project or organization.'+ )+ )+ await expandPermissionCategory('Project')+ fireEvent.click(await screen.findByLabelText('Project Settings', { exact: false }))+ fireEvent.click(await screen.findByRole('option', { name: 'Read' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Review access' }))+ // Review screen+ await screen.findByText('Elevated Risk')+ await screen.findByText('account-wide read-only access')+ fireEvent.click(await screen.findByRole('button', { name: 'Create token' }))+ // If we can click this checkbox, the token was created+ // Must be a real click, which focuses the button: nothing holds focus once the form+ // unmounts, and copyToClipboard bails out when the document has no focus+ await user.click(await screen.findByRole('button', { name: 'Copy' }))+ await waitFor(async () =>+ expect(await window.navigator.clipboard.readText()).toEqual('a_token_value')+ )+ fireEvent.click(await screen.findByLabelText('I have copied the key and stored it securely'))+ fireEvent.click(await screen.findByRole('button', { name: 'Done' }))+ // Dialog has been closed+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())+ })+})diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsxindex f6e775cc08a..701f1b58646 100644--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsx+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsx@@ -1,327 +1,103 @@-import { zodResolver } from '@hookform/resolvers/zod'-import dayjs from 'dayjs'-import { ExternalLink } from 'lucide-react'-import Link from 'next/link'-import { useCallback, useState } from 'react'-import { useForm, useWatch, type SubmitHandler } from 'react-hook-form'+import { useState } from 'react'import { toast } from 'sonner'import {Button,- Form,- ScrollArea,- Separator,Sheet,SheetContent,SheetDescription,- SheetFooter,SheetHeader,SheetTitle,+ SheetTrigger,} from 'ui'-import { Admonition } from 'ui-patterns/Admonition'+import { selectionToScopes } from '../AccessToken.permissions'+import { NewScopedTokenForm } from './Form/NewScopedTokenForm'+import { getExpiryDate, type TokenFormValues } from './Form/NewScopedTokenForm.utils'+import { NewScopedTokenSuccess } from './Form/NewScopedTokenSuccess'import {- CUSTOM_EXPIRY_VALUE,- EXPIRES_AT_OPTIONS,- type ScopedAccessTokenPermission,-} from '../AccessToken.constants'-import { TokenSchema, type TokenFormValues } from '../AccessToken.schemas'-import { getExpirationDate, mapPermissionToFGA } from '../AccessToken.utils'-import { useOrgAndProjectData } from '../hooks/useOrgAndProjectData'-import { BasicInfo } from './Form/BasicInfo'-import { Permissions } from './Form/Permissions/Permissions'-import { ResourceAccess } from './Form/ResourceAccess/ResourceAccess'-import {- useAccessTokenCreateMutation,+ useScopedAccessTokenCreateMutation,type NewScopedAccessToken,type ScopedAccessTokenCreateVariables,} from '@/data/scoped-access-tokens/scoped-access-token-create-mutation'import { useTrack } from '@/lib/telemetry/track'-export interface NewScopedTokenSheetProps {- visible: boolean- onOpenChange: (open: boolean) => void- tokenScope: 'V0' | undefined- onCreateToken: (token: NewScopedAccessToken) => void-}--export const NewScopedTokenSheet = ({- visible,- onOpenChange,- tokenScope,- onCreateToken,-}: NewScopedTokenSheetProps) => {- const [resourceSearchOpen, setResourceSearchOpen] = useState(false)- const { organizations, projects } = useOrgAndProjectData()-- const form = useForm<TokenFormValues>({- resolver: zodResolver(TokenSchema),- defaultValues: {- tokenName: '',- expiresAt: EXPIRES_AT_OPTIONS['month'].value,- customExpiryDate: undefined,- resourceAccess: 'all-orgs',- selectedOrganizations: [],- selectedProjects: [],- permissionRows: [],- },- mode: 'onChange',- })-+export const NewScopedTokenSheet = () => {+ const [isOpen, setIsOpen] = useState(false)const track = useTrack()- const { mutate: createAccessToken, isPending } = useAccessTokenCreateMutation()-- const resourceAccess = useWatch({ control: form.control, name: 'resourceAccess' })- const expiresAt = useWatch({ control: form.control, name: 'expiresAt' })- const permissionRows = useWatch({ control: form.control, name: 'permissionRows' }) || []-- const onSubmit: SubmitHandler<TokenFormValues> = async (values) => {- if (!permissionRows || permissionRows.length === 0) {- toast.error('Please configure at least one permission.')- return- }-- const hasValidPermissions = permissionRows.every(- (row) => row.resource && row.actions && row.actions.length > 0- )- if (!hasValidPermissions) {- toast.error('Please ensure all permissions have both resource and action selected.')- return- }+ const { mutate: createToken, isPending } = useScopedAccessTokenCreateMutation()- if (values.resourceAccess === 'selected-orgs') {- const selectedOrgs = values.selectedOrganizations || []-- if (selectedOrgs.length === 0) {- toast.error('Please select at least one organization.')- return- }-- const availableOrgSlugs = organizations.map((org) => org.slug)- const invalidOrgs = selectedOrgs.filter((slug) => !availableOrgSlugs.includes(slug))-- if (invalidOrgs.length > 0) {- toast.error(- `You don't have access to the following organization(s): ${invalidOrgs.join(', ')}`- )- return- }- }-- if (values.resourceAccess === 'selected-projects') {- const selectedProjects = values.selectedProjects || []-- if (selectedProjects.length === 0) {- toast.error('Please select at least one project.')- return- }-- const availableProjectRefs = projects.map((project) => project.ref)- const invalidProjects = selectedProjects.filter((ref) => !availableProjectRefs.includes(ref))-- if (invalidProjects.length > 0) {- toast.error(- `You don't have access to the following project(s): ${invalidProjects.join(', ')}`- )- return- }- }+ const [step, setStep] = useState<'form' | 'success'>('form')+ const [createdToken, setCreatedToken] = useState<NewScopedAccessToken | undefined>()- const finalExpiresAt =- values.expiresAt === CUSTOM_EXPIRY_VALUE- ? values.customExpiryDate- : getExpirationDate(values.expiresAt || '')+ const handleCreate = (values: TokenFormValues) => {+ const permissions = selectionToScopes(values.permissions)+ if (permissions.length === 0) return- const permissions = permissionRows- .flatMap((row) => {- const { resource, actions } = row- return actions.flatMap((action) => mapPermissionToFGA(resource, action))- })- .filter(Boolean) as ScopedAccessTokenPermission[]+ const expires_at =+ values.expiresAt === 'custom' ? values.customExpiryDate : getExpiryDate(values.expiresAt)- if (!permissions || permissions.length === 0) {- toast.error('Please configure at least one valid permission.')- return- }-- const finalPayload: ScopedAccessTokenCreateVariables = {- name: values.tokenName,+ const payload: ScopedAccessTokenCreateVariables = {+ name: values.tokenName.trim(),permissions,+ ...(expires_at ? { expires_at } : {}),+ ...(values.resourceAccess === 'project' ? { project_refs: values.projectRefs } : {}),+ ...(values.resourceAccess === 'organization'+ ? { organization_slugs: values.organizationSlugs }+ : {}),}- if (finalExpiresAt) {- finalPayload.expires_at = finalExpiresAt- }-- if (- values.resourceAccess === 'selected-orgs' &&- values.selectedOrganizations &&- values.selectedOrganizations.length > 0- ) {- finalPayload.organization_slugs = values.selectedOrganizations- } else if (- values.resourceAccess === 'selected-projects' &&- values.selectedProjects &&- values.selectedProjects.length > 0- ) {- finalPayload.project_refs = values.selectedProjects- }-- if (!finalPayload.name || finalPayload.name.trim() === '') {- toast.error('Please enter a token name.')- return- }-- if (!finalPayload.permissions || finalPayload.permissions.length === 0) {- toast.error('Please configure at least one permission.')- return- }-- createAccessToken(finalPayload, {+ createToken(payload, {onSuccess: (data) => {track('access_token_created', {tokenType: 'scoped',- expiryPreset: values.expiresAt || 'never',+ expiryPreset: values.expiresAt,resourceAccess: values.resourceAccess,permissionCount: permissions.length,})toast.success('Access token created successfully')- onCreateToken(data)- handleClose()- },- onError: (error) => {- if (error.message && error.message.includes("don't have access")) {- toast.error(- `Access Error: ${error.message}. Please verify you have access to the selected resources.`- )- } else {- toast.error(`Failed to create access token: ${error.message}`)- }+ setCreatedToken(data)+ setStep('success')},})}- const handleClose = () => {- form.reset({- tokenName: '',- expiresAt: EXPIRES_AT_OPTIONS['month'].value,- customExpiryDate: undefined,- resourceAccess: 'all-orgs',- selectedOrganizations: [],- selectedProjects: [],- permissionRows: [],- })- onOpenChange(false)+ // By default, if users created a token successfully, they can't click outside the sheet to close it+ // as we need to make sure they copied the new token first+ const handleOpenChange = (open: boolean, isSafe = false) => {+ if (open === false && step === 'success' && !isSafe) return+ setStep('form')+ setIsOpen(open)}- const handleCustomDateChange = useCallback(- (date: { date: string } | undefined) => {- form.setValue('customExpiryDate', date?.date, { shouldValidate: true })- },- [form]- )-- const handleCustomExpiryChange = useCallback(- (isCustom: boolean) => {- if (isCustom && !form.getValues('customExpiryDate')) {- form.setValue('customExpiryDate', dayjs().endOf('day').toISOString(), {- shouldValidate: true,- })- }- if (!isCustom) {- form.setValue('customExpiryDate', undefined, { shouldValidate: true })- }- },- [form]- )-return (- <Sheet- open={visible}- onOpenChange={(open) => {- if (!open) {- handleClose()- } else {- onOpenChange(open)- }- }}- >+ <Sheet open={isOpen} onOpenChange={handleOpenChange}>+ <SheetTrigger asChild>+ <Button variant="primary">Generate new token</Button>+ </SheetTrigger><SheetContentshowClose={false}size="default"- className="min-w-[600px]! flex flex-col h-full gap-0"+ className="flex h-full flex-col gap-0 sm:w-[656px] lg:w-[800px]"><SheetHeader>- <SheetTitle>- {tokenScope === 'V0' ? 'Generate token for experimental API' : 'Generate New Token'}- </SheetTitle>+ <SheetTitle>{step === 'success' ? 'Token created' : 'Generate token'}</SheetTitle><SheetDescription className="sr-only">- A form to generate a new scoped access token.+ Generate a new scoped access token in two steps: configure, then review.</SheetDescription></SheetHeader>- <ScrollArea className="flex-1 max-h-[calc(100vh-116px)]">- <div className="flex flex-col overflow-visible">- {tokenScope === 'V0' && (- <div className="px-4 sm:px-5 py-4 pb-4">- <Admonition- type="warning"- title="The experimental API provides additional endpoints which allows you to manage your organizations and projects."- description={- <>- <p>- These include deleting organizations and projects which cannot be undone. As- such, be very careful when using this API.- </p>- <div className="mt-4">- <Button asChild variant="default" icon={<ExternalLink />}>- <Link- href="https://api.supabase.com/api/v0"- target="_blank"- rel="noreferrer"- >- Experimental API documentation- </Link>- </Button>- </div>- </>- }- />- </div>- )}-- <Form {...form}>- <div className="flex flex-col gap-0 overflow-visible">- <BasicInfo- control={form.control}- expirationDate={expiresAt || ''}- onCustomDateChange={handleCustomDateChange}- onCustomExpiryChange={handleCustomExpiryChange}- />- <Separator />- <ResourceAccess- control={form.control}- resourceAccess={resourceAccess}- setValue={form.setValue}- />- <Separator />- <Permissions- control={form.control}- resourceSearchOpen={resourceSearchOpen}- setResourceSearchOpen={setResourceSearchOpen}- />- </div>- </Form>- </div>- </ScrollArea>- <SheetFooter className="justify-end! w-full mt-auto py-4 border-t">- <div className="flex gap-2">- <Button variant="default" disabled={isPending} onClick={handleClose}>- Cancel- </Button>- <Button onClick={form.handleSubmit(onSubmit)} loading={isPending}>- Generate token- </Button>- </div>- </SheetFooter>+ {step === 'success' && createdToken ? (+ <NewScopedTokenSuccess+ tokenName={createdToken.name}+ tokenValue={createdToken.token}+ onClose={() => handleOpenChange(false, true)}+ />+ ) : (+ <NewScopedTokenForm+ isPending={isPending}+ onCreateToken={handleCreate}+ onCancel={() => handleOpenChange(false, true)}+ />+ )}</SheetContent></Sheet>)diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ScopedTokenList.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ScopedTokenList.tsxdeleted file mode 100644index a902a92966a..00000000000--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ScopedTokenList.tsx+++ /dev/null@@ -1,190 +0,0 @@-import { Key, MoreVertical, Trash } from 'lucide-react'-import { parseAsStringLiteral, useQueryState } from 'nuqs'-import { useMemo, useState } from 'react'-import { toast } from 'sonner'-import {- Button,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from 'ui'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'-import { TableCell, TableRow } from 'ui/src/components/shadcn/ui/table'--import {- ACCESS_TOKEN_SORT_VALUES,- AccessTokenSort,- AccessTokenSortColumn,-} from '../AccessToken.types'-import { filterAndSortTokens, handleSortChange } from '../AccessToken.utils'-import { RowLoading } from '../AccessTokenTable/RowLoading'-import { TableContainer } from '../AccessTokenTable/TableContainer'-import { ExpiresCell, LastUsedCell, TokenNameCell } from '../AccessTokenTable/TokenCells'-import { ViewTokenSheet } from './ViewTokenSheet'-import { AlertError } from '@/components/ui/AlertError'-import {- ScopedAccessToken,- useScopedAccessTokensQuery,-} from '@/data/scoped-access-tokens/scoped-access-token-query'-import { useScopedAccessTokenDeleteMutation } from '@/data/scoped-access-tokens/scoped-access-tokens-delete-mutation'-import { useTrack } from '@/lib/telemetry/track'--export interface ScopedTokenListProps {- searchString?: string- onDeleteSuccess: (id: string | number) => void-}--export const ScopedTokenList = ({ searchString = '', onDeleteSuccess }: ScopedTokenListProps) => {- const track = useTrack()- const [isOpen, setIsOpen] = useState(false)- const [token, setToken] = useState<ScopedAccessToken | undefined>(undefined)- const [viewToken, setViewToken] = useState<ScopedAccessToken | undefined>(undefined)- const [isViewSheetOpen, setIsViewSheetOpen] = useState(false)- const [sort, setSort] = useQueryState(- 'sort',- parseAsStringLiteral<AccessTokenSort>(ACCESS_TOKEN_SORT_VALUES).withDefault('created_at:desc')- )-- const { data: tokensData, error, isPending: isLoading, isError } = useScopedAccessTokensQuery()-- const tokens = tokensData?.tokens-- const { mutate: deleteToken } = useScopedAccessTokenDeleteMutation({- onSuccess: (_, vars) => {- track('access_token_removed', { tokenType: 'scoped' })- onDeleteSuccess(vars.id)- toast.success('Successfully deleted access token')- setIsOpen(false)- },- onError: (error) => {- toast.error(`Failed to delete access token: ${error.message}`)- },- })-- const onSortChange = (column: AccessTokenSortColumn) => {- handleSortChange(sort, column, setSort)- }-- const filteredTokens = useMemo(- () => filterAndSortTokens(tokens, searchString, sort),- [tokens, searchString, sort]- )-- const empty = filteredTokens?.length === 0 && !isLoading-- if (isError) {- return (- <TableContainer sort={sort} onSortChange={onSortChange}>- <TableRow>- <TableCell colSpan={4} className="p-0">- <AlertError- error={error}- subject="Failed to retrieve access tokens"- className="rounded-none border-0"- />- </TableCell>- </TableRow>- </TableContainer>- )- }-- if (isLoading) {- return (- <TableContainer sort={sort} onSortChange={onSortChange}>- <RowLoading />- <RowLoading />- </TableContainer>- )- }-- if (empty) {- return (- <TableContainer sort={sort} onSortChange={onSortChange}>- <TableRow>- <TableCell colSpan={4} className="py-12">- <p className="text-sm text-center text-foreground">No scoped access tokens found</p>- <p className="text-sm text-center text-foreground-light">- You do not have any scoped tokens created yet- </p>- </TableCell>- </TableRow>- </TableContainer>- )- }-- return (- <>- <TableContainer sort={sort} onSortChange={onSortChange}>- {filteredTokens?.map((x) => (- <TableRow key={x.id}>- <TokenNameCell name={x.name} tokenAlias={x.token_alias} />- <LastUsedCell lastUsedAt={x.last_used_at} />- <ExpiresCell expiresAt={x.expires_at} />- <TableCell>- <div className="flex items-center justify-end gap-x-2">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="default"- title="More options"- className="w-7"- icon={<MoreVertical />}- />- </DropdownMenuTrigger>- <DropdownMenuContent side="bottom" align="end" className="w-40">- <DropdownMenuItem- className="gap-x-2"- onClick={() => {- setViewToken(x)- setIsViewSheetOpen(true)- }}- >- <Key size={12} />- <p>View permissions</p>- </DropdownMenuItem>- <DropdownMenuItem- className="gap-x-2"- onClick={() => {- setToken(x)- setIsOpen(true)- }}- >- <Trash size={12} />- <p>Delete token</p>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>- </TableCell>- </TableRow>- ))}- </TableContainer>-- <ConfirmationModal- visible={isOpen}- variant="destructive"- title="Confirm to delete"- confirmLabel="Delete"- confirmLabelLoading="Deleting"- onCancel={() => setIsOpen(false)}- onConfirm={() => {- if (token) deleteToken({ id: token.id as string })- }}- >- <p className="py-4 text-sm text-foreground-light">- This action cannot be undone. Are you sure you want to delete "{token?.name}" token?- </p>- </ConfirmationModal>-- <ViewTokenSheet- visible={isViewSheetOpen}- tokenId={viewToken ? String(viewToken.id) : undefined}- onClose={() => {- setIsViewSheetOpen(false)- setViewToken(undefined)- }}- />- </>- )-}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsxindex e6f16ba25c0..7c2b2f8a5b9 100644--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx@@ -1,26 +1,25 @@import dayjs from 'dayjs'import { useMemo } from 'react'-import {- Card,- CardContent,- cn,- ScrollArea,- Sheet,- SheetContent,- SheetHeader,- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow,-} from 'ui'+import { Badge, cn, ScrollArea, Sheet, SheetContent, SheetHeader } from 'ui'import { TimestampInfo } from 'ui-patterns/TimestampInfo'-import { ACCESS_TOKEN_RESOURCES } from '../AccessToken.constants'-import { formatAccessText, getRealAccess } from '../AccessToken.utils'+import {+ computeOverallRisk,+ PERMISSION_CATALOG_BY_CATEGORY,+ scopesToSelection,+ type OverallRisk,+ type PermissionCatalogEntry,+ type PermissionMode,+ type ResourceAccessMode,+ type RiskLevel,+} from '../AccessToken.permissions'import { useOrgAndProjectData } from '../hooks/useOrgAndProjectData'import { DocsButton } from '@/components/ui/DocsButton'+import {+ getEnabledEndpointsForCapability,+ getEnabledMcpTools,+ useGetEnabledEndpointsForCapability,+} from '@/data/scoped-access-tokens/permission-scope-map-query'import { useScopedAccessTokenQuery } from '@/data/scoped-access-tokens/scoped-access-token-query'import { DOCS_URL } from '@/lib/constants'@@ -30,8 +29,34 @@ interface ViewTokenSheetProps {onClose: () => void}+const RISK_TONE_VARIANT: Record<+ OverallRisk['tone'],+ 'default' | 'success' | 'warning' | 'destructive'+> = {+ default: 'default',+ low: 'success',+ medium: 'warning',+ high: 'destructive',+}++const RISK_DOT_CLASS: Record<RiskLevel, string> = {+ low: 'bg-brand-600',+ medium: 'bg-warning-600',+ high: 'bg-destructive-600',+}++const modeLabel = (mode: PermissionMode) =>+ mode === 'readwrite' ? 'Read-write' : mode === 'read' ? 'Read' : 'None'++const SCOPE_TO_RESOURCE_ACCESS: Record<'user' | 'organization' | 'project', ResourceAccessMode> = {+ user: 'account',+ organization: 'organization',+ project: 'project',+}+export function ViewTokenSheet({ visible, tokenId, onClose }: ViewTokenSheetProps) {const { organizations, projects } = useOrgAndProjectData()+ const { data: permissionScopeMap } = useGetEnabledEndpointsForCapability()const {data: token,@@ -46,267 +71,281 @@ export function ViewTokenSheet({ visible, tokenId, onClose }: ViewTokenSheetProp})- const groupedResourcesByAccess = useMemo(() => {- const grouped: Record<string, string[]> = {}+ const resourceAccess = token ? SCOPE_TO_RESOURCE_ACCESS[token.scope] : 'project'+ const grantedScopes = useMemo(() => token?.permissions ?? [], [token?.permissions])- if (!token?.permissions) {- return grouped- }+ const selection = useMemo(() => scopesToSelection(grantedScopes), [grantedScopes])- ACCESS_TOKEN_RESOURCES.forEach((resource) => {- const access = getRealAccess(resource.resource, token.permissions)- if (access !== 'no access') {- const formattedAccess = formatAccessText(access)- if (!grouped[formattedAccess]) {- grouped[formattedAccess] = []- }- grouped[formattedAccess].push(resource.title)- }- })+ const risk = useMemo(+ () => computeOverallRisk(selection, resourceAccess),+ [selection, resourceAccess]+ )- return grouped- }, [token?.permissions])+ const activeByCategory = useMemo(+ () =>+ PERMISSION_CATALOG_BY_CATEGORY.map((category) => ({+ ...category,+ entries: category.entries+ .map((entry) => ({ entry, mode: selection[entry.key] ?? 'none' }))+ .filter(({ mode }) => mode !== 'none'),+ })).filter((category) => category.entries.length > 0),+ [selection]+ )+ const hasCapabilities = grantedScopes.length > 0- const getResourceAccessInfo = () => {- const resources: Array<{ name: string; type: string; identifier: string }> = []+ const mcpTools = useMemo(+ () => getEnabledMcpTools({ grantedScopes, permissionScopeMap }),+ [grantedScopes, permissionScopeMap]+ )- const organizationSlugs = token?.organization_slugs- if (organizationSlugs && Array.isArray(organizationSlugs) && organizationSlugs.length > 0) {- organizationSlugs.forEach((orgSlug: string) => {- const org = organizations.find((o) => o.slug === orgSlug)- resources.push({- name: org?.name || orgSlug,- type: 'Organization',- identifier: orgSlug,+ const capabilityGroups = useMemo(() => {+ const groups: { entry: PermissionCatalogEntry; mode: PermissionMode; endpoints: string[][] }[] =+ []+ for (const category of activeByCategory) {+ for (const { entry, mode } of category.entries) {+ const capabilityScopes =+ mode === 'readwrite' ? [...entry.readScopes, ...entry.writeScopes] : entry.readScopes+ const endpoints = getEnabledEndpointsForCapability({+ capabilityScopes,+ allGrantedScopes: grantedScopes,+ permissionScopeMap,})- })+ if (endpoints.length > 0) {+ groups.push({ entry, mode, endpoints: endpoints.map((e) => [e.method, e.path]) })+ }+ }}+ return groups+ }, [activeByCategory, grantedScopes, permissionScopeMap])- const projectRefs = token?.project_refs- if (projectRefs && Array.isArray(projectRefs) && projectRefs.length > 0) {- projectRefs.forEach((projectRef: string) => {- const project = projects.find((p) => p.ref === projectRef)- resources.push({- name: project?.name || projectRef,- type: 'Project',- identifier: projectRef,- })- })+ const resourceSummary = useMemo(() => {+ if (resourceAccess === 'project') {+ const selectedProjects = projects.filter((p) => (token?.project_refs ?? []).includes(p.ref))+ return {+ title: 'Project',+ items: selectedProjects.length > 0 ? selectedProjects.map((p) => p.name) : ['-'],+ }}+ if (resourceAccess === 'organization') {+ const selectedOrganizations = organizations.filter((o) =>+ (token?.organization_slugs ?? []).includes(o.slug)+ )+ return {+ title: 'Organization',+ items: selectedOrganizations.length > 0 ? selectedOrganizations.map((o) => o.name) : ['-'],+ }+ }+ return { title: 'Account', items: ['Account-level access'] }+ }, [resourceAccess, token, projects, organizations])- return resources- }-- return (- <>- <Sheet open={visible} onOpenChange={() => onClose()}>- <SheetContent- showClose={false}- size="default"- className="min-w-[600px]! flex flex-col h-full gap-0"- >- <SheetHeader- className={cn('flex flex-row justify-between gap-x-4 items-center border-b')}- >- <p className="truncate" title={`Manage access for ${token?.name}`}>- View access for {token?.name}+ const rows: [string, React.ReactNode][] = token+ ? [+ [+ 'Created',+ token.created_at ? (+ <TimestampInfo+ utcTimestamp={token.created_at}+ label={dayjs(token.created_at).format('DD MMM YYYY')}+ className="text-sm"+ />+ ) : (+ <span className="text-foreground-lighter">Unknown</span>+ ),+ ],+ [+ 'Last used',+ token.last_used_at ? (+ <TimestampInfo+ utcTimestamp={token.last_used_at}+ label={dayjs(token.last_used_at).fromNow()}+ className="text-sm"+ />+ ) : (+ <span className="text-foreground-lighter">Never</span>+ ),+ ],+ [+ 'Expires',+ token.expires_at ? (+ <TimestampInfo+ utcTimestamp={token.expires_at}+ label={dayjs(token.expires_at).format('DD MMM YYYY')}+ className="text-sm"+ />+ ) : (+ <span className="text-foreground-lighter">Never</span>+ ),+ ],+ [+ 'Resource access',+ <div key="resource-access" className="space-y-2">+ <p className="text-[11px] font-mono uppercase tracking-wide text-foreground-lighter">+ {resourceSummary.title}</p>- <DocsButton href={`${DOCS_URL}/reference/api/introduction`} />- </SheetHeader>- <ScrollArea className="flex-1 max-h-[calc(100vh-60px)]">- <div className="space-y-8 px-5 sm:px-6 py-6">- {isTokenLoading && (- <div className="flex items-center justify-center py-8">- <p className="text-foreground-light">Loading token information...</p>- </div>- )}-- {tokenError && (- <div className="flex items-center justify-center py-8">- <p className="text-foreground-light text-red-500">- Error loading token information. Please try again.+ <div className="divide-y">+ {resourceSummary.items.map((item) => (+ <p key={item} className="py-2 text-sm text-foreground">+ {item}+ </p>+ ))}+ </div>+ </div>,+ ],+ [+ 'Capabilities',+ hasCapabilities ? (+ <div className="space-y-4">+ {activeByCategory.map((category) => (+ <div key={category.key} className="space-y-2">+ <p className="text-[11px] font-mono uppercase tracking-wide text-foreground-lighter">+ {category.name}</p>+ <div className="divide-y">+ {category.entries.map(({ entry, mode }) => (+ <div+ key={entry.key}+ className="flex items-center justify-between gap-2 text-sm py-2"+ >+ <span className="flex items-center gap-2">+ <span+ className={cn(+ 'h-1.5 w-1.5 shrink-0 rounded-full',+ RISK_DOT_CLASS[entry.risk]+ )}+ />+ <span className="text-foreground text-wrap">{entry.name}</span>+ </span>+ <span className="text-foreground-lighter text-xs font-mono uppercase font-normal text-right">+ {modeLabel(mode)}+ </span>+ </div>+ ))}+ </div></div>- )}+ ))}+ </div>+ ) : (+ <span className="text-foreground-lighter">No capabilities selected</span>+ ),+ ],+ [+ 'Risk level',+ <span key="risk" className="flex flex-wrap items-center gap-2">+ <span className="flex">+ <Badge variant={RISK_TONE_VARIANT[risk.tone]}>{risk.level} Risk</Badge>+ </span>+ <span className="text-sm text-foreground leading-px">+ {risk.text.replace(`${risk.level} — `, '')}+ </span>+ </span>,+ ],+ ]+ : []- {token && (- <>- <div className="space-y-3">- <h3 className="text-sm font-medium text-foreground">Token Information</h3>- <Card className="w-full overflow-hidden bg-surface-100">- <CardContent className="p-0">- <Table className="p-5 table-auto">- <TableHeader>- <TableRow className="bg-200">- <TableHead className="text-left font-mono uppercase text-xs text-foreground-lighter h-auto py-2 w-[60%]">- Info- </TableHead>- <TableHead className="text-left font-mono uppercase text-xs text-foreground-lighter h-auto py-2">- Date- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- <TableRow>- <TableCell>- <p className="truncate text-foreground-light">Created</p>- </TableCell>- <TableCell>- {token?.created_at ? (- <TimestampInfo- utcTimestamp={token.created_at}- label={dayjs(token.created_at).format('DD MMM YYYY')}- className="text-sm"- />- ) : (- <span className="text-foreground">Unknown</span>- )}- </TableCell>- </TableRow>- <TableRow>- <TableCell>- <p className="truncate text-foreground-light">Last used</p>- </TableCell>- <TableCell>- {token?.last_used_at ? (- <TimestampInfo- utcTimestamp={token.last_used_at}- label={dayjs(token.last_used_at).fromNow()}- className="text-sm"- />- ) : (- <span className="text-foreground">Never</span>- )}- </TableCell>- </TableRow>- <TableRow>- <TableCell>- <p className="truncate text-foreground-light">Expires</p>- </TableCell>- <TableCell>- {token?.expires_at ? (- <TimestampInfo- utcTimestamp={token.expires_at}- label={dayjs(token.expires_at).format('DD MMM YYYY')}- className="text-sm"- />- ) : (- <span className="text-foreground">Never</span>- )}- </TableCell>- </TableRow>- </TableBody>- </Table>- </CardContent>- </Card>- </div>+ return (+ <Sheet open={visible} onOpenChange={() => onClose()}>+ <SheetContent+ showClose={false}+ size="default"+ className="flex h-full flex-col gap-0 sm:w-[656px] lg:w-[800px]"+ >+ <SheetHeader className={cn('flex flex-row justify-between gap-x-4 items-center border-b')}>+ <p className="truncate" title={`View access for ${token?.name}`}>+ View access for {token?.name}+ </p>+ <DocsButton href={`${DOCS_URL}/reference/api/introduction`} />+ </SheetHeader>+ <ScrollArea className="flex-1">+ <div className="space-y-6 px-5 sm:px-6 py-6">+ {isTokenLoading && (+ <div className="flex items-center justify-center py-8">+ <p className="text-foreground-light">Loading token information...</p>+ </div>+ )}- <div className="space-y-3">- <h3 className="text-sm font-medium text-foreground">Resource Access</h3>- <Card className="w-full overflow-hidden bg-surface-100">- <CardContent className="p-0">- <Table className="p-5 table-auto">- <TableHeader>- <TableRow className="bg-200">- <TableHead className="text-left font-mono uppercase text-xs text-foreground-lighter h-auto py-2 w-[60%]">- Resource- </TableHead>- <TableHead className="text-left font-mono uppercase text-xs text-foreground-lighter h-auto py-2">- Type- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {getResourceAccessInfo().length > 0 ? (- getResourceAccessInfo().map((resource, index) => (- <TableRow key={`${resource.type}-${resource.identifier}-${index}`}>- <TableCell>- <p className="truncate text-foreground">{resource.name}</p>- </TableCell>- <TableCell>- <span className="text-foreground-light">{resource.type}</span>- </TableCell>- </TableRow>- ))- ) : (- <TableRow>- <TableCell colSpan={2}>- <p className="text-foreground-light text-center py-4">- {token?.scope === 'organization'- ? token.organization_slugs &&- token.organization_slugs.length > 0- ? 'This token has access to specific organizations.'- : 'This token has no accessible organizations.'- : token?.scope === 'project'- ? token.project_refs && token.project_refs.length > 0- ? 'This token has access to specific projects.'- : 'This token has no accessible projects.'- : 'This token has access to all resources.'}- </p>- </TableCell>- </TableRow>- )}- </TableBody>- </Table>- </CardContent>- </Card>- </div>+ {tokenError && (+ <div className="flex items-center justify-center py-8">+ <p className="text-destructive">+ Error loading token information. Please try again.+ </p>+ </div>+ )}- <div className="space-y-3">- <h3 className="text-sm font-medium text-foreground">Permissions</h3>- <Card className="w-full overflow-hidden bg-surface-100">- <CardContent className="p-0">- <Table className="p-5 table-auto">- <TableHeader>- <TableRow className="bg-200">- <TableHead className="text-left font-mono uppercase text-xs text-foreground-lighter h-auto py-2 w-[60%]">- Permission- </TableHead>- <TableHead className="text-left font-mono uppercase text-xs text-foreground-lighter h-auto py-2">- Access- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {Object.keys(groupedResourcesByAccess).length === 0 ? (- <TableRow>- <TableCell colSpan={2}>- <p className="text-foreground-light text-center py-4">- No permissions configured for this token.- </p>- </TableCell>- </TableRow>- ) : (- Object.entries(groupedResourcesByAccess).map(- ([accessLevel, resources]) => {- return resources.map((resource) => (- <TableRow key={`${accessLevel}-${resource}`}>- <TableCell>- <p className="truncate text-foreground capitalize">- {resource}- </p>- </TableCell>- <TableCell>- <span className="text-foreground-light">- {formatAccessText(accessLevel)}- </span>- </TableCell>- </TableRow>- ))- }- )- )}- </TableBody>- </Table>- </CardContent>- </Card>- </div>- </>- )}- </div>- </ScrollArea>- </SheetContent>- </Sheet>- </>+ {token && (+ <>+ <div className="flex flex-col gap-3">+ <h3 className="text-sm">Token summary</h3>+ <dl className="divide-y rounded-md border bg-surface-300">+ {rows.map(([key, value]) => (+ <div key={key} className="grid grid-cols-3 gap-4 px-4 py-3">+ <dt className="text-sm text-foreground-lighter">{key}</dt>+ <dd className="col-span-2 text-sm text-foreground">{value}</dd>+ </div>+ ))}+ </dl>+ </div>++ {hasCapabilities && (+ <>+ <div className="flex flex-col gap-3">+ <h3 className="text-sm">Management API endpoints enabled</h3>+ {capabilityGroups.length === 0 ? (+ <p className="text-xs text-foreground-light">+ No Management API endpoints are enabled by the selected capabilities.+ </p>+ ) : (+ capabilityGroups.map(({ entry, mode, endpoints }) => (+ <div key={entry.key} className="rounded-md border">+ <div className="flex items-center justify-between border-b bg-surface-100 px-3 py-2">+ <span className="text-xs text-foreground">{entry.name}</span>+ <span className="text-[11px] font-mono uppercase text-foreground-lighter">+ {mode === 'readwrite' ? 'Read-write' : 'Read'}+ </span>+ </div>+ <div className="divide-y">+ {endpoints.map(([method, path]) => (+ <div+ key={`${method} ${path}`}+ className="flex items-center gap-2 px-3 py-1.5 font-mono text-xs"+ >+ <span className="w-14 shrink-0 text-foreground-light">+ {method}+ </span>+ <span className="text-foreground">{path}</span>+ </div>+ ))}+ </div>+ </div>+ ))+ )}+ </div>++ <div className="flex flex-col gap-3">+ <h3 className="text-sm">MCP tools</h3>+ {mcpTools.length === 0 ? (+ <p className="text-xs text-foreground-light">+ No MCP tools are enabled by the selected capabilities.+ </p>+ ) : (+ <div className="flex flex-wrap gap-2">+ {mcpTools.map((tool) => (+ <span+ key={tool}+ className="rounded border bg-surface-100 px-2 py-1 font-mono text-xs text-foreground-light"+ >+ {tool}+ </span>+ ))}+ </div>+ )}+ </div>+ </>+ )}+ </>+ )}+ </div>+ </ScrollArea>+ </SheetContent>+ </Sheet>)}diff --git a/apps/studio/components/interfaces/Account/AccessTokens/hooks/useMergedAccessTokens.ts b/apps/studio/components/interfaces/Account/AccessTokens/hooks/useMergedAccessTokens.tsnew file mode 100644index 00000000000..3a4c14854ab--- /dev/null+++ b/apps/studio/components/interfaces/Account/AccessTokens/hooks/useMergedAccessTokens.ts@@ -0,0 +1,65 @@+import { useMemo } from 'react'++import type { BaseToken } from '../AccessToken.types'+import { useAccessTokensQuery } from '@/data/access-tokens/access-tokens-query'+import { useScopedAccessTokensQuery } from '@/data/scoped-access-tokens/scoped-access-token-query'++export type TokenKind = 'classic' | 'scoped'++export type MergedAccessToken = ClassicAccessToken | ScopedAccessToken++export interface ClassicAccessToken extends BaseToken {+ id: number+ kind: 'classic'+}++export interface ScopedAccessToken extends BaseToken {+ id: string+ kind: 'scoped'+}++interface UseMergedAccessTokensOptions {+ /** Whether scoped tokens should be fetched + merged (gated on the scopedPAT flag). */+ scopedTokensEnabled?: boolean+}++/**+ * Merges classic and scoped access tokens into a single list, tagging each row with its `kind`.+ * Classic is the baseline (its loading/error state drives the list); scoped failures degrade+ * gracefully so a missing/undeployed scoped endpoint never hides classic tokens. Sorting is left to+ * the consuming list (via filterAndSortTokens), so this only merges + tags.+ */+export const useMergedAccessTokens = ({+ scopedTokensEnabled,+}: UseMergedAccessTokensOptions = {}) => {+ const classic = useAccessTokensQuery()+ const scoped = useScopedAccessTokensQuery({ enabled: scopedTokensEnabled })++ return useMemo(() => {+ const classicTokens: MergedAccessToken[] = (classic.data ?? []).map((token) => ({+ ...token,+ kind: 'classic',+ }))+ const scopedTokens: MergedAccessToken[] = (scoped.data?.tokens ?? []).map((token) => ({+ ...token,+ kind: 'scoped',+ }))+ return {+ tokens: [...classicTokens, ...scopedTokens],+ // Classic drives the primary states; a scoped fetch that is still loading shouldn't block the list.+ isLoading: classic.isPending || (scopedTokensEnabled && scoped.isPending),+ isError: classic.isError,+ error: classic.error,+ isSuccess: classic.isSuccess,+ }+ }, [+ classic.data,+ classic.isPending,+ classic.isError,+ classic.error,+ classic.isSuccess,+ scoped.data,+ scoped.isPending,+ scopedTokensEnabled,+ ])+}diff --git a/apps/studio/components/layouts/AccessTokens/AccessTokensLayout.tsx b/apps/studio/components/layouts/AccessTokens/AccessTokensLayout.tsxindex 8590e9c817a..b920d79eaf6 100644--- a/apps/studio/components/layouts/AccessTokens/AccessTokensLayout.tsx+++ b/apps/studio/components/layouts/AccessTokens/AccessTokensLayout.tsx@@ -1,39 +1,14 @@-import { useFlag } from 'common'-import Link from 'next/link'-import { useRouter } from 'next/router'import { PropsWithChildren } from 'react'-import { NavMenu, NavMenuItem } from 'ui'import { PageContainer } from 'ui-patterns/PageContainer'import {PageHeader,PageHeaderDescription,PageHeaderMeta,- PageHeaderNavigationTabs,PageHeaderSummary,PageHeaderTitle,} from 'ui-patterns/PageHeader'export const AccessTokensLayout = ({ children }: PropsWithChildren) => {- const router = useRouter()- const scopedTokensEnabled = useFlag('scopedPAT')-- const navigationItems = [- {- label: 'Classic Tokens',- href: `/account/tokens`,- id: 'classic-tokens',- },- ...(scopedTokensEnabled- ? [- {- label: 'Scoped Tokens',- href: `/account/tokens/scoped`,- id: 'scoped-tokens',- },- ]- : []),- ]-const title = 'Access Tokens'const description = 'Create and manage access tokens for API authentication.'@@ -46,20 +21,6 @@ export const AccessTokensLayout = ({ children }: PropsWithChildren) => {<PageHeaderDescription>{description}</PageHeaderDescription></PageHeaderSummary></PageHeaderMeta>- {navigationItems.length > 0 && (- <PageHeaderNavigationTabs>- <NavMenu>- {navigationItems.map((item) => {- const isActive = router.asPath.split('?')[0] === item.href- return (- <NavMenuItem key={item.label} active={isActive}>- <Link href={item.href}>{item.label}</Link>- </NavMenuItem>- )- })}- </NavMenu>- </PageHeaderNavigationTabs>- )}</PageHeader><PageContainer size="small" className="pt-8 pb-16">{children}diff --git a/apps/studio/data/scoped-access-tokens/keys.ts b/apps/studio/data/scoped-access-tokens/keys.tsindex f3dc146c2bf..b1ef15e336e 100644--- a/apps/studio/data/scoped-access-tokens/keys.ts+++ b/apps/studio/data/scoped-access-tokens/keys.ts@@ -1,4 +1,5 @@export const scopedAccessTokenKeys = {list: () => ['scoped-access-tokens'] as const,detail: (id: string) => ['scoped-access-tokens', id] as const,+ permissions: () => ['scoped-access-token-permissions'],}diff --git a/apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts b/apps/studio/data/scoped-access-tokens/permission-scope-map-query.tsnew file mode 100644index 00000000000..976b6a0d127--- /dev/null+++ b/apps/studio/data/scoped-access-tokens/permission-scope-map-query.ts@@ -0,0 +1,188 @@+import { useQuery } from '@tanstack/react-query'++import { scopedAccessTokenKeys } from './keys'+import { BASE_PATH } from '@/lib/constants'+import { ResponseError } from '@/types'++/**+ * Cross-reference between OpenFGA permission scopes, Management API endpoints, and MCP tools.+ */++export interface ScopeMapEntry {+ endpoints: string[]+ mcp_tools: string[]+}++/* e.g+ {+ "branching_production_read": {+ "endpoints": [+ "GET /v1/branches/{branch_id_or_ref}",+ "GET /v1/projects/{ref}/branches",+ "GET /v1/projects/{ref}/branches/{name}"+ ],+ "mcp_tools": [+ "list_branches"+ ]+ }+ }+*/+export type ScopeMap = Record<string, ScopeMapEntry>+// e.g { 'GET /v2/projects/{ref}/analytics/log-drains': ['analytics_config_read'] }+export type EndpointMap = Record<string, string[]>+// e.g { 'deploy_edge_function': ['edge_functions_write'] }+export type McpMap = Record<string, string[]>++export interface PermissionScopeMap {+ /** scope id -> the endpoints / MCP tools it (partially) authorizes */+ scopes: ScopeMap+ /** endpoint -> ALL scopes it requires (conjunctive) */+ endpoints: EndpointMap+ /** MCP tool -> ALL scopes it requires (conjunctive) */+ mcp_tools: McpMap+}++export interface EnabledEndpoint {+ /** HTTP method, e.g. "GET" */+ method: string+ /** Path, e.g. "/v1/projects/{ref}" */+ path: string+ /** The raw "METHOD /path" key */+ raw: string+}++const splitEndpoint = (raw: string): EnabledEndpoint => {+ const spaceIndex = raw.indexOf(' ')+ if (spaceIndex === -1) return { method: '', path: raw, raw }+ return { method: raw.slice(0, spaceIndex), path: raw.slice(spaceIndex + 1), raw }+}++/**+ * Given the set of granted scope ids, returns the Management API endpoints the token can call.+ * An endpoint is only enabled when ALL of its required scopes are granted (conjunctive), which is+ * how the mgmt-api `FgaPermissionsGuard` evaluates the `@AuthWithFgaPermissions` decorator.+ */+export const getEnabledEndpoints = ({+ grantedScopes,+ permissionScopeMap,+}: {+ grantedScopes: Iterable<string>+ permissionScopeMap: PermissionScopeMap | undefined+}): EnabledEndpoint[] => {+ if (permissionScopeMap == null) return []++ const granted = new Set(grantedScopes)+ return Object.entries(permissionScopeMap.endpoints)+ .filter(([, required]) => required.length > 0 && required.every((scope) => granted.has(scope)))+ .map(([raw]) => splitEndpoint(raw))+}++/**+ * Given the set of granted scope ids, returns the MCP tools the token can call. As with endpoints,+ * a tool is only enabled when ALL of its required scopes are granted.+ */+export const getEnabledMcpTools = ({+ grantedScopes,+ permissionScopeMap,+}: {+ grantedScopes: Iterable<string>+ permissionScopeMap: PermissionScopeMap | undefined+}): string[] => {+ if (permissionScopeMap == null) return []++ const granted = new Set(grantedScopes)+ return Object.entries(permissionScopeMap.mcp_tools)+ .filter(([, required]) => required.length > 0 && required.every((scope) => granted.has(scope)))+ .map(([tool]) => tool)+}++/**+ * Endpoints that (a) are fully satisfied by the complete granted-scope set AND (b) require at least+ * one of `capabilityScopes`. Used by the review step to group enabled endpoints under the capability+ * that contributes them, while still honouring dual-scope requirements (a dual-scope endpoint only+ * appears once all its scopes are granted, and shows under each contributing capability).+ */+export const getEnabledEndpointsForCapability = ({+ capabilityScopes,+ allGrantedScopes,+ permissionScopeMap,+}: {+ capabilityScopes: Iterable<string>+ allGrantedScopes: Iterable<string>+ permissionScopeMap: PermissionScopeMap | undefined+}): EnabledEndpoint[] => {+ if (permissionScopeMap == null) return []++ const granted = new Set(allGrantedScopes)+ const capability = new Set(capabilityScopes)+ return Object.entries(permissionScopeMap.endpoints)+ .filter(+ ([, required]) =>+ required.length > 0 &&+ required.every((scope) => granted.has(scope)) &&+ required.some((scope) => capability.has(scope))+ )+ .map(([raw]) => splitEndpoint(raw))+}++/**+ * Informational lookup for the per-permission risk tooltip: the MCP tools associated with any of+ * the given scopes. Unlike getEnabledMcpTools this is not conjunctive — it surfaces every tool that+ * lists one of these scopes, so users can see what a capability relates to before granting it.+ */+export const getMcpToolsForScopes = ({+ scopeIds,+ permissionScopeMap,+}: {+ scopeIds: Iterable<string>+ permissionScopeMap: PermissionScopeMap | undefined+}): string[] => {+ if (permissionScopeMap == null) return []++ const tools = new Set<string>()+ for (const id of scopeIds) {+ permissionScopeMap.scopes[id]?.mcp_tools.forEach((tool) => tools.add(tool))+ }+ return Array.from(tools)+}++export async function getGetScopedTokenPermissionsForScope(signal?: AbortSignal) {+ const response = await fetch(`${BASE_PATH}/api/scoped-access-token-permissions`, {+ signal,+ method: 'GET',+ credentials: 'omit',+ headers: {+ 'Content-Type': 'application/json',+ },+ })++ if (!response.ok) {+ const errorText = await response.text()+ console.error('[getScopedAccessTokenPermissions] Failed:', response.status, errorText)++ let retryAfter: number | undefined+ const retryAfterHeader = response.headers.get('Retry-After')+ if (retryAfterHeader !== null) {+ const parsed = Number(retryAfterHeader)+ if (Number.isFinite(parsed) && parsed > 0) retryAfter = parsed+ }++ throw new ResponseError(+ `Failed to fetch scoped access token permissions: ${response.statusText}`,+ response.status,+ undefined,+ retryAfter+ )+ }++ return await response.json()+}++export type ScopedAccessTokenPermissionsForScopeError = ResponseError++export const useGetEnabledEndpointsForCapability = <TData = PermissionScopeMap>() => {+ return useQuery<TData, ScopedAccessTokenPermissionsForScopeError, TData>({+ queryKey: scopedAccessTokenKeys.permissions(),+ queryFn: ({ signal }) => getGetScopedTokenPermissionsForScope(signal),+ })+}diff --git a/apps/studio/data/scoped-access-tokens/scoped-access-token-create-mutation.ts b/apps/studio/data/scoped-access-tokens/scoped-access-token-create-mutation.tsindex 7ec01cb363c..7e2dc7abf0b 100644--- a/apps/studio/data/scoped-access-tokens/scoped-access-token-create-mutation.ts+++ b/apps/studio/data/scoped-access-tokens/scoped-access-token-create-mutation.ts@@ -26,7 +26,7 @@ export async function createScopedAccessToken({export type NewScopedAccessToken = components['schemas']['CreateScopedAccessTokenResponse']-export const useAccessTokenCreateMutation = ({+export const useScopedAccessTokenCreateMutation = ({onSuccess,onError,...optionsdiff --git a/apps/studio/lib/hosted-api-allowlist.ts b/apps/studio/lib/hosted-api-allowlist.tsindex 614d863ddc3..8d70221994d 100644--- a/apps/studio/lib/hosted-api-allowlist.ts+++ b/apps/studio/lib/hosted-api-allowlist.ts@@ -27,6 +27,7 @@ export const HOSTED_SUPPORTED_API_URLS = ['/api/integrations/stripe-sync','/content/graphql','/parse-query',+ '/scoped-access-token-permissions',]// `pathname` must be basePath-relative — Next's `nextUrl.pathname` already is,diff --git a/apps/studio/package.json b/apps/studio/package.jsonindex 2f3d947c9ed..e3dff9d1c64 100644--- a/apps/studio/package.json+++ b/apps/studio/package.json@@ -74,7 +74,7 @@"@supabase/mcp-server-supabase": "^0.7.0","@supabase/pg-meta": "workspace:*","@supabase/realtime-js": "catalog:",- "@supabase/shared-types": "0.1.88",+ "@supabase/shared-types": "0.1.91","@supabase/supabase-js": "catalog:","@tanstack/react-devtools": "^0.10.3","@tanstack/react-hotkeys": "^0.10.0",diff --git a/apps/studio/pages/account/tokens.tsx b/apps/studio/pages/account/tokens.tsxindex f12f55577bf..7eebc76d97d 100644--- a/apps/studio/pages/account/tokens.tsx+++ b/apps/studio/pages/account/tokens.tsx@@ -1,3 +1,4 @@+import { useFlag } from 'common'import { ExternalLink, Search } from 'lucide-react'import { useState } from 'react'import { Button } from 'ui'@@ -6,21 +7,26 @@ import { Input } from 'ui-patterns/DataInputs/Input'import { AccessTokenList } from '@/components/interfaces/Account/AccessTokens/AccessTokenList'import { AccessTokenNewBanner } from '@/components/interfaces/Account/AccessTokens/AccessTokenNewBanner/AccessTokenNewBanner'import { NewTokenButton } from '@/components/interfaces/Account/AccessTokens/Classic/NewTokenButton'+import { MigrationAdmonition } from '@/components/interfaces/Account/AccessTokens/MigrationAdmonition'+import { NewScopedTokenSheet } from '@/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet'import { AccessTokensLayout } from '@/components/layouts/AccessTokens/AccessTokensLayout'import AccountLayout from '@/components/layouts/AccountLayout/AccountLayout'import { AppLayout } from '@/components/layouts/AppLayout/AppLayout'import { DefaultLayout } from '@/components/layouts/DefaultLayout'import { NewAccessToken } from '@/data/access-tokens/access-tokens-create-mutation'+import { NewScopedAccessToken } from '@/data/scoped-access-tokens/scoped-access-token-create-mutation'import { DOCS_URL } from '@/lib/constants'import type { NextPageWithLayout } from '@/types'const UserAccessTokens: NextPageWithLayout = () => {- const [newToken, setNewToken] = useState<NewAccessToken | undefined>()+ const scopedTokensEnabled = useFlag('scopedPAT')+ const [newToken, setNewToken] = useState<NewScopedAccessToken | NewAccessToken | undefined>()const [searchString, setSearchString] = useState('')return (<AccessTokensLayout><div className="space-y-4">+ {scopedTokensEnabled && <MigrationAdmonition />}{newToken && (<AccessTokenNewBannertoken={newToken}@@ -50,7 +56,11 @@ const UserAccessTokens: NextPageWithLayout = () => {CLI docs</a></Button>- <NewTokenButton onCreateToken={setNewToken} />+ {scopedTokensEnabled ? (+ <NewScopedTokenSheet />+ ) : (+ <NewTokenButton onCreateToken={setNewToken} />+ )}</div></div><AccessTokenList@@ -58,6 +68,7 @@ const UserAccessTokens: NextPageWithLayout = () => {onDeleteSuccess={(id) => {if (id === newToken?.id) setNewToken(undefined)}}+ scopedTokensEnabled={scopedTokensEnabled}/></div></AccessTokensLayout>diff --git a/apps/studio/pages/account/tokens/scoped.tsx b/apps/studio/pages/account/tokens/scoped.tsxindex 15ac0f3ef11..1f3ee998a49 100644--- a/apps/studio/pages/account/tokens/scoped.tsx+++ b/apps/studio/pages/account/tokens/scoped.tsx@@ -1,91 +1,13 @@-import { ExternalLink, Search } from 'lucide-react'-import { useState } from 'react'-import { Button } from 'ui'-import { Input } from 'ui-patterns/DataInputs/Input'+import { useRouter } from 'next/router'+import { useEffect } from 'react'-import { AccessTokenNewBanner } from '@/components/interfaces/Account/AccessTokens/AccessTokenNewBanner/AccessTokenNewBanner'-import { NewScopedTokenButton } from '@/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenButton'-import { ScopedTokenList } from '@/components/interfaces/Account/AccessTokens/Scoped/ScopedTokenList'-import { AccessTokensLayout } from '@/components/layouts/AccessTokens/AccessTokensLayout'-import AccountLayout from '@/components/layouts/AccountLayout/AccountLayout'-import { AppLayout } from '@/components/layouts/AppLayout/AppLayout'-import { DefaultLayout } from '@/components/layouts/DefaultLayout'-import { NewScopedAccessToken } from '@/data/scoped-access-tokens/scoped-access-token-create-mutation'-import { DOCS_URL } from '@/lib/constants'import type { NextPageWithLayout } from '@/types'const ScopedTokens: NextPageWithLayout = () => {- const [searchString, setSearchString] = useState('')- const [newToken, setNewToken] = useState<NewScopedAccessToken | undefined>()-- return (- <AccessTokensLayout>- <div className="space-y-4">- {newToken && (- <AccessTokenNewBanner- token={newToken}- onClose={() => setNewToken(undefined)}- getTokenValue={(token) => token.token}- getTokenPermissions={(token) => token.permissions}- />- )}- <div className="flex items-center justify-between gap-x-2 mb-3">- <Input- size="tiny"- autoComplete="off"- icon={<Search size={12} />}- value={searchString}- onChange={(e) => setSearchString(e.target.value)}- name="search"- id="search"- placeholder="Filter by name"- />- <div className="flex items-center gap-x-2">- <Button asChild variant="default" icon={<ExternalLink />}>- <a- href={`${DOCS_URL}/reference/api/introduction`}- target="_blank"- rel="noopener noreferrer"- >- API Docs- </a>- </Button>- <Button asChild variant="default" icon={<ExternalLink />}>- <a href={`${DOCS_URL}/reference/cli/start`} target="_blank" rel="noopener noreferrer">- CLI docs- </a>- </Button>- <NewScopedTokenButton onCreateToken={setNewToken} />- </div>- </div>-- <ScopedTokenList- searchString={searchString}- onDeleteSuccess={(id) => {- if (id === newToken?.id) setNewToken(undefined)- }}- />-- <p className="text-sm text-foreground-muted text-center mt-6">- Looking for Private Apps?{' '}- <a- href="/org"- className="text-foreground-light underline hover:text-foreground transition-colors"- >- Go to Organization Settings → Connections → Private Apps- </a>- </p>- </div>- </AccessTokensLayout>- )+ const router = useRouter()+ useEffect(() => {+ router.replace('/account/tokens')+ }, [router])}-ScopedTokens.getLayout = (page) => (- <AppLayout>- <DefaultLayout headerTitle="Account">- <AccountLayout title="Access Tokens">{page}</AccountLayout>- </DefaultLayout>- </AppLayout>-)-export default ScopedTokensdiff --git a/apps/studio/routeTree.gen.ts b/apps/studio/routeTree.gen.tsindex e7f21b42556..c134b2af421 100644--- a/apps/studio/routeTree.gen.ts+++ b/apps/studio/routeTree.gen.ts@@ -26,6 +26,7 @@ import { Route as OrgChar91_Char93RouteImport } from './routes/org.[_]'import { Route as NewSlugRouteImport } from './routes/new/$slug'import { Route as IntegrationsVercelRouteImport } from './routes/integrations/vercel'import { Route as ApiStatusOverrideRouteImport } from './routes/api/status-override'+import { Route as ApiScopedAccessTokenPermissionsRouteImport } from './routes/api/scoped-access-token-permissions'import { Route as ApiParseQueryRouteImport } from './routes/api/parse-query'import { Route as ApiIncidentStatusRouteImport } from './routes/api/incident-status'import { Route as ApiIncidentBannerRouteImport } from './routes/api/incident-banner'@@ -401,6 +402,12 @@ const ApiStatusOverrideRoute = ApiStatusOverrideRouteImport.update({path: '/api/status-override',getParentRoute: () => rootRouteImport,} as any)+const ApiScopedAccessTokenPermissionsRoute =+ ApiScopedAccessTokenPermissionsRouteImport.update({+ id: '/api/scoped-access-token-permissions',+ path: '/api/scoped-access-token-permissions',+ getParentRoute: () => rootRouteImport,+ } as any)const ApiParseQueryRoute = ApiParseQueryRouteImport.update({id: '/api/parse-query',path: '/api/parse-query',@@ -2066,6 +2073,7 @@ export interface FileRoutesByFullPath {'/api/incident-banner': typeof ApiIncidentBannerRoute'/api/incident-status': typeof ApiIncidentStatusRoute'/api/parse-query': typeof ApiParseQueryRoute+ '/api/scoped-access-token-permissions': typeof ApiScopedAccessTokenPermissionsRoute'/api/status-override': typeof ApiStatusOverrideRoute'/integrations/vercel': typeof IntegrationsVercelRouteWithChildren'/new/$slug': typeof NewSlugRoute@@ -2372,6 +2380,7 @@ export interface FileRoutesByTo {'/api/incident-banner': typeof ApiIncidentBannerRoute'/api/incident-status': typeof ApiIncidentStatusRoute'/api/parse-query': typeof ApiParseQueryRoute+ '/api/scoped-access-token-permissions': typeof ApiScopedAccessTokenPermissionsRoute'/api/status-override': typeof ApiStatusOverrideRoute'/integrations/vercel': typeof IntegrationsVercelRouteWithChildren'/new/$slug': typeof NewSlugRoute@@ -2671,6 +2680,7 @@ export interface FileRoutesById {'/api/incident-banner': typeof ApiIncidentBannerRoute'/api/incident-status': typeof ApiIncidentStatusRoute'/api/parse-query': typeof ApiParseQueryRoute+ '/api/scoped-access-token-permissions': typeof ApiScopedAccessTokenPermissionsRoute'/api/status-override': typeof ApiStatusOverrideRoute'/integrations/vercel': typeof IntegrationsVercelRouteWithChildren'/new/$slug': typeof NewSlugRoute@@ -2980,6 +2990,7 @@ export interface FileRouteTypes {| '/api/incident-banner'| '/api/incident-status'| '/api/parse-query'+ | '/api/scoped-access-token-permissions'| '/api/status-override'| '/integrations/vercel'| '/new/$slug'@@ -3286,6 +3297,7 @@ export interface FileRouteTypes {| '/api/incident-banner'| '/api/incident-status'| '/api/parse-query'+ | '/api/scoped-access-token-permissions'| '/api/status-override'| '/integrations/vercel'| '/new/$slug'@@ -3584,6 +3596,7 @@ export interface FileRouteTypes {| '/api/incident-banner'| '/api/incident-status'| '/api/parse-query'+ | '/api/scoped-access-token-permissions'| '/api/status-override'| '/integrations/vercel'| '/new/$slug'@@ -3883,6 +3896,7 @@ export interface RootRouteChildren {ApiIncidentBannerRoute: typeof ApiIncidentBannerRouteApiIncidentStatusRoute: typeof ApiIncidentStatusRouteApiParseQueryRoute: typeof ApiParseQueryRoute+ ApiScopedAccessTokenPermissionsRoute: typeof ApiScopedAccessTokenPermissionsRouteApiStatusOverrideRoute: typeof ApiStatusOverrideRouteIntegrationsVercelRoute: typeof IntegrationsVercelRouteWithChildrenNewSlugRoute: typeof NewSlugRoute@@ -4103,6 +4117,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ApiStatusOverrideRouteImportparentRoute: typeof rootRouteImport}+ '/api/scoped-access-token-permissions': {+ id: '/api/scoped-access-token-permissions'+ path: '/api/scoped-access-token-permissions'+ fullPath: '/api/scoped-access-token-permissions'+ preLoaderRoute: typeof ApiScopedAccessTokenPermissionsRouteImport+ parentRoute: typeof rootRouteImport+ }'/api/parse-query': {id: '/api/parse-query'path: '/api/parse-query'@@ -6836,6 +6857,7 @@ const rootRouteChildren: RootRouteChildren = {ApiIncidentBannerRoute: ApiIncidentBannerRoute,ApiIncidentStatusRoute: ApiIncidentStatusRoute,ApiParseQueryRoute: ApiParseQueryRoute,+ ApiScopedAccessTokenPermissionsRoute: ApiScopedAccessTokenPermissionsRoute,ApiStatusOverrideRoute: ApiStatusOverrideRoute,IntegrationsVercelRoute: IntegrationsVercelRouteWithChildren,NewSlugRoute: NewSlugRoute,diff --git a/apps/studio/routes/api/scoped-access-token-permissions.ts b/apps/studio/routes/api/scoped-access-token-permissions.tsnew file mode 100644index 00000000000..558cfd9f582--- /dev/null+++ b/apps/studio/routes/api/scoped-access-token-permissions.ts@@ -0,0 +1,16 @@+import { createFileRoute } from '@tanstack/react-router'++// App Router route (apps/studio/app/api/scoped-access-token/route.ts) — already+// Web-native, uses NextResponse which extends `Response`. Direct re-export of+// each HTTP method; no shim needed.+import { GET, HEAD, OPTIONS } from '@/app/api/scoped-access-token-permissions/route'++export const Route = createFileRoute('/api/scoped-access-token-permissions')({+ server: {+ handlers: {+ GET: () => GET(),+ HEAD: () => HEAD(),+ OPTIONS: () => OPTIONS(),+ },+ },+})diff --git a/apps/studio/vite.config.ts b/apps/studio/vite.config.tsindex 29998d6d8a2..a238efe54a3 100644--- a/apps/studio/vite.config.ts+++ b/apps/studio/vite.config.ts@@ -792,11 +792,11 @@ export default defineConfig(({ command, mode }) => {postcss: { plugins: [] },},ssr: {- // `lodash` must stay inlined so its ids flow through the plugin- // pipeline, where ssrLodashEs (above) rewrites them to lodash-es.- // Externalized bare ids skip user plugins in the dev module runner, so- // dropping this entry resurfaces Node's CJS named-export failure- // ("Named export 'debounce' not found") on every `from 'lodash'` import.+ optimizeDeps: {+ include: ['lodash'],+ },++ // `lodash` is CJS; its named-export interop fails in Node ESM unless bundled.// `next/*` must be bundled so our nextCompat shim wins — otherwise Vite's// SSR externalizer leaves `next/router` as a runtime package import and// Node resolves it to Next's real module.diff --git a/packages/common/constants/local-storage.ts b/packages/common/constants/local-storage.tsindex edf85c0a1f8..9cea4e26385 100644--- a/packages/common/constants/local-storage.ts+++ b/packages/common/constants/local-storage.ts@@ -119,9 +119,9 @@ export const LOCAL_STORAGE_KEYS = {`project-upgrade-failed-banner-dismissed-at-${ref}`,UNIFIED_LOGS_BANNER_DISMISSED: 'unified-logs-banner-dismissed',UNIFIED_LOGS_SIDEBAR_BANNER_DISMISSED: 'unified-logs-sidebar-banner-dismissed',+ SCOPED_TOKENS_MIGRATION_ADMONITION_DISMISSED: 'scoped-tokens-migration-admonition-dismissed',STORAGE_PUBLIC_BUCKET_SELECT_POLICY_WARNING_DISMISSED: (ref: string, bucketId: string) =>`storage-public-bucket-select-policy-warning-dismissed-${ref}-${bucketId}`,-/*** COMMON*/diff --git a/packages/common/telemetry-constants.ts b/packages/common/telemetry-constants.tsindex 7ee0d6e52a1..236e0309e1e 100644--- a/packages/common/telemetry-constants.ts+++ b/packages/common/telemetry-constants.ts@@ -3401,7 +3401,7 @@ export interface AccessTokenCreatedEvent {properties: {tokenType: 'classic' | 'scoped'expiryPreset: string- resourceAccess?: 'all-orgs' | 'selected-orgs' | 'selected-projects'+ resourceAccess?: 'project' | 'organization' | 'account'permissionCount?: number}groups: Omit<TelemetryGroups, 'project'>diff --git a/packages/ui-patterns/src/Admonition/Admonition.tsx b/packages/ui-patterns/src/Admonition/Admonition.tsxindex 7333aac1d74..93d8d1fa33f 100644--- a/packages/ui-patterns/src/Admonition/Admonition.tsx+++ b/packages/ui-patterns/src/Admonition/Admonition.tsx@@ -98,7 +98,7 @@ export const Admonition = forwardRef<{actions && (<divclassName={cn(- 'flex flex-row gap-3',+ 'flex flex-row gap-2',layout === 'vertical' && 'mt-3 items-start',layout === 'horizontal' && 'items-center',layout === 'responsive' && 'mt-3 items-start @md:mt-0 @md:items-center'diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6266009a7b7..dad4f818cfb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -991,8 +991,8 @@ importers:specifier: 'catalog:'version: 2.110.9'@supabase/shared-types':- specifier: 0.1.88- version: 0.1.88+ specifier: 0.1.91+ version: 0.1.91'@supabase/supabase-js':specifier: 'catalog:'version: 2.110.9@@ -7696,8 +7696,8 @@ packages:resolution: {integrity: sha512-XHau+5jIOEAtS9hNiSrL4/2SXSt0EApChsj+f2VJL2mL+eicpUYLkANBu+5awFLIjXGOkys+ClYQ7Dg/3UTHcA==}engines: {node: '>=22.0.0'}- '@supabase/[email protected]':- resolution: {integrity: sha512-9LYy+pD6cD2o8ZSxeUeJ1nrHPigeoP1kzhd2+k6MmzrwBHwxwUhWjywQJVjpU6fLNQxdkoNqxPfI7UQgOjG7Lg==}+ '@supabase/[email protected]':+ resolution: {integrity: sha512-n4co7cT2MD0RGKkAdVPRz8O+f+LaWAqfujV/ug/4U434u5bmopLvCWrA8AzIgNSEr9xyJ+Yv3ksCQo9C0UJWTw==}'@supabase/[email protected]':resolution: {integrity: sha512-06KgjeINtc6405XQvfnchBE1azEsU8G2NElfadmvVHKmHa5l2bFzjbtFbpaYgpgTzccHlcDmBaCgedVf2Gyl8Q==}@@ -23700,7 +23700,7 @@ snapshots:'@supabase/phoenix': 0.4.5tslib: 2.8.1- '@supabase/[email protected]': {}+ '@supabase/[email protected]': {}dependencies: