Files
Danny WhiteandJoshen Lim be27ad8cf5 feat(studio): show apps and confirm token access changes (#53917)
> [!WARNING]
> This PR relies on #53705 being merged first.

## Problem

Project admins need to see authorised apps before changing token access.
[DEPR-734](https://linear.app/supabase/issue/DEPR-734)

## Solution

- Show Apps below Members only when authorised apps exist; hide the
section while loading or empty, and retain verification errors.
- Show access levels and links to each app’s access sheet.
- Include members and authorised apps in toggle confirmations; wait for
complete counts and offer retry on errors.

| After |
| --- |
| <img width="725" height="560" alt="CleanShot 2026-12-02 at 14 44 13"
src="https://github.com/user-attachments/assets/6f033b2f-a8b4-4a64-824f-ef0cc270ff6c"
/> |
| No authorised apps (no empty state) |
| <img width="728" height="773" alt="CleanShot 2026-12-02 at 14 11 31"
src="https://github.com/user-attachments/assets/76b31461-abca-4f9a-b76d-bb664093dd67"
/> |
| Loading error |
| <img width="727" height="749" alt="CleanShot 2026-12-02 at 14 38 34"
src="https://github.com/user-attachments/assets/0722002c-a5cf-4877-b00b-15f9e4a6524c"
/> |
| 1× authorised app |
| <img width="418" height="222" alt="CleanShot 2026-12-02 at 14 39 27"
src="https://github.com/user-attachments/assets/db5cc89a-2099-4a6f-969c-b4e2c38ac972"
/> |
| Disabling token access whilst 1× app is relying on it |
| <img width="424" height="387" alt="CleanShot 2026-12-02 at 14 39 58"
src="https://github.com/user-attachments/assets/e15c1227-8190-42f4-876b-5f55a321848b"
/> |
| Re-enabling token access which will immediately restore access for N
members and apps |


## Review instructions

1. Open the [staging
preview](https://studio-staging-git-dnywh-depr-734-temporary-acc-b81819-supabase.vercel.app/dashboard),
select a project you administer, and open **Database → Settings**.
Enable database token access in **Feature previews**, plus `jitDbAccess`
and `enableScopedOAuthManage` in the dev toolbar’s **Flags** tab if
needed.
2. Open DevTools → **Console**, paste the setup below and run it.
Navigate to another Studio page (possibly outside of Database) and back
to **Database → Settings**, without reloading. Check **Test Partner
App** appears under Apps with **Read and write** access.
3. Turn token access off. Check the confirmation includes the app, then
choose **Cancel**.
4. Run `tokenAccessReview.state = 'disabled'` in Console, then navigate
away and back. Turn token access on, expand **Who will regain access?**,
check the app is listed, then choose **Cancel**.
5. Run `tokenAccessReview.state = 'enabled'; tokenAccessReview.fail =
true`, then navigate away and back. Check the Apps error disables the
toggle. Run `tokenAccessReview.fail = false` and choose **Retry apps**
to recover.
6. Run `tokenAccessReview.apps = false`, then navigate outside Database
and back. Check Apps is hidden once loaded. Reload to remove the setup.

The setup mocks GET responses only, requires no app authorisation, and
does not change saved access. Use **Cancel** in both confirmations. Do
not reload between steps; reloading removes the setup. Network’s
Response tab does not show these browser-generated responses.

<details>
<summary>Console setup</summary>

```js
(() => {
  if (window.tokenAccessReview) throw new Error('Review setup is already active. Reload to reset it.')
  const projectRef = location.pathname.match(/\/project\/([^/]+)/)?.[1]
  if (!projectRef) throw new Error('Open a project’s Database Settings first.')
  const appId = '75e64165-b74e-432f-bb70-80d6ae432f06'
  const grantId = 'review-org-grant'
  const scopes = ['database_token_access:write']
  const originalFetch = window.fetch
  const review = window.tokenAccessReview = { state: 'enabled', apps: true, fail: false }
  const approvals = /\/platform\/organizations\/[^/]+\/oauth\/approvals$/
  const grants = new RegExp(`/platform/organizations/[^/]+/oauth/approvals/${appId}/grants$`)
  const page = (data) => Response.json({ data, links: { next: null, prev: null } })
  window.fetch = function (input, init) {
    const url = new URL(input instanceof Request ? input.url : input, location.href)
    const method = init?.method ?? (input instanceof Request ? input.method : 'GET')
    if (method.toUpperCase() === 'GET') {
      if (url.pathname.endsWith(`/v1/projects/${projectRef}/jit-access`)) {
        return Promise.resolve(Response.json({ state: review.state, appliedSuccessfully: true }))
      }
      if (approvals.test(url.pathname)) {
        return Promise.resolve(page(review.apps ? [{
          id: appId, type: 'oauth_app', attributes: {
            app: { name: 'Test Partner App', icon: null, created_by: null },
            last_approved_at: '', target: 'organization',
            org_grant: { grant_id: grantId, approved_scopes: scopes, approved_at: '' },
          },
        }] : []))
      }
      if (grants.test(url.pathname)) {
        if (review.fail) return Promise.resolve(Response.json({ message: 'Review: apps unavailable' }, { status: 500 }))
        return Promise.resolve(page([{
          id: grantId, type: 'oauth_grant', attributes: {
            kind: 'organization_bound', user: null, approved_at: '', approved_scopes: scopes,
            projects: [{ ref: projectRef, name: 'Review project' }],
          },
        }]))
      }
    }
    return originalFetch.call(this, input, init)
  }
})()
```

</details>

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-12-02 19:55:19 +07:00

238 lines
8.7 KiB
TypeScript

import { useParams } from 'common'
import { EllipsisVerticalIcon, PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react'
import {
Badge,
Button,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
Skeleton,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from 'ui'
import type { JitUserRule } from './JitDbAccess.types'
import { getJitStatusDisplay } from './JitDbAccess.utils'
import { JitDbAccessInfo } from './JitDbAccessInfo'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { useJitDbAccessStatusQuery } from '@/data/jit-db-access/jit-db-access-status-query'
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
interface JitDbAccessRulesTableProps {
users: JitUserRule[]
isLoading?: boolean
canUpdate: boolean
disableActions?: boolean
allProjectMembersHaveRules?: boolean
onAddRule: () => void
onEditRule: (user: JitUserRule) => void
onDeleteRule: (user: JitUserRule) => void
}
export function JitDbAccessRulesTable({
users,
isLoading = false,
canUpdate,
disableActions = false,
allProjectMembersHaveRules = false,
onAddRule,
onEditRule,
onDeleteRule,
}: JitDbAccessRulesTableProps) {
const { ref: projectRef } = useParams()
const addDisabled = disableActions || !canUpdate || allProjectMembersHaveRules
const addRuleTooltip = !canUpdate
? 'Additional permissions required'
: allProjectMembersHaveRules
? 'All project members already have access rules'
: undefined
const { can: canManageJitDbAccess } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.DATABASE_JIT_WRITE
)
const { data: jitDbAccess, isPending: isLoadingUserJitDbAccess } = useJitDbAccessStatusQuery({
projectRef,
})
if (isLoading || isLoadingUserJitDbAccess) {
return (
<CardContent className="space-y-4 p-4">
<div className="flex items-center justify-between">
<div className="space-y-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-64" />
</div>
<Skeleton className="h-9 w-24" />
</div>
<Skeleton className="h-32 w-full" />
</CardContent>
)
}
return (
<>
<CardContent className="p-0">
<CardHeader className="bg flex flex-row items-center justify-between">
<div className="flex flex-col gap-y-0.5 mb-0">
<CardTitle>Members</CardTitle>
<CardDescription>Members with token access to this database.</CardDescription>
</div>
{canManageJitDbAccess && (
<ButtonTooltip
icon={<PlusIcon />}
onClick={onAddRule}
disabled={addDisabled}
tooltip={{ content: { side: 'bottom', text: addRuleTooltip } }}
>
Add member
</ButtonTooltip>
)}
</CardHeader>
<JitDbAccessInfo />
{canManageJitDbAccess && (
<Table>
<TableHeader className="[&>tr]:bg-background">
<TableRow>
<TableHead>Member</TableHead>
<TableHead>Roles</TableHead>
<TableHead>Status</TableHead>
<TableHead className="w-1">
<span className="sr-only">Actions</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{users.length === 0 ? (
<TableRow className="[&>td]:hover:bg-inherit">
<TableCell colSpan={4}>
<p className="text-sm text-foreground">No rules yet</p>
<p className="text-sm text-foreground-lighter">
Add a member access rule to grant a database role
</p>
</TableCell>
</TableRow>
) : (
users.map((user) => {
const statusDisplay = getJitStatusDisplay(user.status)
const enabledGrants = user.grants.filter((grant) => grant.enabled)
const rowIsInteractive = canUpdate && !disableActions
return (
<TableRow
key={user.id}
className={
rowIsInteractive ? 'relative focus-inset cursor-pointer' : undefined
}
onClick={
rowIsInteractive
? (event) => {
if ((event.target as HTMLElement).closest('button')) return
onEditRule(user)
}
: undefined
}
onKeyDown={
rowIsInteractive
? (event) => {
if ((event.target as HTMLElement).closest('button')) return
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
onEditRule(user)
}
}
: undefined
}
tabIndex={rowIsInteractive ? 0 : undefined}
>
<TableCell className="text-sm">
{user.name && <p>{user.name}</p>}
<p className="text-foreground-lighter">{user.email}</p>
</TableCell>
<TableCell className="text-sm text-foreground-light">
{enabledGrants.length} role
{enabledGrants.length === 1 ? '' : <span>s</span>}
</TableCell>
<TableCell className="text-sm text-foreground-light">
{statusDisplay.badges.length > 0 ? (
<span className="flex flex-wrap gap-1.5">
{statusDisplay.badges.map((badge) => (
<Badge key={badge.label} variant={badge.variant}>
{badge.label}
</Badge>
))}
</span>
) : null}
</TableCell>
<TableCell className="text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
icon={<EllipsisVerticalIcon />}
aria-label="More actions"
size="tiny"
className="w-7 hit-area-2"
disabled={!canUpdate || disableActions}
/>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" side="bottom" className="w-40">
<DropdownMenuItem
className="gap-x-2"
onClick={(event) => {
event.stopPropagation()
onEditRule(user)
}}
disabled={!canUpdate || disableActions}
>
<PencilIcon size={14} className="text-foreground-lighter" />
Edit
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="gap-x-2"
onClick={(event) => {
event.stopPropagation()
onDeleteRule(user)
}}
disabled={!canUpdate || disableActions}
>
<Trash2Icon size={14} className="text-foreground-lighter" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
</TableRow>
)
})
)}
</TableBody>
</Table>
)}
</CardContent>
{!canManageJitDbAccess && jitDbAccess?.user_id !== undefined && (
<CardFooter>
<p className="text-foreground-lighter text-sm">
You need additional permissions to manage member access
</p>
</CardFooter>
)}
</>
)
}