The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix: Check the password strength before creating a project (#41586)
Ivan Vasilovdb4b10f32833
diff --git a/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/CreateNewProjectDialog.tsx b/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/CreateNewProjectDialog.tsxindex e62e335673a..a57a29ef738 100644--- a/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/CreateNewProjectDialog.tsx+++ b/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/CreateNewProjectDialog.tsx@@ -4,12 +4,12 @@ import { useForm } from 'react-hook-form'import { toast } from 'sonner'import { z } from 'zod'-import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'+import { PasswordStrengthBar } from 'components/ui/PasswordStrengthBar'import { useProjectCloneMutation } from 'data/projects/clone-mutation'import { useCloneBackupsQuery } from 'data/projects/clone-query'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'-import { passwordStrength } from 'lib/password-strength'+import { passwordStrength, PasswordStrengthScore } from 'lib/password-strength'import { generateStrongPassword } from 'lib/project'import {Button,@@ -171,7 +171,7 @@ export const CreateNewProjectDialog = ({}}descriptionText={<PasswordStrengthBar- passwordStrengthScore={passwordStrengthScore}+ passwordStrengthScore={passwordStrengthScore as PasswordStrengthScore}password={field.value}passwordStrengthMessage={passwordStrengthMessage}generateStrongPassword={generatePassword}diff --git a/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsx b/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsxindex bb26e0e4496..450a2906fe2 100644--- a/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsx+++ b/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsx@@ -1,7 +1,7 @@import { UseFormReturn } from 'react-hook-form'import Panel from 'components/ui/Panel'-import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'+import { PasswordStrengthBar } from 'components/ui/PasswordStrengthBar'import { passwordStrength } from 'lib/password-strength'import { generateStrongPassword } from 'lib/project'import { FormControl_Shadcn_, FormField_Shadcn_ } from 'ui'@@ -13,33 +13,34 @@ import { SpecialSymbolsCallout } from './SpecialSymbolsCallout'interface DatabasePasswordInputProps {form: UseFormReturn<CreateProjectForm>- passwordStrengthMessage: string- setPasswordStrengthMessage: (value: string) => void- setPasswordStrengthWarning: (value: string) => void}-export const DatabasePasswordInput = ({- form,- passwordStrengthMessage,- setPasswordStrengthMessage,- setPasswordStrengthWarning,-}: DatabasePasswordInputProps) => {- async function checkPasswordStrength(value: any) {- const { message, warning, strength } = await passwordStrength(value)+const updatePasswordStrength = async (form: UseFormReturn<CreateProjectForm>, value: string) => {+ try {+ const { warning, message, strength } = await passwordStrength(value)+ form.setValue('dbPassStrength', strength, { shouldValidate: false, shouldDirty: false })+ form.setValue('dbPassStrengthMessage', message ?? '', {+ shouldValidate: false,+ shouldDirty: false,+ })+ form.setValue('dbPassStrengthWarning', warning ?? '', {+ shouldValidate: false,+ shouldDirty: false,+ })- form.setValue('dbPassStrength', strength)- form.trigger('dbPassStrength')form.trigger('dbPass')-- setPasswordStrengthWarning(warning)- setPasswordStrengthMessage(message)+ } catch (error) {+ console.error(error)}+}+export const DatabasePasswordInput = ({ form }: DatabasePasswordInputProps) => {// [Refactor] DB Password could be a common component used in multiple pages with repeated logic- function generatePassword() {+ async function generatePassword() {const password = generateStrongPassword()form.setValue('dbPass', password)- checkPasswordStrength(password)++ updatePasswordStrength(form, password)}return (@@ -61,7 +62,7 @@ export const DatabasePasswordInput = ({<PasswordStrengthBarpasswordStrengthScore={form.getValues('dbPassStrength')}password={field.value}- passwordStrengthMessage={passwordStrengthMessage}+ passwordStrengthMessage={form.getValues('dbPassStrengthMessage')}generateStrongPassword={generatePassword}/></>@@ -75,15 +76,10 @@ export const DatabasePasswordInput = ({{...field}autoComplete="off"onChange={async (event) => {+ const newValue = event.target.valuefield.onChange(event)- form.trigger('dbPassStrength')- const value = event.target.value- if (event.target.value === '') {- await form.setValue('dbPassStrength', 0)- await form.trigger('dbPass')- } else {- await checkPasswordStrength(value)- }++ updatePasswordStrength(form, newValue)}}/></FormControl_Shadcn_>diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.tsindex 334050a6928..d2e25ceb266 100644--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.ts+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.schema.ts@@ -1,33 +1,49 @@+import { DEFAULT_MINIMUM_PASSWORD_STRENGTH } from 'lib/constants'import { z } from 'zod'-export const FormSchema = z.object({- organization: z.string({- required_error: 'Please select an organization',- }),- projectName: z- .string()- .trim()- .min(1, 'Please enter a project name.') // Required field check- .min(3, 'Project name must be at least 3 characters long.') // Minimum length check- .max(64, 'Project name must be no longer than 64 characters.'), // Maximum length check- postgresVersion: z.string({- required_error: 'Please enter a Postgres version.',- }),- dbRegion: z.string({- required_error: 'Please select a region.',- }),- cloudProvider: z.string({- required_error: 'Please select a cloud provider.',- }),- dbPassStrength: z.number(),- dbPass: z- .string({ required_error: 'Please enter a database password.' })- .min(1, 'Password is required.'),- instanceSize: z.string().optional(),- dataApi: z.boolean(),- useApiSchema: z.boolean(),- postgresVersionSelection: z.string(),- useOrioleDb: z.boolean(),-})+export const FormSchema = z+ .object({+ organization: z.string({+ required_error: 'Please select an organization',+ }),+ projectName: z+ .string()+ .trim()+ .min(1, 'Please enter a project name.') // Required field check+ .min(3, 'Project name must be at least 3 characters long.') // Minimum length check+ .max(64, 'Project name must be no longer than 64 characters.'), // Maximum length check+ postgresVersion: z.string({+ required_error: 'Please enter a Postgres version.',+ }),+ dbRegion: z.string({+ required_error: 'Please select a region.',+ }),+ cloudProvider: z.string({+ required_error: 'Please select a cloud provider.',+ }),++ dbPass: z+ .string({ required_error: 'Please enter a database password.' })+ .min(1, 'Password is required.'),+ dbPassStrength: z+ .union([z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(4)])+ .default(0),+ dbPassStrengthMessage: z.string().default(''),+ dbPassStrengthWarning: z.string().default(''),+ instanceSize: z.string().optional(),+ dataApi: z.boolean(),+ useApiSchema: z.boolean(),+ postgresVersionSelection: z.string(),+ useOrioleDb: z.boolean(),+ })+ .superRefine(({ dbPassStrength, dbPassStrengthWarning }, ctx) => {+ if (dbPassStrength < DEFAULT_MINIMUM_PASSWORD_STRENGTH) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['dbPass'],+ message: dbPassStrengthWarning || 'Password not secure enough',+ })+ }+ })export type CreateProjectForm = z.infer<typeof FormSchema>diff --git a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsxindex 9be22d528c1..47cd9883c2b 100644--- a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx+++ b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx@@ -5,12 +5,12 @@ import { toast } from 'sonner'import { useParams } from 'common'import { useIsProjectActive } from 'components/layouts/ProjectLayout/ProjectContext'import { ButtonTooltip } from 'components/ui/ButtonTooltip'-import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'+import { PasswordStrengthBar } from 'components/ui/PasswordStrengthBar'import { useDatabasePasswordResetMutation } from 'data/database/database-password-reset-mutation'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { DEFAULT_MINIMUM_PASSWORD_STRENGTH } from 'lib/constants'-import { passwordStrength } from 'lib/password-strength'+import { passwordStrength, PasswordStrengthScore } from 'lib/password-strength'import { generateStrongPassword } from 'lib/project'import { Button, Card, CardContent, Input, Modal } from 'ui'import { FormLayout } from 'ui-patterns/form/Layout/FormLayout'@@ -35,7 +35,7 @@ const ResetDbPassword = ({ disabled = false }) => {const [password, setPassword] = useState<string>('')const [passwordStrengthMessage, setPasswordStrengthMessage] = useState<string>('')const [passwordStrengthWarning, setPasswordStrengthWarning] = useState<string>('')- const [passwordStrengthScore, setPasswordStrengthScore] = useState<number>(0)+ const [passwordStrengthScore, setPasswordStrengthScore] = useState(0)const { mutate: resetDatabasePassword, isPending: isUpdatingPassword } =useDatabasePasswordResetMutation({@@ -134,7 +134,7 @@ const ResetDbPassword = ({ disabled = false }) => {// @ts-ignoredescriptionText={<PasswordStrengthBar- passwordStrengthScore={passwordStrengthScore}+ passwordStrengthScore={passwordStrengthScore as PasswordStrengthScore}passwordStrengthMessage={passwordStrengthMessage}password={password}generateStrongPassword={generatePassword}diff --git a/apps/studio/components/ui/PasswordStrengthBar.tsx b/apps/studio/components/ui/PasswordStrengthBar.tsxindex 22c1a1c41c9..f77c23d00cc 100644--- a/apps/studio/components/ui/PasswordStrengthBar.tsx+++ b/apps/studio/components/ui/PasswordStrengthBar.tsx@@ -1,14 +1,15 @@import { PASSWORD_STRENGTH_COLOR, PASSWORD_STRENGTH_PERCENTAGE } from 'lib/constants'+import { PasswordStrengthScore } from 'lib/password-strength'import { InlineLinkClassName } from './InlineLink'interface Props {- passwordStrengthScore: number+ passwordStrengthScore: PasswordStrengthScorepasswordStrengthMessage: stringpassword: stringgenerateStrongPassword: () => void}-const PasswordStrengthBar = ({+export const PasswordStrengthBar = ({passwordStrengthScore = 0,passwordStrengthMessage = '',password = '',@@ -20,18 +21,16 @@ const PasswordStrengthBar = ({<divaria-valuemax={100}aria-valuemin={0}- aria-valuenow={(PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore]}- aria-valuetext={(PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore]}+ aria-valuenow={PASSWORD_STRENGTH_PERCENTAGE[passwordStrengthScore]}+ aria-valuetext={`${PASSWORD_STRENGTH_PERCENTAGE[passwordStrengthScore]}%`}role="progressbar"className="mb-2 overflow-hidden transition-all border rounded bg-200 w-full"><divstyle={{- width: (PASSWORD_STRENGTH_PERCENTAGE as any)[passwordStrengthScore],+ width: `${PASSWORD_STRENGTH_PERCENTAGE[passwordStrengthScore]}%`,}}- className={`relative h-1 w-full ${- (PASSWORD_STRENGTH_COLOR as any)[passwordStrengthScore]- } transition-all duration-500 ease-out shadow-inner`}+ className={`relative h-1 w-full ${PASSWORD_STRENGTH_COLOR[passwordStrengthScore]} transition-all duration-500 ease-out shadow-inner`}/></div>)}@@ -48,5 +47,3 @@ const PasswordStrengthBar = ({</>)}--export default PasswordStrengthBardiff --git a/apps/studio/lib/constants/infrastructure.ts b/apps/studio/lib/constants/infrastructure.tsindex d9343193b46..8c939c3ff66 100644--- a/apps/studio/lib/constants/infrastructure.ts+++ b/apps/studio/lib/constants/infrastructure.ts@@ -118,11 +118,11 @@ export const PASSWORD_STRENGTH_COLOR = {}export const PASSWORD_STRENGTH_PERCENTAGE = {- 0: '10%',- 1: '30%',- 2: '50%',- 3: '80%',- 4: '100%',+ 0: 10,+ 1: 30,+ 2: 50,+ 3: 80,+ 4: 100,}export const DEFAULT_PROJECT_API_SERVICE_ID = 1diff --git a/apps/studio/lib/password-strength.ts b/apps/studio/lib/password-strength.tsindex 5dd1502e5ce..39a34cc44ae 100644--- a/apps/studio/lib/password-strength.ts+++ b/apps/studio/lib/password-strength.ts@@ -1,12 +1,16 @@import { DEFAULT_MINIMUM_PASSWORD_STRENGTH, PASSWORD_STRENGTH } from 'lib/constants'+// This is the same as the ZXCVBNScore type from zxcvbn+// but we need to define it here because we don't to import zxcvbn everywhere+export type PasswordStrengthScore = 0 | 1 | 2 | 3 | 4+export async function passwordStrength(value: string) {// [Alaister]: Lazy load zxcvbn to avoid bundling it with the main app (it's pretty chunky)const zxcvbn = await import('zxcvbn').then((module) => module.default)let message: string = ''let warning: string = ''- let strength: number = 0+ let strength: PasswordStrengthScore = 0if (value && value !== '') {if (value.length > 99) {diff --git a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsxindex 44aa1cef64b..6bebe8d9309 100644--- a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx+++ b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx@@ -7,7 +7,7 @@ import { isVercelUrl } from 'components/interfaces/Integrations/Vercel/VercelIntimport { Markdown } from 'components/interfaces/Markdown'import VercelIntegrationWindowLayout from 'components/layouts/IntegrationsLayout/VercelIntegrationWindowLayout'import { ScaffoldColumn, ScaffoldContainer } from 'components/layouts/Scaffold'-import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'+import { PasswordStrengthBar } from 'components/ui/PasswordStrengthBar'import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'import { useIntegrationsQuery } from 'data/integrations/integrations-query'import { useIntegrationVercelConnectionsCreateMutation } from 'data/integrations/integrations-vercel-connections-create-mutation'@@ -17,7 +17,7 @@ import { useProjectCreateMutation } from 'data/projects/project-create-mutation'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { BASE_PATH, PROVIDERS } from 'lib/constants'import { getInitialMigrationSQLFromGitHubRepo } from 'lib/integration-utils'-import { passwordStrength } from 'lib/password-strength'+import { passwordStrength, PasswordStrengthScore } from 'lib/password-strength'import { generateStrongPassword } from 'lib/project'import { AWS_REGIONS } from 'shared-data'import { useIntegrationInstallationSnapshot } from 'state/integration-installation'@@ -232,7 +232,7 @@ const CreateProject = () => {onChange={onDbPassChange}descriptionText={<PasswordStrengthBar- passwordStrengthScore={passwordStrengthScore}+ passwordStrengthScore={passwordStrengthScore as PasswordStrengthScore}password={dbPass}passwordStrengthMessage={passwordStrengthMessage}generateStrongPassword={generatePassword}diff --git a/apps/studio/pages/new/[slug].tsx b/apps/studio/pages/new/[slug].tsxindex 899461efa3e..29494cd39f1 100644--- a/apps/studio/pages/new/[slug].tsx+++ b/apps/studio/pages/new/[slug].tsx@@ -51,17 +51,11 @@ import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { withAuth } from 'hooks/misc/withAuth'-import {- DEFAULT_MINIMUM_PASSWORD_STRENGTH,- DOCS_URL,- PROJECT_STATUS,- PROVIDERS,- useDefaultProvider,-} from 'lib/constants'+import { DOCS_URL, PROJECT_STATUS, PROVIDERS, useDefaultProvider } from 'lib/constants'import { useTrack } from 'lib/telemetry/track'import { AWS_REGIONS, type CloudProvider } from 'shared-data'import type { NextPageWithLayout } from 'types'-import { Button, Form_Shadcn_, FormField_Shadcn_ } from 'ui'+import { Button, Form_Shadcn_, FormField_Shadcn_, useWatch_Shadcn_ } from 'ui'import { Admonition } from 'ui-patterns/admonition'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'@@ -103,21 +97,9 @@ const Wizard: NextPageWithLayout = () => {}const [allProjects, setAllProjects] = useState<OrgProject[] | undefined>(undefined)- const [passwordStrengthMessage, setPasswordStrengthMessage] = useState('')- const [passwordStrengthWarning, setPasswordStrengthWarning] = useState('')const [isComputeCostsConfirmationModalVisible, setIsComputeCostsConfirmationModalVisible] =useState(false)- FormSchema.superRefine(({ dbPassStrength }, refinementContext) => {- if (dbPassStrength < DEFAULT_MINIMUM_PASSWORD_STRENGTH) {- refinementContext.addIssue({- code: z.ZodIssueCode.custom,- path: ['dbPass'],- message: passwordStrengthWarning || 'Password not secure enough',- })- }- })-const form = useForm<z.infer<typeof FormSchema>>({resolver: zodResolver(FormSchema),mode: 'onChange',@@ -128,6 +110,7 @@ const Wizard: NextPageWithLayout = () => {cloudProvider: PROVIDERS[defaultProvider].id,dbPass: '',dbPassStrength: 0,+ dbPassStrengthMessage: '',dbRegion: undefined,instanceSize: canChooseInstanceSize ? sizes[0] : undefined,dataApi: true,@@ -136,7 +119,12 @@ const Wizard: NextPageWithLayout = () => {useOrioleDb: false,},})- const { instanceSize: watchedInstanceSize, cloudProvider, dbRegion, organization } = form.watch()+ const {+ instanceSize: watchedInstanceSize,+ cloudProvider,+ dbRegion,+ organization,+ } = useWatch_Shadcn_({ control: form.control })// [Charis] Since the form is updated in a useEffect, there is an edge case// when switching from free to paid, where canChooseInstanceSize is true for@@ -224,12 +212,12 @@ const Wizard: NextPageWithLayout = () => {const canCreateProject = isAdmin && !freePlanWithExceedingLimits && !hasOutstandingInvoices- const dbRegionExact = smartRegionToExactRegion(dbRegion)+ const dbRegionExact = smartRegionToExactRegion(dbRegion ?? '')const availableOrioleVersion = useAvailableOrioleImageVersion({cloudProvider: cloudProvider as CloudProvider,- dbRegion: smartRegionEnabled ? dbRegionExact : dbRegion,+ dbRegion: smartRegionEnabled ? dbRegionExact : dbRegion ?? '',organizationSlug: organization,},{ enabled: currentOrg !== null }@@ -420,12 +408,7 @@ const Wizard: NextPageWithLayout = () => {{canChooseInstanceSize && <ComputeSizeSelector form={form} />}- <DatabasePasswordInput- form={form}- passwordStrengthMessage={passwordStrengthMessage}- setPasswordStrengthMessage={setPasswordStrengthMessage}- setPasswordStrengthWarning={setPasswordStrengthWarning}- />+ <DatabasePasswordInput form={form} /><RegionSelectorform={form}