The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
makes it possible to reset password from connect dialog (#46866)
Saxon Fletcherd8fadcc1c8b2
diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsxindex 7c0265a7a7e..6f7670270f4 100644--- a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx@@ -190,6 +190,8 @@ export function ConnectStepsSection({ steps, state, projectKeys }: ConnectStepsS!ipv4Addon &&(state.connectionMethod === 'direct' ||(state.connectionMethod === 'transaction' && !state.useSharedPooler))+ const showSessionPoolerNotice =+ deploymentMode.isPlatform && state.mode === 'direct' && state.connectionMethod === 'session'const showSelfHostedMcpNotice = deploymentMode.isSelfHosted && state.mode === 'mcp'@@ -200,8 +202,6 @@ export function ConnectStepsSection({ steps, state, projectKeys }: ConnectStepsS<div className="p-8 flex flex-col gap-y-6"><h3>Connect your app</h3>- <CopyPromptAdmonition stepsContainerRef={stepsContainerRef} />-{showIpv4AddonNotice && (<Admonitiontype="default"@@ -216,6 +216,14 @@ export function ConnectStepsSection({ steps, state, projectKeys }: ConnectStepsS/>)}+ {showSessionPoolerNotice && (+ <Admonition+ type="default"+ title="Only use Session Pooler on an IPv4 network"+ description="Session pooler connections are IPv4 proxied for free. Use Direct Connection if connecting via an IPv6 network."+ />+ )}+{showSelfHostedMcpNotice && (<Admonitiontype="default"@@ -230,6 +238,8 @@ export function ConnectStepsSection({ steps, state, projectKeys }: ConnectStepsS/>)}+ <CopyPromptAdmonition stepsContainerRef={stepsContainerRef} />+<div className="mt-6" ref={stepsContainerRef}>{steps.map((step, index) => (<ConnectSheetStepdiff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.test.ts b/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.test.tsindex b05ba6802cb..15efba43f21 100644--- a/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.test.ts+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.test.ts@@ -2,6 +2,7 @@ import { describe, expect, test } from 'vitest'import {buildConnectionParameters,+ buildConnectionStringWithPassword,buildSafeConnectionString,DEFAULT_PORT,parseConnectionParams,@@ -70,6 +71,23 @@ describe('buildSafeConnectionString', () => {})})+describe('buildConnectionStringWithPassword', () => {+ test('returns the original string when input or password is empty', () => {+ const uri = `postgresql://postgres:${PASSWORD_PLACEHOLDER}@localhost:5432/postgres`++ expect(buildConnectionStringWithPassword('', 'password')).toBe('')+ expect(buildConnectionStringWithPassword(uri, '')).toBe(uri)+ })++ test('replaces every password placeholder with the encoded password', () => {+ const uri = `postgresql://postgres:${PASSWORD_PLACEHOLDER}@localhost:5432/postgres?password=${PASSWORD_PLACEHOLDER}`++ expect(buildConnectionStringWithPassword(uri, 'p@ss/word#1')).toBe(+ 'postgresql://postgres:p%40ss%2Fword%231@localhost:5432/postgres?password=p%40ss%2Fword%231'+ )+ })+})+describe('resolveConnectionString', () => {const pooler = {transactionShared: 'tx-shared',diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.ts b/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.tsindex 96c07fa8851..16c3e900447 100644--- a/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.ts+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectionString.utils.ts@@ -92,6 +92,23 @@ export const buildSafeConnectionString = (return `postgresql://${params.user}:${PASSWORD_PLACEHOLDER}@${params.host}:${params.port}/${params.database}${search}`}+export const buildConnectionStringWithPassword = (+ connectionString: string,+ password: string+): string => {+ if (!connectionString || !password) return connectionString++ const encodedPassword = (() => {+ try {+ return encodeURIComponent(password)+ } catch {+ return password+ }+ })()++ return connectionString.split(PASSWORD_PLACEHOLDER).join(encodedPassword)+}+export const buildConnectionParameters = (params: ConnectionParams) => [{ key: 'host', value: params.host },{ key: 'port', value: params.port },diff --git a/apps/studio/components/interfaces/ConnectSheet/CopyPromptAdmonition.test.ts b/apps/studio/components/interfaces/ConnectSheet/CopyPromptAdmonition.test.tsnew file mode 100644index 00000000000..49f7bacfa52--- /dev/null+++ b/apps/studio/components/interfaces/ConnectSheet/CopyPromptAdmonition.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test } from 'vitest'++import { buildConnectPrompt } from './CopyPromptAdmonition'++describe('buildConnectPrompt', () => {+ test('uses redacted copy values instead of temporarily visible passwords', () => {+ const container = document.createElement('div')+ container.innerHTML = `+ <div+ data-connect-step+ data-step-title="Connection string"+ data-step-description="Copy the connection details for your database."+ >+ <div data-step-content>+ <div+ data-connect-copy-value="postgresql://postgres:[YOUR-PASSWORD]@db.example.supabase.co:5432/postgres"+ >+ <pre>postgresql://postgres:[email protected]:5432/postgres</pre>+ </div>+ </div>+ </div>+ `++ const prompt = buildConnectPrompt(container)++ expect(prompt).toContain(+ 'postgresql://postgres:[YOUR-PASSWORD]@db.example.supabase.co:5432/postgres'+ )+ expect(prompt).not.toContain('temporary-password')+ })+})diff --git a/apps/studio/components/interfaces/ConnectSheet/CopyPromptAdmonition.tsx b/apps/studio/components/interfaces/ConnectSheet/CopyPromptAdmonition.tsxindex 9c70466cd78..e4fb94dc9f0 100644--- a/apps/studio/components/interfaces/ConnectSheet/CopyPromptAdmonition.tsx+++ b/apps/studio/components/interfaces/ConnectSheet/CopyPromptAdmonition.tsx@@ -8,117 +8,124 @@ interface CopyPromptAdmonitionProps {stepsContainerRef: RefObject<HTMLDivElement | null>}-export function CopyPromptAdmonition({ stepsContainerRef }: CopyPromptAdmonitionProps) {- const normalizeTextLines = (value: string) => {- return value- .split('\n')- .map((line) => line.trim())- .filter(Boolean)- .join('\n')- }-- const getStepTextContent = (contentElement: HTMLElement) => {- const clone = contentElement.cloneNode(true) as HTMLElement- clone- .querySelectorAll('pre, button, svg, input, textarea, select, [aria-hidden="true"]')- .forEach((element) => {- element.remove()- })+const normalizeTextLines = (value: string) => {+ return value+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean)+ .join('\n')+}- clone.querySelectorAll('p, div').forEach((el) => {- el.appendChild(document.createTextNode('\n'))+const getStepTextContent = (contentElement: HTMLElement) => {+ const clone = contentElement.cloneNode(true) as HTMLElement+ clone+ .querySelectorAll('pre, button, svg, input, textarea, select, [aria-hidden="true"]')+ .forEach((element) => {+ element.remove()})- const text = clone.textContent ?? ''- return normalizeTextLines(text)+ clone.querySelectorAll('p, div').forEach((el) => {+ el.appendChild(document.createTextNode('\n'))+ })++ const text = clone.textContent ?? ''+ return normalizeTextLines(text)+}++const getStepCodeSnippets = (contentElement: HTMLElement) => {+ const snippets: Array<{ label: string; snippet: string }> = []+ const seen = new Set<string>()++ const addSnippet = (label: string, snippet: string) => {+ if (!snippet || seen.has(snippet)) return+ seen.add(snippet)+ snippets.push({ label, snippet })}- const getStepCodeSnippets = (contentElement: HTMLElement) => {- const snippets: Array<{ label: string; snippet: string }> = []- const seen = new Set<string>()+ const getSnippet = (element: Element) => {+ const copyValueElement = element.closest('[data-connect-copy-value]') as HTMLElement | null+ return copyValueElement?.dataset.connectCopyValue?.trim() || element.textContent?.trim()+ }- const addSnippet = (label: string, snippet: string) => {- if (!snippet || seen.has(snippet)) return- seen.add(snippet)- snippets.push({ label, snippet })- }+ const tabContents = Array.from(+ contentElement.querySelectorAll('[data-connect-tab-content]')+ ) as HTMLElement[]- const tabContents = Array.from(- contentElement.querySelectorAll('[data-connect-tab-content]')- ) as HTMLElement[]+ tabContents.forEach((tabContent) => {+ const label = tabContent.getAttribute('data-tab-label') || 'Code'+ const tabSnippets = Array.from(tabContent.querySelectorAll('pre'))+ .map(getSnippet)+ .filter((snippet): snippet is string => Boolean(snippet))- tabContents.forEach((tabContent) => {- const label = tabContent.getAttribute('data-tab-label') || 'Code'- const tabSnippets = Array.from(tabContent.querySelectorAll('pre'))- .map((pre) => pre.textContent?.trim())+ if (tabSnippets.length === 0) {+ const inlineSnippets = Array.from(tabContent.querySelectorAll('code'))+ .filter((code) => !code.closest('pre') && code.closest('.font-mono'))+ .map((code) => code.textContent?.trim()).filter((snippet): snippet is string => Boolean(snippet))-- if (tabSnippets.length === 0) {- const inlineSnippets = Array.from(tabContent.querySelectorAll('code'))- .filter((code) => !code.closest('pre') && code.closest('.font-mono'))- .map((code) => code.textContent?.trim())- .filter((snippet): snippet is string => Boolean(snippet))- inlineSnippets.forEach((snippet, index) => {- const inlineLabel = inlineSnippets.length > 1 ? `${label} (part ${index + 1})` : label- addSnippet(inlineLabel, snippet)- })- return- }-- tabSnippets.forEach((snippet, index) => {- const tabLabel = tabSnippets.length > 1 ? `${label} (part ${index + 1})` : label- addSnippet(tabLabel, snippet)+ inlineSnippets.forEach((snippet, index) => {+ const inlineLabel = inlineSnippets.length > 1 ? `${label} (part ${index + 1})` : label+ addSnippet(inlineLabel, snippet)})- })+ return+ }- contentElement.querySelectorAll('pre').forEach((pre) => {- if (pre.closest('[data-connect-tab-content]')) return- const snippet = pre.textContent?.trim()- if (snippet) addSnippet('Code', snippet)+ tabSnippets.forEach((snippet, index) => {+ const tabLabel = tabSnippets.length > 1 ? `${label} (part ${index + 1})` : label+ addSnippet(tabLabel, snippet)})+ })++ contentElement.querySelectorAll('pre').forEach((pre) => {+ if (pre.closest('[data-connect-tab-content]')) return+ const snippet = getSnippet(pre)+ if (snippet) addSnippet('Code', snippet)+ })++ contentElement.querySelectorAll('code').forEach((code) => {+ if (code.closest('pre')) return+ if (code.closest('[data-connect-tab-content]')) return+ if (!code.closest('.font-mono')) return+ const snippet = code.textContent?.trim()+ if (snippet) addSnippet('Code', snippet)+ })++ return snippets+}- contentElement.querySelectorAll('code').forEach((code) => {- if (code.closest('pre')) return- if (code.closest('[data-connect-tab-content]')) return- if (!code.closest('.font-mono')) return- const snippet = code.textContent?.trim()- if (snippet) addSnippet('Code', snippet)+export const buildConnectPrompt = (stepsContainer: HTMLElement | null) => {+ const stepElements = stepsContainer?.querySelectorAll('[data-connect-step]')+ if (!stepElements?.length) return ''++ const promptContent = Array.from(stepElements)+ .map((stepElement, index) => {+ const title = stepElement.getAttribute('data-step-title') ?? `Step ${index + 1}`+ const description = stepElement.getAttribute('data-step-description') ?? ''+ const contentElement = stepElement.querySelector('[data-step-content]') as HTMLElement | null++ const details = contentElement ? getStepTextContent(contentElement) : ''+ const codeSnippets = contentElement ? getStepCodeSnippets(contentElement) : []++ const sections = [+ `${index + 1}. ${title}`,+ description,+ details ? `Details:\n${details}` : null,+ codeSnippets.length+ ? `Code:\n${codeSnippets+ .map(({ label, snippet }) => `File: ${label}\n\`\`\`\n${snippet}\n\`\`\``)+ .join('\n\n')}`+ : null,+ ].filter(Boolean)++ return sections.join('\n')})+ .join('\n\n')- return snippets- }+ return promptContent+}+export function CopyPromptAdmonition({ stepsContainerRef }: CopyPromptAdmonitionProps) {const handleCopyPrompt = () => {- const stepElements = stepsContainerRef.current?.querySelectorAll('[data-connect-step]')- if (!stepElements?.length) return ''-- const promptContent = Array.from(stepElements)- .map((stepElement, index) => {- const title = stepElement.getAttribute('data-step-title') ?? `Step ${index + 1}`- const description = stepElement.getAttribute('data-step-description') ?? ''- const contentElement = stepElement.querySelector(- '[data-step-content]'- ) as HTMLElement | null-- const details = contentElement ? getStepTextContent(contentElement) : ''- const codeSnippets = contentElement ? getStepCodeSnippets(contentElement) : []-- const sections = [- `${index + 1}. ${title}`,- description,- details ? `Details:\n${details}` : null,- codeSnippets.length- ? `Code:\n${codeSnippets- .map(({ label, snippet }) => `File: ${label}\n\`\`\`\n${snippet}\n\`\`\``)- .join('\n\n')}`- : null,- ].filter(Boolean)-- return sections.join('\n')- })- .join('\n\n')-- return promptContent+ return buildConnectPrompt(stepsContainerRef.current)}return (diff --git a/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsx b/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsxindex 7cfe723a089..60402805e54 100644--- a/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsx+++ b/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsx@@ -1,16 +1,14 @@import { useParams } from 'common'-import { useMemo } from 'react'+import { Check, KeyRound } from 'lucide-react'+import { useMemo, useState } from 'react'import { Badge } from 'ui'import { CodeBlock } from 'ui-patterns/CodeBlock'import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'import { buildConnectionStringPooler, getConnectionStrings } from '../../../DatabaseSettings.utils'-import { IPv4StatusPanel, type IPv4Status } from './IPv4StatusPanel'import { getAddons } from '@/components/interfaces/Billing/Subscription/Subscription.utils'import {DATABASE_CONNECTION_TYPES,- IPV4_ADDON_TEXT,- PGBOUNCER_ENABLED_BUT_NO_IPV4_ADDON_TEXT,type ConnectionStringMethod,type DatabaseConnectionType,} from '@/components/interfaces/ConnectSheet/Connect.constants'@@ -22,11 +20,13 @@ import type {import { ConnectionParameters } from '@/components/interfaces/ConnectSheet/ConnectionParameters'import {buildConnectionParameters,+ buildConnectionStringWithPassword,buildSafeConnectionString,parseConnectionParams,PASSWORD_PLACEHOLDER,resolveConnectionString,} from '@/components/interfaces/ConnectSheet/ConnectionString.utils'+import { ResetDbPasswordDialog } from '@/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPasswordDialog'import { usePgbouncerConfigQuery } from '@/data/database/pgbouncer-config-query'import { useSupavisorConfigurationQuery } from '@/data/database/supavisor-configuration-query'import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'@@ -143,9 +143,9 @@ const CONNECTION_METHOD_TO_TELEMETRY: Record<*/function DirectConnectionContent({ state, deploymentMode }: StepContentProps) {const track = useTrack()- const { ref: projectRef } = useParams()const { hasAccess: hasDedicatedPooler } = useCheckEntitlements('dedicated_pooler')const isHighAvailability = useIsHighAvailability()+ const [temporaryDatabasePassword, setTemporaryDatabasePassword] = useState('')const connectionSource = state.connectionSourceconst connectionType = (state.connectionType as DatabaseConnectionType) ?? 'uri'@@ -155,8 +155,6 @@ function DirectConnectionContent({ state, deploymentMode }: StepContentProps) {const connectionStrings = useConnectionStringDatabases(deploymentMode)const connectionStringPooler: ConnectionStringPooler | undefined =connectionStrings[connectionSource as keyof typeof connectionStrings]- const hasIPv4Addon = connectionStringPooler?.ipv4SupportedForDedicatedPooler ?? false-// Determine which connection string to useconst resolvedConnectionString = useMemo(() =>@@ -178,7 +176,7 @@ function DirectConnectionContent({ state, deploymentMode }: StepContentProps) {[resolvedConnectionString, connectionParams])- const connectionString = useMemo(() => {+ const redactedConnectionString = useMemo(() => {switch (connectionType) {case 'psql':return buildPsqlCommand(connectionParams)@@ -192,6 +190,19 @@ function DirectConnectionContent({ state, deploymentMode }: StepContentProps) {}}, [connectionType, connectionParams, safeConnectionString])+ const connectionString = useMemo(() => {+ if (!temporaryDatabasePassword) return redactedConnectionString++ if (connectionType === 'psql') {+ return `psql "${buildConnectionStringWithPassword(+ safeConnectionString,+ temporaryDatabasePassword+ )}"`+ }++ return buildConnectionStringWithPassword(redactedConnectionString, temporaryDatabasePassword)+ }, [connectionType, redactedConnectionString, safeConnectionString, temporaryDatabasePassword])+const trackCopy = () => {const typeConfig = DATABASE_CONNECTION_TYPES.find((t) => t.id === connectionType)track('connection_string_copied', {@@ -211,57 +222,6 @@ function DirectConnectionContent({ state, deploymentMode }: StepContentProps) {)}- const sharedPoolerPreferred = !hasDedicatedPooler- const ipv4AddOnUrl = {- text: 'IPv4 add-on',- url: `/project/${projectRef}/settings/addons?panel=ipv4`,- }- const ipv4SettingsUrl = {- text: 'IPv4 settings',- url: `/project/${projectRef}/settings/addons?panel=ipv4`,- }- const poolerSettingsUrl = {- text: 'Pooler settings',- url: `/project/${projectRef}/database/settings#connection-pooling`,- }- const buttonLinks = !hasIPv4Addon- ? [ipv4AddOnUrl, ...(sharedPoolerPreferred ? [poolerSettingsUrl] : [])]- : [ipv4SettingsUrl, ...(sharedPoolerPreferred ? [poolerSettingsUrl] : [])]-- let ipv4Status: IPv4Status- if (connectionMethod === 'direct') {- ipv4Status = {- type: !hasIPv4Addon ? 'error' : 'success',- title: !hasIPv4Addon ? 'Not IPv4 compatible' : 'IPv4 compatible',- description:- !sharedPoolerPreferred && !hasIPv4Addon- ? PGBOUNCER_ENABLED_BUT_NO_IPV4_ADDON_TEXT- : sharedPoolerPreferred- ? 'Use Session Pooler if on a IPv4 network or purchase IPv4 add-on'- : IPV4_ADDON_TEXT,- links: buttonLinks,- }- } else if (connectionMethod === 'transaction') {- const isUsingSharedPooler = useSharedPooler || !hasDedicatedPooler- ipv4Status = {- type: !isUsingSharedPooler && !hasIPv4Addon ? 'error' : 'success',- title: !isUsingSharedPooler && !hasIPv4Addon ? 'Not IPv4 compatible' : 'IPv4 compatible',- description:- !isUsingSharedPooler && !hasIPv4Addon- ? PGBOUNCER_ENABLED_BUT_NO_IPV4_ADDON_TEXT- : isUsingSharedPooler- ? 'Transaction pooler connections are IPv4 proxied for free.'- : IPV4_ADDON_TEXT,- links: !isUsingSharedPooler ? buttonLinks : undefined,- }- } else {- ipv4Status = {- type: 'success',- title: 'IPv4 compatible',- description: 'Session pooler connections are IPv4 proxied for free',- }- }-const poolerBadge =connectionMethod === 'transaction'? useSharedPooler || !hasDedicatedPooler@@ -280,16 +240,39 @@ function DirectConnectionContent({ state, deploymentMode }: StepContentProps) {<Badge>{poolerBadge}</Badge></div>)}- <CodeBlock- className="[&_code]:text-foreground"- wrapperClassName="lg:col-span-2"- value={connectionString}- hideLineNumbers- language="bash"- onCopyCallback={trackCopy}- >- {connectionString}- </CodeBlock>+ <div className="overflow-hidden rounded-lg border bg-surface-75">+ <div data-connect-copy-value={redactedConnectionString}>+ <CodeBlock+ className="rounded-none border-0 [&_code]:text-foreground"+ wrapperClassName="lg:col-span-2"+ value={connectionString}+ hideLineNumbers+ language="bash"+ onCopyCallback={trackCopy}+ >+ {connectionString}+ </CodeBlock>+ </div>+ {deploymentMode.isPlatform && (+ <div className="flex flex-col gap-2 border-t px-6 py-3 sm:flex-row sm:items-center sm:justify-between">+ <div className="text-sm text-foreground-light">+ {temporaryDatabasePassword ? (+ <span className="flex items-center gap-2">+ <Check size={16} className="text-brand shrink-0" />+ <span>New password shown until refresh.</span>+ </span>+ ) : (+ 'Forgot your database password?'+ )}+ </div>+ <ResetDbPasswordDialog+ triggerLabel="Reset password"+ triggerIcon={<KeyRound />}+ onPasswordReset={setTemporaryDatabasePassword}+ />+ </div>+ )}+ </div>{showSelfHostedDirectNotice && (<p className="text-sm text-foreground-light">Manually{' '}@@ -304,15 +287,6 @@ function DirectConnectionContent({ state, deploymentMode }: StepContentProps) {for self-hosted Supabase.</p>)}- {deploymentMode.isPlatform && projectRef && !isHighAvailability && (- <div className="mt-2">- <IPv4StatusPanel- method={connectionMethod}- ipv4Status={ipv4Status}- projectRef={projectRef}- />- </div>- )}<ConnectionParametersparameters={buildConnectionParameters(connectionParams)}onCopy={trackCopy}diff --git a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsxindex 502d5c4485d..f31820fbb2a 100644--- a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx+++ b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx@@ -1,22 +1,4 @@-import { PermissionAction } from '@supabase/shared-types/out/constants'-import { useParams } from 'common'-import { useEffect, useState } from 'react'-import { toast } from 'sonner'-import {- Button,- Card,- CardContent,- Dialog,- DialogContent,- DialogFooter,- DialogHeader,- DialogSection,- DialogSectionSeparator,- DialogTitle,- DialogTrigger,-} from 'ui'-import { Input } from 'ui-patterns/DataInputs/Input'-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { Card, CardContent } from 'ui'import {PageSection,PageSectionContent,@@ -26,177 +8,33 @@ import {PageSectionTitle,} from 'ui-patterns/PageSection'-import { ButtonTooltip } from '@/components/ui/ButtonTooltip'-import { PasswordStrengthBar } from '@/components/ui/PasswordStrengthBar'-import { useDatabasePasswordResetMutation } from '@/data/database/database-password-reset-mutation'-import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'-import { useIsProjectActive, useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'-import { DEFAULT_MINIMUM_PASSWORD_STRENGTH } from '@/lib/constants'-import { passwordStrength, PasswordStrengthScore } from '@/lib/password-strength'-import { generateStrongPassword } from '@/lib/project'+import { ResetDbPasswordDialog } from './ResetDbPasswordDialog'const ResetDbPassword = ({ disabled = false }) => {- const { ref } = useParams()- const isProjectActive = useIsProjectActive()- const { data: project } = useSelectedProjectQuery()-- const { can: canResetDbPassword } = useAsyncCheckPermissions(- PermissionAction.UPDATE,- 'projects',- {- resource: {- project_id: project?.id,- },- }- )-- const [showResetDbPass, setShowResetDbPass] = useState<boolean>(false)-- const [password, setPassword] = useState<string>('')- const [passwordStrengthMessage, setPasswordStrengthMessage] = useState<string>('')- const [passwordStrengthWarning, setPasswordStrengthWarning] = useState<string>('')- const [passwordStrengthScore, setPasswordStrengthScore] = useState(0)-- const { mutate: resetDatabasePassword, isPending: isUpdatingPassword } =- useDatabasePasswordResetMutation({- onSuccess: async () => {- toast.success('Successfully updated database password')- setShowResetDbPass(false)- },- })-- useEffect(() => {- if (showResetDbPass) {- setPassword('')- setPasswordStrengthMessage('')- setPasswordStrengthWarning('')- setPasswordStrengthScore(0)- }- }, [showResetDbPass])-- async function checkPasswordStrength(value: any) {- const { message, warning, strength } = await passwordStrength(value)- setPasswordStrengthScore(strength)- setPasswordStrengthWarning(warning)- setPasswordStrengthMessage(message)- }-- const onDbPassChange = (e: any) => {- const value = e.target.value- setPassword(value)- if (value == '') {- setPasswordStrengthScore(-1)- setPasswordStrengthMessage('')- } else checkPasswordStrength(value)- }-- const confirmResetDbPass = async () => {- if (!ref) return console.error('Project ref is required')-- if (passwordStrengthScore >= DEFAULT_MINIMUM_PASSWORD_STRENGTH) {- resetDatabasePassword({ ref, password })- }- }-- function generatePassword() {- const password = generateStrongPassword()- setPassword(password)- checkPasswordStrength(password)- }-return (- <>- <PageSection id="database-password">- <PageSectionMeta>- <PageSectionSummary>- <PageSectionTitle>Database password</PageSectionTitle>-- <PageSectionDescription>Used for direct Postgres connections</PageSectionDescription>- </PageSectionSummary>- </PageSectionMeta>- <PageSectionContent>- <Card>- <CardContent className="flex flex-row items-center gap-x-2 justify-between">- <div className="space-y-0.5">- <h3 className="text-sm text-foreground">Reset database password</h3>- <p className="text-sm text-foreground-light text-balance">- The database password isn’t viewable after creation. Resetting it will break any- existing connections.- </p>- </div>- <Dialog open={showResetDbPass} onOpenChange={(open) => setShowResetDbPass(open)}>- <DialogTrigger asChild>- <ButtonTooltip- type="default"- disabled={!canResetDbPassword || !isProjectActive || disabled}- tooltip={{- content: {- side: 'bottom',- text: !canResetDbPassword- ? 'You need additional permissions to reset the database password'- : !isProjectActive- ? 'Unable to reset database password as project is not active'- : undefined,- },- }}- >- Reset password- </ButtonTooltip>- </DialogTrigger>- <DialogContent size="medium">- <DialogHeader>- <DialogTitle>Reset database password</DialogTitle>- </DialogHeader>- <DialogSectionSeparator />- <DialogSection className="w-full space-y-8">- <FormItemLayout- layout="vertical"- isReactForm={false}- error={passwordStrengthWarning}- description={- <PasswordStrengthBar- passwordStrengthScore={passwordStrengthScore as PasswordStrengthScore}- passwordStrengthMessage={passwordStrengthMessage}- password={password}- generateStrongPassword={generatePassword}- />- }- >- <Input- copy={password.length > 0}- aria-invalid={!!passwordStrengthWarning}- type="password"- placeholder="Type in a strong password"- value={password}- autoComplete="off"- onChange={onDbPassChange}- />- </FormItemLayout>- </DialogSection>- <DialogFooter>- <Button- type="default"- disabled={isUpdatingPassword}- onClick={() => setShowResetDbPass(false)}- >- Cancel- </Button>- <Button- type="primary"- loading={isUpdatingPassword}- disabled={isUpdatingPassword}- onClick={() => confirmResetDbPass()}- >- Reset password- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </CardContent>- </Card>- </PageSectionContent>- </PageSection>- </>+ <PageSection id="database-password">+ <PageSectionMeta>+ <PageSectionSummary>+ <PageSectionTitle>Database password</PageSectionTitle>++ <PageSectionDescription>Used for direct Postgres connections</PageSectionDescription>+ </PageSectionSummary>+ </PageSectionMeta>+ <PageSectionContent>+ <Card>+ <CardContent className="flex flex-row items-center gap-x-2 justify-between">+ <div className="space-y-0.5">+ <h3 className="text-sm text-foreground">Reset database password</h3>+ <p className="text-sm text-foreground-light text-balance">+ The database password isn’t viewable after creation. Resetting it will break any+ existing connections.+ </p>+ </div>+ <ResetDbPasswordDialog disabled={disabled} />+ </CardContent>+ </Card>+ </PageSectionContent>+ </PageSection>)}diff --git a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPasswordDialog.tsx b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPasswordDialog.tsxnew file mode 100644index 00000000000..1bde44e8d9d--- /dev/null+++ b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPasswordDialog.tsx@@ -0,0 +1,202 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useParams } from 'common'+import type { ChangeEvent, ComponentProps, ReactNode } from 'react'+import { useEffect, useRef, useState } from 'react'+import { toast } from 'sonner'+import {+ Button,+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogSection,+ DialogSectionSeparator,+ DialogTitle,+ DialogTrigger,+} from 'ui'+import { Input } from 'ui-patterns/DataInputs/Input'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'++import { ButtonTooltip } from '@/components/ui/ButtonTooltip'+import { PasswordStrengthBar } from '@/components/ui/PasswordStrengthBar'+import { useDatabasePasswordResetMutation } from '@/data/database/database-password-reset-mutation'+import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'+import { useIsProjectActive, useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { DEFAULT_MINIMUM_PASSWORD_STRENGTH } from '@/lib/constants'+import { passwordStrength, PasswordStrengthScore } from '@/lib/password-strength'+import { generateStrongPassword } from '@/lib/project'++export type ResetDbPasswordDialogProps = {+ disabled?: boolean+ onPasswordReset?: (password: string) => void+ triggerClassName?: string+ triggerIcon?: ReactNode+ triggerLabel?: string+ triggerType?: ComponentProps<typeof ButtonTooltip>['type']+}++export const ResetDbPasswordDialog = ({+ disabled = false,+ onPasswordReset,+ triggerClassName,+ triggerIcon,+ triggerLabel = 'Reset password',+ triggerType = 'default',+}: ResetDbPasswordDialogProps) => {+ const { ref } = useParams()+ const isProjectActive = useIsProjectActive()+ const { data: project } = useSelectedProjectQuery()++ const { can: canResetDbPassword } = useAsyncCheckPermissions(+ PermissionAction.UPDATE,+ 'projects',+ {+ resource: {+ project_id: project?.id,+ },+ }+ )++ const [showResetDbPass, setShowResetDbPass] = useState<boolean>(false)++ const [password, setPassword] = useState<string>('')+ const [passwordStrengthMessage, setPasswordStrengthMessage] = useState<string>('')+ const [passwordStrengthWarning, setPasswordStrengthWarning] = useState<string>('')+ const [passwordStrengthScore, setPasswordStrengthScore] = useState(0)+ const latestPasswordStrengthValueRef = useRef('')+ const passwordStrengthResultValueRef = useRef('')++ const { mutate: resetDatabasePassword, isPending: isUpdatingPassword } =+ useDatabasePasswordResetMutation({+ onSuccess: async (_data, variables) => {+ toast.success('Successfully updated database password')+ onPasswordReset?.(variables.password)+ setShowResetDbPass(false)+ },+ })++ useEffect(() => {+ if (showResetDbPass) {+ setPassword('')+ setPasswordStrengthMessage('')+ setPasswordStrengthWarning('')+ setPasswordStrengthScore(0)+ latestPasswordStrengthValueRef.current = ''+ passwordStrengthResultValueRef.current = ''+ }+ }, [showResetDbPass])++ async function checkPasswordStrength(value: string) {+ latestPasswordStrengthValueRef.current = value+ const { message, warning, strength } = await passwordStrength(value)++ if (latestPasswordStrengthValueRef.current !== value) return++ passwordStrengthResultValueRef.current = value+ setPasswordStrengthScore(strength)+ setPasswordStrengthWarning(warning)+ setPasswordStrengthMessage(message)+ }++ const onDbPassChange = (e: ChangeEvent<HTMLInputElement>) => {+ const value = e.target.value+ setPassword(value)+ if (value == '') {+ latestPasswordStrengthValueRef.current = value+ passwordStrengthResultValueRef.current = value+ setPasswordStrengthScore(-1)+ setPasswordStrengthMessage('')+ setPasswordStrengthWarning('')+ } else checkPasswordStrength(value)+ }++ const confirmResetDbPass = async () => {+ if (!ref) return console.error('Project ref is required')++ if (+ passwordStrengthResultValueRef.current === password &&+ passwordStrengthScore >= DEFAULT_MINIMUM_PASSWORD_STRENGTH+ ) {+ resetDatabasePassword({ ref, password })+ }+ }++ function generatePassword() {+ const password = generateStrongPassword()+ setPassword(password)+ checkPasswordStrength(password)+ }++ return (+ <Dialog open={showResetDbPass} onOpenChange={(open) => setShowResetDbPass(open)}>+ <DialogTrigger asChild>+ <ButtonTooltip+ type={triggerType}+ className={triggerClassName}+ icon={triggerIcon}+ disabled={!canResetDbPassword || !isProjectActive || disabled}+ tooltip={{+ content: {+ side: 'bottom',+ text: !canResetDbPassword+ ? 'You need additional permissions to reset the database password'+ : !isProjectActive+ ? 'Unable to reset database password as project is not active'+ : undefined,+ },+ }}+ >+ {triggerLabel}+ </ButtonTooltip>+ </DialogTrigger>+ <DialogContent size="medium">+ <DialogHeader>+ <DialogTitle>Reset database password</DialogTitle>+ </DialogHeader>+ <DialogSectionSeparator />+ <DialogSection className="w-full space-y-8">+ <FormItemLayout+ layout="vertical"+ isReactForm={false}+ error={passwordStrengthWarning}+ description={+ <PasswordStrengthBar+ passwordStrengthScore={passwordStrengthScore as PasswordStrengthScore}+ passwordStrengthMessage={passwordStrengthMessage}+ password={password}+ generateStrongPassword={generatePassword}+ />+ }+ >+ <Input+ copy={password.length > 0}+ aria-invalid={!!passwordStrengthWarning}+ type="password"+ placeholder="Type in a strong password"+ value={password}+ autoComplete="off"+ onChange={onDbPassChange}+ />+ </FormItemLayout>+ </DialogSection>+ <DialogFooter>+ <Button+ type="default"+ disabled={isUpdatingPassword}+ onClick={() => setShowResetDbPass(false)}+ >+ Cancel+ </Button>+ <Button+ type="primary"+ loading={isUpdatingPassword}+ disabled={isUpdatingPassword}+ onClick={() => confirmResetDbPass()}+ >+ Reset password+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}