The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(auth): expose access token expiry under auth settings (#48236)
fadymak19dfbd250ab8
diff --git a/apps/docs/content/guides/auth/sessions.mdx b/apps/docs/content/guides/auth/sessions.mdxindex c7eac35d2bf..2a4083b87a2 100644--- a/apps/docs/content/guides/auth/sessions.mdx+++ b/apps/docs/content/guides/auth/sessions.mdx@@ -69,7 +69,7 @@ Otherwise sessions are progressively deleted from the database 24 hours after th### What are recommended values for access token (JWT) expiration?-Most applications should use the default expiration time of 1 hour. This can be customized in your [project's settings](/dashboard/project/_/settings/jwt/legacy) in the JWT Keys > Legacy JWT Secret section.+Most applications should use the default expiration time of 1 hour. You can customize this value in the [Auth settings > Sessions](/dashboard/project/_/auth/sessions).Setting a value over 1 hour is generally discouraged for security reasons, but it may make sense in certain situations.diff --git a/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.test.tsx b/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.test.tsxnew file mode 100644index 00000000000..bf389146c3b--- /dev/null+++ b/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.test.tsx@@ -0,0 +1,106 @@+import { fireEvent, screen, waitFor, within } from '@testing-library/react'+import { mockAnimationsApi } from 'jsdom-testing-mocks'+import { HttpResponse } from 'msw'+import { describe, expect, test, vi } from 'vitest'++import { SessionsAuthSettingsForm } from './SessionsAuthSettingsForm'+import { customRender } from '@/tests/lib/custom-render'+import { addAPIMock } from '@/tests/lib/msw'++// FormMessage animates via framer-motion, which relies on the Web Animations API.+mockAnimationsApi()++vi.mock('@/lib/constants', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/lib/constants')>()+ return { ...actual, IS_PLATFORM: true }+})++vi.mock('@/hooks/misc/useCheckEntitlements', () => ({+ useCheckEntitlements: () => ({ hasAccess: true, isLoading: false }),+}))++vi.mock('@/hooks/misc/useCheckPermissions', () => ({+ useAsyncCheckPermissions: () => ({ can: true, isLoading: false, isSuccess: true }),+}))++function mockAuthConfig(overrides: Record<string, unknown> = {}) {+ addAPIMock({+ method: 'get',+ path: '/platform/auth/:ref/config',+ response: () =>+ HttpResponse.json<any>({+ JWT_EXP: 3600,+ REFRESH_TOKEN_ROTATION_ENABLED: true,+ SECURITY_REFRESH_TOKEN_REUSE_INTERVAL: 10,+ SESSIONS_TIMEBOX: 0,+ SESSIONS_INACTIVITY_TIMEOUT: 0,+ SESSIONS_SINGLE_PER_USER: false,+ ...overrides,+ }),+ })+}++function mockUpdateAuthConfig(onPatch?: (body: unknown) => void) {+ addAPIMock({+ method: 'patch',+ path: '/platform/auth/:ref/config',+ response: async ({ request }) => {+ const body = await request.json()+ onPatch?.(body)+ return HttpResponse.json<any>({ ...(body as object) })+ },+ })+}++describe('SessionsAuthSettingsForm — Access Tokens', () => {+ test('renders the access token expiry from the auth config', async () => {+ mockAuthConfig({ JWT_EXP: 3600 })++ customRender(<SessionsAuthSettingsForm />)++ expect(await screen.findByText('Access Tokens')).toBeInTheDocument()+ expect(await screen.findByDisplayValue('3600')).toBeInTheDocument()+ expect(screen.getByText('Access token expiry time')).toBeInTheDocument()+ })++ test('saving a new expiry issues a PATCH with the JWT_EXP payload', async () => {+ mockAuthConfig({ JWT_EXP: 3600 })+ let patchBody: unknown+ mockUpdateAuthConfig((body) => {+ patchBody = body+ })++ customRender(<SessionsAuthSettingsForm />)++ const input = await screen.findByDisplayValue('3600')+ fireEvent.change(input, { target: { value: '7200' } })++ const form = input.closest('form') as HTMLFormElement+ const saveButton = within(form).getByRole('button', { name: 'Save changes' })+ await waitFor(() => expect(saveButton).toBeEnabled())+ fireEvent.click(saveButton)++ await waitFor(() => expect(patchBody).toEqual({ JWT_EXP: 7200 }))+ })++ test('blocks submit when the expiry exceeds the maximum', async () => {+ mockAuthConfig({ JWT_EXP: 3600 })+ let patchCalled = false+ mockUpdateAuthConfig(() => {+ patchCalled = true+ })++ customRender(<SessionsAuthSettingsForm />)++ const input = await screen.findByDisplayValue('3600')+ fireEvent.change(input, { target: { value: '999999' } })++ const form = input.closest('form') as HTMLFormElement+ const saveButton = within(form).getByRole('button', { name: 'Save changes' })+ await waitFor(() => expect(saveButton).toBeEnabled())+ fireEvent.click(saveButton)++ expect(await screen.findByText('Must be less than 604800')).toBeInTheDocument()+ expect(patchCalled).toBe(false)+ })+})diff --git a/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.tsx b/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.tsxindex a57bdfd515a..3f3aee161b3 100644--- a/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.tsx+++ b/apps/studio/components/interfaces/Auth/SessionsAuthSettingsForm/SessionsAuthSettingsForm.tsx@@ -48,6 +48,16 @@ function HoursOrNeverText({ value }: { value: number }) {}}+const MAX_JWT_EXP = 604800++const AccessTokenSchema = z.object({+ JWT_EXP: z.coerce+ .number()+ .int('Must be a whole number')+ .positive('Must be greater than 0')+ .max(MAX_JWT_EXP, `Must be less than ${MAX_JWT_EXP}`),+})+const RefreshTokenSchema = z.object({REFRESH_TOKEN_ROTATION_ENABLED: z.boolean(),SECURITY_REFRESH_TOKEN_REUSE_INTERVAL: z.coerce.number().min(0, 'Must be a value more than 0'),@@ -73,6 +83,7 @@ export const SessionsAuthSettingsForm = () => {const { mutate: updateAuthConfig } = useAuthConfigUpdateMutation()// Separate loading states for each form+ const [isUpdatingAccessToken, setIsUpdatingAccessToken] = useState(false)const [isUpdatingRefreshTokens, setIsUpdatingRefreshTokens] = useState(false)const [isUpdatingUserSessions, setIsUpdatingUserSessions] = useState(false)@@ -89,6 +100,13 @@ export const SessionsAuthSettingsForm = () => {useCheckEntitlements('auth.user_sessions')const promptProPlanUpgrade = IS_PLATFORM && !hasUserSessionsEntitlement+ const accessTokenForm = useForm<z.infer<typeof AccessTokenSchema>>({+ resolver: zodResolver(AccessTokenSchema),+ defaultValues: {+ JWT_EXP: 3600,+ },+ })+const refreshTokenForm = useForm<z.infer<typeof RefreshTokenSchema>>({resolver: zodResolver(RefreshTokenSchema),defaultValues: {@@ -109,6 +127,12 @@ export const SessionsAuthSettingsForm = () => {useEffect(() => {if (authConfig) {// Only reset forms if they're not currently being updated+ if (!isUpdatingAccessToken) {+ accessTokenForm.reset({+ JWT_EXP: authConfig.JWT_EXP ?? 3600,+ })+ }+if (!isUpdatingRefreshTokens) {refreshTokenForm.reset({REFRESH_TOKEN_ROTATION_ENABLED: authConfig.REFRESH_TOKEN_ROTATION_ENABLED || false,@@ -124,7 +148,26 @@ export const SessionsAuthSettingsForm = () => {})}}- }, [authConfig, isUpdatingRefreshTokens, isUpdatingUserSessions])+ }, [authConfig, isUpdatingAccessToken, isUpdatingRefreshTokens, isUpdatingUserSessions])++ const onSubmitAccessToken = (values: z.infer<typeof AccessTokenSchema>) => {+ const payload = { ...values }+ setIsUpdatingAccessToken(true)++ updateAuthConfig(+ { projectRef: projectRef!, config: payload },+ {+ onError: (error) => {+ toast.error(`Failed to update access token settings: ${error?.message}`)+ setIsUpdatingAccessToken(false)+ },+ onSuccess: () => {+ toast.success('Successfully updated access token settings')+ setIsUpdatingAccessToken(false)+ },+ }+ )+ }const onSubmitRefreshTokens = (values: any) => {const payload = { ...values }@@ -199,46 +242,47 @@ export const SessionsAuthSettingsForm = () => {<PageSection><PageSectionMeta><PageSectionSummary>- <PageSectionTitle>Refresh Tokens</PageSectionTitle>+ <PageSectionTitle>User Sessions</PageSectionTitle></PageSectionSummary></PageSectionMeta><PageSectionContent>- <Form {...refreshTokenForm}>+ <Form {...userSessionsForm}><form- onSubmit={refreshTokenForm.handleSubmit(onSubmitRefreshTokens)}+ onSubmit={userSessionsForm.handleSubmit(onSubmitUserSessions)}className="space-y-4"><Card><CardContent><FormField- control={refreshTokenForm.control}- name="REFRESH_TOKEN_ROTATION_ENABLED"+ control={userSessionsForm.control}+ name="SESSIONS_SINGLE_PER_USER"render={({ field }) => (<FormItemLayoutlayout="flex-row-reverse"- label="Detect and revoke potentially compromised refresh tokens"- description="Prevent replay attacks from potentially compromised refresh tokens."+ label="Enforce single session per user"+ description="If enabled, all but a user's most recently active session will be terminated."><FormControl><Switchchecked={field.value}onCheckedChange={field.onChange}- disabled={!canUpdateConfig}+ disabled={!canUpdateConfig || !hasUserSessionsEntitlement}/></FormControl></FormItemLayout>)}/></CardContent>+<CardContent><FormField- control={refreshTokenForm.control}- name="SECURITY_REFRESH_TOKEN_REUSE_INTERVAL"+ control={userSessionsForm.control}+ name="SESSIONS_TIMEBOX"render={({ field }) => (<FormItemLayoutlayout="flex-row-reverse"- label="Refresh token reuse interval"- description="Time interval where the same refresh token can be used multiple times to request for an access token. Recommendation: 10 seconds."+ label="Time-box user sessions"+ description="The amount of time before a user is forced to sign in again. Use 0 for never."><FormControl className="w-full"><InputGroup>@@ -246,10 +290,42 @@ export const SessionsAuthSettingsForm = () => {type="number"min={0}{...field}- disabled={!canUpdateConfig}+ disabled={!canUpdateConfig || !hasUserSessionsEntitlement}/><InputGroupAddon align="inline-end">- <InputGroupText>seconds</InputGroupText>+ <InputGroupText>+ <HoursOrNeverText value={field.value || 0} />+ </InputGroupText>+ </InputGroupAddon>+ </InputGroup>+ </FormControl>+ </FormItemLayout>+ )}+ />+ </CardContent>++ <CardContent>+ <FormField+ control={userSessionsForm.control}+ name="SESSIONS_INACTIVITY_TIMEOUT"+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Inactivity timeout"+ description="The amount of time a user needs to be inactive to be forced to sign in again. Use 0 for never."+ >+ <FormControl className="w-full">+ <InputGroup>+ <FormInputGroupInput+ type="number"+ {...field}+ className="flex-1"+ disabled={!canUpdateConfig || !hasUserSessionsEntitlement}+ />+ <InputGroupAddon align="inline-end">+ <InputGroupText>+ <HoursOrNeverText value={field.value || 0} />+ </InputGroupText></InputGroupAddon></InputGroup></FormControl>@@ -257,21 +333,32 @@ export const SessionsAuthSettingsForm = () => {)}/></CardContent>++ {promptProPlanUpgrade && (+ <UpgradeToPro+ fullWidth+ source="authSessions"+ featureProposition="configure user sessions"+ primaryText="Configuring user sessions is only available on the Pro Plan and above"+ secondaryText="Upgrade to Pro Plan to configure settings for user sessions."+ />+ )}+<CardFooter className="justify-end space-x-2">- {refreshTokenForm.formState.isDirty && (- <Button variant="default" onClick={() => refreshTokenForm.reset()}>+ {userSessionsForm.formState.isDirty && (+ <Button variant="default" onClick={() => userSessionsForm.reset()}>Cancel</Button>)}<Button- variant="primary"+ variant={promptProPlanUpgrade ? 'default' : 'primary'}type="submit"disabled={!canUpdateConfig ||- isUpdatingRefreshTokens ||- !refreshTokenForm.formState.isDirty+ isUpdatingUserSessions ||+ !userSessionsForm.formState.isDirty}- loading={isUpdatingRefreshTokens}+ loading={isUpdatingUserSessions}>Save changes</Button>@@ -285,90 +372,122 @@ export const SessionsAuthSettingsForm = () => {<PageSection><PageSectionMeta><PageSectionSummary>- <PageSectionTitle>User Sessions</PageSectionTitle>+ <PageSectionTitle>Access Tokens</PageSectionTitle></PageSectionSummary></PageSectionMeta><PageSectionContent>- <Form {...userSessionsForm}>+ <Form {...accessTokenForm}><form- onSubmit={userSessionsForm.handleSubmit(onSubmitUserSessions)}+ onSubmit={accessTokenForm.handleSubmit(onSubmitAccessToken)}className="space-y-4"><Card><CardContent><FormField- control={userSessionsForm.control}- name="SESSIONS_SINGLE_PER_USER"+ control={accessTokenForm.control}+ name="JWT_EXP"render={({ field }) => (<FormItemLayoutlayout="flex-row-reverse"- label="Enforce single session per user"- description="If enabled, all but a user's most recently active session will be terminated."+ label="Access token expiry time"+ description="How long access tokens are valid for before they must be refreshed. Recommendation: 3600 seconds.">- <FormControl>- <Switch- checked={field.value}- onCheckedChange={field.onChange}- disabled={!canUpdateConfig || !hasUserSessionsEntitlement}- />+ <FormControl className="w-full">+ <InputGroup>+ <FormInputGroupInput+ type="number"+ min={1}+ {...field}+ disabled={!canUpdateConfig}+ />+ <InputGroupAddon align="inline-end">+ <InputGroupText>seconds</InputGroupText>+ </InputGroupAddon>+ </InputGroup></FormControl></FormItemLayout>)}/></CardContent>+ <CardFooter className="justify-end space-x-2">+ {accessTokenForm.formState.isDirty && (+ <Button variant="default" onClick={() => accessTokenForm.reset()}>+ Cancel+ </Button>+ )}+ <Button+ variant="primary"+ type="submit"+ disabled={+ !canUpdateConfig ||+ isUpdatingAccessToken ||+ !accessTokenForm.formState.isDirty+ }+ loading={isUpdatingAccessToken}+ >+ Save changes+ </Button>+ </CardFooter>+ </Card>+ </form>+ </Form>+ </PageSectionContent>+ </PageSection>+ <PageSection>+ <PageSectionMeta>+ <PageSectionSummary>+ <PageSectionTitle>Refresh Tokens</PageSectionTitle>+ </PageSectionSummary>+ </PageSectionMeta>+ <PageSectionContent>+ <Form {...refreshTokenForm}>+ <form+ onSubmit={refreshTokenForm.handleSubmit(onSubmitRefreshTokens)}+ className="space-y-4"+ >+ <Card><CardContent><FormField- control={userSessionsForm.control}- name="SESSIONS_TIMEBOX"+ control={refreshTokenForm.control}+ name="REFRESH_TOKEN_ROTATION_ENABLED"render={({ field }) => (<FormItemLayoutlayout="flex-row-reverse"- label="Time-box user sessions"- description="The amount of time before a user is forced to sign in again. Use 0 for never."+ label="Detect and revoke potentially compromised refresh tokens"+ description="Prevent replay attacks from potentially compromised refresh tokens.">- <FormControl className="w-full">- <InputGroup>- <FormInputGroupInput- type="number"- min={0}- {...field}- disabled={!canUpdateConfig || !hasUserSessionsEntitlement}- />- <InputGroupAddon align="inline-end">- <InputGroupText>- <HoursOrNeverText value={field.value || 0} />- </InputGroupText>- </InputGroupAddon>- </InputGroup>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ disabled={!canUpdateConfig}+ /></FormControl></FormItemLayout>)}/></CardContent>-<CardContent><FormField- control={userSessionsForm.control}- name="SESSIONS_INACTIVITY_TIMEOUT"+ control={refreshTokenForm.control}+ name="SECURITY_REFRESH_TOKEN_REUSE_INTERVAL"render={({ field }) => (<FormItemLayoutlayout="flex-row-reverse"- label="Inactivity timeout"- description="The amount of time a user needs to be inactive to be forced to sign in again. Use 0 for never."+ label="Refresh token reuse interval"+ description="Time interval where the same refresh token can be used multiple times to request for an access token. Recommendation: 10 seconds."><FormControl className="w-full"><InputGroup><FormInputGroupInputtype="number"+ min={0}{...field}- className="flex-1"- disabled={!canUpdateConfig || !hasUserSessionsEntitlement}+ disabled={!canUpdateConfig}/><InputGroupAddon align="inline-end">- <InputGroupText>- <HoursOrNeverText value={field.value || 0} />- </InputGroupText>+ <InputGroupText>seconds</InputGroupText></InputGroupAddon></InputGroup></FormControl>@@ -376,32 +495,21 @@ export const SessionsAuthSettingsForm = () => {)}/></CardContent>-- {promptProPlanUpgrade && (- <UpgradeToPro- fullWidth- source="authSessions"- featureProposition="configure user sessions"- primaryText="Configuring user sessions is only available on the Pro Plan and above"- secondaryText="Upgrade to Pro Plan to configure settings for user sessions."- />- )}-<CardFooter className="justify-end space-x-2">- {userSessionsForm.formState.isDirty && (- <Button variant="default" onClick={() => userSessionsForm.reset()}>+ {refreshTokenForm.formState.isDirty && (+ <Button variant="default" onClick={() => refreshTokenForm.reset()}>Cancel</Button>)}<Button- variant={promptProPlanUpgrade ? 'default' : 'primary'}+ variant="primary"type="submit"disabled={!canUpdateConfig ||- isUpdatingUserSessions ||- !userSessionsForm.formState.isDirty+ isUpdatingRefreshTokens ||+ !refreshTokenForm.formState.isDirty}- loading={isUpdatingUserSessions}+ loading={isUpdatingRefreshTokens}>Save changes</Button>diff --git a/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx b/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsxindex f6fe9c81b13..24d12cb3adf 100644--- a/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx+++ b/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx@@ -21,8 +21,8 @@ import {TriangleAlert,} from 'lucide-react'import Link from 'next/link'-import { useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react'-import { useForm, type SubmitHandler } from 'react-hook-form'+import { useState, type Dispatch, type SetStateAction } from 'react'+import { useForm } from 'react-hook-form'import { toast } from 'sonner'import {Button,@@ -45,14 +45,11 @@ import {Form,FormControl,FormField,- FormInputGroupInput,- InputGroup,- InputGroupAddon,- InputGroupText,} from 'ui'import { Admonition } from 'ui-patterns/admonition'import { Input } from 'ui-patterns/DataInputs/Input'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { FormLayout } from 'ui-patterns/form/Layout/FormLayout'import * as z from 'zod'import {@@ -60,13 +57,10 @@ import {JWT_SECRET_UPDATE_PROGRESS_MESSAGES,} from './jwt.constants'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'-import { FormActions } from '@/components/ui/Forms/FormActions'import { InlineLink } from '@/components/ui/InlineLink'import Panel from '@/components/ui/Panel'import { TextConfirmModal } from '@/components/ui/TextConfirmModalWrapper'import { useLegacyAPIKeysStatusQuery } from '@/data/api-keys/legacy-api-keys-status-query'-import { useAuthConfigQuery } from '@/data/auth/auth-config-query'-import { useAuthConfigUpdateMutation } from '@/data/auth/auth-config-update-mutation'import { useJwtSecretUpdateMutation } from '@/data/config/jwt-secret-update-mutation'import { useJwtSecretUpdatingStatusQuery } from '@/data/config/jwt-secret-updating-status-query'import { useProjectPostgrestConfigQuery } from '@/data/config/project-postgrest-config-query'@@ -75,21 +69,6 @@ import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'import { DOCS_URL } from '@/lib/constants'import { uuidv4 } from '@/lib/helpers'-const MAX_JWT_EXP = 604800-const formSchema = z.object({- JWT_EXP: z.preprocess(- (val) => (val === '' || val === null || val === undefined ? undefined : val),- z.coerce- .number({- required_error: 'Must have a JWT expiry value',- invalid_type_error: 'Must have a JWT expiry value',- })- .positive('Must be greater than 0')- .max(MAX_JWT_EXP, `Must be less than ${MAX_JWT_EXP}`)- ),-})-const formId = 'jwt-exp-form'-const customJwtSecretFormSchema = z.object({customToken: z.string()@@ -115,10 +94,6 @@ export const JWTSettings = () => {PermissionAction.INFRA_EXECUTE,'queue_job.projects.update_jwt')- const { can: canUpdateConfig } = useAsyncCheckPermissions(- PermissionAction.UPDATE,- 'custom_config_gotrue'- )const { data } = useJwtSecretUpdatingStatusQuery({ projectRef }, { enabled: IS_PLATFORM })const { data: config, isError } = useProjectPostgrestConfigQuery({ projectRef })@@ -135,13 +110,6 @@ export const JWTSettings = () => {{ enabled: IS_PLATFORM && canReadAPIKeys })- const { data: authConfig, isPending: isLoadingAuthConfig } = useAuthConfigQuery(- { projectRef },- { enabled: IS_PLATFORM }- )- const { mutate: updateAuthConfig, isPending: isUpdatingAuthConfig } =- useAuthConfigUpdateMutation()-const { Failed, Updated, Updating } = JwtSecretUpdateStatusconst isJwtSecretUpdateFailed = data?.jwtSecretUpdateStatus === Failed@@ -153,47 +121,11 @@ export const JWTSettings = () => {const jwtSecretUpdateProgressMessage =JWT_SECRET_UPDATE_PROGRESS_MESSAGES[data?.jwtSecretUpdateProgress as JwtSecretUpdateProgress]- const INITIAL_VALUES = useMemo(- () => ({- JWT_EXP: authConfig?.JWT_EXP ?? 3600,- }),- [authConfig]- )-- const form = useForm<z.infer<typeof formSchema>>({- defaultValues: INITIAL_VALUES,- resolver: zodResolver(formSchema),- })-const customJwtSecretForm = useForm<z.infer<typeof customJwtSecretFormSchema>>({defaultValues: { customToken: '' },resolver: zodResolver(customJwtSecretFormSchema),})- const { reset, formState } = form- const { isDirty } = formState-- useEffect(() => {- reset(INITIAL_VALUES)- }, [INITIAL_VALUES, reset])-- const onUpdateJwtExp: SubmitHandler<z.infer<typeof formSchema>> = async (values) => {- if (!projectRef) return console.error('Project ref is required')-- updateAuthConfig(- { projectRef, config: values },- {- onError: (error) => {- toast.error(`Failed to update JWT expiry: ${error?.message}`)- },- onSuccess: (newValues) => {- toast.success('Successfully updated JWT expiry')- reset({ JWT_EXP: newValues.JWT_EXP ?? values.JWT_EXP })- },- }- )- }-async function handleJwtSecretUpdate(jwt_secret: string,setModalVisibility: Dispatch<SetStateAction<boolean>>@@ -215,16 +147,14 @@ export const JWTSettings = () => {return (<Panel><Panel.Content className="border-t border-panel-border-interior-light in-data-[theme*=dark]:border-panel-border-interior-dark">- <Form {...form}>- <FormItemLayout- layout="flex-row-reverse"- id="JWT_SECRET"- label="JWT secret"- description="Used to verify legacy user session JWTs issued by Supabase Auth."- >- <Input id="JWT_SECRET" copy reveal readOnly value={config?.jwt_secret || ''} />- </FormItemLayout>- </Form>+ <FormLayout+ layout="flex-row-reverse"+ id="JWT_SECRET"+ label="JWT secret"+ description="Used to verify legacy user session JWTs issued by Supabase Auth."+ >+ <Input id="JWT_SECRET" copy reveal readOnly value={config?.jwt_secret || ''} />+ </FormLayout></Panel.Content></Panel>)@@ -232,158 +162,89 @@ export const JWTSettings = () => {return (<>- <Panel- footer={- <div className="flex py-4 w-full">- <FormActions- form={formId}- isSubmitting={isUpdatingAuthConfig}- hasChanges={isDirty}- handleReset={reset}- disabled={!canUpdateConfig}- helper={- !canUpdateConfig- ? 'You need additional permissions to update JWT settings'- : undefined- }- />- </div>- }- >+ <Panel><Panel.Content className="border-t border-panel-border-interior-light in-data-[theme*=dark]:border-panel-border-interior-dark">- <Form {...form}>- <form- id={formId}- onSubmit={form.handleSubmit(onUpdateJwtExp)}- className="space-y-6"- noValidate- >- {isError ? (- <div className="flex items-center justify-center py-8 space-x-2">- <AlertCircle size={16} strokeWidth={1.5} />- <p className="text-sm text-foreground-light">Failed to retrieve JWT settings</p>- </div>- ) : (- <>- {legacyKey && legacyKey.status !== 'revoked' && (- <Admonition- type="warning"- title="Legacy JWT secret has been migrated to new JWT Signing Keys"- >+ <div className="space-y-6">+ {isError ? (+ <div className="flex items-center justify-center py-8 space-x-2">+ <AlertCircle size={16} strokeWidth={1.5} />+ <p className="text-sm text-foreground-light">Failed to retrieve JWT settings</p>+ </div>+ ) : (+ <>+ {legacyKey && legacyKey.status !== 'revoked' && (+ <Admonition+ type="warning"+ title="Legacy JWT secret has been migrated to new JWT Signing Keys"+ >+ <p className="leading-normal!">+ Legacy JWT secret can only be changed by rotating to a standby key and then+ revoking it. It is used to{' '}+ <em className="text-foreground not-italic">+ {legacyKey.status === 'in_use' ? 'sign and verify' : 'only verify'}+ </em>{' '}+ JSON Web Tokens by Supabase products.+ </p>++ {legacyAPIKeysStatus && legacyAPIKeysStatus.enabled && (<p className="leading-normal!">- Legacy JWT secret can only be changed by rotating to a standby key and then- revoking it. It is used to{' '}- <em className="text-foreground not-italic">- {legacyKey.status === 'in_use' ? 'sign and verify' : 'only verify'}+ <em className="text-warning not-italic">+ This includes the <code className="text-code-inline">anon</code> and{' '}+ <code className="text-code-inline">service_role</code> JWT based API keys.</em>{' '}- JSON Web Tokens by Supabase products.+ Consider switching to publishable and secret API keys to disable them.</p>+ )}- {legacyAPIKeysStatus && legacyAPIKeysStatus.enabled && (- <p className="leading-normal!">- <em className="text-warning not-italic">- This includes the <code className="text-code-inline">anon</code> and{' '}- <code className="text-code-inline">service_role</code> JWT based API- keys.- </em>{' '}- Consider switching to publishable and secret API keys to disable them.- </p>- )}-- <Button asChild variant="default" icon={<ExternalLink />} className="mt-2">- <Link href={`/project/${projectRef}/settings/api-keys`}>- Go to API keys- </Link>- </Button>- </Admonition>- )}- {legacyKey && legacyKey.status === 'revoked' && (- <Admonition- type="note"- title="Your project has revoked the legacy JWT secret"- description="No new JSON Web Tokens are issued nor verified with it by Supabase products."- />- )}- <FormItemLayout- layout="flex-row-reverse"+ <Button asChild variant="default" icon={<ExternalLink />} className="mt-2">+ <Link href={`/project/${projectRef}/settings/api-keys`}>Go to API keys</Link>+ </Button>+ </Admonition>+ )}+ {legacyKey && legacyKey.status === 'revoked' && (+ <Admonition+ type="note"+ title="Your project has revoked the legacy JWT secret"+ description="No new JSON Web Tokens are issued nor verified with it by Supabase products."+ />+ )}+ <FormLayout+ layout="flex-row-reverse"+ id="JWT_SECRET"+ label={+ legacyKey?.status === 'revoked'+ ? 'Revoked legacy JWT secret'+ : legacyKey+ ? 'Legacy JWT secret (still used)'+ : 'Legacy JWT secret'+ }+ description={+ legacyKey?.status === 'revoked'+ ? 'No longer used to sign JWTs by Supabase Auth.'+ : !legacyKey || legacyKey.status === 'in_use'+ ? 'Used to sign and verify JWTs issued by Supabase Auth.'+ : 'Used only to verify JWTs.'+ }+ >+ <Inputid="JWT_SECRET"- label={- legacyKey?.status === 'revoked'- ? 'Revoked legacy JWT secret'- : legacyKey- ? 'Legacy JWT secret (still used)'- : 'Legacy JWT secret'+ copy={canReadJWTSecret && isNotUpdatingJwtSecret}+ reveal={canReadJWTSecret && isNotUpdatingJwtSecret}+ readOnly+ value={+ !canReadJWTSecret+ ? 'You need additional permissions to view the JWT secret'+ : isJwtSecretUpdateFailed+ ? 'JWT secret update failed'+ : isUpdatingJwtSecret+ ? 'Updating JWT secret...'+ : config?.jwt_secret || ''}- description={- legacyKey?.status === 'revoked'- ? 'No longer used to sign JWTs by Supabase Auth.'- : !legacyKey || legacyKey.status === 'in_use'- ? 'Used to sign and verify JWTs issued by Supabase Auth.'- : 'Used only to verify JWTs.'- }- >- <Input- id="JWT_SECRET"- copy={canReadJWTSecret && isNotUpdatingJwtSecret}- reveal={canReadJWTSecret && isNotUpdatingJwtSecret}- readOnly- value={- !canReadJWTSecret- ? 'You need additional permissions to view the JWT secret'- : isJwtSecretUpdateFailed- ? 'JWT secret update failed'- : isUpdatingJwtSecret- ? 'Updating JWT secret...'- : config?.jwt_secret || ''- }- />- </FormItemLayout>-- <FormField- control={form.control}- name="JWT_EXP"- disabled={!canUpdateConfig || isLoadingAuthConfig}- render={({ field }) => (- <FormItemLayout- name="JWT_EXP"- layout="flex-row-reverse"- label="Access token expiry time"- description={- <>- <p>- How long access tokens are valid for before a refresh token has to be- used.- </p>- <p>Recommendation: 3600 (1 hour).</p>- </>- }- >- <FormControl>- <InputGroup>- <FormInputGroupInput- {...field}- id="JWT_EXP"- type="number"- min={0}- max={MAX_JWT_EXP}- onChange={(e) =>- field.onChange(- isNaN(e.target.valueAsNumber) ? '' : e.target.valueAsNumber- )- }- />- <InputGroupAddon align="inline-end">- <InputGroupText>seconds</InputGroupText>- </InputGroupAddon>- </InputGroup>- </FormControl>- </FormItemLayout>- )}/>- </>- )}- </form>- </Form>+ </FormLayout>+ </>+ )}+ </div>{!isPending && !legacyKey && (<>diff --git a/apps/studio/pages/project/[ref]/auth/sessions.tsx b/apps/studio/pages/project/[ref]/auth/sessions.tsxindex 1ef04b4557f..0fe62065225 100644--- a/apps/studio/pages/project/[ref]/auth/sessions.tsx+++ b/apps/studio/pages/project/[ref]/auth/sessions.tsx@@ -34,7 +34,7 @@ const SessionsPage: NextPageWithLayout = () => {<PageHeaderSummary><PageHeaderTitle>User Sessions</PageHeaderTitle><PageHeaderDescription>- Configure settings for user sessions and refresh tokens+ Configure settings for access tokens, refresh tokens, and user sessions</PageHeaderDescription></PageHeaderSummary></PageHeaderMeta>