@better-auth/infra

中文文档
0.4.27发布于 2026/11/05MITTypeScriptES Module近 30 天下载 115.2万

Dashboard and analytics plugin for Better Auth

原始使用文档
文档目录20 节
  1. Installation
  2. Server Usage
  3. Client Usage
  4. Native client
  5. Install peers
  6. Example
  7. Options ( sentinelNativeClient )
  8. Audit Log APIs
  9. dashClient() API
  10. Filtering
  11. Search Patterns
  12. Pagination Helper
  13. dash() Event Endpoints
  14. Option Types
  15. DashOptions
  16. SentinelOptions
  17. DashClientOptions
  18. SentinelNativeClientOptions
  19. Migration
  20. Security Notes

Better Auth Infrastructure

Infra plugins for Better Auth:

  • dash() for dashboard/admin APIs, analytics tracking, and infra endpoints.
  • dashClient() for dashboard client actions (including audit log queries).
  • sentinel() for security checks and abuse protection.
  • sentinelClient() for browser fingerprint headers + optional PoW auto-solving.
  • sentinelNativeClient() (from @better-auth/infra/native) for React Native / Expo.

Installation

npm install @better-auth/infra
# or
pnpm add @better-auth/infra
# or
bun add @better-auth/infra

Server Usage

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

export const auth = betterAuth({
  // ...your Better Auth config
  plugins: [
    dash({
      apiUrl: process.env.BETTER_AUTH_API_URL,
      kvUrl: process.env.BETTER_AUTH_KV_URL,
      apiKey: process.env.BETTER_AUTH_API_KEY,
    }),
    sentinel({
      apiUrl: process.env.BETTER_AUTH_API_URL,
      kvUrl: process.env.BETTER_AUTH_KV_URL,
      apiKey: process.env.BETTER_AUTH_API_KEY,
      security: {
        credentialStuffing: {
          enabled: true,
          thresholds: { challenge: 3, block: 5 },
        },
      },
    }),
  ],
});

Client Usage

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

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

// Resolve user from session or pass explicit user/org context
const auditLogs = await authClient.dash.getAuditLogs({
  session: await authClient.getSession().then((r) => r.data),
  organizationId: "org_123",
  limit: 20,
});

Native client

Use this plugin for your React Native / Expo app. This plugin is designed to work along with the server side sentinel and dash plugins and will ensure your app is protected from abuse and bot attacks.

Install peers

pnpm add react-native @react-native-async-storage/async-storage
# Optional, for richer device metadata in the identify payload:
pnpm add expo-constants expo-device
# Optional, secure visitor-id RNG (Expo):
pnpm add expo-crypto
# Or plain React Native — first import in the app entry:
# import "react-native-get-random-values";

@react-native-async-storage/async-storage is optional; if it is not installed, a session-only in-memory visitor id is used. For production, install it or pass storage (for example secure storage).

Example

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

export const authClient = createAuthClient({
  baseURL: "https://your-api.example.com",
  plugins: [
    dashClient(),
    sentinelNativeClient({
      identifyUrl: process.env.EXPO_PUBLIC_BETTER_AUTH_KV_URL,
      autoSolveChallenge: true,
    }),
  ],
});

Options (sentinelNativeClient)

  • identifyUrl?: string — identify endpoint base (defaults to BETTER_AUTH_KV_URL from env, then https://kv.better-auth.com/api/v1).
  • identifyOptions?: { timeout?: number; retry?: { attempts?: number; baseDelay?: number; maxDelay?: number } } — identify HTTP timeout (ms, default 1000) and POST retry (defaults 2 / 400 / 600).
  • kvTimeout?: number — deprecated, use identifyOptions.timeout.
  • autoSolveChallenge?: boolean — When true (default), 423 responses that include a PoW challenge header are solved and retried once with the solution header.
  • sentinelHeaders?: "legacy" | "modern" — "modern" uses X-Sentinel-* protocol headers instead of legacy names. Match on server sentinel(). Default "legacy".
  • onChallengeReceived? / onChallengeSolved? / onChallengeFailed? — PoW lifecycle hooks (reason string, solve time in ms, or error).
  • storage?: { getItem, setItem } — Async key/value storage for a stable per-install visitor id (recommended for production).

Audit Log APIs

dashClient() API

dashClient() adds:

  • authClient.dash.getAuditLogs(input)

getAuditLogs(input) accepts:

  • limit?: number (default 50, max 100)
  • offset?: number (default 0)
  • organizationId?: string
  • identifier?: string
  • eventType?: string
  • userId?: string
  • user?: { id?: string | null }
  • session?: { user?: { id?: string | null } }

The resolved user ID is determined in this order:

  • input.userId
  • dashClient({ resolveUserId })
  • input.user?.id
  • input.session?.user?.id

Response shape:

  • events: DashAuditLog[]
  • total: number
  • limit: number
  • offset: number

Example:

const session = await authClient.getSession().then((r) => r.data);

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

To fetch all events, keep paginating with offset until events.length < limit.

Filtering

Use getAuditLogs filters directly in the query:

  • eventType: only return a specific event type (for example user_signed_in)
  • organizationId: scope logs to one organization
  • identifier: narrow organization logs to a specific identifier
  • userId / user / session: resolve which user the logs should be scoped to

Examples:

// 1) Filter by event type
const signIns = await authClient.dash.getAuditLogs({
  session,
  eventType: "user_signed_in",
  limit: 20,
});

// 2) Filter by org + identifier
const orgMemberEvents = await authClient.dash.getAuditLogs({
  session,
  organizationId: "org_123",
  identifier: "[email protected]",
  limit: 50,
});

// 3) Combine filters
const orgSignIns = await authClient.dash.getAuditLogs({
  session,
  organizationId: "org_123",
  eventType: "user_signed_in",
  limit: 50,
});

Search Patterns

getAuditLogs does not currently expose a dedicated full-text search query param. For text search, fetch pages and filter client-side.

const matchesText = (event: { eventType: string; eventKey: string; eventData: Record<string, unknown> }, query: string) => {
  const q = query.toLowerCase().trim();
  if (!q) return true;

  const haystack = [
    event.eventType,
    event.eventKey,
    JSON.stringify(event.eventData ?? {}),
  ]
    .join(" ")
    .toLowerCase();

  return haystack.includes(q);
};

const page = await authClient.dash.getAuditLogs({ session, limit: 100, offset: 0 });
const filtered = page.data?.events.filter((event) => matchesText(event, "password")) ?? [];

You can apply the same pattern for:

  • date range filtering (by createdAt)
  • location filtering (by location.country, location.city, etc.)
  • multi-field compound filters

Pagination Helper

async function getAllAuditLogs(session: unknown) {
  const limit = 100;
  let offset = 0;
  const all: Array<{
    eventType: string;
    createdAt: string;
    eventData: Record<string, unknown>;
  }> = [];

  while (true) {
    const result = await authClient.dash.getAuditLogs({ session, limit, offset });
    const events = result.data?.events ?? [];
    all.push(...events);

    if (events.length < limit) break;
    offset += limit;
  }

  return all;
}

dash() Event Endpoints

The dash() plugin registers these event endpoints:

  • getUserEvents on GET /events/list
  • getAuditLogs on GET /events/audit-logs
  • getEventTypes on GET /events/types

getAuditLogs supports query params:

  • limit, offset, eventType
  • organizationId, identifier
  • userId (must match the authenticated session user)

Option Types

DashOptions

  • apiUrl?: string
  • kvUrl?: string
  • apiKey?: string
  • apiOptions?: { timeout?: number } (ms, default 3000)
  • kvOptions?: { timeout?: number; retry?: { attempts?: number; baseDelay?: number; maxDelay?: number } } — KV timeout default 1000; retry defaults 2 / 400 / 600
  • apiTimeout?: number — deprecated, use apiOptions.timeout
  • kvTimeout?: number — deprecated, use kvOptions.timeout
  • activityTracking?: { enabled?: boolean; updateInterval?: number }
  • managedDirectorySync?: { enabled?: boolean; ssoPairing?: boolean; membershipProjection?: { enabled?: boolean; role?: string }; fieldProjection?: { enabled?: boolean } } — opt into the 1.7+ managed directory-sync control plane (schema + reservation APIs). enabled alone turns on reservation tables/APIs. When enabled, dash init can also wire sibling-plugin callbacks: ssoPairing installs SSO resolveUser / guardProviderMutation (needed only for paired directories; requires sso({}) or richer options — bare sso() leaves options undefined), and membershipProjection installs SCIM projection.reconcileUser for org membership sync. fieldProjection (default false) is a separate opt-in: when enabled, per-connection dashboard mappings project curated SCIM User attributes (and optional defaults) onto Better Auth user/member additional fields — migrate after enabling. Defaults: enabled: false, ssoPairing: true, membershipProjection.enabled: true, membershipProjection.role: "member", fieldProjection.enabled: false. Required with scim({ managedConnections }) for managed mode; does not affect or replace legacy pre-1.7 SCIM directory sync.

dash() no longer accepts sentinel security config.

SentinelOptions

  • apiUrl?: string
  • kvUrl?: string
  • apiKey?: string
  • apiOptions?: { timeout?: number } — same as DashOptions
  • kvOptions?: { timeout?: number; retry?: { attempts?: number; baseDelay?: number; maxDelay?: number } } — same as DashOptions
  • apiTimeout?: number — deprecated, use apiOptions.timeout
  • kvTimeout?: number — deprecated, use kvOptions.timeout
  • sentinelHeaders?: "legacy" | "modern" — "modern" uses X-Sentinel-* protocol headers instead of legacy names. Match on client. Default "legacy". Upgrade clients before the server.
  • security?: SecurityOptions

All security configuration now belongs in sentinel().

DashClientOptions

  • resolveUserId?: ({ userId, user, session }) => string | undefined

See Audit Log APIs above for full method details.

SentinelNativeClientOptions

Exported from @better-auth/infra/native. See React Native client for the full option list and usage.

Migration

If you previously passed security config to dash(), move it to sentinel():

// before
dash({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  // no longer supported in dash
  security: {
    credentialStuffing: { enabled: true },
  },
});

// after
dash({ apiKey: process.env.BETTER_AUTH_API_KEY });
sentinel({
  apiKey: process.env.BETTER_AUTH_API_KEY,
  security: {
    credentialStuffing: { enabled: true },
  },
});

Security Notes

  • Use sentinel() to enforce security checks. dash() is focused on telemetry/admin behavior.
  • Provide BETTER_AUTH_API_KEY; without it, sentinel cannot securely call infra APIs and will warn at startup.
  • If you run behind a proxy/CDN, validate your upstream header trust model (x-forwarded-for, etc.) to avoid spoofed client IP attribution.
  • Optional sentinelHeaders: "modern" (server + client) uses X-Sentinel-* protocol headers so proxies that rewrite X-Request-Id do not break identification. Upgrade clients first. When enabled cross-origin, allow/expose the exact X-Sentinel-* header names in CORS (not a wildcard).

版本与发布记录

@better-auth/infra 共发布 61 个版本,首次发布于 2026/02/19;过去 12 个月发布了 61 个版本。

版本发布日期距今
0.4.27latest2026/11/053 天前
0.4.262026/11/035 天前
0.4.252026/10/2910 天前
0.4.242026/10/2811 天前
0.4.232026/10/2712 天前
0.4.222026/10/2217 天前

其他发布通道:beta → 0.1.10。

关于 @better-auth/infra 的常见问题

@better-auth/infra 是什么?

Dashboard and analytics plugin for Better Auth

如何安装 @better-auth/infra?

在项目目录运行 npm install @better-auth/infra,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:zod(>=4.1.12)、better-auth(>=1.4.0)、@better-auth/core(>=1.4.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@better-auth/infra 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@better-auth/infra 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@better-auth/infra 可以商用吗?

@better-auth/infra 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@better-auth/infra 的下载量有多少?

根据 npm 官方下载统计,@better-auth/infra 在 2026/10/08 – 2026/11/06 这 30 天内被下载 1,152,266 次,日均约 38,409 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@better-auth/infra 还在维护吗?

最新版本 0.4.27 发布于 2026/11/05(3 天前);至今共发布 61 个版本,其中过去 12 个月发布了 61 个;首次发布于 2026/02/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。