Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat(better-auth): Update to v1.4.10 with OAuth 2.1 Provider
Jez69270c5ee845
diff --git a/skills/better-auth/.claude-plugin/plugin.json b/skills/better-auth/.claude-plugin/plugin.jsonindex 872f6ead..4f9d55bf 100644--- a/skills/better-auth/.claude-plugin/plugin.json+++ b/skills/better-auth/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "better-auth",- "description": "Build authentication systems for TypeScript/Cloudflare Workers with social auth, 2FA, passkeys, organizations, and RBAC. Self-hosted alternative to Clerk/Auth.js. IMPORTANT: Requires Drizzle ORM or Kysely for D1 - no direct D1 adapter. v1.4.0 (Nov 2025) adds stateless sessions, ESM-only (breaking), JWT key rotation, SCIM provisioning. v1.3 adds SSO/SAML, multi-team support. Use when: self-hosting auth on Cloudflare D1, migrating from Clerk, implementing multi-tenant SaaS, or troubleshooting D1 a",+ "description": "Build authentication systems for TypeScript/Cloudflare Workers with social auth, 2FA, passkeys, organizations, RBAC, and OAuth 2.1 provider capabilities. Self-hosted alternative to Clerk/Auth.js. IMPORTANT: Requires Drizzle ORM or Kysely for D1 - no direct D1 adapter. v1.4.10 (Dec 2025) adds OAuth 2.1 Provider plugin (MCP deprecated), admin impersonation prevention, background tasks, Patreon/Kick/Vercel OAuth providers. v1.4.0 adds ESM-only (breaking), stateless sessions, SCIM. Use when: self-ho","version": "1.0.0","author": {"name": "Jeremy Dawes",diff --git a/skills/better-auth/README.md b/skills/better-auth/README.mdindex 562aa2ef..b987e759 100644--- a/skills/better-auth/README.md+++ b/skills/better-auth/README.md@@ -40,6 +40,18 @@ This skill should be automatically invoked when you mention:- **"API key authentication"** - API-only auth- **"TanStack Query session"** - Session state with React Query- **"nanostores auth"** - Nanostore session invalidation+- **"OAuth 2.1 provider"** - Build your own OAuth server+- **"OAuth provider for MCP"** - MCP server authentication+- **"better-auth MCP"** - MCP plugin (deprecated, use OAuth provider)+- **"admin impersonation"** - Admin impersonate user feature+- **"user impersonation"** - View as another user+- **"admin ban user"** - User management+- **"better-auth admin"** - Admin dashboard patterns+- **"custom RBAC"** - Role-based access control+- **"createAccessControl"** - Permission system+- **"allowImpersonatingAdmins"** - Admin security setting+- **"Hono better-auth"** - Hono integration+- **"better-auth Hono"** - Hono framework setup---@@ -196,7 +208,10 @@ npm install better-auth drizzle-orm drizzle-kit @cloudflare/workers-types hono- **Docs**: https://better-auth.com- **GitHub**: https://github.com/better-auth/better-auth (22.4k ⭐)-- **Package**: `[email protected]`+- **Package**: `[email protected]`+- **OAuth 2.1 Provider**: https://www.better-auth.com/docs/plugins/oauth-provider+- **Admin Plugin**: https://www.better-auth.com/docs/plugins/admin+- **Hono Example**: https://hono.dev/examples/better-auth-on-cloudflare- **Examples**: https://github.com/better-auth/better-auth/tree/main/examples---diff --git a/skills/better-auth/SKILL.md b/skills/better-auth/SKILL.mdindex b840cd0f..fe311f5e 100644--- a/skills/better-auth/SKILL.md+++ b/skills/better-auth/SKILL.md@@ -1,11 +1,11 @@---name: better-authdescription: |- Build authentication systems for TypeScript/Cloudflare Workers with social auth, 2FA, passkeys, organizations, and RBAC. Self-hosted alternative to Clerk/Auth.js.+ Build authentication systems for TypeScript/Cloudflare Workers with social auth, 2FA, passkeys, organizations, RBAC, and OAuth 2.1 provider capabilities. Self-hosted alternative to Clerk/Auth.js.- IMPORTANT: Requires Drizzle ORM or Kysely for D1 - no direct D1 adapter. v1.4.0 (Nov 2025) adds stateless sessions, ESM-only (breaking), JWT key rotation, SCIM provisioning. v1.3 adds SSO/SAML, multi-team support.+ IMPORTANT: Requires Drizzle ORM or Kysely for D1 - no direct D1 adapter. v1.4.10 (Dec 2025) adds OAuth 2.1 Provider plugin (MCP deprecated), admin impersonation prevention, background tasks, Patreon/Kick/Vercel OAuth providers. v1.4.0 adds ESM-only (breaking), stateless sessions, SCIM.- Use when: self-hosting auth on Cloudflare D1, migrating from Clerk, implementing multi-tenant SaaS, or troubleshooting D1 adapter errors, session serialization, OAuth flows, TanStack Start cookie issues, nanostore session invalidation.+ Use when: self-hosting auth on Cloudflare D1, building OAuth provider for MCP servers, implementing multi-tenant SaaS, admin dashboards with impersonation, or troubleshooting D1 adapter errors, session serialization, OAuth flows, nanostore invalidation.allowed-tools:- Read- Write@@ -17,8 +17,8 @@ allowed-tools:# better-auth - D1 Adapter & Error Prevention Guide-**Package**: [email protected] (Nov 22, 2025)-**Breaking Changes**: ESM-only (v1.4.0), Multi-team table changes (v1.3), D1 requires Drizzle/Kysely (no direct adapter)+**Package**: [email protected] (Dec 31, 2025)+**Breaking Changes**: ESM-only (v1.4.0), Admin impersonation prevention default (v1.4.6), Multi-team table changes (v1.3), D1 requires Drizzle/Kysely (no direct adapter)---@@ -32,6 +32,33 @@ See Issue #1 below for details.---+## What's New in v1.4.10 (Dec 31, 2025)++**Major Features:**+- **OAuth 2.1 Provider plugin** - Build your own OAuth provider (replaces MCP plugin)+- **Patreon OAuth provider** - Social sign-in with Patreon+- **Kick OAuth provider** - With refresh token support+- **Vercel OAuth provider** - Sign in with Vercel+- **Global `backgroundTasks` config** - Deferred actions for better performance+- **Form data support** - Email authentication with fetch metadata fallback+- **Stripe enhancements** - Flexible subscription lifecycle, `disableRedirect` option++**Admin Plugin Updates:**+- ⚠️ **Breaking**: Impersonation of admins disabled by default (v1.4.6)+- Support role with permission-based user updates+- Role type inference improvements++**Security Fixes:**+- SAML XML parser hardening with configurable size constraints+- SAML assertion timestamp validation with per-provider clock skew+- SSO domain-verified provider trust+- Deprecated algorithm rejection+- Line nonce enforcement++📚 **Docs**: https://www.better-auth.com/changelogs++---+## What's New in v1.4.0 (Nov 22, 2025)**Major Features:**@@ -156,17 +183,78 @@ export const Route = createFileRoute('/api/auth/$')({----## Available Plugins (v1.3+)+## Available Plugins (v1.4+)Better Auth provides plugins for advanced authentication features:| Plugin | Import | Description | Docs ||--------|--------|-------------|------|-| **OIDC Provider** | `better-auth/plugins` | Build your own OpenID Connect provider (become an OAuth provider for other apps) | [📚](https://www.better-auth.com/docs/plugins/oidc-provider) |+| **OAuth 2.1 Provider** | `better-auth/plugins` | Build OAuth 2.1 provider with PKCE, JWT tokens, consent flows (replaces MCP & OIDC plugins) | [📚](https://www.better-auth.com/docs/plugins/oauth-provider) || **SSO** | `better-auth/plugins` | Enterprise Single Sign-On with OIDC, OAuth2, and SAML 2.0 support | [📚](https://www.better-auth.com/docs/plugins/sso) |-| **Stripe** | `better-auth/plugins` | Payment and subscription management (stable as of v1.3+) | [📚](https://www.better-auth.com/docs/plugins/stripe) |-| **MCP** | `better-auth/plugins` | Act as OAuth provider for Model Context Protocol (MCP) clients | [📚](https://www.better-auth.com/docs/plugins/mcp) |-| **Expo** | `better-auth/expo` | React Native/Expo integration with secure cookie management | [📚](https://www.better-auth.com/docs/integrations/expo) |+| **Stripe** | `better-auth/plugins` | Payment and subscription management with flexible lifecycle handling | [📚](https://www.better-auth.com/docs/plugins/stripe) |+| **MCP** | `better-auth/plugins` | ⚠️ **Deprecated** - Use OAuth 2.1 Provider instead | [📚](https://www.better-auth.com/docs/plugins/mcp) |+| **Expo** | `better-auth/expo` | React Native/Expo with `webBrowserOptions` and last-login-method tracking | [📚](https://www.better-auth.com/docs/integrations/expo) |++### OAuth 2.1 Provider Plugin (New in v1.4.9)++Build your own OAuth provider for MCP servers, third-party apps, or API access:++```typescript+import { betterAuth } from "better-auth";+import { oauthProvider } from "better-auth/plugins";+import { jwt } from "better-auth/plugins";++export const auth = betterAuth({+ plugins: [+ jwt(), // Required for token signing+ oauthProvider({+ // Token expiration (seconds)+ accessTokenExpiresIn: 3600, // 1 hour+ refreshTokenExpiresIn: 2592000, // 30 days+ authorizationCodeExpiresIn: 600, // 10 minutes+ }),+ ],+});+```++**Key Features:**+- **OAuth 2.1 compliant** - PKCE mandatory, S256 only, no implicit flow+- **Three grant types**: `authorization_code`, `refresh_token`, `client_credentials`+- **JWT or opaque tokens** - Configurable token format+- **Dynamic client registration** - RFC 7591 compliant+- **Consent management** - Skip consent for trusted clients+- **OIDC UserInfo endpoint** - `/oauth2/userinfo` with scope-based claims++**Required Well-Known Endpoints:**++```typescript+// app/api/.well-known/oauth-authorization-server/route.ts+export async function GET() {+ return Response.json({+ issuer: process.env.BETTER_AUTH_URL,+ authorization_endpoint: `${process.env.BETTER_AUTH_URL}/api/auth/oauth2/authorize`,+ token_endpoint: `${process.env.BETTER_AUTH_URL}/api/auth/oauth2/token`,+ // ... other metadata+ });+}+```++**Create OAuth Client:**++```typescript+const client = await auth.api.createOAuthClient({+ body: {+ name: "My MCP Server",+ redirectURLs: ["https://claude.ai/callback"],+ type: "public", // or "confidential"+ },+});+// Returns: { clientId, clientSecret (if confidential) }+```++📚 **Full Docs**: https://www.better-auth.com/docs/plugins/oauth-provider++⚠️ **Note**: This plugin is in active development and may not be suitable for production use yet.---@@ -330,6 +418,17 @@ import { organization } from "better-auth/plugins";```typescriptimport { admin } from "better-auth/plugins";++// v1.4.10 configuration options+admin({+ defaultRole: "user",+ adminRoles: ["admin"],+ adminUserIds: ["user_abc123"], // Always grant admin to specific users+ impersonationSessionDuration: 3600, // 1 hour (seconds)+ allowImpersonatingAdmins: false, // ⚠️ Default changed in v1.4.6+ defaultBanReason: "Violation of Terms of Service",+ bannedUserMessage: "Your account has been suspended",+})```| Endpoint | Method | Description |@@ -340,7 +439,7 @@ import { admin } from "better-auth/plugins";| `/admin/set-user-password` | POST | Change user password || `/admin/update-user` | PUT | Modify user details || `/admin/remove-user` | DELETE | Delete user account |-| `/admin/ban-user` | POST | Ban user account |+| `/admin/ban-user` | POST | Ban user account (with optional expiry) || `/admin/unban-user` | POST | Unban user || `/admin/list-user-sessions` | GET | Get user's active sessions || `/admin/revoke-user-session` | DELETE | End specific user session |@@ -348,6 +447,40 @@ import { admin } from "better-auth/plugins";| `/admin/impersonate-user` | POST | Start impersonating user || `/admin/stop-impersonating` | POST | End impersonation session |+**⚠️ Breaking Change (v1.4.6)**: `allowImpersonatingAdmins` now defaults to `false`. Set to `true` explicitly if you need admin-on-admin impersonation.++**Custom Roles with Permissions (v1.4.10):**++```typescript+import { createAccessControl } from "better-auth/plugins/access";++// Define resources and permissions+const ac = createAccessControl({+ user: ["create", "read", "update", "delete", "ban", "impersonate"],+ project: ["create", "read", "update", "delete", "share"],+} as const);++// Create custom roles+const supportRole = ac.newRole({+ user: ["read", "ban"], // Can view and ban users+ project: ["read"], // Can view projects+});++const managerRole = ac.newRole({+ user: ["read", "update"],+ project: ["create", "read", "update", "delete"],+});++// Use in plugin+admin({+ ac,+ roles: {+ support: supportRole,+ manager: managerRole,+ },+})+```+📚 **Docs**: https://www.better-auth.com/docs/plugins/admin##### Other Plugin Endpoints@@ -1170,27 +1303,42 @@ await refetch()## Version Compatibility**Tested with**:-- `[email protected]`+- `[email protected]`- `@cloudflare/workers-types@latest`-- `[email protected]`+- `[email protected]`- Node.js 18+, Bun 1.0+-**Breaking changes**: Check changelog when upgrading: https://github.com/better-auth/better-auth/releases+**Breaking changes**:+- v1.4.6: `allowImpersonatingAdmins` defaults to `false`+- v1.4.0: ESM-only (no CommonJS)+- v1.3.0: Multi-team table structure change++Check changelog: https://github.com/better-auth/better-auth/releases++---++## Community Resources++**Cloudflare-specific guides:**+- [zpg6/better-auth-cloudflare](https://github.com/zpg6/better-auth-cloudflare) - Drizzle + D1 reference+- [Hono + better-auth on Cloudflare](https://hono.dev/examples/better-auth-on-cloudflare) - Official Hono example+- [React Router + Cloudflare D1](https://dev.to/atman33/setup-better-auth-with-react-router-cloudflare-d1-2ad4) - React Router v7 guide+- [SvelteKit + Cloudflare D1](https://medium.com/@dasfacc/sveltekit-better-auth-using-cloudflare-d1-and-drizzle-91d9d9a6d0b4) - SvelteKit guide---**Token Efficiency**:-- **Without skill**: ~28,000 tokens (D1 adapter errors, TanStack Start cookies, nanostore invalidation, OAuth flows, API discovery)-- **With skill**: ~5,600 tokens (focused on errors + breaking changes + API reference)-- **Savings**: ~80% (~22,400 tokens)+- **Without skill**: ~30,000 tokens (D1 adapter errors, OAuth provider setup, admin RBAC, MCP deprecation, API discovery)+- **With skill**: ~6,000 tokens (focused on errors + breaking changes + OAuth 2.1 Provider + API reference)+- **Savings**: ~80% (~24,000 tokens)**Errors prevented**: 13 documented issues with exact solutions-**Key value**: D1 adapter requirement, v1.4.0/v1.3 breaking changes, TanStack Start fix, nanostore pattern, 80+ endpoint reference+**Key value**: D1 adapter requirement, OAuth 2.1 Provider (MCP deprecated), admin impersonation breaking change, v1.4.x updates, 80+ endpoint reference----**Last verified**: 2025-11-22 | **Skill version**: 3.0.0 | **Changes**: Added v1.4.0 (ESM-only, stateless sessions, SCIM) and v1.3 (SSO/SAML, multi-team) knowledge gaps. Removed tutorial/setup (~700 lines). Focused on error prevention + breaking changes + API reference.+**Last verified**: 2025-12-31 | **Skill version**: 4.0.0 | **Changes**: Updated to v1.4.10. Added OAuth 2.1 Provider plugin (MCP deprecated). Added admin impersonation breaking change. Added Hono integration template. Added new social providers (Patreon, Kick, Vercel). Added custom RBAC pattern.diff --git a/skills/better-auth/references/hono-cloudflare.ts b/skills/better-auth/references/hono-cloudflare.tsnew file mode 100644index 00000000..9709daff--- /dev/null+++ b/skills/better-auth/references/hono-cloudflare.ts@@ -0,0 +1,237 @@+/**+ * better-auth + Hono + Cloudflare Workers Integration+ *+ * This is the recommended pattern for using better-auth with Hono on Cloudflare Workers.+ * Based on: https://hono.dev/examples/better-auth-on-cloudflare+ *+ * @package [email protected]+ * @package [email protected]+ */++import { Hono } from "hono";+import { cors } from "hono/cors";+import { betterAuth } from "better-auth";+import { drizzleAdapter } from "better-auth/adapters/drizzle";+import { admin, organization, twoFactor, oauthProvider, jwt } from "better-auth/plugins";+import { drizzle } from "drizzle-orm/d1";+import * as schema from "./db/schema";++// ============================================================================+// Types+// ============================================================================++interface Env {+ DB: D1Database;+ BETTER_AUTH_SECRET: string;+ BETTER_AUTH_URL: string;+ GOOGLE_CLIENT_ID?: string;+ GOOGLE_CLIENT_SECRET?: string;+ GITHUB_CLIENT_ID?: string;+ GITHUB_CLIENT_SECRET?: string;+}++// ============================================================================+// Auth Factory (per-request instance)+// ============================================================================++/**+ * Create auth instance with environment bindings.+ *+ * IMPORTANT: better-auth must be instantiated per-request in Workers+ * because env bindings are only available in request context.+ */+export function createAuth(env: Env) {+ const db = drizzle(env.DB, { schema });++ return betterAuth({+ secret: env.BETTER_AUTH_SECRET,+ baseURL: env.BETTER_AUTH_URL,++ database: drizzleAdapter(db, { provider: "sqlite" }),++ // Email + Password Authentication+ emailAndPassword: {+ enabled: true,+ requireEmailVerification: false, // Enable in production+ },++ // Social Providers (optional)+ socialProviders: {+ ...(env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET && {+ google: {+ clientId: env.GOOGLE_CLIENT_ID,+ clientSecret: env.GOOGLE_CLIENT_SECRET,+ scope: ["openid", "email", "profile"],+ },+ }),+ ...(env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET && {+ github: {+ clientId: env.GITHUB_CLIENT_ID,+ clientSecret: env.GITHUB_CLIENT_SECRET,+ scope: ["user:email", "read:user"],+ },+ }),+ },++ // Session Configuration+ session: {+ expiresIn: 60 * 60 * 24 * 7, // 7 days+ updateAge: 60 * 60 * 24, // Update every 24 hours+ },++ // Plugins+ plugins: [+ twoFactor(),+ organization(),+ admin({+ allowImpersonatingAdmins: false, // v1.4.6+ default+ }),+ // Uncomment for OAuth provider capabilities:+ // jwt(),+ // oauthProvider({+ // accessTokenExpiresIn: 3600,+ // refreshTokenExpiresIn: 2592000,+ // }),+ ],+ });+}++// Type helper for the auth instance+export type Auth = ReturnType<typeof createAuth>;++// ============================================================================+// Hono App+// ============================================================================++const app = new Hono<{ Bindings: Env }>();++// CORS middleware for SPA clients+app.use(+ "/api/auth/*",+ cors({+ origin: (origin) => origin, // Or specify allowed origins+ credentials: true,+ allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],+ allowHeaders: ["Content-Type", "Authorization"],+ })+);++// Mount better-auth handler+// Handles all /api/auth/* routes automatically+app.on(["GET", "POST"], "/api/auth/*", async (c) => {+ const auth = createAuth(c.env);+ return auth.handler(c.req.raw);+});++// ============================================================================+// Auth Middleware for Protected Routes+// ============================================================================++/**+ * Middleware to protect routes with authentication.+ *+ * Usage:+ * app.use("/api/protected/*", authMiddleware);+ */+app.use("/api/protected/*", async (c, next) => {+ const auth = createAuth(c.env);++ const session = await auth.api.getSession({+ headers: c.req.raw.headers,+ });++ if (!session) {+ return c.json({ error: "Unauthorized" }, 401);+ }++ // Attach user and session to context for downstream handlers+ c.set("user", session.user);+ c.set("session", session.session);++ await next();+});++// Example protected route+app.get("/api/protected/profile", async (c) => {+ const user = c.get("user");+ return c.json({ user });+});++// ============================================================================+// Admin Middleware+// ============================================================================++/**+ * Middleware to protect admin routes.+ * Requires user to have 'admin' role.+ */+app.use("/api/admin/*", async (c, next) => {+ const auth = createAuth(c.env);++ const session = await auth.api.getSession({+ headers: c.req.raw.headers,+ });++ if (!session) {+ return c.json({ error: "Unauthorized" }, 401);+ }++ // Check for admin role+ if (session.user.role !== "admin") {+ return c.json({ error: "Forbidden" }, 403);+ }++ c.set("user", session.user);+ c.set("session", session.session);++ await next();+});++// Example admin route+app.get("/api/admin/users", async (c) => {+ const auth = createAuth(c.env);++ const users = await auth.api.listUsers({+ query: { limit: 50 },+ headers: c.req.raw.headers,+ });++ return c.json(users);+});++// ============================================================================+// Health Check+// ============================================================================++app.get("/health", (c) => {+ return c.json({ status: "ok", timestamp: new Date().toISOString() });+});++export default app;++// ============================================================================+// Type Augmentation for Hono Context+// ============================================================================++declare module "hono" {+ interface ContextVariableMap {+ user: {+ id: string;+ email: string;+ name: string | null;+ image: string | null;+ role: string | null;+ emailVerified: boolean;+ createdAt: Date;+ updatedAt: Date;+ };+ session: {+ id: string;+ userId: string;+ expiresAt: Date;+ token: string;+ createdAt: Date;+ updatedAt: Date;+ };+ }+}diff --git a/skills/better-auth/rules/better-auth.md b/skills/better-auth/rules/better-auth.mdindex 386facd1..8d005b83 100644--- a/skills/better-auth/rules/better-auth.md+++ b/skills/better-auth/rules/better-auth.md@@ -28,14 +28,27 @@ database: {}```-## v1.4.0 Breaking Changes (Nov 2025)+## v1.4.x Breaking Changes```typescript-/* ❌ CommonJS no longer supported */+/* ❌ CommonJS no longer supported (v1.4.0) */const { betterAuth } = require('better-auth')/* ✅ ESM only */import { betterAuth } from 'better-auth'++/* ❌ MCP plugin deprecated (v1.4.9) */+import { mcp } from 'better-auth/plugins'++/* ✅ Use OAuth 2.1 Provider instead */+import { oauthProvider, jwt } from 'better-auth/plugins'+plugins: [jwt(), oauthProvider({ accessTokenExpiresIn: 3600 })]++/* ❌ Admin impersonation of admins (v1.4.6 default changed) */+admin() // allowImpersonatingAdmins now defaults to false++/* ✅ Explicit if you need admin-on-admin impersonation */+admin({ allowImpersonatingAdmins: true })```## TanStack Start: Cookie Plugin Required