Files
supabase/apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsx
kemal.earth 1a2e8c679b feat(studio): handle visible project permissions for scoped pat (#53227)
## Problem

We had some org permissions lingering when the permission form was
scoped to project only.

## Solution

We narrow the possible permissions you can pass, here's what changed
with some guards.

- On Project scope, 11 permissions that can’t work no longer appear.
These are the org-level ones (Members, Projects, Billing and the like)
plus a few rows with nothing behind them. Organization scope and
full-access tokens look exactly as before.
- Organization Settings lost its “Read” option on Project scope. You can
pick None or Read-write. Read-write is still needed for one thing:
claiming a project through OAuth.
- Hidden permissions can’t slip through. Switching scope clears them,
presets skip them, the counters ignore them, and the request sent to the
API drops them as a last check.
- A shared package was updated, which wasn’t in the plan. Six of those
rows weren’t showing in the form at all because shared-data was on an
older version of @supabase/shared-types than Studio. Claude Code updated
it so the form matches the full permission list. **That makes the PR
touch package.json and the lockfile, so call it out in review.**
- One loose end: the Full access preset description still mentions
“organization members”, which is now hidden on Project scope. Fixing it
would mean changing copy, so it was left for a follow-up.

## Review instructions

1. Check out the branch and run `pnpm install` — `packages/shared-data`
picks up a new `@supabase/shared-types`, so this isn't optional.
2. Run `pnpm dev:studio` and open http://localhost:8082/account/tokens.
3. Open the dev toolbar (the floating Supabase button, or the user
dropdown), go to **FLAGS → ConfigCat**, and turn on `scopedPAT`.
4. Click **Generate new token**. **Resource access** defaults to
**Project**.
5. Expand all five permission categories. See that 11 rows are gone:
Organizations, Organization Audit Logs, Organization Billing And
Invoices, Organization Configuration, Organization Members, Organization
Projects, Platform Webhooks (organization), Project Authentication
Hooks, Project Authentication Users, Perform Developer Level Operations,
and the project-level SQL Snippets.
6. See that SQL Snippets (account-wide), Projects (account-wide),
Organization Settings, and every other row are still there.
7. Open the **Organization Settings** dropdown. See that it offers only
**None** and **Read-write**.
8. Switch **Resource access** to **Organization**. See that all 11 rows
come back, and Organization Settings offers **Read** again.
9. Set **Organization Members** to Read-write and **Organization
Settings** to Read. Switch to Project, then back to Organization. See
that both are now **None**.
10. Switch back to Project and apply **Preset · Read-only**. See that
Organization Settings stays at None and no hidden row is set.
11. Fill in a name, organization, and project, then create the token.
See that the `POST /platform/profile/scoped-access-tokens` request body
contains none of the hidden scope IDs.
2026-11-11 09:33:57 +00:00

176 lines
6.2 KiB
TypeScript

import { useRef, useState } from 'react'
import { toast } from 'sonner'
import {
Button,
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
SheetTrigger,
} from 'ui'
import { sanitizeSelection, selectionToScopes } from '../AccessToken.permissions'
import { ExperimentalTokenDropdown } from '../Classic/ExperimentalTokenDropdown'
import { NewScopedTokenForm, type NewScopedTokenFormHandle } from './Form/NewScopedTokenForm'
import { getExpiryDate, type TokenFormValues } from './Form/NewScopedTokenForm.utils'
import { NewScopedTokenSuccess } from './Form/NewScopedTokenSuccess'
import { TokenDocsButtons } from './TokenDocsButtons'
import {
useAccessTokenCreateMutation,
type NewAccessToken,
} from '@/data/access-tokens/access-tokens-create-mutation'
import {
useScopedAccessTokenCreateMutation,
type NewScopedAccessToken,
type ScopedAccessTokenCreateVariables,
} from '@/data/scoped-access-tokens/scoped-access-token-create-mutation'
import { useTrack } from '@/lib/telemetry/track'
interface NewScopedTokenSheetProps {
/** Called with the created token when one is generated through the experimental API dialog. */
onCreateExperimentalToken: (token: NewAccessToken) => void
}
export const NewScopedTokenSheet = ({ onCreateExperimentalToken }: NewScopedTokenSheetProps) => {
const [isOpen, setIsOpen] = useState(false)
const track = useTrack()
const formRef = useRef<NewScopedTokenFormHandle>(null)
const { mutate: createToken, isPending: isCreatingScopedToken } =
useScopedAccessTokenCreateMutation()
const { mutate: createClassicToken, isPending: isCreatingClassicToken } =
useAccessTokenCreateMutation()
const [step, setStep] = useState<'form' | 'success'>('form')
const [createdToken, setCreatedToken] = useState<
{ token: NewScopedAccessToken | NewAccessToken; tokenType: 'classic' | 'scoped' } | undefined
>()
const showCreatedToken = (
data: NewScopedAccessToken | NewAccessToken,
tokenType: 'classic' | 'scoped'
) => {
toast.success('Access token created successfully')
setCreatedToken({ token: data, tokenType })
setStep('success')
}
const handleCreate = (values: TokenFormValues) => {
const expires_at =
values.expiresAt === 'custom' ? values.customExpiryDate : getExpiryDate(values.expiresAt)
// 'account' access creates a classic (account-wide) token via the legacy endpoint.
if (values.resourceAccess === 'account') {
createClassicToken(
{ name: values.tokenName.trim(), expires_at },
{
onSuccess: (data) => {
track('access_token_created', {
tokenType: 'classic',
expiryPreset: values.expiresAt,
resourceAccess: 'account',
})
showCreatedToken(data, 'classic')
},
}
)
return
}
const permissions = selectionToScopes(
sanitizeSelection(values.permissions, values.resourceAccess)
)
if (permissions.length === 0) return
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 }
: {}),
}
createToken(payload, {
onSuccess: (data) => {
track('access_token_created', {
tokenType: 'scoped',
expiryPreset: values.expiresAt,
resourceAccess: values.resourceAccess,
permissionCount: permissions.length,
})
showCreatedToken(data, 'scoped')
},
})
}
const trackDismissed = (trigger: 'user' | 'permissions_load_error') => {
const abandonmentContext = formRef.current?.getAbandonmentContext()
track('access_token_creation_sheet_dismissed', {
resourceAccess: abandonmentContext?.resourceAccess ?? 'project',
formStep: abandonmentContext?.formStep ?? 'form',
isFormTouched: abandonmentContext?.isFormTouched ?? false,
trigger,
})
}
// 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
if (open === false && !isSafe) trackDismissed('user')
setStep('form')
setIsOpen(open)
}
const handlePermissionsLoadError = () => {
trackDismissed('permissions_load_error')
handleOpenChange(false, true)
}
return (
<Sheet open={isOpen} onOpenChange={handleOpenChange}>
<div className="flex items-center">
<SheetTrigger asChild>
<Button
variant="primary"
className="rounded-r-none px-3 hover:z-10 focus-visible:z-10 focus-visible:rounded-r-sm"
>
Generate new token
</Button>
</SheetTrigger>
<ExperimentalTokenDropdown onCreateToken={onCreateExperimentalToken} />
</div>
<SheetContent
showClose={false}
size="default"
className="flex h-full flex-col gap-0 sm:w-[656px] lg:w-[800px]"
>
<SheetHeader className="flex flex-col md:flex-row justify-between gap-4 items-start md:items-center">
<SheetTitle>{step === 'success' ? 'Token created' : 'Generate token'}</SheetTitle>
<SheetDescription className="sr-only">
Configure and create a new access token.
</SheetDescription>
{step !== 'success' && <TokenDocsButtons />}
</SheetHeader>
{step === 'success' && createdToken ? (
<NewScopedTokenSuccess
tokenName={createdToken.token.name}
tokenValue={createdToken.token.token}
tokenType={createdToken.tokenType}
onClose={() => handleOpenChange(false, true)}
/>
) : (
<NewScopedTokenForm
ref={formRef}
isPending={isCreatingScopedToken || isCreatingClassicToken}
onCreateToken={handleCreate}
onCancel={handlePermissionsLoadError}
/>
)}
</SheetContent>
</Sheet>
)
}