The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: move password check to frontend (#39927)
Alaister Younga3e7cb7285c2
diff --git a/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/CreateNewProjectDialog.tsx b/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/CreateNewProjectDialog.tsxindex 22f464b6bfe..ae019d3d254 100644--- a/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/CreateNewProjectDialog.tsx+++ b/apps/studio/components/interfaces/Database/Backups/RestoreToNewProject/CreateNewProjectDialog.tsx@@ -1,6 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'-import { debounce } from 'lodash'-import { useRef, useState } from 'react'+import { useState } from 'react'import { useForm } from 'react-hook-form'import { toast } from 'sonner'import { z } from 'zod'@@ -10,7 +9,7 @@ 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/helpers'+import { passwordStrength } from 'lib/password-strength'import { generateStrongPassword } from 'lib/project'import {Button,@@ -86,10 +85,6 @@ export const CreateNewProjectDialog = ({},})- const delayedCheckPasswordStrength = useRef(- debounce((value: string) => checkPasswordStrength(value), 300)- ).current-async function checkPasswordStrength(value: string) {const { message, strength } = await passwordStrength(value)setPasswordStrengthScore(strength)@@ -99,7 +94,7 @@ export const CreateNewProjectDialog = ({const generatePassword = () => {const password = generateStrongPassword()form.setValue('password', password)- delayedCheckPasswordStrength(password)+ checkPasswordStrength(password)}return (@@ -173,7 +168,7 @@ export const CreateNewProjectDialog = ({if (value == '') {setPasswordStrengthScore(-1)setPasswordStrengthMessage('')- } else delayedCheckPasswordStrength(value)+ } else checkPasswordStrength(value)}}descriptionText={<PasswordStrengthBardiff --git a/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsx b/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsxindex 27779203902..bb26e0e4496 100644--- a/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsx+++ b/apps/studio/components/interfaces/ProjectCreation/DatabasePasswordInput.tsx@@ -1,10 +1,8 @@-import { debounce } from 'lodash'-import { useRef } from 'react'import { UseFormReturn } from 'react-hook-form'import Panel from 'components/ui/Panel'import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'-import passwordStrength from 'lib/password-strength'+import { passwordStrength } from 'lib/password-strength'import { generateStrongPassword } from 'lib/project'import { FormControl_Shadcn_, FormField_Shadcn_ } from 'ui'import { Input } from 'ui-patterns/DataInputs/Input'@@ -37,15 +35,11 @@ export const DatabasePasswordInput = ({setPasswordStrengthMessage(message)}- const delayedCheckPasswordStrength = useRef(- debounce((value) => checkPasswordStrength(value), 300)- ).current-// [Refactor] DB Password could be a common component used in multiple pages with repeated logicfunction generatePassword() {const password = generateStrongPassword()form.setValue('dbPass', password)- delayedCheckPasswordStrength(password)+ checkPasswordStrength(password)}return (@@ -88,7 +82,7 @@ export const DatabasePasswordInput = ({await form.setValue('dbPassStrength', 0)await form.trigger('dbPass')} else {- await delayedCheckPasswordStrength(value)+ await checkPasswordStrength(value)}}}/>diff --git a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsxindex 17e30ace690..0642690718d 100644--- a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx+++ b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx@@ -1,6 +1,5 @@import { PermissionAction } from '@supabase/shared-types/out/constants'-import { debounce } from 'lodash'-import { useEffect, useRef, useState } from 'react'+import { useEffect, useState } from 'react'import { toast } from 'sonner'import { useParams } from 'common'@@ -12,7 +11,7 @@ import { useDatabasePasswordResetMutation } from 'data/database/database-passworimport { 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 } from 'lib/password-strength'import { generateStrongPassword } from 'lib/project'import { Button, Input, Modal } from 'ui'@@ -62,17 +61,13 @@ const ResetDbPassword = ({ disabled = false }) => {setPasswordStrengthMessage(message)}- const delayedCheckPasswordStrength = useRef(- debounce((value) => checkPasswordStrength(value), 300)- ).current-const onDbPassChange = (e: any) => {const value = e.target.valuesetPassword(value)if (value == '') {setPasswordStrengthScore(-1)setPasswordStrengthMessage('')- } else delayedCheckPasswordStrength(value)+ } else checkPasswordStrength(value)}const confirmResetDbPass = async () => {@@ -86,7 +81,7 @@ const ResetDbPassword = ({ disabled = false }) => {function generatePassword() {const password = generateStrongPassword()setPassword(password)- delayedCheckPasswordStrength(password)+ checkPasswordStrength(password)}return (diff --git a/apps/studio/components/ui/PasswordStrengthBar.tsx b/apps/studio/components/ui/PasswordStrengthBar.tsxindex 90a5ae9c937..15e14073560 100644--- a/apps/studio/components/ui/PasswordStrengthBar.tsx+++ b/apps/studio/components/ui/PasswordStrengthBar.tsx@@ -35,9 +35,10 @@ const PasswordStrengthBar = ({</div>)}<p>- {passwordStrengthMessage+ {(passwordStrengthMessage? passwordStrengthMessage- : 'This is the password to your Postgres database, so it must be strong and hard to guess.'}{' '}+ : 'This is the password to your Postgres database, so it must be strong and hard to guess.') ++ ' '}<spanclassName="text-inherit underline hover:text-foreground transition-colors cursor-pointer"onClick={generateStrongPassword}diff --git a/apps/studio/lib/helpers.ts b/apps/studio/lib/helpers.tsindex d5abad608a4..7c4d38c1b0b 100644--- a/apps/studio/lib/helpers.ts+++ b/apps/studio/lib/helpers.ts@@ -1,4 +1,3 @@-export { default as passwordStrength } from './password-strength'export { default as uuidv4 } from './uuid'import { UIEvent } from 'react'import type { TablesData } from '../data/tables/tables-query'diff --git a/apps/studio/lib/password-strength.test.ts b/apps/studio/lib/password-strength.test.tsindex 41f09655ad1..96992040144 100644--- a/apps/studio/lib/password-strength.test.ts+++ b/apps/studio/lib/password-strength.test.ts@@ -1,27 +1,10 @@import { describe, it, expect, beforeEach, vi } from 'vitest'-import passwordStrength from './password-strength'-import { toast } from 'sonner'--// Hoist the post_ mock so it's available before the module is loaded-const postMock = vi.hoisted(() => vi.fn())--vi.mock('data/fetchers', () => ({- post: postMock,-}))--vi.mock('sonner', () => ({- toast: { error: vi.fn() },-}))+import { passwordStrength } from './password-strength'describe('passwordStrength', () => {- beforeEach(() => {- vi.clearAllMocks()- })-it('returns empty values for message, warning and strength for empty input', async () => {const result = await passwordStrength('')expect(result).toEqual({ message: '', warning: '', strength: 0 })- expect(postMock).not.toHaveBeenCalled()})it('returns max length message, warning, and strength 0 for password longer than 99 characters', async () => {@@ -30,51 +13,21 @@ describe('passwordStrength', () => {expect(result.message).toMatch(/maximum length/i)expect(result.warning).toMatch(/less than 100 characters/i)expect(result.strength).toBe(0)- expect(postMock).not.toHaveBeenCalled()})it('returns strong score, suggestion, and empty warning for strong password', async () => {- postMock.mockResolvedValue({- data: {- result: {- score: 4,- feedback: { suggestions: ['Successfully updated database password'] },- },- },- error: null,- })- const result = await passwordStrength('StrongPassword123!')+ const result = await passwordStrength('ActuallyAStrongPassword123!')expect(result.message).toMatch(/strong/i)- expect(result.message).toContain('Successfully updated database password')+ expect(result.message).toContain('This password is strong')expect(result.warning).toBe('')expect(result.strength).toBe(4)})it('returns weak score, suggestion, and warning for weak password', async () => {- postMock.mockResolvedValue({- data: {- result: {- score: 2,- feedback: {- suggestions: ['Try a longer password'],- warning: 'Too short',- },- },- },- error: null,- })const result = await passwordStrength('weak')expect(result.message).toMatch(/not secure/i)- expect(result.message).toContain('Try a longer password')- expect(result.warning).toMatch(/too short/i)+ expect(result.message).toContain('This password is not secure enough')expect(result.warning).toMatch(/you need a stronger password/i)- expect(result.strength).toBe(2)- })-- it('returns empty values and shows toast error on server error', async () => {- postMock.mockResolvedValue({ data: null, error: { message: 'Server error' } })- const result = await passwordStrength('any')- expect(result).toEqual({ message: '', warning: '', strength: 0 })- expect(toast.error).toHaveBeenCalledTimes(1)+ expect(result.strength).toBe(1)})})diff --git a/apps/studio/lib/password-strength.ts b/apps/studio/lib/password-strength.tsindex cf813807e54..5dd1502e5ce 100644--- a/apps/studio/lib/password-strength.ts+++ b/apps/studio/lib/password-strength.ts@@ -1,9 +1,9 @@-import { post as post_ } from 'data/fetchers'import { DEFAULT_MINIMUM_PASSWORD_STRENGTH, PASSWORD_STRENGTH } from 'lib/constants'-import { toast } from 'sonner'-import { ResponseError } from 'types'-export default async function passwordStrength(value: string) {+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@@ -13,29 +13,20 @@ export default async function passwordStrength(value: string) {message = `${PASSWORD_STRENGTH[0]} Maximum length of password exceeded`warning = `Password should be less than 100 characters`} else {- const { data, error } = await post_('/platform/profile/password-check', {- body: { password: value },- })- if (!error) {- const { result } = data- const resultScore = result?.score ?? 0+ const result = zxcvbn(value)+ const resultScore = result?.score ?? 0- const score = (PASSWORD_STRENGTH as any)[resultScore]- const suggestions = result.feedback?.suggestions- ? result.feedback.suggestions.join(' ')- : ''+ const score = (PASSWORD_STRENGTH as any)[resultScore]+ const suggestions = result.feedback?.suggestions?.join(' ') ?? ''- message = `${score} ${suggestions}`- strength = resultScore+ message = `${score} ${suggestions}`+ strength = resultScore- // warning message for anything below 4 strength :string- if (resultScore < DEFAULT_MINIMUM_PASSWORD_STRENGTH) {- warning = `${- result?.feedback?.warning ? result?.feedback?.warning + '.' : ''- } You need a stronger password.`- }- } else {- toast.error(`Failed to check password strength: ${(error as ResponseError).message}`)+ // warning message for anything below 4 strength :string+ if (resultScore < DEFAULT_MINIMUM_PASSWORD_STRENGTH) {+ warning = `${+ result?.feedback?.warning ? result?.feedback?.warning + '.' : ''+ } You need a stronger password.`}}}diff --git a/apps/studio/pages/api/platform/profile/password-check.ts b/apps/studio/pages/api/platform/profile/password-check.tsdeleted file mode 100644index 46c2e932f49..00000000000--- a/apps/studio/pages/api/platform/profile/password-check.ts+++ /dev/null@@ -1,23 +0,0 @@-import { NextApiRequest, NextApiResponse } from 'next'-import zxcvbn from 'zxcvbn'-import apiWrapper from 'lib/api/apiWrapper'--export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)--async function handler(req: NextApiRequest, res: NextApiResponse) {- const { method } = req-- switch (method) {- case 'POST':- return handlePost(req, res)- default:- res.setHeader('Allow', ['POST'])- res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })- }-}--const handlePost = async (req: NextApiRequest, res: NextApiResponse) => {- const { body } = req- const result = zxcvbn(body.password)- return res.status(200).json({ result })-}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 52e49b7aa04..d96812b48ad 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@@ -1,6 +1,5 @@import { useParams } from 'common'-import { debounce } from 'lodash'-import { ChangeEvent, useRef, useState } from 'react'+import { ChangeEvent, useState } from 'react'import { toast } from 'sonner'import { Alert, Button, Checkbox, Input, Listbox } from 'ui'@@ -18,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 } from 'lib/password-strength'import { generateStrongPassword } from 'lib/project'import { AWS_REGIONS } from 'shared-data'import { useIntegrationInstallationSnapshot } from 'state/integration-installation'@@ -63,9 +62,11 @@ const CreateProject = () => {const snapshot = useIntegrationInstallationSnapshot()- const delayedCheckPasswordStrength = useRef(- debounce((value: string) => checkPasswordStrength(value), 300)- ).current+ async function checkPasswordStrength(value: string) {+ const { message, strength } = await passwordStrength(value)+ setPasswordStrengthScore(strength)+ setPasswordStrengthMessage(message)+ }const { slug, next, currentProjectId: foreignProjectId, externalId } = useParams()@@ -105,19 +106,13 @@ const CreateProject = () => {if (value == '') {setPasswordStrengthScore(-1)setPasswordStrengthMessage('')- } else delayedCheckPasswordStrength(value)- }-- async function checkPasswordStrength(value: string) {- const { message, strength } = await passwordStrength(value)- setPasswordStrengthScore(strength)- setPasswordStrengthMessage(message)+ } else checkPasswordStrength(value)}function generatePassword() {const password = generateStrongPassword()setDbPass(password)- delayedCheckPasswordStrength(password)+ checkPasswordStrength(password)}const [newProjectRef, setNewProjectRef] = useState<string | undefined>(undefined)