{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "password-strength",
  "title": "Password strength",
  "description": "How strong a new password is while it is typed: the Meter’s bar, the level in words, and the rules the form asks for, each ticked as it is met. A screen reader hears the level once typing pauses.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/meter.json",
    "https://kinoui.com/r/checkbox.json",
    "https://kinoui.com/r/choice.json",
    "https://kinoui.com/r/announce.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/password-strength.tsx",
      "content": "'use client'\n\nimport { CheckboxMark } from '@/registry/components/kino/checkbox'\nimport { Meter, MeterLabel, MeterValue } from '@/registry/components/kino/meter'\nimport { announce } from '@/registry/lib/announce'\nimport { choiceMarkBoxClassName } from '@/registry/lib/choice'\nimport { graphemes, Swap } from '@/registry/lib/swap'\nimport { FieldDescription, useFieldControl } from '@ui-sdk/react/field'\nimport { type ComponentProps, type ReactNode, useEffect, useRef } from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/** A rule the password must meet, ticked while `met` returns true. */\ntype PasswordRule = {\n  label: ReactNode\n  met: (password: string) => boolean\n}\n\n/** How long typing has to pause before the strength is read out, in milliseconds. */\nconst ANNOUNCE_WAIT = 1000\n\n/*\n * How strong a new password is while it is typed: the Meter's bar under the\n * password box, the level in words, and the rules the form asks for, each\n * ticked as it is met. Weak warns in red, Fair in amber, and Good and Strong\n * are green. A screen reader hears the level once typing pauses, and the\n * rules describe the box inside a Field.\n */\nfunction PasswordStrength({\n  className,\n  value,\n  userInputs,\n  score,\n  rules,\n  label = 'Password strength',\n  levels = ['Weak', 'Fair', 'Good', 'Strong'],\n  emptyLabel = 'Nothing typed yet',\n  metLabel = 'Done',\n  ...props\n}: Omit<ComponentProps<'div'>, 'children'> & {\n  /** The password as it is typed. */\n  value: string\n  /** What the person typed elsewhere, such as their name and email, and your product's name: a password built on them is weaker. */\n  userInputs?: readonly string[]\n  /** Your own score from 0 to 4, such as zxcvbn's, in place of Kino's estimate. */\n  score?: number\n  /** The rules the form asks for, listed under the bar. */\n  rules?: readonly PasswordRule[]\n  /** Names the meter, and starts what a screen reader hears. */\n  label?: string\n  /** The words for each level, weakest first. */\n  levels?: readonly [string, string, string, string]\n  /** What a screen reader hears for the level while the box is empty. */\n  emptyLabel?: string\n  /** Read after a rule that is met. */\n  metLabel?: string\n}) {\n  const level = value\n    ? strengthLevel(score ?? estimatePasswordScore(value, userInputs))\n    : null\n  const word = level === null ? null : levels[level]\n\n  const announced = useRef(word)\n  const said = `${label}: ${word ?? emptyLabel}`\n  useEffect(() => {\n    if (announced.current === word) return undefined\n    const timer = setTimeout(() => {\n      announced.current = word\n      announce(said)\n    }, ANNOUNCE_WAIT)\n    return () => clearTimeout(timer)\n  })\n\n  const inField = useFieldControl() !== null\n  const rulesClassName = 'flex flex-col gap-1.5 text-xs'\n  const ruleItems = rules?.map((rule, index) => {\n    const met = rule.met(value)\n    return (\n      <li\n        key={index}\n        data-slot='password-strength-rule'\n        data-met={met || undefined}\n        className='text-muted-foreground data-met:text-foreground flex items-start gap-2 leading-4 transition-colors duration-(--motion-press-duration) ease-(--motion-press-fade-easing)'\n      >\n        <span\n          aria-hidden\n          data-checked={met || undefined}\n          className={cn(choiceMarkBoxClassName, 'group/checkbox')}\n        >\n          <CheckboxMark />\n        </span>\n        <span className='min-w-0 [overflow-wrap:anywhere]'>\n          {rule.label}\n          {met ? <span className='sr-only'>, {metLabel}</span> : null}\n        </span>\n      </li>\n    )\n  })\n\n  return (\n    <div\n      data-slot='password-strength'\n      data-level={level ?? undefined}\n      className={cn(\n        'group/password-strength flex min-w-0 flex-col gap-3 pt-3 [grid-area:detail] data-[level=1]:**:data-[slot=meter-indicator]:bg-warning data-[level=2]:**:data-[slot=meter-indicator]:bg-success data-[level=3]:**:data-[slot=meter-indicator]:bg-success',\n        className,\n      )}\n      {...props}\n    >\n      <Meter\n        value={level === null ? 0 : level + 1}\n        max={4}\n        low={2}\n        getValueLabel={() => word ?? emptyLabel}\n      >\n        <MeterLabel className='text-muted-foreground text-xs font-normal'>\n          {label}\n        </MeterLabel>\n        <MeterValue className='group-data-[level=1]/password-strength:text-warning-foreground group-data-[level=2]/password-strength:text-success-foreground group-data-[level=3]/password-strength:text-success-foreground text-xs font-medium'>\n          {() => (\n            <Swap roll align='end'>\n              {word ?? ''}\n            </Swap>\n          )}\n        </MeterValue>\n      </Meter>\n      {rules?.length ? (\n        inField ? (\n          // In a Field, the rules describe its password box.\n          <FieldDescription render={<ul />} className={rulesClassName}>\n            {ruleItems}\n          </FieldDescription>\n        ) : (\n          <ul data-slot='password-strength-rules' className={rulesClassName}>\n            {ruleItems}\n          </ul>\n        )\n      ) : null}\n    </div>\n  )\n}\n\n/** A 0 to 4 score, zxcvbn's scale, as a level: 0 and 1 are Weak, then Fair, Good and Strong. */\nfunction strengthLevel(score: number): 0 | 1 | 2 | 3 {\n  if (score >= 4) return 3\n  if (score >= 3) return 2\n  if (score >= 2) return 1\n  return 0\n}\n\n/*\n * Passwords and words that are guessed first. Each counts as one guess from a\n * short list, wherever it sits in a password, after look-alike characters\n * are read as letters (\"p@ssw0rd\" is \"password\").\n */\nconst COMMON_WORDS = [\n  'password',\n  'passwort',\n  '1q2w3e4r5t6y',\n  '1q2w3e4r',\n  'q1w2e3r4',\n  '1qaz2wsx3edc',\n  '1qaz2wsx',\n  'qazwsxedcrfv',\n  'qazwsxedc',\n  'zaq12wsx',\n  'qazwsx',\n  'qweasd',\n  'basketball',\n  'letmein',\n  'welcome',\n  'admin',\n  'login',\n  'master',\n  'secret',\n  'changeme',\n  'default',\n  'iloveyou',\n  'trustno',\n  'monkey',\n  'dragon',\n  'shadow',\n  'sunshine',\n  'princess',\n  'football',\n  'baseball',\n  'soccer',\n  'hockey',\n  'superman',\n  'batman',\n  'starwars',\n  'pokemon',\n  'minecraft',\n  'freedom',\n  'whatever',\n  'hello',\n  'qwerty',\n  'azerty',\n  'qwertz',\n  'asdf',\n  'zxcv',\n  'abc',\n  'love',\n  'angel',\n  'cookie',\n  'cheese',\n  'chicken',\n  'banana',\n  'orange',\n  'purple',\n  'summer',\n  'winter',\n  'spring',\n  'autumn',\n  'flower',\n  'hunter',\n  'ranger',\n  'killer',\n  'charlie',\n  'michael',\n  'jennifer',\n  'jordan',\n  'thomas',\n  'robert',\n  'daniel',\n  'jessica',\n  'ashley',\n  'pepper',\n  'ginger',\n  'maggie',\n  'tigger',\n  'buster',\n  'matrix',\n  'computer',\n  'internet',\n  'money',\n  'guest',\n  'user',\n  'test',\n  'root',\n  'god',\n  'access',\n  'mustang',\n  'harley',\n  'ninja',\n  'blink',\n] as const\n\nconst KEYBOARD_ROWS = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm', '1234567890'] as const\n\nconst LOOK_ALIKES: Record<string, string> = {\n  '0': 'o',\n  '1': 'i',\n  '3': 'e',\n  '4': 'a',\n  '5': 's',\n  '7': 't',\n  '@': 'a',\n  $: 's',\n  '!': 'i',\n}\n\n/** Each character in lower case, one for one, so places in the result are places in the password. */\nfunction lowerChars(text: string) {\n  return graphemes(text).map((char) => {\n    const lower = char.toLowerCase()\n    return graphemes(lower).length === 1 ? lower : char\n  })\n}\n\n/** The password in lower case, with look-alike characters read as the letters they stand for. */\nfunction readAsLetters(text: string) {\n  return lowerChars(text).map((char) => LOOK_ALIKES[char] ?? char)\n}\n\n/** Whether `a` then `b` repeat or step through the alphabet, the digits or a keyboard row. */\nfunction follows(a: string, b: string) {\n  if (a === b) return true\n  const step = b.charCodeAt(0) - a.charCodeAt(0)\n  if ((step === 1 || step === -1) && /[a-z\\d]/.test(a + b)) return true\n  return KEYBOARD_ROWS.some((row) => {\n    const at = row.indexOf(a)\n    return at !== -1 && (row[at + 1] === b || row[at - 1] === b)\n  })\n}\n\n/** The words of three letters or more in what the person typed elsewhere, read as `readAsLetters` reads a password. */\nfunction ownWords(userInputs: readonly string[]) {\n  return userInputs\n    .flatMap((input) => input.split(/[^\\p{L}\\p{N}]+/u))\n    .filter((part) => graphemes(part).length >= 3)\n    .map((part) => readAsLetters(part).join(''))\n}\n\n/**\n * Whether the password holds a word of three letters or more from what the\n * person typed elsewhere, such as their name, their email or the product's\n * name, with look-alikes read as letters (\"M@yaCh3n\" holds \"maya\").\n */\nfunction usesUserInputs(password: string, userInputs: readonly string[]) {\n  const read = readAsLetters(password).join('')\n  return ownWords(userInputs).some((word) => read.includes(word))\n}\n\n/** What a character no pattern explains costs a guesser, in bits: one of ten, as zxcvbn counts it, so mixing in capitals and symbols earns nothing on its own. */\nconst CHAR_BITS = Math.log2(10)\n\n/**\n * About how many bits a guesser has to get through, in the way zxcvbn counts\n * them but much smaller: a known word or one of the person's own counts as\n * one pick from a short list, a run that repeats or steps (`aaaa`, `1234`,\n * `qwer`) or a year as a handful of guesses, and every other character as\n * `CHAR_BITS`.\n */\nfunction passwordBits(password: string, userInputs: readonly string[] = []) {\n  // Runs are read as typed, so \"123456\" steps rather than reading as letters.\n  const typed = lowerChars(password)\n  const read = readAsLetters(password).join('')\n  const counted = typed.map(() => false)\n  let bits = 0\n\n  const own = ownWords(userInputs)\n  const words = [\n    ...own.map((word) => ({ word, bits: 4 })),\n    ...COMMON_WORDS.map((word) => ({ word, bits: 8 })),\n  ]\n  // Longest first, so \"password\" is found before \"pass\" could be.\n  words.sort((a, b) => b.word.length - a.word.length)\n  // A block typed again (\"elephantelephant\") costs its first copy and a guess at how many times.\n  const asTyped = typed.join('')\n  const repeats = /(.{3,})\\1+/gu\n  for (let match = repeats.exec(asTyped); match; match = repeats.exec(asTyped)) {\n    const start = graphemes(asTyped.slice(0, match.index)).length\n    const copy = graphemes(match[1]!).length\n    const all = graphemes(match[0]).length\n    counted.fill(true, start + copy, start + all)\n    bits += Math.log2(all / copy)\n  }\n\n  // Words are found with look-alikes read as letters, and as typed, for keyboard walks such as \"1q2w3e4r\".\n  for (const { word, bits: wordBits } of words) {\n    for (const text of [read, asTyped]) {\n      let from = text.indexOf(word)\n      while (from !== -1) {\n        const span = graphemes(text.slice(0, from)).length\n        const length = graphemes(word).length\n        if (!counted.slice(span, span + length).some(Boolean)) {\n          counted.fill(true, span, span + length)\n          bits += wordBits\n        }\n        from = text.indexOf(word, from + 1)\n      }\n    }\n  }\n\n  // Years as typed, since look-alikes would read \"2026\" as \"2o26\".\n  const years = /(?:19|20)\\d\\d/g\n  for (let match = years.exec(asTyped); match; match = years.exec(asTyped)) {\n    const span = graphemes(asTyped.slice(0, match.index)).length\n    if (!counted.slice(span, span + 4).some(Boolean)) {\n      counted.fill(true, span, span + 4)\n      bits += 7\n    }\n  }\n\n  let index = 0\n  while (index < typed.length) {\n    if (counted[index]) {\n      index += 1\n      continue\n    }\n    let end = index + 1\n    while (end < typed.length && !counted[end] && follows(typed[end - 1]!, typed[end]!)) {\n      end += 1\n    }\n    const run = end - index\n    // A run of three or more is one guess of where it starts and how long it is.\n    bits += run >= 3 ? CHAR_BITS + Math.log2(run) : run * CHAR_BITS\n    index = end\n  }\n  return bits\n}\n\n/**\n * Kino's estimate of how hard the password is to guess, on zxcvbn's 0 to 4\n * scale. Length counts most: a password under 8 characters is never more than\n * 1, under 10 never more than 2, and under 12 never more than 3.\n */\nfunction estimatePasswordScore(password: string, userInputs: readonly string[] = []) {\n  if (!password) return 0\n  const bits = passwordBits(password, userInputs)\n  const length = graphemes(password).length\n  // zxcvbn's bounds: 10^3, 10^6, 10^8 and 10^10 guesses.\n  let score = bits < 10 ? 0 : bits < 20 ? 1 : bits < 26.6 ? 2 : bits < 33.2 ? 3 : 4\n  if (length < 8) score = Math.min(score, 1)\n  else if (length < 10) score = Math.min(score, 2)\n  else if (length < 12) score = Math.min(score, 3)\n  return score\n}\n\n/**\n * Whether the password is one that's guessed first: a known word or keyboard\n * walk with at most digits and symbols around it (\"Password1!\", \"1q2w3e4r\"),\n * only repeats and steps (\"aaaaaa\", \"123456\", \"qwerty\"), or one of those\n * typed again (\"qwertyqwerty\").\n */\nfunction isCommonPassword(password: string): boolean {\n  const lower = lowerChars(password).join('')\n  if (!lower) return false\n  // As typed, and with digits and symbols taken off its ends (\"qwertyuiop123\").\n  const core = lower.replace(/^[\\d\\W_]+|[\\d\\W_]+$/gu, '')\n  const known = COMMON_WORDS as readonly string[]\n  for (const text of [lower, core]) {\n    const chars = graphemes(text)\n    if (chars.length === 0) continue\n    if (chars.every((char, index) => index === 0 || follows(chars[index - 1]!, char))) {\n      return true\n    }\n    if (known.includes(text) || known.includes(readAsLetters(text).join(''))) return true\n  }\n  // A known password typed more than once, in any case, such as \"Passwordpassword\".\n  const block = /^(.{3,}?)\\1+$/u.exec(core || lower)\n  return block ? isCommonPassword(block[1]!) : false\n}\n\nexport {\n  PasswordStrength,\n  estimatePasswordScore,\n  isCommonPassword,\n  strengthLevel,\n  usesUserInputs,\n}\nexport type { PasswordRule }\n",
      "type": "registry:component",
      "target": "@components/kino/password-strength.tsx"
    }
  ],
  "type": "registry:component"
}