安全

双因素认证 (2FA)

基于 TOTP 的双因素认证配置与集成

双因素认证 (2FA)

项目通过 Better Auth 的 twoFactor 插件支持基于 TOTP 的双因素认证。

配置

config.auth.enableTwoFactor(应用配置)中开启:

// apps/01mvp-web/src/lib/auth/auth-config.ts
const twoFactorPlugin = (() => {
  if (!config.auth.enableTwoFactor) {
    return null;
  }
  return twoFactor();
})();

插件初始化失败时会记录错误日志并自动降级(不启用 2FA),不会影响应用启动。

用户流程

  1. 用户在设置页选择「启用双因素认证」
  2. 系统生成 TOTP 密钥,前端展示二维码
  3. 用户用 Authenticator App 扫描二维码
  4. 输入 App 显示的 6 位验证码完成验证
  5. 系统同时生成一组备份码,用户需妥善保存

数据库模型

Drizzle schema 中的 twoFactor 表存储 2FA 数据:

export const twoFactor = pgTable("twoFactor", {
  id: text("id").primaryKey(),
  userId: text("userId").notNull(),
  secret: text("secret").notNull(),
  backupCodes: text("backupCodes").notNull(),
});

客户端集成

客户端使用 twoFactorClient() 插件,已在 apps/01mvp-web/src/lib/auth/client.ts 中注册。前端可以通过 Better Auth 客户端 API 调用 twoFactor.enabletwoFactor.verifytwoFactor.disable 等方法。