Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: update legacy jwt settings form to use react-hook-form (#44179)

Gildas Garcia875216d4857b
diff --git a/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx b/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx
index d6b4d6d5b68..48d75ab8eec 100644
--- a/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx
+++ b/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx
@@ -1,3 +1,4 @@
+import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import {
JwtSecretUpdateError,
@@ -10,8 +11,6 @@ import {
ChevronDown,
CloudOff,
ExternalLink,
- Eye,
- EyeOff,
Hourglass,
Key,
Lightbulb,
@@ -22,22 +21,31 @@ import {
TriangleAlert,
} from 'lucide-react'
import Link from 'next/link'
-import { Dispatch, SetStateAction, useState } from 'react'
+import { useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react'
+import { useForm, type SubmitHandler } from 'react-hook-form'
import { toast } from 'sonner'
import {
Button,
+ CardContent,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
- Form,
- Input,
- InputNumber,
+ Form_Shadcn_,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ Input_Shadcn_,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ InputGroupText,
Modal,
} from 'ui'
import { Admonition } from 'ui-patterns/admonition'
-import { number, object } from 'yup'
+import { Input } from 'ui-patterns/DataInputs/Input'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import * as z from 'zod'
import {
JWT_SECRET_UPDATE_ERROR_MESSAGES,
@@ -57,17 +65,33 @@ import { useLegacyJWTSigningKeyQuery } from '@/data/jwt-signing-keys/legacy-jwt-
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { uuidv4 } from '@/lib/helpers'
-const schema = object({
- JWT_EXP: number()
- .max(604800, 'Must be less than 604800')
- .required('Must have a JWT expiry value'),
+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()
+ .min(32, 'Must be at least 32 characters')
+ .regex(/^(?!.*[@$]).*$/, '@ and $ are not allowed'),
+})
+const customJwtSecretFormId = 'custom-jwt-secret-form'
const JWTSettings = () => {
const { ref: projectRef } = useParams()
const [customToken, setCustomToken] = useState<string>('')
- const [showCustomTokenInput, setShowCustomTokenInput] = useState(false)
const [isCreatingKey, setIsCreatingKey] = useState<boolean>(false)
const [isRegeneratingKey, setIsGeneratingKey] = useState<boolean>(false)
@@ -116,11 +140,31 @@ const JWTSettings = () => {
const jwtSecretUpdateProgressMessage =
JWT_SECRET_UPDATE_PROGRESS_MESSAGES[data?.jwtSecretUpdateProgress as JwtSecretUpdateProgress]
- const INITIAL_VALUES = {
- JWT_EXP: authConfig?.JWT_EXP ?? 3600,
- }
+ 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 onUpdateJwtExp = async (values: any, { resetForm }: any) => {
+ 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(
@@ -129,9 +173,9 @@ const JWTSettings = () => {
onError: (error) => {
toast.error(`Failed to update JWT expiry: ${error?.message}`)
},
- onSuccess: () => {
+ onSuccess: (newValues) => {
toast.success('Successfully updated JWT expiry')
- resetForm({ values, initialValues: values })
+ reset({ JWT_EXP: newValues.JWT_EXP ?? values.JWT_EXP })
},
}
)
@@ -153,85 +197,83 @@ const JWTSettings = () => {
toast.error(`Failed to update JWT secret: ${error.message}`)
}
}
-
return (
<>
- <Form
- id="jwt-exp-form"
- initialValues={INITIAL_VALUES}
- onSubmit={onUpdateJwtExp}
- validationSchema={schema}
- key={authConfig?.JWT_EXP}
- >
- {({ handleReset, values, initialValues }: any) => {
- const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
-
- return (
- <Panel
- footer={
- <div className="flex py-4 w-full">
- <FormActions
- form="jwt-exp-form"
- isSubmitting={isUpdatingAuthConfig}
- hasChanges={hasChanges}
- handleReset={handleReset}
- disabled={!canUpdateConfig}
- helper={
- !canUpdateConfig
- ? 'You need additional permissions to update JWT settings'
- : undefined
- }
- />
- </div>
+ <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.Content className="border-t border-panel-border-interior-light [[data-theme*=dark]_&]:border-panel-border-interior-dark">
+ <Form_Shadcn_ {...form}>
+ <form
+ id={formId}
+ onSubmit={form.handleSubmit(onUpdateJwtExp)}
+ className="space-y-6"
+ noValidate
>
- <Panel.Content className="space-y-6 border-t border-panel-border-interior-light [[data-theme*=dark]_&]:border-panel-border-interior-dark">
- {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"
- >
+ {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">
+ Changing the legacy JWT secret can only be done 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">
- Changing the legacy JWT secret can only be done 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>anon</code> and <code>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>anon</code> and <code>service_role</code> JWT
- based API keys.
- </em>{' '}
- Consider switching to publishable and secret API keys to disable them.
- </p>
- )}
-
- <Button type="default" asChild icon={<ExternalLink className="size-4" />}>
- <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."
- />
- )}
- <Input
+ <Button type="default" asChild icon={<ExternalLink className="size-4" />}>
+ <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."
+ />
+ )}
+ <CardContent>
+ <FormItemLayout
+ layout="flex-row-reverse"
+ id="JWT_SECRET"
label={
legacyKey?.status === 'revoked'
? 'Revoked legacy JWT secret'
@@ -239,160 +281,182 @@ const JWTSettings = () => {
? 'Legacy JWT secret (still used)'
: 'Legacy JWT secret'
}
- readOnly
- copy={canReadJWTSecret && isNotUpdatingJwtSecret}
- reveal={canReadJWTSecret && isNotUpdatingJwtSecret}
- disabled
- value={
- !canReadJWTSecret
- ? 'You need additional permissions to view the JWT secret'
- : isJwtSecretUpdateFailed
- ? 'JWT secret update failed'
- : isUpdatingJwtSecret
- ? 'Updating JWT secret...'
- : config?.jwt_secret || ''
- }
- className="input-mono"
- descriptionText={
+ 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.'
}
- layout="horizontal"
- />
+ >
+ <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>
+ </CardContent>
- <InputNumber
- id="JWT_EXP"
+ <CardContent>
+ <FormField_Shadcn_
+ control={form.control}
name="JWT_EXP"
- size="small"
- label="Access token expiry time"
- descriptionText="How long access tokens are valid for before a refresh token has to be used. Recommendation: 3600 (1 hour)."
- layout="horizontal"
- actions={<span className="mr-3 text-foreground-lighter">seconds</span>}
disabled={!canUpdateConfig || isLoadingAuthConfig}
+ render={({ field }) => (
+ <FormItemLayout
+ name="JWT_EXP"
+ layout="flex-row-reverse"
+ label="Access token expiry time"
+ description={
+ <>
+ <div>
+ How long access tokens are valid for before a refresh token has to
+ be used.
+ </div>
+ <div>Recommendation: 3600 (1 hour).</div>
+ </>
+ }
+ >
+ <FormControl_Shadcn_>
+ <InputGroup>
+ <InputGroupAddon align="inline-end">
+ <InputGroupText>seconds</InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput
+ {...field}
+ id="JWT_EXP"
+ type="number"
+ min={0}
+ max={MAX_JWT_EXP}
+ onChange={(e) =>
+ field.onChange(
+ isNaN(e.target.valueAsNumber) ? '' : e.target.valueAsNumber
+ )
+ }
+ />
+ </InputGroup>
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
/>
+ </CardContent>
+ </>
+ )}
+ </form>
+ </Form_Shadcn_>
+ {!legacyKey && (
+ <>
+ {isUpdatingJwtSecret && (
+ <div className="flex items-center space-x-2">
+ <Loader2 className="animate-spin" size={14} />
+ <p className="text-sm">Updating JWT secret: {jwtSecretUpdateProgressMessage}</p>
+ </div>
+ )}
- {!legacyKey && (
- <>
- {isUpdatingJwtSecret && (
- <div className="flex items-center space-x-2">
- <Loader2 className="animate-spin" size={14} />
- <p className="text-sm">
- Updating JWT secret: {jwtSecretUpdateProgressMessage}
- </p>
- </div>
- )}
-
- {isJwtSecretUpdateFailed && (
- <Admonition type="warning" title="Failed to update JWT secret">
- Please try again. If the failures persist, please contact Supabase
- support with the following details: <br />
- Change tracking ID: {data?.changeTrackingId} <br />
- Error message: {jwtSecretUpdateErrorMessage}
- </Admonition>
- )}
-
- <div className="flex flex-col gap-6 border rounded-md bg p-6">
- <div className="flex flex-col gap-2">
- <h4 className="text-sm">How to change your JWT secret?</h4>
- <p className="text-sm text-foreground-light">
- Instead of changing the legacy JWT secret use a combination of the JWT
- Signing Keys and API keys features. Consider these advantages:
- </p>
- <ul className="text-sm text-foreground-light list-disc list-inside">
- <li>Zero-downtime, reversible change.</li>
- <li>Users remain signed in and bad actors out.</li>
- <li>
- Create multiple secret API keys that are immediately revocable and
- fully covered by audit logs.
- </li>
- <li>
- Private keys and shared secrets are no longer visible by
- organization members, so they can't leak.
- </li>
- <li>
- Maintain tighter alignment with SOC2 and other security compliance
- frameworks.
- </li>
- <li>
- Improve app's performance by using public keys to verify JWTs
- instead of calling <code>getUser()</code>.
- </li>
- </ul>
- </div>
-
- <div className="flex flex-row gap-4">
- <Button
- type="default"
- icon={<ExternalLink className="size-4" />}
- asChild
- >
- <Link href={`/project/${projectRef}/settings/api-keys/new`}>
- Go to API Keys
- </Link>
- </Button>
- <Button
- type="default"
- icon={<ExternalLink className="size-4" />}
- asChild
- >
- <Link href={`/project/${projectRef}/settings/jwt/signing-keys`}>
- Go to JWT Signing Keys
- </Link>
- </Button>
-
- <div className="grow" />
-
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <ButtonTooltip
- disabled={!canGenerateNewJWTSecret}
- type="default"
- iconRight={<ChevronDown size={14} />}
- loading={isUpdatingJwtSecret}
- tooltip={{
- content: {
- side: 'bottom',
- text: !canGenerateNewJWTSecret
- ? 'You need additional permissions to generate a new JWT secret'
- : undefined,
- },
- }}
- >
- Change legacy JWT secret
- </ButtonTooltip>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" side="bottom">
- <DropdownMenuItem
- className="space-x-2"
- onClick={() => setIsGeneratingKey(true)}
- >
- <RefreshCw size={16} />
- <p>Generate a random secret</p>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- className="space-x-2"
- onClick={() => setIsCreatingKey(true)}
- >
- <PenTool size={16} />
- <p>Create my own secret</p>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- </>
- )}
- </>
- )}
- </Panel.Content>
- </Panel>
- )
- }}
- </Form>
+ {isJwtSecretUpdateFailed && (
+ <Admonition type="warning" title="Failed to update JWT secret">
+ Please try again. If the failures persist, please contact Supabase support with
+ the following details: <br />
+ Change tracking ID: {data?.changeTrackingId} <br />
+ Error message: {jwtSecretUpdateErrorMessage}
+ </Admonition>
+ )}
+
+ <div className="flex flex-col gap-6 border rounded-md bg p-6">
+ <div className="flex flex-col gap-2">
+ <h4 className="text-sm">How to change your JWT secret?</h4>
+ <p className="text-sm text-foreground-light">
+ Instead of changing the legacy JWT secret use a combination of the JWT Signing
+ Keys and API keys features. Consider these advantages:
+ </p>
+ <ul className="text-sm text-foreground-light list-disc list-inside">
+ <li>Zero-downtime, reversible change.</li>
+ <li>Users remain signed in and bad actors out.</li>
+ <li>
+ Create multiple secret API keys that are immediately revocable and fully
+ covered by audit logs.
+ </li>
+ <li>
+ Private keys and shared secrets are no longer visible by organization members,
+ so they can't leak.
+ </li>
+ <li>
+ Maintain tighter alignment with SOC2 and other security compliance frameworks.
+ </li>
+ <li>
+ Improve app's performance by using public keys to verify JWTs instead of
+ calling <code>getUser()</code>.
+ </li>
+ </ul>
+ </div>
+
+ <div className="flex flex-row gap-4">
+ <Button type="default" icon={<ExternalLink className="size-4" />} asChild>
+ <Link href={`/project/${projectRef}/settings/api-keys/new`}>
+ Go to API Keys
+ </Link>
+ </Button>
+ <Button type="default" icon={<ExternalLink className="size-4" />} asChild>
+ <Link href={`/project/${projectRef}/settings/jwt/signing-keys`}>
+ Go to JWT Signing Keys
+ </Link>
+ </Button>
+
+ <div className="grow" />
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <ButtonTooltip
+ disabled={!canGenerateNewJWTSecret}
+ type="default"
+ iconRight={<ChevronDown size={14} />}
+ loading={isUpdatingJwtSecret}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: !canGenerateNewJWTSecret
+ ? 'You need additional permissions to generate a new JWT secret'
+ : undefined,
+ },
+ }}
+ >
+ Change legacy JWT secret
+ </ButtonTooltip>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" side="bottom">
+ <DropdownMenuItem
+ className="space-x-2"
+ onClick={() => setIsGeneratingKey(true)}
+ >
+ <RefreshCw size={16} />
+ <p>Generate a random secret</p>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className="space-x-2"
+ onClick={() => setIsCreatingKey(true)}
+ >
+ <PenTool size={16} />
+ <p>Create my own secret</p>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ </>
+ )}
+ </Panel.Content>
+ </Panel>
<TextConfirmModal
variant="destructive"
@@ -495,6 +559,7 @@ const JWTSettings = () => {
onCancel={() => {
setIsCreatingKey(false)
setCustomToken('')
+ customJwtSecretForm.reset({ customToken: '' })
}}
loading={isSubmittingJwtSecretUpdateRequest}
customFooter={
@@ -504,49 +569,55 @@ const JWTSettings = () => {
onClick={() => {
setIsCreatingKey(false)
setCustomToken('')
+ customJwtSecretForm.reset({ customToken: '' })
}}
>
Cancel
</Button>
<Button
type="primary"
- disabled={
- customToken.length < 32 || customToken.includes('@') || customToken.includes('$')
- }
+ htmlType="submit"
+ form={customJwtSecretFormId}
loading={isSubmittingJwtSecretUpdateRequest}
- onClick={() => {
- setIsGeneratingKey(true)
- setIsCreatingKey(false)
- }}
>
Proceed to final confirmation
</Button>
</div>
}
>
- <Modal.Content className="space-y-2">
- <p className="text-sm text-foreground-light">
- Pick a new custom JWT secret. Make sure it is a strong combination of characters that
- cannot be guessed easily.
- </p>
- <Input
- onChange={(e: any) => setCustomToken(e.target.value)}
- value={customToken}
- icon={<Key />}
- type={showCustomTokenInput ? 'text' : 'password'}
- className="w-full text-left"
- label="Custom JWT secret"
- descriptionText="Minimally 32 characters long, '@' and '$' are not allowed."
- actions={
- <div className="flex items-center justify-center mr-1">
- <Button
- type="default"
- icon={showCustomTokenInput ? <Eye /> : <EyeOff />}
- onClick={() => setShowCustomTokenInput(!showCustomTokenInput)}
- />
- </div>
- }
- />
+ <Modal.Content>
+ <Form_Shadcn_ {...customJwtSecretForm}>
+ <form
+ id={customJwtSecretFormId}
+ onSubmit={customJwtSecretForm.handleSubmit((values) => {
+ setIsGeneratingKey(true)
+ setIsCreatingKey(false)
+ setCustomToken(values.customToken)
+ })}
+ className="flex flex-col space-y-2"
+ noValidate
+ >
+ <p className="text-sm text-foreground-light">
+ Pick a new custom JWT secret. Make sure it is a strong combination of characters
+ that cannot be guessed easily.
+ </p>
+ <FormField_Shadcn_
+ control={customJwtSecretForm.control}
+ name="customToken"
+ render={({ field }) => (
+ <FormItemLayout
+ layout="vertical"
+ label="Custom JWT secret"
+ description="Minimally 32 characters long, '@' and '$' are not allowed."
+ >
+ <FormControl_Shadcn_>
+ <Input copy reveal icon={<Key />} className="w-full text-left" {...field} />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </form>
+ </Form_Shadcn_>
</Modal.Content>
</Modal>
</>