Token导航 LogoToken导航TokenDH.com
前端设计敏感数据github未标认证来源可访问许可证需确认审计通过

better-authBetter Auth 认证

Agent Skill

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查。它适合让 Agent 梳理敏感配置、检查依赖风险、分析鉴权逻辑或生成安全复核清单。使用时不能把工具输出直接当最终结论,涉及密钥、令牌、用户数据或生产系统时,应先确认最小权限、脱敏方式和操作边界。

总安装

13,304

周安装

533

GitHub Stars

229

下载量

4,307
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:better-auth(Better Auth 认证)
来源仓库:https://github.com/giuseppe-trisciuoglio/developer-kit
仓库路径:skills/better-auth
安装命令:
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill better-auth
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill better-auth

简介

better-auth 用于辅助安全审计、权限检查和凭据风险排查,适合梳理敏感配置和分析鉴权逻辑。

  • 适用于 Codex、Claude、Cursor、Gemini CLI 等宿主环境中的前端设计任务。
  • 通过 npx skills add 命令从指定 GitHub 仓库安装并使用。
  • 涉及密钥或生产系统时需确认最小权限和操作边界,不能直接使用工具输出作为结论。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Better Auth Integration Guide

Overview

Better Auth is a type-safe authentication framework for TypeScript supporting multiple providers, 2FA, SSO, organizations, and passkeys. This skill covers integration patterns for NestJS backend with Drizzle ORM + PostgreSQL and Next.js App Router frontend.

When to Use

  • Setting up Better Auth with NestJS backend
  • Integrating Next.js App Router frontend
  • Configuring Drizzle ORM schema with PostgreSQL
  • Implementing social login (GitHub, Google, Facebook, Microsoft)
  • Adding MFA/2FA with TOTP, passkey passwordless auth, or magic links
  • Managing trusted devices and backup codes for account recovery
  • Building multi-tenant apps with organizations or SSO
  • Creating protected routes with session management

Quick Start

Installation

# Backend (NestJS)
npm install better-auth @auth/drizzle-adapter drizzle-orm pg
npm install -D drizzle-kit

# Frontend (Next.js)
npm install better-auth

4-Phase Setup

  1. Database: Install Drizzle, configure schema, run migrations
  2. Backend: Create Better Auth instance with NestJS module
  3. Frontend: Configure auth client, create pages, add middleware
  4. Plugins: Add 2FA, passkey, organizations as needed

See references/nestjs-setup.md for complete backend setup, references/plugins.md for plugin configuration.

Instructions

Phase 1: Database Setup

  1. Install dependencies npm install drizzle-orm pg @auth/drizzle-adapter better-auth npm install -D drizzle-kit
  2. Create Drizzle config (drizzle.config.ts) import {defineConfig} from 'drizzle-kit'; export default defineConfig({schema: './src/auth/schema.ts', out: './drizzle', dialect: 'postgresql', dbCredentials: {url: process.env.DATABASE_URL!},});
  3. Generate and run migrations npx drizzle-kit generate npx drizzle-kit migrate Checkpoint: Verify tables created: psql $DATABASE_URL -c "\dt" should show user, account, session, verification_token tables.

Phase 2: Backend Setup (NestJS)

  1. Create database module - Set up Drizzle connection service
  2. Configure Better Auth instance // src/auth/auth.instance.ts import {betterAuth} from 'better-auth'; import {drizzleAdapter} from '@auth/drizzle-adapter'; import * as schema from './schema'; export const auth = betterAuth({database: drizzleAdapter(schema, {provider: 'postgresql'}), emailAndPassword: {enabled: true}, socialProviders: {github: {clientId: process.env.AUTH_GITHUB_CLIENT_ID!, clientSecret: process.env.AUTH_GITHUB_CLIENT_SECRET!,}}});
  3. Create auth controller @Controller('auth') export class AuthController {@All('*') async handleAuth(@Req() req: Request, @Res() res: Response) {return auth.handler(req);}} Checkpoint: Test endpoint GET /auth/get-session returns {session: null} when unauthenticated (no error).

Phase 3: Frontend Setup (Next.js)

  1. Configure auth client (lib/auth.ts) import {createAuthClient} from 'better-auth/client'; export const authClient = createAuthClient({baseURL: process.env.NEXT_PUBLIC_APP_URL!});
  2. Add middleware (middleware.ts) import {auth} from '@/lib/auth'; export default auth((req) => {if (!req.auth && req.nextUrl.pathname.startsWith('/dashboard')) {return Response.redirect(new URL('/sign-in', req.nextUrl.origin));}}); export const config = {matcher: ['/dashboard/:path*']};
  3. Create sign-in page with form or social buttons Checkpoint: Navigating to /dashboard when logged out should redirect to /sign-in.

Phase 4: Advanced Features

Add plugins from references/plugins.md:

  • 2FA: twoFactor({issuer: 'AppName', otpOptions: {sendOTP}})
  • Passkey: passkey({rpID: 'domain.com', rpName: 'App'})
  • Organizations: organization({avatar: {enabled: true}})
  • Magic Link: magicLink({sendMagicLink})
  • SSO: sso({saml: {enabled: true}}) Checkpoint: After adding plugins, re-run migrations and verify new tables exist.

Examples

Example 1: Server Component with Session

Input: Display user data in a Next.js Server Component.

// app/dashboard/page.tsx
import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
  const session = await auth();

  if (!session) {
    redirect('/sign-in');
  }

  return (
    <div>
      <h1>Welcome, {session.user.name}</h1>
      <p>Email: {session.user.email}</p>
    </div>
  );
}

Output: Renders user info for authenticated users; redirects unauthenticated to sign-in.

Example 2: 2FA TOTP Verification with Trusted Device

Input: User has 2FA enabled and wants to sign in, marking device as trusted.

// Server: Configure 2FA with OTP sending
export const auth = betterAuth({
  plugins: [
    twoFactor({
      issuer: 'MyApp',
      otpOptions: {
        async sendOTP({ user, otp }, ctx) {
          await sendEmail({
            to: user.email,
            subject: 'Your verification code',
            body: `Code: ${otp}`
          });
        }
      }
    })
  ]
});

// Client: Verify TOTP and trust device
const verify2FA = async (code: string) => {
  const { data } = await authClient.twoFactor.verifyTotp({
    code,
    trustDevice: true  // Device trusted for 30 days
  });

  if (data) {
    router.push('/dashboard');
  }
};

Output: User authenticated; device trusted for 30 days without 2FA prompt.

Example 3: Passkey Registration and Login

Input: Enable passkey (WebAuthn) authentication for passwordless login.

// Server
import { passkey } from '@better-auth/passkey';
export const auth = betterAuth({
  plugins: [
    passkey({
      rpID: 'example.com',
      rpName: 'My App',
    })
  ]
});

// Client: Register passkey
const registerPasskey = async () => {
  const { data } = await authClient.passkey.register({
    name: 'My Device'
  });
};

// Client: Sign in with autofill
const signInWithPasskey = async () => {
  await authClient.signIn.passkey({
    autoFill: true,  // Browser suggests passkey
  });
};

Output: Users can register and authenticate with biometrics, PIN, or security keys.

For more examples (backup codes, organizations, magic link, conditional UI), see references/plugins.md and references/passkey.md.

Best Practices

  1. Environment Variables: Store all secrets in .env, add to .gitignore
  2. Secret Generation: Use openssl rand -base64 32 for BETTER_AUTH_SECRET
  3. HTTPS Required: OAuth callbacks need HTTPS (use ngrok for local testing)
  4. Session Expiration: Configure based on security requirements (7 days default)
  5. Database Indexing: Add indexes on email, userId for performance
  6. Error Handling: Return generic errors without exposing sensitive details
  7. Rate Limiting: Add to auth endpoints to prevent brute force attacks
  8. Type Safety: Use npx better-auth typegen for full TypeScript coverage

Constraints and Warnings

Security Notes

  • Never commit secrets: Add .env to .gitignore; never commit OAuth secrets or DB credentials
  • Validate redirect URLs: Always validate OAuth redirect URLs to prevent open redirects
  • Hash passwords: Better Auth handles password hashing automatically; never implement custom hashing
  • Session storage: For production, use Redis or another scalable session store
  • HTTPS Only: Always use HTTPS for authentication in production
  • Email Verification: Always implement email verification for password-based auth

Known Limitations

  • Better Auth requires Node.js 18+ for Next.js App Router support
  • Some OAuth providers require specific redirect URL formats
  • Passkeys require HTTPS and compatible browsers
  • Organization features require additional database tables

Resources

Documentation

Reference Implementations

  • references/nestjs-setup.md - Complete NestJS backend setup
  • references/nextjs-setup.md - Complete Next.js frontend setup
  • references/plugins.md - Plugin configuration (2FA, passkey, organizations, SSO, magic link)
  • references/mfa-2fa.md - Detailed MFA/2FA guide
  • references/passkey.md - Detailed passkey implementation
  • references/schema.md - Drizzle schema reference
  • references/social-providers.md - Social provider configuration

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.79%
按下载量换算1,455

Claude

30.9%
按下载量换算1,331

Cursor

18.32%
按下载量换算789

Gemini CLI

7.87%
按下载量换算339

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills