# Have I Been Pwned (/docs/plugins/have-i-been-pwned)

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



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

## 安装 [#安装]

### 将插件添加到你的 **auth** 配置 [#将插件添加到你的-auth-配置]

```ts title="auth.ts"
import { betterAuth } from "better-auth"
import { haveIBeenPwned } from "better-auth/plugins" // [!code highlight]

export const auth = betterAuth({
    plugins: [
        haveIBeenPwned() // [!code highlight]
    ]
})
```

## 使用 [#使用]

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

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

### 自定义密码流程 [#自定义密码流程]

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

```ts
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` [#enabled]

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

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

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

### `customPasswordCompromisedMessage` [#custompasswordcompromisedmessage]

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

```ts title="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." // [!code highlight]
        })
    ]
})
```

## 安全注意事项 [#安全注意事项]

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

