ユーザーに安全なパスワードの設定を促すために強度を測定しフィードバックしたいといった時にDropbox製のzxcvbnがよく使われていると思います。
ただ、このライブラリのサイズが大きかったりメンテナンスに不安があったりと、
So, I came across this library and was very excited to put it to use. I pulled it down via npm and was shocked to find the minified dist script is 823kb. That's insane. Dist size (JavaScript) makes this lib unusable in a client · Issue #169 · dropbox/zxcvbn · GitHub
代替ライブラリを探していたところzxcvbn-ts
というライブラリを使うとLazy Loading等が使えていい感じに使えそうだったので使い方をメモ📝
zxcvbn-ts
とは?
以下の通りzxcvbn
を再実装したライブラリとのこと。
This is a complete rewrite of zxcvbn in TypeScript which is licensed under the MIT license.
Introduction | zxcvbn-ts
完全に再現しているわけではなく微妙にスコアが違うみたいなのでzxcvbn
からの乗り換えを行う場合には参照しておくと良さそうです。
zxcvbn-ts
のinstall
以下のページの通りですが、
以下のコマンドでインストールできます。
npm install @zxcvbn-ts/core @zxcvbn-ts/language-common --save
各国のよくある名前とかの辞書を取り込みたい場合には以下から任意の国の辞書情報を取り込むこともできます。
zxcvbn-ts
を利用する
以下がzxcvbn-ts
を利用してパスワードの文字列を受け取ってスコアの数値を返却するサンプル実装です。
zxcvbnOptions
を使ってoptionを設定する感じ以外はzxcvbn
とほとんど同じように使うことができます。
import { zxcvbn, zxcvbnOptions, type OptionsType } from "@zxcvbn-ts/core"; import { adjacencyGraphs, dictionary } from "@zxcvbn-ts/language-common"; const defaultOption: () => OptionsType = () => { return { graphs: adjacencyGraphs, dictionary }; }; export const calcPasswordStrengthScore = (password: string): number => { const options = defaultOption(); zxcvbnOptions.setOptions(options); return zxcvbn(password).score; };
zxcvbn-ts
の辞書情報等を遅延読み込みさせる
辞書情報等はサイズが大きいのでパフォーマンス等の問題で実際に利用するまで読み込ませたくないときもあるかもですが、zxcvbn-ts
は遅延読み込みにも対応しているようです。
以下が@zxcvbn-ts/language-common
を遅延importして利用時に読み込むようにしたサンプルです。
※私はviteを使っているので、別のmodule bundlerを利用している場合には微妙にコードを修正する必要があるかもです。
import { zxcvbn, zxcvbnOptions, type OptionsType } from "@zxcvbn-ts/core"; const defaultOption: () => Promise<OptionsType> = async () => { const common = await import("@zxcvbn-ts/language-common"); return { graphs: common.adjacencyGraphs, dictionary: common.dictionary }; }; export const calcPasswordStrengthScore = async (password: string): Promise<number> => { const options = await defaultOption(); zxcvbnOptions.setOptions(options); return zxcvbn(password).score; };
おわりに
zxcvbn-ts
、遅延ローディングも対応してるのとアクティブにメンテナンスされているようて良さそうですね✨