仪表盘

`dash()` 插件将您的 Better Auth 实例连接到 Better Auth Infrastructure,从而支持分析跟踪、活动监控、事件记录和管理仪表盘 API。

仪表盘插件是您的 Better Auth 实例和 Better Auth 基础设施之间的核心连接。它为网页仪表盘提供实时数据,跟踪用户活动,并启用管理员 API。

仪表盘插件的功能

启用 dash() 后,Better Auth Infrastructure 仪表盘将为您提供:

  • 用户管理 — 查看、搜索、封禁和删除用户
  • 会话监控 — 查看活跃会话并撤销会话
  • 组织概览 — 管理组织和成员
  • 分析 — 跟踪注册、登录和活跃用户随时间的变化
  • 审计日志 — 查询事件历史记录(了解更多)

安装

import { betterAuth } from "better-auth";
import { dash } from "@better-auth/infra";

export const auth = betterAuth({
  plugins: [
    dash(),
  ],
});

配置选项

DashOptions

选项类型描述
apiUrlstringBetter Auth Infrastructure API URL。默认值:https://dash.better-auth.com
kvUrlstringKV 存储 URL。默认值:https://kv.better-auth.com
apiKeystring用于身份验证的 API 密钥。未设置时回退到环境变量 BETTER_AUTH_API_KEY。
apiOptionsobjectDash API HTTP 客户端选项。接受 timeout?: number(毫秒,默认 3000)和 headers?: Record<string, string>。
kvOptionsobjectKV HTTP 客户端选项。接受 timeout?: number(毫秒,默认 1000)、retry?: { attempts?: number; baseDelay?: number; maxDelay?: number }(默认值分别为 2 / 400 / 600)以及 headers?: Record<string, string>。
apiTimeoutnumberapiOptions.timeout 的弃用别名。
kvTimeoutnumberkvOptions.timeout 的弃用别名。
activityTrackingobject活动跟踪配置。
managedDirectorySyncobject托管目录同步控制平面选项。

活动跟踪

跟踪用户在您的应用中的最后活跃时间。启用后,用户活动时会自动更新 lastActiveAt 字段。

dash({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  activityTracking: {
    enabled: true,
    updateInterval: 300000,  // 更新间隔,单位毫秒(默认:5 分钟)
  },
}),

模式变更

启用活动跟踪时,插件会在您的用户模式中添加一个字段:

user: {
  fields: {
    lastActiveAt: {
      type: "date",
    },
  },
}

启用活动跟踪需要为 lastActiveAt 用户字段执行数据库迁移。请先运行迁移步骤,再依赖活动数据。

npx auth migrate

如果您的应用单独管理模式生成,请运行 npx auth generate,然后使用您首选的工具应用生成的迁移。

托管目录同步

managedDirectorySync 选项是 SCIM 1.7 插件托管运行时流程在仪表盘侧的配套功能。当 enabled 为 true 时,仪表盘会安装托管目录同步状态所需的预留表和 API。ssoPairing 会启用目录关联用户身份与 SSO 提供商配对时所需的 SSO 钩子,而 membershipProjection 则允许系统将 SCIM 成员变更投影到组织成员记录中。

dash({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  managedDirectorySync: {
    enabled: true,
    ssoPairing: true,
    membershipProjection: {
      enabled: true,
      role: "member",
    },
  },
})

此可选控制平面适用于 SCIM 1.7 插件托管运行时流程。在 Better Auth 1.7 中,SCIM 支持三种连接模式:

  • 静态代码定义的连接
  • 应用自行管理的运行时验证
  • 通过 managedConnections 管理的插件运行时连接

managedDirectorySync 选项可在 dash 中启用用于目录同步预配的插件托管模式。它会创建管理目录连接和配对 SSO 状态所需的预留模式和 API。

托管目录同步选项

OptionTypeDescription
enabledbooleanEnables the managed directory-sync control plane and the SCIM reservation tables / APIs. Default: false.
ssoPairingbooleanInstalls the SSO resolveUser and provider-mutation hooks required when a paired directory needs to reconcile a user identity through SSO. Default: true.
membershipProjectionobjectEnables SCIM-to-organization membership projection when a directory should create group or member membership records.
membershipProjection.enabledbooleanEnables the projection hook. Default: true.
membershipProjection.rolestringRole assigned to projected organization memberships. Default: "member".

当应用希望 Better Auth 管理 SCIM 的运行时租户连接生命周期,并将其与基于 SSO 的身份解析配对时,可使用此选项。此选项适用于新的 1.7 流程,并与 scim({ managedConnections }) 配合使用。

启用 managedDirectorySync 需要为相应的托管目录同步表执行数据库迁移。请先运行迁移步骤,再使用托管运行时流程。

npx auth migrate

如果您的应用单独管理模式生成,请运行 npx auth generate,然后使用您首选的工具应用生成的迁移。

数据库模式

当 managedDirectorySync.enabled 为 true 时,dash 插件会添加以下模型。Better Auth 会为每个模型提供主 id 字段。

directorySyncConnection

存储托管目录的组织、SCIM 连接、SSO 配对、生命周期和停用状态。

ColumnTypeConstraintsDescription
organizationIdstringRequired, indexedOrganization that owns the directory.
providerIdstringRequiredSSO provider identifier.
aliasKeystringRequired, unique, hiddenInternal directory alias.
provisioningDomainIdstringRequired, uniqueSCIM provisioning domain.
activeOrganizationKeystringRequired, unique, hiddenActive organization key for reconciliation.
connectionIdstringOptional, uniqueManaged SCIM connection identifier.
creationRequestIdstringRequired, unique, hiddenImmutable ownership correlation value.
statusstringRequiredCurrent directory lifecycle status.
revisionnumberRequired, default 0, hiddenMutation revision used for concurrency control.
createdAtdateRequiredCreation timestamp.
createdByActorIdstringRequiredActor that created the directory.
updatedAtdateRequiredLast update timestamp.
lastActorIdstringRequiredActor responsible for the latest mutation.
ssoProviderIdstringOptionalPaired SSO provider ID.
ssoProviderRecordIdstringOptional, indexedPaired SSO provider record.
activeSsoProviderKeystringRequired, unique, hiddenActive SSO provider key.
serializedSsoPairingstringOptional, hiddenSerialized SSO pairing metadata.
pairingEnforcedbooleanRequired, default falseWhether the SSO pairing requirement is enforced.
unpairedAtdateOptionalTime at which the directory was unpaired.
unpairedBystringOptionalActor that removed the pairing.
decommissionStartedAtdateOptionalTime decommissioning started.
decommissionedAtdateOptionalTime decommissioning completed.
lastErrorstringOptional, hiddenMost recent reconciliation error.

directorySyncMembershipProvenance

跟踪通过目录同步投影创建或管理的组织成员关系,使插件只能协调其拥有的成员关系。

ColumnTypeConstraintsDescription
membershipKeystringRequired, unique, hiddenStable key for the projected membership.
organizationIdstringRequired, indexedOrganization containing the membership.
userIdstringRequired, indexedBetter Auth User receiving the membership.
memberIdstringRequired, uniqueOrganization member record identifier.
ownershipstringRequired, hiddenProjection ownership state.
provisioningDomainIdstringRequired, indexedSCIM provisioning domain that produced it.
createdAtdateRequiredCreation timestamp.
updatedAtdateRequiredLast update timestamp.

完整的 SCIM 模型和迁移指南,请参阅 SCIM 插件参考和 1.7 升级指南。

事件跟踪

dash 插件会自动跟踪以下事件:

用户事件

EventTrigger
user_signed_upNew user registration
user_profile_updatedUser updates their profile
user_profile_image_updatedUser changes their avatar
user_email_verifiedEmail verification completed
user_bannedUser is banned
user_unbannedUser is unbanned
user_deletedUser account deleted

会话事件

EventTrigger
user_signed_inSuccessful sign-in
user_signed_outUser signs out
session_createdNew session created
session_revokedSingle session revoked
sessions_revoked_allAll sessions revoked
user_impersonatedAdmin starts impersonating user
user_impersonation_stoppedAdmin stops impersonating

账户事件

EventTrigger
account_linkedSocial account linked
account_unlinkedSocial account unlinked
password_changedPassword updated

验证事件

EventTrigger
password_reset_requestedPassword reset initiated
password_reset_completedPassword reset finished
email_verification_sentVerification email sent

组织事件

如果您使用组织插件,也会跟踪以下事件:

EventTrigger
organization_createdNew organization created
organization_updatedOrganization settings changed
member_addedMember added to organization
member_removedMember removed from organization
member_role_updatedMember role changed
member_invitedInvitation sent
invite_acceptedInvitation accepted
invite_rejectedInvitation rejected
invite_cancelledInvitation cancelled
team_createdTeam created
team_updatedTeam updated
team_deletedTeam deleted
team_member_addedMember added to team
team_member_removedMember removed from team

仪表盘端点

dash 插件会为仪表盘注册大量管理端点:

用户管理

EndpointMethodDescription
/dash/usersGETList users with pagination
/dash/users/online-countGETGet online users count
/dash/userGETGet user details
/dash/userPOSTCreate a new user
/dash/userPATCHUpdate user
/dash/userDELETEDelete user
/dash/user/banPOSTBan user
/dash/user/unbanPOSTUnban user
/dash/user/passwordPOSTSet user password
/dash/user/impersonatePOSTImpersonate user

会话管理

EndpointMethodDescription
/dash/sessionsGETList all sessions
/dash/sessionsDELETEDelete sessions
/dash/session/revokePOSTRevoke single session
/dash/sessions/revoke-allPOSTRevoke all user sessions

组织管理

EndpointMethodDescription
/dash/organizationsGETList organizations
/dash/organizationGETGet organization details
/dash/organizationPOSTCreate organization
/dash/organizationPATCHUpdate organization
/dash/organizationDELETEDelete organization
/dash/organization/membersGETList members
/dash/organization/memberPOSTAdd member
/dash/organization/memberDELETERemove member
/dash/organization/member/rolePATCHUpdate member role

团队管理

EndpointMethodDescription
/dash/organization/teamsGETList teams
/dash/organization/teamPOSTCreate team
/dash/organization/teamPATCHUpdate team
/dash/organization/teamDELETEDelete team
/dash/organization/team/memberPOSTAdd team member
/dash/organization/team/memberDELETERemove team member

邀请管理

EndpointMethodDescription
/dash/organization/invitationsGETList invitations
/dash/organization/invitePOSTSend invitation
/dash/organization/invite/cancelPOSTCancel invitation
/dash/organization/invite/resendPOSTResend invitation

SSO 管理

EndpointMethodDescription
/dash/organization/sso-providersGETList SSO providers
/dash/organization/sso-providerPOSTCreate SSO provider
/dash/organization/sso-providerPATCHUpdate SSO provider
/dash/organization/sso-providerDELETEDelete SSO provider
/dash/organization/sso-provider/verify-domainPOSTVerify domain

目录同步

EndpointMethodDescription
/dash/organization/directoriesGETList directories
/dash/organization/directoryPOSTCreate directory
/dash/organization/directoryDELETEDelete directory
/dash/organization/directory/tokenPOSTRegenerate token

日志转发

EndpointMethodDescription
/dash/organization/log-drainsGETList log drains
/dash/organization/log-drainPOSTCreate log drain
/dash/organization/log-drainPATCHUpdate log drain
/dash/organization/log-drainDELETEDelete log drain
/dash/organization/log-drain/testPOSTTest log drain

事件与审计日志

EndpointMethodDescription
/events/listGETGet user events
/events/audit-logsGETGet audit logs
/events/typesGETGet event types

分析

EndpointMethodDescription
/dash/statsGETGet user statistics
/dash/graphGETGet graph data
/dash/retentionGETGet retention data
/dash/mapGETGet geographic data

双重验证管理

EndpointMethodDescription
/dash/user/2fa/enablePOSTEnable 2FA for user
/dash/user/2fa/disablePOSTDisable 2FA for user
/dash/user/2fa/totp-uriGETGet TOTP URI
/dash/user/2fa/backup-codesGETView backup codes
/dash/user/2fa/backup-codes/generatePOSTGenerate new codes

客户端集成

dashClient()

客户端插件提供访问审计日志查询的功能:

import { createAuthClient } from "better-auth/client";
import { dashClient } from "@better-auth/infra/client";

export const authClient = createAuthClient({
  plugins: [dashClient()],
});

注意:对于 Expo 或 React Native,请从 @better-auth/infra/native 导入 dashClient(API 相同),并将其与 sentinelNativeClient 配合使用,具体请参阅 Sentinel — Expo 和 React Native。

配置

dashClient({
  resolveUserId: ({ userId, user, session }) => {
    return userId || user?.id || session?.user?.id;
  },
}),

获取当前用户的审计日志

返回当前用户的审计事件;如果您以成员身份传入 organizationId,则返回组织范围内的事件。

基本查询

const session = await authClient.getSession();

const logs = await authClient.dash.getAuditLogs({
  session: session.data,
  limit: 50,
  offset: 0,
});

// Access the data
console.log(logs.data?.events);  // Array of audit log events
console.log(logs.data?.total);   // Total count
console.log(logs.data?.limit);   // Page size
console.log(logs.data?.offset);  // Current offset

更多信息请参阅获取当前用户的审计日志。

获取所有审计日志

返回当前用户拥有管理员或所有者访问权限的组织中的所有审计事件。角色检查需要组织插件。

基本查询

const session = await authClient.getSession();

const activity = await authClient.dash.getAllAuditLogs({
  session: session.data,
  limit: 50,
  offset: 0,
});

console.log(activity.data?.events);
console.log(activity.data?.total);

更多信息请参阅获取所有审计日志。

最佳实践

  1. 始终设置 API 密钥 — 没有它,插件无法与基础设施 API 通信。

  2. 合理使用活动跟踪 — 更新间隔会影响数据库写入频率。对于高流量应用,考虑使用更长的间隔。

  3. 监控审计日志保留期限 — 不同套餐的保留周期不同,请检查您的套餐限制。

  4. 保护您的端点 — 仪表盘端点需要认证。确保您的仪表盘用户拥有适当权限。