فهرست منبع

Show live password feedback while setting a new password (#637)

* Show live password feedback while setting a new password

* Reserve the height of the longest password message so wrapping moves nothing
Bernt Christian Egeland 2 روز پیش
والد
کامیت
e2fe538534

+ 7 - 0
messages/de/common.json

@@ -31,6 +31,13 @@
     "address": "Adresse",
     "notes": "Notizen"
   },
+  "passwordFeedback": {
+    "tooShort": "Zu kurz, {count, plural, one {noch # Zeichen} other {noch # Zeichen}}",
+    "tooLong": "Zu lang, {count, plural, one {# Zeichen} other {# Zeichen}} über dem Limit von {max} Zeichen",
+    "ok": "Passwort OK",
+    "mismatch": "Stimmt nicht mit dem Passwort oben überein",
+    "match": "Passwörter stimmen überein"
+  },
   "errors": {
     "unexpected": "Ein unerwarteter Fehler ist aufgetreten. Bitte versuchen Sie es erneut.",
     "error": "Fehler"

+ 7 - 0
messages/en/common.json

@@ -31,6 +31,13 @@
     "address": "Address",
     "notes": "Notes"
   },
+  "passwordFeedback": {
+    "tooShort": "Too short, {count, plural, one {# more character} other {# more characters}}",
+    "tooLong": "Too long, {count, plural, one {# character} other {# characters}} over the {max}-character limit",
+    "ok": "Password OK",
+    "mismatch": "Does not match the password above",
+    "match": "Passwords match"
+  },
   "errors": {
     "unexpected": "An unexpected error occurred. Please try again.",
     "error": "Error"

+ 7 - 0
messages/es/common.json

@@ -31,6 +31,13 @@
     "address": "Dirección",
     "notes": "Notas"
   },
+  "passwordFeedback": {
+    "tooShort": "Demasiado corta, {count, plural, one {falta # carácter} other {faltan # caracteres}}",
+    "tooLong": "Demasiado larga, {count, plural, one {# carácter} other {# caracteres}} por encima del límite de {max}",
+    "ok": "Contraseña válida",
+    "mismatch": "No coincide con la contraseña de arriba",
+    "match": "Las contraseñas coinciden"
+  },
   "errors": {
     "unexpected": "Ha ocurrido un error inesperado. Por favor, inténtelo de nuevo.",
     "error": "Error"

+ 7 - 0
messages/fr/common.json

@@ -31,6 +31,13 @@
     "address": "Adresse",
     "notes": "Notes"
   },
+  "passwordFeedback": {
+    "tooShort": "Trop court, {count, plural, one {encore # caractère} other {encore # caractères}}",
+    "tooLong": "Trop long, {count, plural, one {# caractère} other {# caractères}} au-delà de la limite de {max}",
+    "ok": "Mot de passe OK",
+    "mismatch": "Ne correspond pas au mot de passe ci-dessus",
+    "match": "Les mots de passe correspondent"
+  },
   "errors": {
     "unexpected": "Une erreur inattendue s'est produite. Veuillez réessayer.",
     "error": "Erreur"

+ 7 - 0
messages/it/common.json

@@ -31,6 +31,13 @@
     "address": "Indirizzo",
     "notes": "Note"
   },
+  "passwordFeedback": {
+    "tooShort": "Troppo corta, {count, plural, one {manca # carattere} other {mancano # caratteri}}",
+    "tooLong": "Troppo lunga, {count, plural, one {# carattere} other {# caratteri}} oltre il limite di {max}",
+    "ok": "Password OK",
+    "mismatch": "Non corrisponde alla password sopra",
+    "match": "Le password corrispondono"
+  },
   "errors": {
     "unexpected": "Si è verificato un errore imprevisto. La preghiamo di riprovare.",
     "error": "Errore"

+ 7 - 0
messages/lt/common.json

@@ -31,6 +31,13 @@
     "address": "Adresas",
     "notes": "Pastabos"
   },
+  "passwordFeedback": {
+    "tooShort": "Per trumpas, {count, plural, one {trūksta # simbolio} few {trūksta # simbolių} other {trūksta # simbolių}}",
+    "tooLong": "Per ilgas, {count, plural, one {# simboliu} few {# simboliais} other {# simbolių}} viršija {max} simbolių ribą",
+    "ok": "Slaptažodis tinka",
+    "mismatch": "Nesutampa su aukščiau įvestu slaptažodžiu",
+    "match": "Slaptažodžiai sutampa"
+  },
   "errors": {
     "unexpected": "Įvyko netikėta klaida. Bandykite dar kartą.",
     "error": "Klaida"

+ 7 - 0
messages/nb/common.json

@@ -31,6 +31,13 @@
     "address": "Adresse",
     "notes": "Notater"
   },
+  "passwordFeedback": {
+    "tooShort": "For kort, {count, plural, one {# tegn til} other {# tegn til}}",
+    "tooLong": "For langt, {count, plural, one {# tegn} other {# tegn}} over grensen på {max} tegn",
+    "ok": "Passordet er OK",
+    "mismatch": "Samsvarer ikke med passordet over",
+    "match": "Passordene samsvarer"
+  },
   "errors": {
     "unexpected": "En uventet feil oppstod. Vennligst prøv igjen.",
     "error": "Feil"

+ 7 - 0
messages/nl/common.json

@@ -31,6 +31,13 @@
     "address": "Adres",
     "notes": "Notities"
   },
+  "passwordFeedback": {
+    "tooShort": "Te kort, {count, plural, one {nog # teken} other {nog # tekens}}",
+    "tooLong": "Te lang, {count, plural, one {# teken} other {# tekens}} boven de limiet van {max}",
+    "ok": "Wachtwoord OK",
+    "mismatch": "Komt niet overeen met het wachtwoord hierboven",
+    "match": "Wachtwoorden komen overeen"
+  },
   "errors": {
     "unexpected": "Er is een onverwachte fout opgetreden. Probeer het opnieuw.",
     "error": "Fout"

+ 7 - 0
messages/pl/common.json

@@ -31,6 +31,13 @@
     "address": "Adres",
     "notes": "Notatki"
   },
+  "passwordFeedback": {
+    "tooShort": "Za krótkie, {count, plural, one {brakuje # znaku} few {brakuje # znaków} many {brakuje # znaków} other {brakuje # znaku}}",
+    "tooLong": "Za długie, {count, plural, one {# znak} few {# znaki} many {# znaków} other {# znaku}} ponad limit {max} znaków",
+    "ok": "Hasło OK",
+    "mismatch": "Nie pasuje do hasła powyżej",
+    "match": "Hasła są zgodne"
+  },
   "errors": {
     "unexpected": "Wystąpił nieoczekiwany błąd. Spróbuj ponownie.",
     "error": "Błąd"

+ 7 - 0
messages/pt-BR/common.json

@@ -31,6 +31,13 @@
     "address": "Endereço",
     "notes": "Observações"
   },
+  "passwordFeedback": {
+    "tooShort": "Muito curta, {count, plural, one {falta # caractere} other {faltam # caracteres}}",
+    "tooLong": "Muito longa, {count, plural, one {# caractere} other {# caracteres}} acima do limite de {max}",
+    "ok": "Senha OK",
+    "mismatch": "Não confere com a senha acima",
+    "match": "As senhas conferem"
+  },
   "errors": {
     "unexpected": "Ocorreu um erro inesperado. Por favor, tente novamente.",
     "error": "Erro"

+ 7 - 0
messages/pt-PT/common.json

@@ -31,6 +31,13 @@
     "address": "Morada",
     "notes": "Observações"
   },
+  "passwordFeedback": {
+    "tooShort": "Demasiado curta, {count, plural, one {falta # carácter} other {faltam # caracteres}}",
+    "tooLong": "Demasiado longa, {count, plural, one {# carácter} other {# caracteres}} acima do limite de {max}",
+    "ok": "Palavra-passe OK",
+    "mismatch": "Não coincide com a palavra-passe acima",
+    "match": "As palavras-passe coincidem"
+  },
   "errors": {
     "unexpected": "Ocorreu um erro inesperado. Tente novamente.",
     "error": "Erro"

+ 7 - 0
messages/ru/common.json

@@ -31,6 +31,13 @@
     "address": "Адрес",
     "notes": "Заметки"
   },
+  "passwordFeedback": {
+    "tooShort": "Слишком короткий, {count, plural, one {ещё # символ} few {ещё # символа} many {ещё # символов} other {ещё # символа}}",
+    "tooLong": "Слишком длинный, {count, plural, one {на # символ} few {на # символа} many {на # символов} other {на # символа}} больше лимита в {max}",
+    "ok": "Пароль подходит",
+    "mismatch": "Не совпадает с паролем выше",
+    "match": "Пароли совпадают"
+  },
   "errors": {
     "unexpected": "Произошла непредвиденная ошибка. Пожалуйста, попробуйте снова.",
     "error": "Ошибка"

+ 7 - 0
messages/tr/common.json

@@ -31,6 +31,13 @@
     "address": "Adres",
     "notes": "Notlar"
   },
+  "passwordFeedback": {
+    "tooShort": "Çok kısa, {count, plural, one {# karakter daha} other {# karakter daha}}",
+    "tooLong": "Çok uzun, {max} karakter sınırını {count, plural, one {# karakter} other {# karakter}} aşıyor",
+    "ok": "Şifre uygun",
+    "mismatch": "Yukarıdaki şifreyle eşleşmiyor",
+    "match": "Şifreler eşleşiyor"
+  },
   "errors": {
     "unexpected": "Beklenmeyen bir hata oluştu. Lütfen tekrar deneyin.",
     "error": "Hata"

+ 1 - 0
src/__tests__/auth/reset-password-validation.test.tsx

@@ -20,6 +20,7 @@ vi.mock('next/link', () => ({
 // Mock lucide-react icons used in the component
 vi.mock('lucide-react', () => ({
   Gauge: () => <svg data-testid="icon-gauge" />,
+  CheckCircle2: () => <svg data-testid="icon-check" />,
   Loader2: () => <svg data-testid="icon-loader" />,
   XCircle: () => <svg data-testid="icon-xcircle" />,
 }))

+ 110 - 0
src/__tests__/components/password-feedback.test.tsx

@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { PasswordFeedback, PasswordMatchFeedback } from '@/components/password-feedback'
+import { checkPassword, PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH } from '@/lib/password-rules'
+
+function NewPasswordForm({ hint }: { hint?: string }) {
+  const [password, setPassword] = useState('')
+  const [confirmation, setConfirmation] = useState('')
+  return (
+    <>
+      <label htmlFor="pw">New password</label>
+      <input
+        id="pw"
+        type="password"
+        value={password}
+        onChange={(e) => setPassword(e.target.value)}
+        aria-describedby="pw-feedback"
+      />
+      <PasswordFeedback id="pw-feedback" password={password} hint={hint} />
+      <label htmlFor="confirm">Confirm password</label>
+      <input
+        id="confirm"
+        type="password"
+        value={confirmation}
+        onChange={(e) => setConfirmation(e.target.value)}
+        aria-describedby="confirm-feedback"
+      />
+      <PasswordMatchFeedback
+        id="confirm-feedback"
+        password={password}
+        confirmation={confirmation}
+      />
+    </>
+  )
+}
+
+describe('password rules', () => {
+  it('are the limits the server enforces: 8 to 128 characters, nothing else', () => {
+    expect(PASSWORD_MIN_LENGTH).toBe(8)
+    expect(PASSWORD_MAX_LENGTH).toBe(128)
+    expect(checkPassword('')).toEqual({ status: 'empty' })
+    expect(checkPassword('abc')).toEqual({ status: 'tooShort', remaining: 5 })
+    expect(checkPassword('aaaaaaaa')).toEqual({ status: 'ok' })
+    expect(checkPassword('a'.repeat(128))).toEqual({ status: 'ok' })
+    expect(checkPassword('a'.repeat(130))).toEqual({ status: 'tooLong', over: 2 })
+  })
+})
+
+describe('PasswordFeedback', () => {
+  it('shows nothing while the field is empty', () => {
+    render(<NewPasswordForm />)
+    expect(document.getElementById('pw-feedback')).toBeEmptyDOMElement()
+    expect(document.getElementById('confirm-feedback')).toBeEmptyDOMElement()
+  })
+
+  it('shows the hint it is given while the field is empty', () => {
+    render(<NewPasswordForm hint="Must be at least 8 characters" />)
+    expect(screen.getByLabelText('New password')).toHaveAccessibleDescription(
+      'Must be at least 8 characters'
+    )
+  })
+
+  it('counts down the characters still needed while too short', async () => {
+    const user = userEvent.setup()
+    render(<NewPasswordForm hint="Must be at least 8 characters" />)
+    const input = screen.getByLabelText('New password')
+    await user.type(input, 'abc')
+    expect(input).toHaveAccessibleDescription('Too short, 5 more characters')
+    await user.type(input, 'defg')
+    expect(input).toHaveAccessibleDescription('Too short, 1 more character')
+  })
+
+  it('confirms once the password is long enough', async () => {
+    const user = userEvent.setup()
+    render(<NewPasswordForm />)
+    const input = screen.getByLabelText('New password')
+    await user.type(input, 'abcdefgh')
+    expect(input).toHaveAccessibleDescription('Password OK')
+  })
+
+  it('says when a pasted password is over the limit', async () => {
+    const user = userEvent.setup()
+    render(<NewPasswordForm />)
+    const input = screen.getByLabelText('New password')
+    await user.click(input)
+    await user.paste('a'.repeat(PASSWORD_MAX_LENGTH + 3))
+    expect(input).toHaveAccessibleDescription('Too long, 3 characters over the 128-character limit')
+  })
+
+  it('is a polite live region', () => {
+    render(<NewPasswordForm />)
+    expect(document.getElementById('pw-feedback')).toHaveAttribute('aria-live', 'polite')
+    expect(document.getElementById('confirm-feedback')).toHaveAttribute('aria-live', 'polite')
+  })
+})
+
+describe('PasswordMatchFeedback', () => {
+  it('says whether the confirmation matches', async () => {
+    const user = userEvent.setup()
+    render(<NewPasswordForm />)
+    await user.type(screen.getByLabelText('New password'), 'abcdefgh')
+    const confirm = screen.getByLabelText('Confirm password')
+    await user.type(confirm, 'abcd')
+    expect(confirm).toHaveAccessibleDescription('Does not match the password above')
+    await user.type(confirm, 'efgh')
+    expect(confirm).toHaveAccessibleDescription('Passwords match')
+  })
+})

+ 12 - 0
src/__tests__/features/settings/account-set-password.test.tsx

@@ -148,6 +148,18 @@ describe('an account that signed up with Google and has no password', () => {
     expect(screen.getByRole('button', { name: 'Sign in again' })).toBeEnabled()
   })
 
+  it('says while typing whether the new password is long enough and the two match', () => {
+    renderPage(false)
+    const next = screen.getByLabelText('New Password')
+    const confirm = screen.getByLabelText('Confirm New Password')
+    typePasswords('short', 'sho')
+    expect(next).toHaveAccessibleDescription('Too short, 3 more characters')
+    expect(confirm).toHaveAccessibleDescription('Does not match the password above')
+    typePasswords('long enough')
+    expect(next).toHaveAccessibleDescription('Password OK')
+    expect(confirm).toHaveAccessibleDescription('Passwords match')
+  })
+
   it('sends nothing when the two passwords differ', () => {
     renderPage(false)
     typePasswords('correct horse battery', 'correct horse batteri')

+ 10 - 1
src/app/(authenticated)/settings/account/account-settings.tsx

@@ -46,6 +46,7 @@ import { signInUrlFor } from '@/lib/signed-out'
 import { useCooldown } from '@/hooks/use-cooldown'
 import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
+import { PasswordFeedback, PasswordMatchFeedback } from '@/components/password-feedback'
 
 export function AccountSettings({
   twoFactorEnabled: initialTwoFactorEnabled,
@@ -250,7 +251,7 @@ export function AccountSettings({
       toast.error(t('account.passwordsNoMatch'))
       return
     }
-    if (newPassword.length < 8) {
+    if (newPassword.length < PASSWORD_MIN_LENGTH) {
       toast.error(t('account.passwordMinLength'))
       return
     }
@@ -482,7 +483,9 @@ export function AccountSettings({
               autoComplete="new-password"
               value={newPassword}
               onChange={(e) => setNewPassword(e.target.value)}
+              aria-describedby="newPassword-feedback"
             />
+            <PasswordFeedback id="newPassword-feedback" password={newPassword} />
           </div>
           <div className="space-y-2">
             <Label htmlFor="confirmPassword">{t('account.confirmNewPassword')}</Label>
@@ -492,6 +495,12 @@ export function AccountSettings({
               autoComplete="new-password"
               value={confirmPassword}
               onChange={(e) => setConfirmPassword(e.target.value)}
+              aria-describedby="confirmPassword-feedback"
+            />
+            <PasswordMatchFeedback
+              id="confirmPassword-feedback"
+              password={newPassword}
+              confirmation={confirmPassword}
             />
           </div>
         </div>

+ 15 - 3
src/app/(public)/auth/reset-password/page.tsx

@@ -10,6 +10,8 @@ import { Input } from '@/components/ui/input'
 import { Label } from '@/components/ui/label'
 import { Loader2, XCircle } from 'lucide-react'
 import { AuthLogo } from '@/components/auth-logo'
+import { PasswordFeedback, PasswordMatchFeedback } from '@/components/password-feedback'
+import { PASSWORD_MIN_LENGTH } from '@/lib/password-rules'
 
 function ResetPasswordInner() {
   const t = useTranslations('auth.resetPassword')
@@ -31,7 +33,7 @@ function ResetPasswordInner() {
       return
     }
 
-    if (newPassword.length < 8) {
+    if (newPassword.length < PASSWORD_MIN_LENGTH) {
       setError(t('errors.passwordTooShort'))
       return
     }
@@ -99,9 +101,12 @@ function ResetPasswordInner() {
             value={newPassword}
             onChange={(e) => setNewPassword(e.target.value)}
             required
-            minLength={8}
+            minLength={PASSWORD_MIN_LENGTH}
+            autoComplete="new-password"
+            aria-describedby="new-password-feedback"
             className="h-11 bg-background/50"
           />
+          <PasswordFeedback id="new-password-feedback" password={newPassword} />
         </div>
 
         <div className="space-y-2">
@@ -113,9 +118,16 @@ function ResetPasswordInner() {
             value={confirmPassword}
             onChange={(e) => setConfirmPassword(e.target.value)}
             required
-            minLength={8}
+            minLength={PASSWORD_MIN_LENGTH}
+            autoComplete="new-password"
+            aria-describedby="confirm-password-feedback"
             className="h-11 bg-background/50"
           />
+          <PasswordMatchFeedback
+            id="confirm-password-feedback"
+            password={newPassword}
+            confirmation={confirmPassword}
+          />
         </div>
 
         <Button type="submit" className="h-11 w-full" disabled={loading}>

+ 5 - 2
src/app/(public)/auth/sign-up/sign-up-form.tsx

@@ -18,6 +18,8 @@ import { TERMS_URL } from '@/lib/marketing-urls'
 import { acceptInvitation } from '@/features/team/Actions/acceptInvitation'
 import { track } from '@/lib/analytics'
 import { takeHandedEmail } from '@/lib/auth-email-handoff'
+import { PasswordFeedback } from '@/components/password-feedback'
+import { PASSWORD_MIN_LENGTH } from '@/lib/password-rules'
 
 export function SignUpForm({
   inviteToken,
@@ -267,11 +269,12 @@ export function SignUpForm({
               value={password}
               onChange={(e) => setPassword(e.target.value)}
               required
-              minLength={8}
+              minLength={PASSWORD_MIN_LENGTH}
               autoComplete="new-password"
+              aria-describedby="password-feedback"
               className="h-11 bg-background/50"
             />
-            <p className="text-xs text-muted-foreground">{t('passwordHint')}</p>
+            <PasswordFeedback id="password-feedback" password={password} hint={t('passwordHint')} />
           </div>
 
           <div

+ 142 - 0
src/components/password-feedback.tsx

@@ -0,0 +1,142 @@
+'use client'
+
+import { CheckCircle2 } from 'lucide-react'
+import { useTranslations } from 'next-intl'
+import type { ReactNode } from 'react'
+import { checkPassword, PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH } from '@/lib/password-rules'
+import { cn } from '@/lib/utils'
+
+/**
+ * The line under a new-password field that says, while the person types,
+ * whether the server will take it. It states the rules in
+ * `src/lib/password-rules.ts` and nothing else.
+ *
+ * The line is always rendered and keeps the height of its longest message,
+ * so the form does not jump as the text changes. It is a polite live
+ * region: point the input's `aria-describedby` at `id`. A password manager filling the field goes
+ * through the same `value`, so it gets the same answer.
+ *
+ * Not met yet is a hint in the muted colour, not an error: the person has
+ * not finished typing. Met is a check icon and words, never colour alone.
+ */
+export function PasswordFeedback({
+  id,
+  password,
+  hint,
+  className,
+}: {
+  id: string
+  password: string
+  /** Shown while the field is empty, for a form that already states the rule up front. */
+  hint?: ReactNode
+  className?: string
+}) {
+  const t = useTranslations('common.passwordFeedback')
+  const check = checkPassword(password)
+
+  let content: ReactNode = hint ? <Hint>{hint}</Hint> : null
+  if (check.status === 'tooShort') {
+    content = <Hint>{t('tooShort', { count: check.remaining })}</Hint>
+  } else if (check.status === 'tooLong') {
+    content = <Hint>{t('tooLong', { count: check.over, max: PASSWORD_MAX_LENGTH })}</Hint>
+  } else if (check.status === 'ok') {
+    content = <Met>{t('ok')}</Met>
+  }
+
+  // Every message this line can show, laid under the visible one so the line
+  // is always as tall as the longest of them at this width and in this
+  // language. A long message that wraps then moves nothing below it.
+  const sizers = [
+    hint ? <Hint key="hint">{hint}</Hint> : null,
+    <Hint key="short">{t('tooShort', { count: PASSWORD_MIN_LENGTH - 1 })}</Hint>,
+    <Hint key="long">{t('tooLong', { count: 100, max: PASSWORD_MAX_LENGTH })}</Hint>,
+    <Met key="ok">{t('ok')}</Met>,
+  ]
+
+  return (
+    <Line id={id} className={className} sizers={sizers}>
+      {content}
+    </Line>
+  )
+}
+
+/**
+ * The same line under a confirm-password field: nothing until something is
+ * typed in it, then whether it matches the password.
+ */
+export function PasswordMatchFeedback({
+  id,
+  password,
+  confirmation,
+  className,
+}: {
+  id: string
+  password: string
+  confirmation: string
+  className?: string
+}) {
+  const t = useTranslations('common.passwordFeedback')
+
+  let content: ReactNode = null
+  if (confirmation.length > 0) {
+    content = confirmation === password ? <Met>{t('match')}</Met> : <Hint>{t('mismatch')}</Hint>
+  }
+
+  const sizers = [<Met key="match">{t('match')}</Met>, <Hint key="mismatch">{t('mismatch')}</Hint>]
+
+  return (
+    <Line id={id} className={className} sizers={sizers}>
+      {content}
+    </Line>
+  )
+}
+
+/**
+ * One grid cell holding the visible message and, invisibly, every message it
+ * could show. The cell takes the height of the tallest. Only the visible
+ * layer carries the id and the live region, so the input's description and
+ * what a screen reader announces are the message alone.
+ */
+function Line({
+  id,
+  className,
+  sizers,
+  children,
+}: {
+  id: string
+  className?: string
+  sizers: ReactNode[]
+  children: ReactNode
+}) {
+  const layer = 'col-start-1 row-start-1 flex min-h-4 items-start gap-1.5'
+  return (
+    <div className={cn('grid text-xs leading-4', className)}>
+      {sizers.map((sizer, i) =>
+        sizer ? (
+          <div key={i} aria-hidden="true" className={cn(layer, 'invisible')}>
+            {sizer}
+          </div>
+        ) : null
+      )}
+      <p id={id} aria-live="polite" className={layer}>
+        {children}
+      </p>
+    </div>
+  )
+}
+
+function Hint({ children }: { children: ReactNode }) {
+  return <span className="text-muted-foreground">{children}</span>
+}
+
+function Met({ children }: { children: ReactNode }) {
+  return (
+    <>
+      <CheckCircle2
+        aria-hidden="true"
+        className="mt-px size-3.5 shrink-0 text-emerald-700 dark:text-emerald-400"
+      />
+      <span className="font-medium text-emerald-700 dark:text-emerald-400">{children}</span>
+    </>
+  )
+}

+ 2 - 3
src/features/settings/Schema/accountPassword.ts

@@ -1,8 +1,7 @@
 import { z } from 'zod'
+import { PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH } from '@/lib/password-rules'
 
-/** Better Auth's own limits (its defaults; `src/lib/auth.ts` sets neither). */
-export const PASSWORD_MIN_LENGTH = 8
-export const PASSWORD_MAX_LENGTH = 128
+export { PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH }
 
 export const setAccountPasswordSchema = z.object({
   newPassword: z.string().min(PASSWORD_MIN_LENGTH).max(PASSWORD_MAX_LENGTH),

+ 30 - 0
src/lib/password-rules.ts

@@ -0,0 +1,30 @@
+/**
+ * What the server accepts as a new password, in one place for every form
+ * that sets one.
+ *
+ * These are Better Auth's own limits: `src/lib/auth.ts` sets neither
+ * `minPasswordLength` nor `maxPasswordLength`, so its defaults of 8 and 128
+ * apply to sign-up, reset, change and set password alike. Better Auth
+ * measures with `password.length`, and so does this file. There are no
+ * other rules (no character classes, no strength score); the forms say
+ * exactly this and nothing more.
+ */
+export const PASSWORD_MIN_LENGTH = 8
+export const PASSWORD_MAX_LENGTH = 128
+
+export type PasswordCheck =
+  | { status: 'empty' }
+  | { status: 'tooShort'; remaining: number }
+  | { status: 'tooLong'; over: number }
+  | { status: 'ok' }
+
+export function checkPassword(password: string): PasswordCheck {
+  if (password.length === 0) return { status: 'empty' }
+  if (password.length < PASSWORD_MIN_LENGTH) {
+    return { status: 'tooShort', remaining: PASSWORD_MIN_LENGTH - password.length }
+  }
+  if (password.length > PASSWORD_MAX_LENGTH) {
+    return { status: 'tooLong', over: password.length - PASSWORD_MAX_LENGTH }
+  }
+  return { status: 'ok' }
+}