Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

3.1 KB
Raw Blame
import { LemonDivider } from '@posthog/lemon-ui'

import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
import { Tooltip } from 'lib/lemon-ui/Tooltip'

export type ValidatedPasswordResult = {
    score: number // 0 is no passsword - otherwise 1-5,
    feedback?: string
}

let zxcvbnFn: ((password: string) => { score: number; feedback: { warning: string } }) | null = null
let zxcvbnLoading = false

const PASSWORD_NEXT_STEP = "Try a longer password that isn't a common word or pattern."

// zxcvbn's suggestions assume passphrases ("Add another word or two"), so only its warning is
// shown, which names the weakness it found
function weakPasswordFeedback(warning: string): string {
    return warning ? `${warning}. ${PASSWORD_NEXT_STEP}` : `This password is too easy to guess. ${PASSWORD_NEXT_STEP}`
}

// We load zxcvbn asynchronously as it's a large dependency and we don't want to block the main thread
function ensureZxcvbnLoaded(): void {
    if (!zxcvbnFn && !zxcvbnLoading) {
        zxcvbnLoading = true
        void import('zxcvbn')
            .then(({ default: zxcvbn }) => {
                zxcvbnFn = zxcvbn
            })
            .catch(() => {
                zxcvbnLoading = false
            })
    }
}

export function validatePassword(password: string = ''): ValidatedPasswordResult {
    ensureZxcvbnLoaded()

    if (password.length > 72) {
        return {
            score: 0,
            feedback: 'Maximum 72 characters',
        }
    }

    if (password.length > 0 && password.length < 8) {
        return {
            score: 2,
            feedback: 'Must be at least 8 characters long',
        }
    }

    if (!password) {
        return { score: 0 }
    }

    if (!zxcvbnFn) {
        // Return basic length-based validation while zxcvbn is loading
        return { score: 3, feedback: '' }
    }

    const result = zxcvbnFn(password)

    return {
        score: result.score + 1,
        feedback: result.score < 3 ? weakPasswordFeedback(result.feedback.warning) : '',
    }
}

export default function PasswordStrength({
    validatedPassword,
}: {
    validatedPassword: ValidatedPasswordResult
}): JSX.Element {
    const { score, feedback } = validatedPassword

    return (
        <Tooltip
            title={
                <>
                    Your password scores a{' '}
                    <strong className="flex gap-x-0.5">
                        <span>{score}</span>
                        <span>/</span>
                        <span>5</span>
                    </strong>
                    {feedback ? (
                        <>
                            <LemonDivider />
                            {feedback}
                        </>
                    ) : (
                        <> 💪 Nice!</>
                    )}
                </>
            }
        >
            <span className="w-20">
                <LemonProgress
                    percent={score * 20}
                    strokeColor={score <= 2 ? 'var(--danger)' : score <= 3 ? 'var(--warning)' : 'var(--success)'}
                />
            </span>
        </Tooltip>
    )
}