The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: use `react-hook-form` in network restrictions modal (#44238)
Gildas Garciafba5a8a001b0
diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsxindex a122e44d065..2ccdc816efd 100644--- a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx@@ -1,18 +1,28 @@+import { zodResolver } from '@hookform/resolvers/zod'import { useParams } from 'common'-import { toast } from 'sonner'-import { Button, Form, Input, Modal, Tooltip, TooltipContent, TooltipTrigger } from 'ui'-import InformationBox from 'components/ui/InformationBox'import { useNetworkRestrictionsQuery } from 'data/network-restrictions/network-restrictions-query'import { useNetworkRestrictionsApplyMutation } from 'data/network-restrictions/network-retrictions-apply-mutation'import { DOCS_URL } from 'lib/constants'import { HelpCircle } from 'lucide-react'+import { useEffect } from 'react'+import { useForm, useWatch } from 'react-hook-form'+import { toast } from 'sonner'import {- checkIfPrivate,- getAddressEndRange,- isValidAddress,- normalize,-} from './NetworkRestrictions.utils'+ Button,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Input_Shadcn_,+ Modal,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from 'ui'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import * as z from 'zod'++import { checkIfPrivate, getAddressEndRange, normalize } from './NetworkRestrictions.utils'const IPV4_MAX_CIDR_BLOCK_SIZE = 32const IPV6_MAX_CIDR_BLOCK_SIZE = 128@@ -45,40 +55,43 @@ const AddRestrictionModal = ({},})- const validate = (values: any) => {- const errors: any = {}-- if (type === undefined) return errors-- const { ipAddress, cidrBlockSize } = values-- // Validate CIDR block size- const isOutOfCidrSizeRange =- type === 'IPv4'- ? cidrBlockSize < 0 || cidrBlockSize > IPV4_MAX_CIDR_BLOCK_SIZE- : cidrBlockSize < 0 || cidrBlockSize > IPV6_MAX_CIDR_BLOCK_SIZE- if (cidrBlockSize.length === 0 || isOutOfCidrSizeRange) {- errors.cidrBlockSize = `Size has to be between 0 to ${- type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE- }`- }-- // Validate IP address- const isValid = isValidAddress(ipAddress)- if (!isValid) {- errors.ipAddress = 'Please enter a valid IP address'- return errors- }+ const cidrBlockSizeValidationMessage = `Size has to be between 0 to ${+ type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE+ }`+ const formSchema = z.object({+ cidrBlockSize: z.coerce+ .number()+ .min(0, cidrBlockSizeValidationMessage)+ .max(+ type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE,+ cidrBlockSizeValidationMessage+ ),+ ipAddress: z+ .string()+ .min(1, `Please enter a valid IP address`)+ .ip({+ version: type === 'IPv4' ? 'v4' : 'v6',+ message: `Please enter a valid ${type} address`,+ })+ .refine((val) => !checkIfPrivate(type, val), 'Private IP addresses are not supported'),+ })- try {- const isPrivate = checkIfPrivate(type, ipAddress)- if (isPrivate) errors.ipAddress = 'Private IP addresses are not supported'- } catch (error: any) {- errors.ipAddress = error.message- }+ const form = useForm<z.infer<typeof formSchema>>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ ipAddress: '',+ cidrBlockSize: type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE,+ },+ })+ const { reset, formState } = form+ const { errors } = formState- return errors- }+ useEffect(() => {+ reset({+ ipAddress: '',+ cidrBlockSize: type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE,+ })+ }, [type, reset])const onSubmit = async (values: any) => {if (!ref) return console.error('Project ref is required')@@ -106,6 +119,26 @@ const AddRestrictionModal = ({}}+ const [cidrBlockSize, ipAddress] = useWatch({+ name: ['cidrBlockSize', 'ipAddress'],+ control: form.control,+ })++ const availableAddresses =+ type === 'IPv4'+ ? Math.pow(2, IPV4_MAX_CIDR_BLOCK_SIZE - (cidrBlockSize ?? 0))+ : Math.pow(2, IPV6_MAX_CIDR_BLOCK_SIZE - (cidrBlockSize ?? 0))++ const addressRange =+ type !== undefined ? getAddressEndRange(type, `${ipAddress}/${cidrBlockSize}`) : undefined++ const isValidCIDR =+ errors.cidrBlockSize == null && errors.ipAddress == null && addressRange != null++ const normalizedAddress = isValidCIDR+ ? normalize(`${ipAddress}/${cidrBlockSize}`)+ : `${ipAddress}/${cidrBlockSize}`+return (<ModalhideFooter@@ -114,144 +147,117 @@ const AddRestrictionModal = ({onCancel={onClose}header={`Add a new ${type} restriction`}>- <Form- validateOnBlur- id={formId}- className="!border-t-0"- initialValues={{- ipAddress: '',- cidrBlockSize:- type === 'IPv4'- ? IPV4_MAX_CIDR_BLOCK_SIZE.toString()- : IPV6_MAX_CIDR_BLOCK_SIZE.toString(),- }}- validate={validate}- onSubmit={onSubmit}- >- {({ values }: any) => {- const isPrivate =- type !== undefined && isValidAddress(values.ipAddress)- ? checkIfPrivate(type, values.ipAddress)- : false- const isValidBlockSize =- values.cidrBlockSize !== '' &&- ((type === 'IPv4' &&- values.cidrBlockSize >= 0 &&- values.cidrBlockSize <= IPV4_MAX_CIDR_BLOCK_SIZE) ||- (type === 'IPv6' &&- values.cidrBlockSize >= 0 &&- values.cidrBlockSize <= IPV6_MAX_CIDR_BLOCK_SIZE))- const availableAddresses =- type === 'IPv4'- ? Math.pow(2, IPV4_MAX_CIDR_BLOCK_SIZE - (values?.cidrBlockSize ?? 0))- : Math.pow(2, IPV6_MAX_CIDR_BLOCK_SIZE - (values?.cidrBlockSize ?? 0))- const addressRange =- type !== undefined- ? getAddressEndRange(type, `${values.ipAddress}/${values.cidrBlockSize}`)- : undefined-- const isValidCIDR = isValidBlockSize && !isPrivate && addressRange !== undefined- const normalizedAddress = isValidCIDR- ? normalize(`${values.ipAddress}/${values.cidrBlockSize}`)- : `${values.ipAddress}/${values.cidrBlockSize}`-- return (- <>- <Modal.Content className="space-y-4">- <p className="text-sm text-foreground-light">- This will add an IP address range to a list of allowed ranges that can access your- database.- </p>- <InformationBox- title="Note: Restrictions only apply to direct connections to your database and connection pooler"- description="They do not currently apply to APIs offered over HTTPS, such as PostgREST, Storage, or Authentication."- urlLabel="Learn more"- url={`${DOCS_URL}/guides/platform/network-restrictions#limitations`}- />- <div className="flex space-x-4">- <div className="w-[55%]">- <Input- label={`${type} address`}- id="ipAddress"- name="ipAddress"- placeholder={type === 'IPv4' ? '0.0.0.0' : '::0'}- />- </div>- <div className="flex-grow">- <Input- label={- <div className="flex items-center space-x-2">- <p>CIDR Block Size</p>- <Tooltip>- <TooltipTrigger>- <HelpCircle size="14" strokeWidth={2} />- </TooltipTrigger>- <TooltipContent side="bottom" className="w-80">- Classless inter-domain routing (CIDR) notation is the notation used to- identify networks and hosts in the networks. The block size tells us- how many bits we need to take for the network prefix, and is a value- between 0 to{' '}- {type === 'IPv4'- ? IPV4_MAX_CIDR_BLOCK_SIZE- : IPV6_MAX_CIDR_BLOCK_SIZE}- .- </TooltipContent>- </Tooltip>- </div>- }- id="cidrBlockSize"- name="cidrBlockSize"- type="number"- placeholder={- type === 'IPv4'- ? IPV4_MAX_CIDR_BLOCK_SIZE.toString()- : IPV6_MAX_CIDR_BLOCK_SIZE.toString()- }- min={0}- max={type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE}- />- </div>- </div>- </Modal.Content>- <Modal.Separator />- {isValidCIDR ? (- <Modal.Content className="space-y-1">- <p className="text-sm">- The address range <code className="text-code-inline">{normalizedAddress}</code>{' '}- will be restricted- </p>- <p className="text-sm text-foreground-light">- Selected address space:{' '}- <code className="text-code-inline">{addressRange.start}</code> to{' '}- <code className="text-code-inline">{addressRange.end}</code>{' '}- </p>- <p className="text-sm text-foreground-light">- Number of addresses: {availableAddresses}- </p>- </Modal.Content>- ) : (- <Modal.Content>- <div className="h-[68px] flex items-center">- <p className="text-sm text-foreground-light">- A summary of your restriction will be shown here after entering a valid IP- address and CIDR block size. IP addresses will also be normalized.- </p>- </div>- </Modal.Content>- )}- <Modal.Separator />- <Modal.Content className="flex items-center justify-end space-x-2">- <Button type="default" disabled={isApplying} onClick={() => onClose()}>- Cancel- </Button>- <Button htmlType="submit" loading={isApplying} disabled={isApplying}>- Save restriction- </Button>- </Modal.Content>- </>- )- }}- </Form>+ <Form_Shadcn_ {...form}>+ <Modal.Content className="space-y-4">+ <p className="text-sm text-foreground-light">+ This will add an IP address range to a list of allowed ranges that can access your+ database.+ </p>+ <InformationBox+ title="Note: Restrictions only apply to direct connections to your database and connection pooler"+ description="They do not currently apply to APIs offered over HTTPS, such as PostgREST, Storage, or Authentication."+ urlLabel="Learn more"+ url={`${DOCS_URL}/guides/platform/network-restrictions#limitations`}+ />+ <form+ id={formId}+ onSubmit={form.handleSubmit(onSubmit)}+ noValidate+ className="flex space-x-4"+ >+ <div className="w-[55%]">+ <FormField_Shadcn_+ control={form.control}+ name="ipAddress"+ render={({ field }) => (+ <FormItemLayout layout="vertical" label={`${type} address`}>+ <FormControl_Shadcn_>+ <Input_Shadcn_ {...field} placeholder={type === 'IPv4' ? '0.0.0.0' : '::0'} />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </div>+ <div className="flex-grow">+ <FormField_Shadcn_+ control={form.control}+ name="cidrBlockSize"+ render={({ field }) => (+ <FormItemLayout+ layout="vertical"+ label={+ <div className="flex items-center space-x-2">+ <p>CIDR Block Size</p>+ <Tooltip>+ <TooltipTrigger>+ <HelpCircle size="14" strokeWidth={2} />+ </TooltipTrigger>+ <TooltipContent side="bottom" className="w-80">+ Classless inter-domain routing (CIDR) notation is the notation used to+ identify networks and hosts in the networks. The block size tells us how+ many bits we need to take for the network prefix, and is a value between+ 0 to{' '}+ {type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE}.+ </TooltipContent>+ </Tooltip>+ </div>+ }+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_+ {...field}+ type="number"+ min={0}+ max={type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE}+ onChange={(e) => field.onChange(Number(e.target.value))}+ placeholder={+ type === 'IPv4'+ ? IPV4_MAX_CIDR_BLOCK_SIZE.toString()+ : IPV6_MAX_CIDR_BLOCK_SIZE.toString()+ }+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </div>+ </form>+ </Modal.Content>+ <Modal.Separator />+ {isValidCIDR ? (+ <Modal.Content className="space-y-1">+ <p className="text-sm">+ The address range <code className="text-code-inline">{normalizedAddress}</code> will+ be restricted+ </p>+ <p className="text-sm text-foreground-light">+ Selected address space: <code className="text-code-inline">{addressRange.start}</code>{' '}+ to <code className="text-code-inline">{addressRange.end}</code>{' '}+ </p>+ <p className="text-sm text-foreground-light">+ Number of addresses: {availableAddresses}+ </p>+ </Modal.Content>+ ) : (+ <Modal.Content>+ <div className="h-[68px] flex items-center">+ <p className="text-sm text-foreground-light">+ A summary of your restriction will be shown here after entering a valid IP address+ and CIDR block size. IP addresses will also be normalized.+ </p>+ </div>+ </Modal.Content>+ )}+ <Modal.Separator />+ <Modal.Content className="flex items-center justify-end space-x-2">+ <Button type="default" disabled={isApplying} onClick={() => onClose()}>+ Cancel+ </Button>+ <Button form={formId} htmlType="submit" loading={isApplying} disabled={isApplying}>+ Save restriction+ </Button>+ </Modal.Content>+ </Form_Shadcn_></Modal>)}diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.ts b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.tsindex 6a46647ac4a..9d04ecb9381 100644--- a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.ts+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.ts@@ -1,4 +1,4 @@-import { IPv4CidrRange, IPv6CidrRange, Validator, collapseIPv6Number } from 'ip-num'+import { collapseIPv6Number, IPv4CidrRange, IPv6CidrRange, Validator } from 'ip-num'const privateIPv4Ranges = [IPv4CidrRange.fromCidr('10.0.0.0/8'),@@ -16,8 +16,9 @@ export const isValidAddress = (address: string) => {return isIpv4 || isIpv6}-export const checkIfPrivate = (type: 'IPv4' | 'IPv6', cidr: string) => {+export const checkIfPrivate = (type: 'IPv4' | 'IPv6' | undefined, cidr: string) => {try {+ if (type === undefined) return falseif (type === 'IPv4') {const address = IPv4CidrRange.fromCidr(`${cidr}/32`)const res = privateIPv4Ranges.map((range) => address.inside(range))