Skip to content

feat(studio): scoped pat root branch - #48384

Merged
awaseem merged 28 commits into
masterfrom
scopedpat/root-branch
Aug 6, 2026
Merged

awaseem merged 28 commits into
masterfrom
scopedpat/root-branch

Conversation

@djhi

@djhi djhi commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

This is the Scoped PAT stacked PRs root branch

How to test

With the scopedPAT enabled (default on staging)

Go to https://studio-staging-git-scopedpat-merge-token-lists-supabase.vercel.app/dashboard/account/tokens.

  • You shouldn't see two tabs anymore
  • If you had classic tokens, they should have the Legacy badge
  • You can create scoped tokens
  • You have a way to copy newly created tokens before closing the form side panel

With the scopedPAT disabled (use the devtool to override)

  • You shouldn't see two tabs anymore
  • If you had classic tokens, they should not have the Legacy badge
  • You can create classic tokens
  • You have a way to copy newly created tokens above the list upon form submission

Summary by CodeRabbit

  • New Features
    • Show classic and scoped access tokens together in one list, with classic tokens labeled “Legacy” when the scoped experience is enabled.
    • Add scoped access token creation with a two-step configure → review → success flow (when enabled).
    • Add a dismissible migration notice about scoped tokens with a link to API docs.
    • Show “View permissions” only for scoped tokens.
  • Bug Fixes
    • Token deletion now supports both classic and scoped tokens with the correct confirmation and success handling.
    • The scoped tokens page now redirects to the unified access tokens page.
  • Accessibility
    • Improved accessibility by adding a label to the token “more options” action.

First stacked PR for scoped PAT extracted from the prototype #47783 to
ease reviewing.
Next stacked PR is #47979

This PR:
- merge the two existing token lists (classic and scoped) into one
- add an admonition about the scoped PAT migration (missing the docs
URL)

## Notes

It's not possible to create classic tokens anymore with the `scopedPAT`
flag enabled.

## How to test

### With the `scopedPAT` enabled (default on staging)

Go to
https://studio-staging-git-scopedpat-merge-token-lists-supabase.vercel.app/dashboard/account/tokens.
- You shouldn't see two tabs anymore
- If you had classic tokens, they should have the _classic_ badge
- You can create scoped tokens
- You have a way to copy newly created tokens above the list upon form
submission

### With the `scopedPAT` disabled (use the devtool to override)
- You shouldn't see two tabs anymore
- If you had classic tokens, they should **not** have the _classic_
badge
- You can create classic tokens
- You have a way to copy newly created tokens above the list upon form
submission

## Screenshots

Before:
<img width="775" height="515" alt="image"
src="https://github.com/user-attachments/assets/35733e7f-6e3e-40f9-ac5b-cfd7caf5d830"
/>

After:
<img width="767" height="671" alt="image"
src="https://github.com/user-attachments/assets/2fd86e6e-6dc6-46c8-9c89-cbfc553e4eb9"
/>
@djhi
djhi requested a review from a team as a code owner July 28, 2026 09:21
@djhi djhi added the do-not-merge Not ready to be merged yet; pending other dependencies label Jul 28, 2026
@vercel

vercel Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
studio-self-hosted Ready Ready Preview Aug 6, 2026 1:14pm
studio-staging Ready Ready Preview Aug 6, 2026 1:14pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 6, 2026 1:14pm
design-system Skipped Skipped Aug 6, 2026 1:14pm
docs Skipped Skipped Aug 6, 2026 1:14pm
ui-library Skipped Skipped Aug 6, 2026 1:14pm
zone-www-dot-com Skipped Skipped Aug 6, 2026 1:14pm

Request Review

@supabase

supabase Bot commented Jul 28, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Classic and scoped access tokens now share one feature-flagged account page with merged listing, type-specific deletion, scoped-token creation and review, migration messaging, and redirection from the former scoped-token route.

Changes

Access token consolidation

Layer / File(s) Summary
Permission catalog and scope mapping
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts, apps/studio/data/access-tokens/*, apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts
Permission categories, scope conversion, risk calculation, endpoint/MCP mappings, and related tests are added.
Scoped token form and review flow
apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/*
A validated two-step form supports token details, resource access, permission selection, risk review, and capability summaries.
Scoped token creation sheet
apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsx, apps/studio/data/scoped-access-tokens/scoped-access-token-create-mutation.ts
The sheet submits scoped-token payloads, displays the generated token, and requires copy confirmation before closing.
Merged token listing and deletion
apps/studio/components/interfaces/Account/AccessTokens/hooks/useMergedAccessTokens.ts, apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx, apps/studio/components/interfaces/Account/AccessTokens/AccessTokenTable/TokenCells.tsx
Classic and scoped queries are merged with token-kind metadata; deletion selects the corresponding mutation, and classic tokens can display a “Legacy” badge.
Feature-flagged account page and migration route
apps/studio/pages/account/tokens.tsx, apps/studio/components/interfaces/Account/AccessTokens/MigrationAdmonition.tsx, packages/common/constants/local-storage.ts, apps/studio/components/layouts/AccessTokens/AccessTokensLayout.tsx, apps/studio/pages/account/tokens/scoped.tsx, packages/common/telemetry-constants.ts
The scoped-token flag selects creation controls, a dismissible migration notice is added, token-type tabs are removed, the former scoped route redirects, and telemetry resource-access values use the new modes.

Estimated code review effort: 4 (Complex) | ~60 minutes

Suggested reviewers: joshenlim

Sequence Diagram(s)

sequenceDiagram
  participant AccountTokensPage
  participant NewScopedTokenSheet
  participant NewScopedTokenForm
  participant PermissionReview
  participant ScopedTokenMutation
  participant NewScopedTokenSuccess
  AccountTokensPage->>NewScopedTokenSheet: render when scopedPAT is enabled
  NewScopedTokenSheet->>NewScopedTokenForm: display token configuration
  NewScopedTokenForm->>PermissionReview: review selected scopes and capabilities
  PermissionReview-->>NewScopedTokenForm: return validated token values
  NewScopedTokenForm->>NewScopedTokenSheet: submit creation values
  NewScopedTokenSheet->>ScopedTokenMutation: create scoped token
  ScopedTokenMutation-->>NewScopedTokenSheet: return token value
  NewScopedTokenSheet->>NewScopedTokenSuccess: display token once
  NewScopedTokenSuccess-->>NewScopedTokenSheet: confirm copy and close
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change and testing steps but omits the required template sections and CONTRIBUTING.md confirmation. Add the required sections for change type, current behavior, new behavior, additional context, and confirm that CONTRIBUTING.md was read.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the Scoped PAT root branch feature.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch scopedpat/root-branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (next)

passed  240 passed
flaky  3 flaky
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  6 minutes, 51 seconds
commit  1a5a44d

Flaky tests

Features › queue-table-operations.spec.ts › Queue Table Operations › pending changes persist when switching between tables
Features › realtime-inspector.spec.ts › Realtime Inspector › Basic Inspector UI › channel selection popover opens and works
Features › realtime-inspector.spec.ts › Realtime Inspector › Basic Inspector UI › start/stop listening button works

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
apps/studio/pages/account/tokens/scoped.tsx (1)

6-11: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Component has no return, implicitly rendering undefined.

Works at runtime (React 18+ permits function components returning undefined), but an explicit return null is a clearer signal of intent and avoids relying on consistent-return-style lint rules being silent on this pattern.

🔧 Suggested tweak
 const ScopedTokens: NextPageWithLayout = () => {
   const router = useRouter()
   useEffect(() => {
     router.replace('/account/tokens')
   }, [router])
+  return null
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/studio/pages/account/tokens/scoped.tsx` around lines 6 - 11, Update the
ScopedTokens component to explicitly return null after the redirect effect,
preserving the existing router.replace behavior while avoiding an implicit
undefined render.
apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx (1)

53-75: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate onSuccess/onError bodies across the two delete mutations.

The classic and scoped delete mutations differ only by the tokenType literal and which mutate fn is used; the rest of the success/error logic is copy-pasted.

♻️ Suggested extraction
+  const handleDeleteSuccess =
+    (tokenType: TokenKind) =>
+    (_: unknown, vars: { id: number | string }) => {
+      track('access_token_removed', { tokenType })
+      onDeleteSuccess(vars.id)
+      toast.success('Successfully deleted access token')
+      setIsDeleteOpen(false)
+    }
+  const handleDeleteError = (error: { message: string }) =>
+    toast.error(`Failed to delete access token: ${error.message}`)
+
   const { mutate: deleteClassicToken } = useAccessTokenDeleteMutation({
-    onSuccess: (_, vars) => {
-      track('access_token_removed', { tokenType: 'classic' })
-      onDeleteSuccess(vars.id)
-      toast.success('Successfully deleted access token')
-      setIsDeleteOpen(false)
-    },
-    onError: (error) => {
-      toast.error(`Failed to delete access token: ${error.message}`)
-    },
+    onSuccess: handleDeleteSuccess('classic'),
+    onError: handleDeleteError,
   })

   const { mutate: deleteScopedToken } = useScopedAccessTokenDeleteMutation({
-    onSuccess: (_, vars) => {
-      track('access_token_removed', { tokenType: 'scoped' })
-      onDeleteSuccess(vars.id)
-      toast.success('Successfully deleted access token')
-      setIsDeleteOpen(false)
-    },
-    onError: (error) => {
-      toast.error(`Failed to delete access token: ${error.message}`)
-    },
+    onSuccess: handleDeleteSuccess('scoped'),
+    onError: handleDeleteError,
   })
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx`
around lines 53 - 75, Extract the shared success and error handling from the
deleteClassicToken and deleteScopedToken mutation configurations into reusable
callbacks or a helper, parameterized by tokenType. Reuse that shared logic in
both useAccessTokenDeleteMutation and useScopedAccessTokenDeleteMutation while
preserving tracking, onDeleteSuccess, toast, and dialog-closing behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx`:
- Around line 177-184: The AccessTokenList delete confirmation does not reflect
either mutation’s pending state. Extract isPending from both delete mutations,
then pass loading={isDeletingClassic || isDeletingScoped} to the
ConfirmationModal using handleConfirmDelete, so the modal shows its loading
label and prevents duplicate submissions.

In
`@apps/studio/components/interfaces/Account/AccessTokens/hooks/useMergedAccessTokens.ts`:
- Around line 7-11: Replace the single MergedAccessToken interface with separate
classic and scoped variants: classic must use kind 'classic' and numeric id,
while scoped must use kind 'scoped' and string id. Export MergedAccessToken as
their union, preserving the remaining BaseToken fields so kind-based narrowing
provides the correct id type to handleConfirmDelete without casts.

---

Nitpick comments:
In `@apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx`:
- Around line 53-75: Extract the shared success and error handling from the
deleteClassicToken and deleteScopedToken mutation configurations into reusable
callbacks or a helper, parameterized by tokenType. Reuse that shared logic in
both useAccessTokenDeleteMutation and useScopedAccessTokenDeleteMutation while
preserving tracking, onDeleteSuccess, toast, and dialog-closing behavior.

In `@apps/studio/pages/account/tokens/scoped.tsx`:
- Around line 6-11: Update the ScopedTokens component to explicitly return null
after the redirect effect, preserving the existing router.replace behavior while
avoiding an implicit undefined render.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7b540f88-8fcf-44aa-9980-a50043a10412

📥 Commits

Reviewing files that changed from the base of the PR and between b8310db and 68a46eb.

📒 Files selected for processing (9)
  • apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/AccessTokenTable/TokenCells.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/MigrationAdmonition.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/ScopedTokenList.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/hooks/useMergedAccessTokens.ts
  • apps/studio/components/layouts/AccessTokens/AccessTokensLayout.tsx
  • apps/studio/pages/account/tokens.tsx
  • apps/studio/pages/account/tokens/scoped.tsx
  • packages/common/constants/local-storage.ts
💤 Files with no reviewable changes (2)
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/ScopedTokenList.tsx
  • apps/studio/components/layouts/AccessTokens/AccessTokensLayout.tsx

Second stacked PR for scoped PAT extracted from the prototype #47783 to
ease reviewing.
Previous stacked PR is #47886
Next stacked PR is #48003

This PR:
- refactor the scoped token creation form in a multi-step fashion

## How to test

Go to
https://studio-staging-git-scopedpat-scoped-token-creat-80c55b-supabase.vercel.app/dashboard/account/tokens

- Click the _Generate new token_ button
- Try submitting immediately. It should display errors correctly
- Configure everything except permissions and try submitting. It should
display a warning about missing permissions
- Configure the permissions and submit. It should display the review
step
- Try going back, modify anything and submit

- Create the token. It should display the token value with a button to
copy it and a checkbox to confirm the copy. You cannot close the sheet
at this step until you check the box and click _Done_.
@djhi
djhi requested a review from a team as a code owner July 28, 2026 13:41

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Nitpick comments (5)
apps/studio/data/access-tokens/permission-scope-map.ts (1)

27-27: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Validate the generated snapshot at the import boundary.

The double assertion suppresses schema drift in this authorization map. Parse rawScopeMap with a Zod schema before exporting it instead.

As per coding guidelines, “Avoid TypeScript as casts; parse external data with zod using parse or safeParse.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/studio/data/access-tokens/permission-scope-map.ts` at line 27, Replace
the double assertion in PERMISSION_SCOPE_MAP with Zod validation of rawScopeMap
before export. Reuse or define the schema matching PermissionScopeMap, call
parse (or safeParse with appropriate handling) at this import boundary, and
export the validated result without TypeScript casts.

Source: Coding guidelines

apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx (2)

33-34: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Flatten the nested ternary.

Use an if block or lookup map for modeLabel; nested ternaries are prohibited in Studio TSX.

As per coding guidelines, “Use at most one ternary for a binary choice; never nest ternaries.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx`
around lines 33 - 34, Update modeLabel to remove the nested ternary and use an
if-based conditional or lookup map for the PermissionMode values, preserving the
existing Read-write, Read, and None labels.

Source: Coding guidelines


39-97: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the unneeded memoization layer.

These are inexpensive derived values with no demonstrated referential-stability requirement. Compute them directly during render.

As per coding guidelines, “Do not use useMemo or useCallback by default; use them only for measured expense or referential stability required by a memoized child.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx`
around lines 39 - 97, Remove the unnecessary useMemo wrappers around
resourceSummary, expiresSummary, activeByCategory, mcpTools, and
capabilityGroups, computing each derived value directly during render while
preserving their existing logic and outputs. Keep the memoization for
grantedScopes and risk only if their computation or referential stability is
required elsewhere.

Source: Coding guidelines

apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsx (1)

27-27: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Validate the selected mode instead of asserting it.

onValueChange supplies a string; the cast bypasses the PermissionMode contract. Narrow accepted values and only permit readwrite when entry.writable is true.

Proposed fix
-      <Select value={mode} onValueChange={(value) => onChange(value as PermissionMode)}>
+      <Select
+        value={mode}
+        onValueChange={(value) => {
+          if (
+            value === 'none' ||
+            value === 'read' ||
+            (entry.writable && value === 'readwrite')
+          ) {
+            onChange(value)
+          }
+        }}
+      >

As per coding guidelines, “Avoid TypeScript as casts.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsx`
at line 27, Update the Select onValueChange handler in PermissionRow to validate
the incoming string against the allowed PermissionMode values instead of casting
it. Accept read only always, permit readwrite only when entry.writable is true,
and invoke onChange only for validated values.

Source: Coding guidelines

apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.tsx (1)

72-81: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Rename internal handlers to the handleX convention.

enableAccountLevel and switchBackToSingleProject are internal click handlers, not prop callbacks, so per the naming guideline they should be prefixed handle.

♻️ Proposed rename
-  const enableAccountLevel = () => {
+  const handleEnableAccountLevel = () => {
     form.setValue('resourceAccess', 'account', { shouldValidate: true })
     form.setValue('organizationSlugs', [])
     form.setValue('projectRefs', [])
   }

-  const switchBackToSingleProject = () => {
+  const handleSwitchBackToSingleProject = () => {
     form.setValue('resourceAccess', 'project', { shouldValidate: true })
     form.setValue('accountConfirmed', false)
   }

(update the two onClick references accordingly)

As per coding guidelines: "Name prop callbacks `onX`, internal handlers `handleX`."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.tsx`
around lines 72 - 81, Rename the internal handlers enableAccountLevel and
switchBackToSingleProject to handleEnableAccountLevel and
handleSwitchBackToSingleProject, respectively, and update both corresponding
onClick references to use the new names.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts`:
- Around line 407-415: Rename the infrastructure metadata keys to match the
derived resource IDs: update project:infra_addons to project:infra_add_ons in
AccessToken.permissions.ts (lines 407-415) and project:infra_read_replicas in
the same file (lines 425-433). Extend AccessToken.permissions.test.ts (lines
12-36) to verify both catalog entries retain the Infrastructure & Delivery
category and intended metadata.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx`:
- Line 76: Update the ResourceAccessStep invocation in NewScopedTokenForm to
pass the relevant form validation error as its error prop, ensuring superRefine
failures for organizationSlugs or projectRefs reach the component. Use the
existing form error state and preserve the current step flow; coordinate with
ResourceAccessStep’s organizationSlugs/projectRefs FormMessage handling so the
message is visible.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.utils.ts`:
- Around line 63-96: Update the schema’s superRefine validation to require
accountConfirmed when resourceAccess is 'account'; add a custom issue targeting
accountConfirmed when it is not confirmed, while preserving the existing expiry,
project, and organization validation rules.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx`:
- Line 1: Replace the date-fns format import and update the custom expiry
rendering in NewScopedTokenFormReview to use the project’s dayjs date utilities.
Parse the YYYY-MM-DD value as a calendar date without UTC conversion, so
formatting preserves the selected date across time zones.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.tsx`:
- Around line 130-226: Render validation messages for the organizationSlugs and
projectRefs FormField instances in ResourceAccessStep. Use each render
callback’s fieldState.error?.message and the existing FormMessage component,
ensuring errors from TokenFormSchema validation are visible for both project and
organization access modes.
- Around line 192-226: Update the project selector in the resource access form
to gate its disabled state and trigger label on whether organizationSlugs
contains any entries, preserving the existing enabled behavior when an
organization is selected. Also change the nested MultiSelectorInput placeholder
from “Search organizations” to project-specific wording.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/TokenDetails.tsx`:
- Line 1: Replace the date-fns format import and usage in TokenDetails with the
project-standard dayjs date formatting, matching the approach used by
NewScopedTokenForm.utils.ts while preserving the existing custom expiry-date
output.
- Around line 89-118: Update the Calendar in the customExpiryDate FormField to
prevent selecting today or any past date, using its date-disabling mechanism. In
the onSelect handler, normalize valid selections to the local end of day before
storing them via field.onChange, preserving the existing empty-selection
behavior.

In `@apps/studio/data/access-tokens/permission-scope-map.json`:
- Around line 10-13: Model execute_sql conditional requirements in
apps/studio/data/access-tokens/permission-scope-map.json lines 10-13, allowing
database_read alone for read_only=true and requiring database_read plus
database_write for writes; update the evaluation logic in
apps/studio/data/access-tokens/permission-scope-map.ts lines 60-65 to support
alternative requirements, add both read-only and read-write cases in
apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts
lines 75-80, and update NewScopedTokenFormReview.tsx line 81 to display
read-only SQL capability instead of no MCP tools.

---

Nitpick comments:
In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx`:
- Around line 33-34: Update modeLabel to remove the nested ternary and use an
if-based conditional or lookup map for the PermissionMode values, preserving the
existing Read-write, Read, and None labels.
- Around line 39-97: Remove the unnecessary useMemo wrappers around
resourceSummary, expiresSummary, activeByCategory, mcpTools, and
capabilityGroups, computing each derived value directly during render while
preserving their existing logic and outputs. Keep the memoization for
grantedScopes and risk only if their computation or referential stability is
required elsewhere.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsx`:
- Line 27: Update the Select onValueChange handler in PermissionRow to validate
the incoming string against the allowed PermissionMode values instead of casting
it. Accept read only always, permit readwrite only when entry.writable is true,
and invoke onChange only for validated values.

In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.tsx`:
- Around line 72-81: Rename the internal handlers enableAccountLevel and
switchBackToSingleProject to handleEnableAccountLevel and
handleSwitchBackToSingleProject, respectively, and update both corresponding
onClick references to use the new names.

In `@apps/studio/data/access-tokens/permission-scope-map.ts`:
- Line 27: Replace the double assertion in PERMISSION_SCOPE_MAP with Zod
validation of rawScopeMap before export. Reuse or define the schema matching
PermissionScopeMap, call parse (or safeParse with appropriate handling) at this
import boundary, and export the validated result without TypeScript casts.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9be7b6b2-976d-4ecf-ab21-88e9c513b670

📥 Commits

Reviewing files that changed from the base of the PR and between 68a46eb and faac235.

📒 Files selected for processing (21)
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.utils.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenSuccess.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionsAccordion.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/StepIndicator.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/TokenDetails.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenButton.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/hooks/useMergedAccessTokens.ts
  • apps/studio/data/access-tokens/permission-scope-map.json
  • apps/studio/data/access-tokens/permission-scope-map.ts
  • apps/studio/data/scoped-access-tokens/scoped-access-token-create-mutation.ts
  • apps/studio/pages/account/tokens.tsx
  • packages/common/telemetry-constants.ts
💤 Files with no reviewable changes (1)
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenButton.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/studio/pages/account/tokens.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/hooks/useMergedAccessTokens.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsx`:
- Around line 32-35: Update handleCreate in NewScopedTokenSheet so an empty
result from selectionToScopes(values.permissions) surfaces visible feedback,
such as the existing toast or error-state mechanism, before returning. Keep the
token creation flow unchanged for non-empty permissions and ensure the user
receives a clear explanation instead of a silent no-op.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: ad718748-111b-49f0-9139-72efd5f59c88

📥 Commits

Reviewing files that changed from the base of the PR and between b8310db and bccc18a.

📒 Files selected for processing (27)
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/AccessTokenTable/TokenCells.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/MigrationAdmonition.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.utils.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenSuccess.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionsAccordion.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/StepIndicator.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/TokenDetails.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenButton.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenSheet.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/ScopedTokenList.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/hooks/useMergedAccessTokens.ts
  • apps/studio/components/layouts/AccessTokens/AccessTokensLayout.tsx
  • apps/studio/data/access-tokens/permission-scope-map.json
  • apps/studio/data/access-tokens/permission-scope-map.ts
  • apps/studio/data/scoped-access-tokens/scoped-access-token-create-mutation.ts
  • apps/studio/pages/account/tokens.tsx
  • apps/studio/pages/account/tokens/scoped.tsx
  • packages/common/constants/local-storage.ts
  • packages/common/telemetry-constants.ts
💤 Files with no reviewable changes (3)
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/NewScopedTokenButton.tsx
  • apps/studio/components/layouts/AccessTokens/AccessTokensLayout.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/ScopedTokenList.tsx
🚧 Files skipped from review as they are similar to previous changes (22)
  • packages/common/telemetry-constants.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionRow.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenSuccess.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/StepIndicator.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/RiskMarker.tsx
  • packages/common/constants/local-storage.ts
  • apps/studio/components/interfaces/Account/AccessTokens/MigrationAdmonition.tsx
  • apps/studio/data/scoped-access-tokens/scoped-access-token-create-mutation.ts
  • apps/studio/pages/account/tokens/scoped.tsx
  • apps/studio/data/access-tokens/permission-scope-map.json
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.test.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/TokenDetails.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/PermissionsAccordion.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenFormReview.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/ResourceAccessStep.tsx
  • apps/studio/pages/account/tokens.tsx
  • apps/studio/data/access-tokens/permission-scope-map.ts
  • apps/studio/components/interfaces/Account/AccessTokens/AccessTokenList.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.tsx
  • apps/studio/components/interfaces/Account/AccessTokens/AccessToken.permissions.ts
  • apps/studio/components/interfaces/Account/AccessTokens/Scoped/Form/NewScopedTokenForm.utils.ts
  • apps/studio/components/interfaces/Account/AccessTokens/hooks/useMergedAccessTokens.ts

@pamelachia pamelachia left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved from a telemetry naming perspective. Other approvers should check whether the overall/other changes are intended.

Third stacked PR for scoped PAT extracted from the prototype #47783 to
ease reviewing.
Previous stacked PR is #47979
Next stacked PR is #47999

This PR add a way to view the tokens permissions

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
  * Added a “View permissions” option for scoped access tokens.
  * Scoped token permissions now open in a dedicated viewing panel.
  * Scoped token support is enabled by default.

* **Bug Fixes**
* Improved token deletion confirmation to clearly identify the selected
token.
  * Deletion dialogs now close correctly after successful removal.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
djhi added 2 commits July 29, 2026 14:13
Fourth stacked PR for scoped PAT extracted from the prototype #47783 to
ease reviewing.
Previous stacked PR is #48003
Next stacked PR is #48002

This PR:
- fix some accessibility issues
- add unit tests

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Tests**
* Added coverage for creating scoped access tokens at the project,
organization, and account levels.
* Verified validation for required fields, successful token creation,
clipboard copying, and completion flow.

* **Chores**
* Added temporary browser console logging when viewing a scoped access
token.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
…n API specs (#48182)

Fifth stacked PR for scoped PAT extracted from the prototype #47783 to
ease reviewing.
Previous stacked PR is #47999
Next stacked PR is #48359

This PR refactor how we get the map of which scopes enable which
endpoint or mcp tool. Previously it was an hardcoded file. We now
compute it from the OpenAPI specs of our API. This ensure the map stays
up to date when the API changes.

However, we don't have an always up-to-date equivalent for mcp tools so
we duplicated code from platform that map the OAuth scopes they check
with the FGA permissions.

## Notes

The react-hook-form usage is not great. A follow up PR will fix it

## How to test

- On
https://studio-staging-git-scopedpat-scope-permissions-api-supabase.vercel.app/dashboard/account/tokens
- Create a new token with a few permissions (their risk marker should be
displayed: (_High risk_, _Medium risk_ or _Low risk_)
- You should see the available endpoints and mcp tools in the review
step

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Added dynamic permission mapping for scoped access tokens, covering
Management API endpoints and MCP tools.
* Added a permissions endpoint with hosted-platform support and caching.
* Updated scoped token creation and review screens to show capabilities
based on granted permissions.
  * Added permission-aware risk indicators and tool visibility.

* **Bug Fixes**
* Improved authorization checks so endpoints and tools require all
necessary scopes.

* **Tests**
  * Added coverage for endpoint, scope, and MCP tool mapping behavior.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
We don't follow good practices using react-hook-form for the scoped PAT.
This PR aims to fix that:

- pass `control` and `setValue` instead of `form`
- call `useWatch` instead of `form.watch`

No functional nor visual changes

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved the scoped access token creation flow so permission
selections and configured counts update reliably.
* Ensured the review step and final token creation use the validated
settings entered in the form.
* Reset dependent resource selections when changing access modes to
prevent conflicting configurations.
* Improved handling of account-level confirmation and token expiration
settings.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
djhi and others added 9 commits July 30, 2026 18:11
Fixes UX/UI issues:
- when organization scope is selected: org selector should take the full
width
- Use org name and project name as the selected values label instead of
their ids
- There's a wrapping issue in multi-selector when more than one value is
selected
- There's an hover effect on disabled selects (when account scope
selected)
- On the review step: use the project/org names instead of their ids
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

@w3b6x9 initial pass at the announcement banner here. Please have a read
of the copy and feel free to improve where you see fit. I also corrected
how the actions are passed to our `<Admonition />` component. There's
also an inline comment to remind us to update the `Learn more` link when
we go live.

| Before | After |
|--------|--------|
| <img width="755" height="264" alt="Screenshot 2026-08-03 at 14 03 34"
src="https://github.com/user-attachments/assets/05b9e577-4d56-4c42-961a-37ac1e753141"
/> | <img width="769" height="300" alt="Screenshot 2026-08-03 at 14 03
46"
src="https://github.com/user-attachments/assets/11b7bdef-f7a3-47e5-a8b5-a021aafb0bca"
/> |
@kemaldotearth
kemaldotearth requested a review from a team as a code owner August 4, 2026 07:43
@kemaldotearth kemaldotearth changed the title Scoped PAT: root branch feat(studio): scoped pat root branch Aug 4, 2026
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

This touches a few things, brushing them up in anticipation of release.

**Fixes and updates:**
- Fixed sheet width resizing on content changing within sheet.
- Tidied up labelling styles on Permissions row.
- Show expand icon on multi select input.
- Permissions list got a small tidy up.
- Vertical padding on footer to match rest of the sheet.
- Risk badge updated.
- Risk badge tooltip tidied up.
- View permissions sheet tidied up and updated to include MCP and API
endpoints.
- Second step/token summary tidied up.

@kemaldotearth kemaldotearth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving from design standpoint after some styling brush ups. @awaseem might be good if you want to have a pass/update the branch and we just merge it in to prevent super massive PR growth?

awaseem added 2 commits August 6, 2026 06:42
The permissions accordion now starts fully collapsed, so the tests expand
the Project category before configuring a permission. The review step also
renders the risk as a badge plus a separate description, which the
assertions now match.

Copying the token needs a real click as well: since #48521 the sheet
wrapper is no longer focusable, so nothing holds focus once the form
unmounts and copyToClipboard bails out on !document.hasFocus().
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants