Have I Been Pwned

用于检查密码是否已遭泄露的插件

Have I Been Pwned 插件通过阻止使用已在已知数据泄露中曝光的密码来帮助保护用户账户。它使用 Have I Been Pwned API 来检查密码是否已被泄露。

安装

将插件添加到你的 auth 配置

auth.ts
import { betterAuth } from "better-auth"
import { haveIBeenPwned } from "better-auth/plugins"

export const auth = betterAuth({
    plugins: [
        haveIBeenPwned() 
    ]
})

使用

当用户尝试使用被泄露的密码创建账户或更新密码时,他们将收到以下默认错误信息:

{
  "code": "PASSWORD_COMPROMISED",
  "message": "The password you entered has been compromised. Please choose a different password."
}

自定义密码流程

使用 isPasswordCompromised 在不使用 Better Auth 端点的服务端流程中检查密码。

import { isPasswordCompromised } from "better-auth/plugins/haveibeenpwned"

const compromised = await isPasswordCompromised(password)
if (compromised) {
    throw new Error("Please choose a password that has not been compromised")
}

此函数只会向 Have I Been Pwned 发送密码 SHA-1 哈希的前五个字符。如果服务无法完成检查,则会抛出 APIError。

选项

enabled

启用或禁用对 HIBP 数据库的密码检查。在开发或测试环境中跳过检查很有用,无需移除插件。默认为 true。

auth.ts
import { betterAuth } from "better-auth"
import { haveIBeenPwned } from "better-auth/plugins"

const auth = betterAuth({
    plugins: [
        haveIBeenPwned({
            enabled: process.env.NODE_ENV === 'production'
        })
    ]
})

customPasswordCompromisedMessage

自定义检测到被泄露密码时显示的错误信息。

auth.ts
import { betterAuth } from "better-auth"
import { haveIBeenPwned } from "better-auth/plugins"

const auth = betterAuth({
    plugins: [
        haveIBeenPwned({
            customPasswordCompromisedMessage: "Please choose a more secure password."
        })
    ]
})

安全注意事项

  • 仅将密码哈希的前 5 个字符发送到 API
  • 完整的密码从未被传输
  • 提供额外的账户安全层