UNPKG

codalware-auth

Version:

Complete authentication system with enterprise security, attack protection, team workspaces, waitlist, billing, UI components, 2FA, and account recovery - production-ready in 5 minutes. Enhanced CLI with verification, rollback, and App Router scaffolding.

1,409 lines (1,054 loc) • 54.9 kB
# AuthCore **Production-ready authentication for Next.js in minutes.** Complete UI components, multi-tenant policies, enterprise security, and 2FA - all customizable source code. [![npm version](https://img.shields.io/npm/v/codalware-auth.svg)](https://www.npmjs.com/package/codalware-auth) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) šŸ“š **[Complete Documentation](https://authcore-liard.vercel.app/)** | šŸš€ **[Quick Start](https://authcore-liard.vercel.app/getting-started/quick-start)** | šŸ“ **[Changelog](https://authcore-liard.vercel.app/changelog)** --- ## Quick Start ```bash # Install package npm install codalware-auth # Interactive setup wizard (RECOMMENDED - truly zero config!) npx authcore init --interactive # The wizard will: # āœ“ Detect your Next.js setup automatically # āœ“ Offer SQLite for instant dev (no database setup needed!) # āœ“ Configure auth provider (NextAuth or Better-Auth) # āœ“ Generate .env with secure defaults # āœ“ Run migrations automatically # āœ“ Create admin user # āœ“ Ready in 2 minutes! ``` **That's it!** Start building: ```tsx import { AuthForm } from 'codalware-auth'; <AuthForm mode="login" onSuccess={(user) => router.push('/dashboard')} /> ``` --- # AuthCore — concise Production-ready authentication for Next.js with components, hooks, and optional template generators. Current version: 3.4.12 Install: ```bash npm install codalware-auth ``` Quick links: - Docs: https://authcore-liard.vercel.app/ - Changelog: ./CHANGELOG.md Notes: - The package supports three template modes (standard, main, full). - This release (3.4.12) rebuilds the template copy script for deterministic scaffolding, applies consistent import rewrites, and refreshes the generated README and `.env.example` guidance for every run. For full usage and examples see the docs site. - `OrganizationSwitcher` - Multi-tenant selector - `SecuritySettings` - Enterprise security controls - **[30+ components →](https://authcore-liard.vercel.app/components)** ### šŸŖ React Hooks - `useAuth`, `useLogin`, `useRegister` - `useTwoFactor`, `useMagicLink` - `useUserProfile`, `useAuditLogs` - **[All hooks →](https://authcore-liard.vercel.app/hooks)** ### šŸ”’ Enterprise Security - Account lockout & rate limiting - Email allowlist/blocklist - Password policies & strength validation - Session management & device tracking - User enumeration protection - **[Security features →](https://authcore-liard.vercel.app/security)** ### šŸ“” Complete API - Authentication endpoints (login, register, 2FA, magic links) - Organization management - Waitlist & billing webhooks - **[API reference →](https://authcore-liard.vercel.app/api-reference)** --- ## Key Features āœ… **Zero Configuration** - Interactive wizard with SQLite default āœ… **Template Generator** - All code copied to YOUR project, fully editable āœ… **Update Management** - `check-updates` and `diff` commands āœ… **Multi-Tenant** - Organizations, teams, custom domains āœ… **Passwordless** - Magic links, email OTP āœ… **2FA/MFA** - TOTP authenticator apps āœ… **Modern UI** - Glassmorphism, dark mode, responsive āœ… **i18n Ready** - English & French included āœ… **Type-Safe** - Full TypeScript support --- ## What's New in v3.4.12 šŸŽ‰ ### Template copier reboot + deterministic scaffolding **Highlights:** - āœ… Rebuilt `scripts/copy-full-template.js` as a lean ESM utility that centralizes directory copying, alias-aware import rewrites, and router detection. - āœ… Supplementary assets (`config`, `locales`, `styles`, `prisma`, and root config files) now go through the same transform pipeline, eliminating lingering `codalware-auth` imports after generation. - āœ… Template README and `.env.example` files regenerate per mode, so dev teams always receive up-to-date instructions when re-running the copier. **Impact:** Both main and full template modes now produce clean projects with correct imports, fresh documentation, and zero duplicate script content. **Tested:** āœ… `npm run lint` at the package root. _(Run the template copier in a throwaway Next.js app to validate your target mode before publishing.)_ šŸ“ **[Full changelog →](https://authcore-liard.vercel.app/changelog)** --- ## CLI Commands ```bash # Setup npx authcore init --interactive # Interactive wizard (recommended) npx authcore init --template-mode=main --migrate --theme # Automated # Database npx authcore migrate # Run migrations npx authcore studio # Open Prisma Studio # Testing npx authcore verify # Test auth endpoints npx authcore status # Check setup status # Updates npx authcore check-updates # Check for new versions npx authcore diff # Compare your changes # Maintenance npx authcore rollback # Remove generated files npx authcore admin:create # Create admin user ``` šŸ“– **[Complete CLI reference →](https://authcore-liard.vercel.app/guides/cli-reference)** --- ## Documentation šŸ“š **[authcore-liard.vercel.app](https://authcore-liard.vercel.app/)** - [Quick Start Guide](https://authcore-liard.vercel.app/getting-started/quick-start) - [Installation](https://authcore-liard.vercel.app/getting-started/installation) - [Configuration](https://authcore-liard.vercel.app/getting-started/configuration) - [Component Demos](https://authcore-liard.vercel.app/components) - [Hooks API](https://authcore-liard.vercel.app/hooks) - [Security Features](https://authcore-liard.vercel.app/security) - [Examples](https://authcore-liard.vercel.app/examples) --- ## Requirements - Node.js 18+ | Next.js 13+ | React 18+ - Prisma 5+ or Drizzle ORM - NextAuth 4.24+ OR Better-Auth 0.1+ --- ## Support - šŸ“– [Documentation](https://authcore-liard.vercel.app/) - šŸ“¦ [NPM Package](https://www.npmjs.com/package/codalware-auth) - šŸ› Issues: Check documentation or review examples --- **Current version: 3.4.12** (October 26, 2025) Released under the MIT License. ## Zero-Configuration Quick Start ```bash npm install codalware-auth # Interactive setup wizard (RECOMMENDED - truly zero config!) npx authcore init --interactive # The wizard will: # Detect your Next.js setup automatically # Offer SQLite for instant dev (no database setup needed!) # Configure auth provider (NextAuth or Better-Auth) # Generate .env with secure defaults # Run migrations automatically # Create admin user with password # Install components and routes # Ready in 2 minutes! # Or use command-line flags for CI/CD npx authcore init --template-mode=full --migrate --with-api=app --seed-admin --theme -y ``` ## Three Setup Modes ### Interactive Mode (Zero Config - RECOMMENDED) ```bash npx authcore init --interactive ``` - Truly zero configuration needed - SQLite by default (no database setup!) - Guides you through every option - Auto-generates secure .env - Creates admin user automatically - Production-ready in minutes ### MAIN TEMPLATE MODE ```bash npx authcore init --template-mode=main ``` - **AuthCore becomes your primary source code** - complete source tree copied - All files from `src/` (adapters, auth, components, hooks, config, email, i18n, lib, types, utils, validation, pages, app) - Files copied directly to `src/components/`, `src/hooks/`, `src/auth/`, `src/lib/`, etc. - Import from `@/components`, `@/hooks`, `@/auth`, `@/lib` (no subdirectories) - Complete ownership - modify everything as your main codebase - 157+ source files with all dependencies and imports wired up - Perfect for: Projects where AuthCore IS the application ### FULL TEMPLATE MODE ```bash npx authcore init --template-mode=full ``` - Copies ALL source code to your project - Import from `@/components/authcore` instead of `codalware-auth` - Modify any component, hook, or logic file - No dependency on the package (optional to keep for updates) - Perfect for: Custom designs, unique workflows, full control ### Standard Mode ```bash npx authcore init ``` - Imports components from `codalware-auth` - Smaller project size - Easier updates via npm - Perfect for: Quick setup, standard flows The CLI scaffolds Prisma schema, API routes, server actions, adapters, and environment templates. Configure `.env`, run migrations, and you're ready to launch. Use `npx authcore rollback` to cleanly remove generated files. ## Choosing Your Auth Provider AuthCore supports two production-ready authentication providers. Choose the one that fits your needs: ### NextAuth.js (Stable & Battle-Tested) ```bash npx authcore init --auth-provider=nextauth --with-api=app ``` - **Mature & Stable** - Used by thousands of production apps - **50+ Social Providers** - Google, GitHub, Twitter, Discord, etc. - **Extensive Documentation** - Large community & ecosystem - **Enterprise Ready** - Battle-tested in production - **JWT & Database Sessions** - Flexible session management **Best for:** Production apps, enterprises, extensive OAuth requirements ### Better Auth (Modern & Type-Safe) ```bash npx authcore init --auth-provider=better-auth --with-api=app ``` - **Modern TypeScript** - Fully type-safe, excellent DX - **Zero Configuration** - Works out of the box, no placeholders - **Auto-Detection** - Smart database & provider configuration - **Built-in Features** - 2FA, organizations, magic links - **Smaller Bundle** - Optimized for performance **Best for:** New projects, TypeScript-first teams, modern stack ### Interactive Setup (Let the Wizard Decide) ```bash npx authcore init --interactive ``` The interactive wizard will: - Ask which provider you prefer - Ask which database you want - Auto-install required packages - Generate provider-specific configuration - Set up API routes automatically - Configure environment variables - **No manual setup needed!** ### What Gets Installed **NextAuth Setup:** - `/app/api/auth/[...nextauth]/route.ts` - Auth handler - `/lib/auth.ts` - NextAuth configuration - Auto-installs: `next-auth`, `@next-auth/prisma-adapter` **Better Auth Setup:** - `/app/api/auth/[...all]/route.ts` - Auth handler - `/lib/better-auth.ts` - Server configuration - `/lib/better-auth-client.ts` - Client hooks - Auto-installs: `better-auth` ## Multi-Database & ORM Support AuthCore supports **6 production-ready databases** and **2 ORM options** out of the box. Choose what works best for your project: ### ORM Options | ORM | Best For | Features | |-----|----------|----------| | **Prisma** (Default) | Type-safety, Auto-migrations | Auto-complete, Schema validation, Easy migrations | | **Drizzle** | Performance, SQL-like | Lightweight, SQL queries, Full TypeScript | ### Database Options | Database | Best For | Setup Time | External Service | |----------|----------|-----------|------------------| | **MySQL** (Default) | Production, Most reliable | 2 minutes | Required | | **PostgreSQL** | Advanced features | 2 minutes | Required | | **SQLite** | Development, Testing | 30 seconds | None needed | | **Neon** | Serverless Postgres | 1 minute | Free tier | | **Supabase** | Full Backend platform | 1 minute | Free tier | | **PlanetScale** | Serverless MySQL | 1 minute | Free tier | ### Zero-Config Development Setup ```bash npx authcore init --interactive # 1. Select ORM: "Prisma (Recommended)" # 2. Select Database: "SQLite (Zero-config for dev)" # 3. Select Auth: "NextAuth.js" or "Better Auth" # No external database needed! # Everything auto-configured! # Start coding immediately! ``` ### Production-Ready MySQL Setup (Recommended) ```bash npx authcore init --interactive # 1. Select ORM: "Prisma (Recommended)" # 2. Select Database: "MySQL (Recommended for production)" # 3. Enter your MySQL connection details # Auto-configured with best practices! # Connection pooling enabled! # Optimized charset and collation! ``` ### Production Setup Examples **Neon (Serverless Postgres):** ```bash npx authcore init --interactive # Select: "Neon Serverless Postgres" # Enter your Neon connection string from console.neon.tech # Auto-scales with your traffic # Connection pooling built-in ``` **Supabase (Backend-as-a-Service):** ```bash npx authcore init --interactive # Select: "Supabase" # Enter your Supabase connection string # Includes realtime, storage, auth # Dashboard for database management ``` **PlanetScale (Serverless MySQL):** ```bash npx authcore init --interactive # Select: "PlanetScale MySQL" # Enter your PlanetScale connection string from app.planetscale.com # Database branching workflow # Non-blocking schema changes ``` ### Features - **Auto-Detection** - Prisma schema updated automatically - **Runtime Detection** - Better Auth detects provider from DATABASE_URL - **Easy Migration** - Start with SQLite, move to production DB anytime - **No Lock-in** - Use any Prisma-supported database - **Connection Pooling** - Serverless options include built-in pooling ### Switching Providers ``` You can switch providers anytime: ```bash # Switch to Better Auth npx authcore init --auth-provider=better-auth --with-api=app # Switch to NextAuth npx authcore init --auth-provider=nextauth --with-api=app ``` Both providers work with all AuthCore features: 2FA, organizations, RBAC, audit logs, etc. ## Highlights - **Template Generator**: Scaffolds complete auth infrastructure directly into YOUR project - all code is visible and editable - **Not a Black Box**: Generated code includes `// CUSTOMIZE` comments and file metadata showing update safety - Policy-aware auth forms adapt automatically when you enable magic links, enforced 2FA, email OTPs, or approval workflows - NextAuth + Better-Auth provider abstraction with automatic detection - **Update Management**: Built-in `check-updates` and `diff` commands to safely manage updates - Glassmorphism UI kit with translations, theme, and Tailwind preset included out of the box See the documentation for feature tours, flow diagrams, and adapter guides. The doc site showcases the full step-by-step experience for modal and standalone auth surfaces, plus every toggle you can enable. --- ## Next steps 1. Follow the Quick Start: <https://authcore-liard.vercel.app/getting-started/quick-start> 2. Review the flow gallery: <https://authcore-liard.vercel.app/flows> 3. Track releases: <https://authcore-liard.vercel.app/changelog> --- Released under the MIT License. --- ## What's New in v3.4.4 ### CRITICAL FIX - src/ Directory Structure **Template mode now correctly respects your project's folder structure!** - **Smart Detection**: Automatically detects if your project uses `src/` directory - **Correct Placement**: - Projects WITH `src/`: API routes go to `src/app/` - Projects WITHOUT `src/`: API routes go to root `app/` - **No More Errors**: Prevents build failures from incorrect folder placement - **Tested**: All three template modes verified with real Next.js projects **Why This Matters**: Previous version could place `app/` folder in wrong location, causing build errors and making API routes inaccessible. Now everything goes to the right place automatically. āœ… Standard mode: Package imports work āœ… Main template (no src/): API routes in `app/` āœ… Full template (with src/): API routes in `src/app/` ## What's New in v3.4.3 ### Template Mode Complete - API Routes & Full Source Access **Template mode now includes ALL source files and API routes!** - **Complete API Structure**: Template copy now includes 14+ API route files - `app/api/auth/` - Login, register, magic links, 2FA verification - `app/api/organizations/` - Organization management - `app/api/waitlist/` - Waitlist functionality - `app/api/webhooks/` - Webhook handlers - `app/actions/` - Server actions for auth and waitlist - `app/services/` - Auth adapter and type definitions - **Source Code Access**: `src/` folder now included in npm package for full customization - **Auto-Detection**: Automatically detects App Router vs Pages Router and copies appropriate structure - **Production Ready**: Get a complete, working auth system with one command - Main template mode now copies **92 files** (up from 78) including all API routes **Before v3.4.3**: Template mode only copied components and hooks (missing API routes) **Now**: Complete authentication system with all API endpoints ready to customize ## What's New in v3.4.0 ### Multi-ORM Security Support **All security features now work with ANY supported ORM!** Previously in v3.4.0 beta, security features only worked with Prisma. Now they work with: - **Prisma** (Default) - **Drizzle** - **PostgreSQL** (Raw SQL) - **Appwrite** - **Memory** (In-memory storage) The same adapter pattern that powers core authentication now extends to all enterprise security features. Use any ORM - the security components, APIs, and database operations automatically adapt. ### Enterprise Security Features **NEW: Comprehensive security management for production applications** - **SecuritySettingsManager** - Complete security configuration interface - Sign-up mode control (Public, Restricted, Waitlist) - Account lockout policies with customizable thresholds - Password complexity requirements with strength validation - Session timeout and concurrent session limits - IP whitelisting and blacklisting - MFA enforcement for administrators - **Works with any ORM** - Prisma, Drizzle, PostgreSQL, Appwrite, Memory - **AccountLockoutManager** - Monitor and manage account security - View all locked accounts with unlock times - Manual unlock functionality - Recent login attempt history with IP tracking - Failed login reason tracking - **ORM-agnostic** - Uses adapter pattern - **EmailListManager** - Email access control - Email allowlist (restrict to specific emails/domains) - Email blocklist (prevent specific emails/domains) - Wildcard support (@domain.com) - Easy add/remove interface - **Database-independent** - Works with your chosen backend **8 New API Endpoints** (All ORM-agnostic): - `/api/tenant/security-settings` - GET/PATCH security config - `/api/tenant/security/locked-accounts` - View locked accounts - `/api/tenant/security/locked-accounts/[id]/unlock` - Manual unlock - `/api/tenant/security/login-attempts` - Login history - `/api/tenant/security/email-allowlist` - GET/POST/DELETE - `/api/tenant/security/email-blocklist` - GET/POST/DELETE **Enhanced Configuration:** - All security features configurable via `authcore.config.json` - Environment variable support for all settings - Auto-create defaults from config when missing - Choose your ORM, security features adapt automatically See the complete [CHANGELOG](./CHANGELOG.md) for details. --- ## What's New in v3.3.6 ### Zero-Configuration Excellence - ** No More Placeholders**: All templates ship with production-ready values - no more "your-value-here" - ** Smart Project Detection**: Automatically detects `src/` vs root structure, places files correctly - ** Auto-Provider Setup**: Better Auth auto-installs and configures when selected - ** Instant Setup**: `npx authcore init --interactive` - truly zero configuration needed - ** No Duplicate Folders**: Fixed bug causing duplicate app/ or src/ directories - ** Clean Code**: All linting errors resolved, duplicate functions removed ### Better Auth Improvements - **Production-Ready Config**: Auto-detects database provider from DATABASE_URL - **Smart Social Auth**: OAuth providers auto-enable when credentials provided - **Environment Intelligence**: All env variables have working defaults - **Type-Safe Throughout**: Full TypeScript support with proper imports - **Comprehensive .env.example**: Real values, not placeholders ### Developer Experience - **Interactive Wizard**: Guides through every option with smart defaults - **Clear Documentation**: Updated README with provider selection guide - **Better Error Messages**: Helpful output throughout installation - **One-Command Setup**: From zero to production-ready in minutes ### Bug Fixes - Fixed `SyntaxError: Identifier already declared` in copy-full-template.js - Fixed duplicate function declarations - Fixed linting error: `@typescript-eslint/no-explicit-any` - Fixed project structure detection for src/ directories - Fixed API routes placement in Next.js projects --- ## What's New in v3.3.5 ### Package Exports (NPM) **Core Authentication Components** - Available via `npm install codalware-auth`: - `AuthForm` - Main authentication component (login, register, password reset, 2FA) - `AuthModal` - Modal wrapper for AuthForm - `PasswordInput` - Password field with visibility toggle - `LoadingSpinner` - Loading indicator - `withAuthentication` - HOC for route protection - `OtpInput` - UI component for OTP/verification codes - All hooks, i18n, config, validation, and TypeScript types **Full Component Library** - Still available via template modes: - `UserProfile`, `ProfileDropdown`, `ProfileTabs` - User profile management - `AdminSettings` - Admin dashboard components - `TwoFactorSetup` - 2FA setup wizard - `DashboardLayout`, `PageLayout` - Layout components - `ThemeSwitcher`, `PasswordStrengthIndicator` - UI utilities - **Organization Components**: `OrganizationSwitcher`, `CreateOrganization`, etc. - **Billing Components**: `PricingTable`, `CheckoutPage`, payment methods - **Waitlist Components**: `WaitlistForm` and management - **Security Components**: `SecuritySettings`, `EmailListManager` ### Changes - **Removed from Source**: Deleted legacy `LoginForm` and `RegisterForm` (replaced by unified `AuthForm` in v3.0.0) - **Simplified NPM Exports**: Package now exports only core authentication components to reduce bundle size - **Template Modes Unchanged**: All 30+ components remain available when using `--template-mode=full` or `--template-mode=main` ### How to Access All Components ```bash # Option 1: Full Template Mode (Recommended for customization) npx authcore init --template-mode=full # Copies ALL components to src/components/authcore/ # Import: import { UserProfile } from '@/components/authcore' # Option 2: Main Template Mode npx authcore init --template-mode=main # Copies ALL components directly to src/components/ # Import: import { UserProfile } from '@/components' ``` ### Migration Guide **If you were using `LoginForm` or `RegisterForm` from npm:** ```tsx // Before (v3.3.4) import { LoginForm, RegisterForm } from 'codalware-auth'; // After (v3.3.5) import { AuthForm } from 'codalware-auth'; <AuthForm mode="login" /> <AuthForm mode="register" /> ``` **If you need other components** (Profile, Admin, Organization, Billing, Waitlist): - Use template mode to get full source code: `npx authcore init --template-mode=full` - All components work exactly as before, just accessed via local imports ## What's New in v3.3.4 ### Release note - Zero ESLint warnings/errors across the repository; removed all explicit `any` usages and improved TypeScript typings. - Type-safety and runtime wiring improvements to middleware, hooks, and components to ensure the package builds and ships cleanly. ### Glassmorphic Auth Experience - `AuthForm` now renders inside layered glass panels with gradient atmospherics, polished switcher controls, and a refined step progress bar that mirrors the documentation site aesthetic. - Social login clusters received their own frosted card so marketing pages and dashboards inherit the upgraded visual weight without extra configuration. ### Password Guidance Enhancements - The password strength indicator ships with curated gradients, requirement tracking, and actionable recommendations that surface automatically during registration flows. - Headings and copy within the form were tuned for clarity, keeping the experience professional across light and dark modes. ### Inline Password Visibility Toggle - `TextInput` exposes the eye icon toggle across every password field so end users can quickly confirm entries without leaving the polished UI. --- ## What's New in v3.1.1 (archive) ### README Updates & Documentation Fixes - Fixed version inconsistencies throughout documentation - Updated Requirements section to reflect both NextAuth and Better-Auth support - Clarified peer dependency installation for both providers - Corrected release date to October 16, 2025 ### Provider Abstraction Layer (introduced in v3.1.0) - Choose between NextAuth or Better-Auth without changing component code - Universal hooks API: `useSession()`, `useSignIn()`, `useSignOut()` work with both providers - Better-Auth integration: Modern TypeScript-first authentication as an alternative to NextAuth - Switch providers via `NEXT_PUBLIC_AUTH_PROVIDER` environment variable - Zero breaking changes: Existing NextAuth implementations continue working - Optional peer dependencies: Install only the authentication provider you need ### Previous Release (v3.0) - Component Auto-Wiring: All 84 client components + 50 server exports work immediately after installation - Enhanced CLI: Dry-run mode, router selection, database choice, theme installation - App Router Support: Complete templates with server actions, adapters, and typed services - Verification Workflow: `npx authcore verify` tests critical endpoints - Rollback Support: Safe file removal with manifest tracking - Smart Templates: CUSTOMIZE comments guide schema adaptation See the [Changelog](https://authcore-liard.vercel.app/changelog) for full details. --- ## AuthCore - Complete Authentication System [![npm version](https://img.shields.io/npm/v/codalware-auth.svg)](https://www.npmjs.com/package/codalware-auth) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) **Production-ready authentication system that you can integrate in 5 minutes.** AuthCore provides everything you need for modern authentication: UI components, server logic, 2FA, email verification, account recovery, webhooks, and complete customization access. **Complete documentation:** [https://authcore-liard.vercel.app/](https://authcore-liard.vercel.app/) --- ## Provider Abstraction: NextAuth or Better-Auth Choose your authentication provider without changing any component code. AuthCore v3.1.0+ introduces a unified provider abstraction layer that supports both NextAuth and Better-Auth seamlessly. ### Why Provider Abstraction? - **Flexibility**: Switch providers by changing one environment variable - **Modern Options**: Use Better-Auth's TypeScript-first approach or stick with battle-tested NextAuth - **Smaller Bundles**: Install only the provider you need as an optional peer dependency - **Easy Migration**: Migrate from NextAuth to Better-Auth (or vice versa) without touching component code - **Zero Breaking Changes**: Existing NextAuth implementations continue working perfectly ### Quick Comparison | Feature | NextAuth | Better-Auth | |---------|----------|-------------| | **TypeScript** | Good | Excellent (TypeScript-first) | | **Social OAuth** | Full support | Full support | | **Email/Password** | Via credentials | Built-in | | **Magic Links** | Via email provider | Built-in | | **2FA/MFA** | Custom implementation | Built-in TOTP | | **Session Management** | JWT or Database | Database sessions | | **Edge Runtime** | Supported | Optimized | | **Bundle Size** | Medium | Smaller | | **Maturity** | Very mature | Newer, active development | ### Setup with NextAuth (Default) ```bash # 1. Install NextAuth peer dependencies npm install next-auth @next-auth/prisma-adapter # 2. Set provider in .env NEXT_PUBLIC_AUTH_PROVIDER=nextauth # 3. Use AuthCore components - they work automatically! import { AuthForm, useSession, useSignIn } from 'codalware-auth'; ``` ### Setup with Better-Auth (Available in v3.1.0+) ```bash # 1. Install Better-Auth peer dependency npm install better-auth # 2. Set provider in .env NEXT_PUBLIC_AUTH_PROVIDER=better-auth # 3. Use the SAME components - no code changes needed! import { AuthForm, useSession, useSignIn } from 'codalware-auth'; ``` ### Universal Hooks API All hooks work identically with both providers: ```tsx import { useSession, useSignIn, useSignOut } from 'codalware-auth'; function MyComponent() { // Works with both NextAuth and Better-Auth const { data: session, status } = useSession(); const signIn = useSignIn(); const signOut = useSignOut(); if (status === 'loading') return <Spinner />; return ( <div> {session ? ( <> <p>Welcome, {session.user?.name}!</p> <button onClick={() => signOut()}>Sign Out</button> </> ) : ( <button onClick={() => signIn('google')}>Sign In with Google</button> )} </div> ); } ``` ### Social OAuth with Both Providers Configure social providers in your auth setup: **NextAuth** (`pages/api/auth/[...nextauth].ts`): ```typescript import NextAuth from 'next-auth'; import GoogleProvider from 'next-auth/providers/google'; import GitHubProvider from 'next-auth/providers/github'; export default NextAuth({ providers: [ GoogleProvider({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET }), GitHubProvider({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET }), ], }); ``` **Better-Auth** (`lib/auth.ts`): ```typescript import { betterAuth } from 'better-auth'; export const auth = betterAuth({ socialProviders: { google: { clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET }, github: { clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET }, }, }); ``` **Your components** (same code for both): ```tsx import { AuthForm } from 'codalware-auth'; <AuthForm mode="login" socialProviders={['google', 'github', 'discord']} onSuccess={(user) => router.push('/dashboard')} /> ``` ### Migration Guide **Migrating from NextAuth to Better-Auth:** 1. Install Better-Auth: `npm install better-auth` 2. Create Better-Auth configuration file 3. Update environment variable: `NEXT_PUBLIC_AUTH_PROVIDER=better-auth` 4. Restart dev server - **that's it!** All components continue working **No code changes required** in your React components, pages, or layouts! ### Technical Details The provider abstraction uses React hooks and dynamic imports to detect which provider you're using: - **Environment Detection**: Reads `NEXT_PUBLIC_AUTH_PROVIDER` (defaults to `nextauth`) - **Dynamic Loading**: Imports the appropriate provider package at runtime - **Type Safety**: Full TypeScript support with proper typing for both providers - **React Hooks Compliance**: All hooks follow React rules - no conditional hook calls For complete implementation details, see [BETTER_AUTH_INTEGRATION.md](./BETTER_AUTH_INTEGRATION.md) and [PROVIDER_ABSTRACTION_SUMMARY.md](./PROVIDER_ABSTRACTION_SUMMARY.md). --- ## Update Management AuthCore v3.3.3 includes powerful update management tools to keep your authentication system current: ### Check for Updates ```bash # Check if there's a new version available npx authcore check-updates # This shows: # - Current version vs latest version # - Type of update (major/minor/patch) # - Breaking changes warnings # - List of files you've customized ``` ### Compare Your Changes ```bash # See all differences between your files and the template npx authcore diff # Compare a specific file npx authcore diff --file app/api/auth/register/route.ts # This shows: # - Files you've modified # - Line-by-line differences # - Statistics (additions/deletions) # - Git diff format for easy reading ``` ### Understanding File Metadata Files copied by AuthCore include metadata headers: ```typescript /** * @authcore-version 3.3.3 * @authcore-safe-to-update true * @authcore-customization-level low * * @customization-points * - Email validation rules * - Password requirements * - Rate limiting thresholds */ ``` - **safe-to-update**: `true` = safe to overwrite, `false` = review changes carefully - **customization-level**: `low`/`medium`/`high` indicates expected modification frequency - **customization-points**: Lists common areas developers modify ### Update Strategies **For Full Template Mode:** - Review changes with `npx authcore diff` - Manually merge updates to customized files - Safe-to-update files can be overwritten - High-customization files require careful review **For Standard Mode:** - Update package: `npm install codalware-auth@latest` - Component imports get new features automatically - Review breaking changes in changelog --- ## Features ### Complete UI Components - Pre-built login/register forms with validation and filterable social login providers - Policy-aware auth flows that honor tenant rules (magic link vs. password, enforced 2FA, email OTP guidance) without extra wiring - 2FA setup wizard with QR codes - Account restoration and password reset - User profile management - Organization and team management - Modern checkout page with pluggable payment methods, brandable provider logos, and a pay button that reflects the total due - Dark mode support - Fully responsive and accessible - Two-factor authentication (TOTP) - User enumeration protection - Bot protection (Cloudflare Turnstile) - Email restrictions (allowlist/blocklist) - Disposable email blocking - Session and device tracking - English & French dictionaries bundled by default - `registerDictionary(locale, messages)` helper for custom locales - Webhook-friendly status updates secured via `AUTHCORE_CHECKOUT_SECRET` - Checkout UI component ready to host Stripe Elements, Adyen Drop-in, Paddle, or manual invoicing --- --- ## Quick Installation ### 1. Install the Package ```bash npm install codalware-auth ``` ### 2. Install Required Peer Dependencies ```bash # Core dependencies (always required) npm install @prisma/client npm install -D prisma # Choose your authentication provider (install only one) # Option A: NextAuth (default) npm install next-auth @next-auth/prisma-adapter # Option B: Better-Auth (alternative) npm install better-auth # Optional: only if you plan to send transactional emails npm install nodemailer ``` > **Note:** codalware-auth automatically installs its utility dependencies (react-icons, zxcvbn, bcryptjs, etc.). > Choose either NextAuth or Better-Auth as your authentication provider. The provider abstraction layer will automatically detect which one you're using via the `NEXT_PUBLIC_AUTH_PROVIDER` environment variable. ### 3. Initialize AuthCore (Enhanced CLI) The AuthCore CLI scaffolds a complete auth stack with database schema, API routes, server actions, adapters, and verification tools. #### Quick Start ```bash # Interactive setup (recommended) npx authcore init # Automated setup with all features npx authcore init --migrate --with-api=app --seed-admin --theme # Preview changes without modifying files npx authcore init --dry-run --with-api=both ``` #### CLI Flags | Flag | Description | |------|-------------| | `--yes, -y` | Accept all defaults without prompts | | `--migrate` | Run database migrations automatically | | `--with-api <router>` | Copy API templates: `pages`, `app`, `both`, or `none` | | `--router <type>` | Choose router: `app` (default) or `pages` | | `--db <type>` | Choose ORM: `prisma` (default), `drizzle`, or `none` | | `--seed-admin` | Create super admin user after setup | | `--theme` | Install AuthCore theme styles | | `--no-theme` | Skip theme installation | | `--dry-run` | Show what would be created without writing files | #### What the CLI Creates **Core Files:** - `prisma/schema.prisma` Complete auth database schema - `.env.example` All required environment variables (DATABASE_URL, NEXTAUTH_SECRET, SMTP, Stripe, etc.) - `.scaffold-auth/manifest.json` Audit trail of created files **API Routes (when using `--with-api`):** - App Router: `app/api/auth/*`, `app/api/waitlist`, `app/api/organizations` - Pages Router: `pages/api/auth/*`, `pages/api/waitlist`, etc. - Includes: register, login, 2FA, magic links, policy, webhooks **Server Actions (App Router only):** - `src/actions/auth.ts` register, login, verify, logout actions - `src/actions/waitlist.ts` waitlist management **Adapters & Types:** - `src/services/auth/adapter.ts` Map your DB models to AuthCore expectations - `src/services/auth/types.ts` TypeScript definitions **Scripts:** - `scripts/verify-auth.js` Smoke tests for your auth endpoints - `scripts/undo-scaffold-auth.js` Rollback generated files #### CLI Commands ```bash # Setup and initialization npx authcore init # Interactive setup wizard npx authcore setup # Alternative setup flow # Database operations npx authcore migrate # Run database migrations npx authcore generate # Generate Prisma client npx authcore studio # Open Prisma Studio (DB GUI) # Testing and verification npx authcore verify # Run smoke tests against endpoints npx authcore verify --url=https://staging.app.com # Test remote server npx authcore status # Check setup status # User management npx authcore admin:create # Create super admin user # Maintenance npx authcore rollback # Remove all generated files npx authcore rollback --dry-run # Preview what would be deleted # Update Management (Enhanced in v3.3.3) npx authcore check-updates # Check for available updates npx authcore diff # Show differences from templates npx authcore diff --file=app/api/auth/register/route.ts # Diff specific file # Styling npx authcore styles:install # Install theme CSS ``` #### Verification Workflow After setup, verify your auth stack: ```bash # 1. Start your dev server npm run dev # 2. Run verification tests npx authcore verify # The verify command tests: # - POST /api/auth/register (user creation) # - POST /api/auth/check-2fa (2FA status) # - GET /api/auth/policy (tenant policy) # - POST /api/waitlist (waitlist join) # - GET /api/organizations (org listing) ``` #### Rollback & Manifest Every `init` creates a manifest at `.scaffold-auth/manifest.json` tracking all generated files and migrations. To undo: ```bash npx authcore rollback # Interactive deletion npx authcore rollback --dry-run # Preview only ``` **Note:** Database migrations are NOT automatically rolled back. The rollback command will print safe instructions for reverting schema changes. > **App Router Users:** Generated templates include `// CUSTOMIZE` comments showing where to adapt code to your schema. The adapter pattern lets you map your existing User/Tenant models to AuthCore expectations without changing your database structure. --- ## Template Generator Approach **AuthCore is NOT just a component library** - it's a comprehensive auth template generator that scaffolds production-ready authentication code directly into your project. ### Why Template Generation? **Traditional Component Libraries:** ``` node_modules/auth-library/ hidden code you can't easily customize ``` **AuthCore Approach:** ``` your-project/ app/api/auth/ YOUR code, fully editable src/services/ YOUR adapters prisma/schema.prisma YOUR database node_modules/codalware-auth/ Just utilities ``` ### Benefits - **Full Visibility**: All auth code is in YOUR project, not hidden in node_modules - **Complete Customization**: Modify any file - add fields, change logic, integrate services - **No Lock-in**: You own the code. Remove the package anytime and keep your auth working - **Easy Debugging**: Set breakpoints, add logs, see exactly what's happening - **Update Control**: Use `check-updates` and `diff` to review changes before applying ### Generated Code Includes Metadata Every generated file has helpful metadata: ```typescript /** * @authcore-version 3.3.3 * @authcore-safe-to-update true * @authcore-customization-level low * * CUSTOMIZATION POINTS: * - Line 45: Add custom validation * - Line 78: Modify webhooks */ ``` This tells you: - Whether the file is safe to update - How much customization is expected - Exactly where to add your custom logic ### Update Management ```bash # Check what's new npx authcore check-updates # Output: # Update available! # Current: 3.3.0 Latest: 3.3.3 # Changes: Security patches, new features # Customized files: 3 detected # See what changed npx authcore diff # Shows which files you've modified # Compares with latest templates # Safe updates npx authcore diff --file=app/api/auth/register/route.ts # Review specific file changes before updating ``` --- ## Component Auto-Wiring **All AuthCore components automatically connect to your APIs, server actions, email flows, and auth policies after installation.** No manual wiring required! ### What Gets Auto-Wired 1. **Client Components** (84 exports from `codalware-auth`): - `AuthForm`, `LoginForm`, `RegisterForm` Call `/api/auth/policy` and render forms based on tenant rules - `TwoFactorSetup`, `TwoFactorVerify` Wire to `/api/auth/2fa/*` endpoints - `WaitlistForm` Posts to `/api/waitlist` - `CreateOrganization` Calls `/api/organizations` - `UserProfile`, `ProfileDropdown`, `DashboardLayout` Use session context automatically - All hooks: `useAuth`, `useLogin`, `useRegister`, `useMagicLink`, `useTwoFactor`, `useAuthPolicy` 2. **Server Functions** (50 exports from `codalware-auth/server`): - `AuthService`, `TenantService`, `TwoFactorService` Used in API routes and server actions - Middleware: `withAuth`, `withTenant`, `requireAdmin`, `protectedRoute` - Utils: `TokenUtils`, `PasswordUtils`, email service 3. **API Routes & Actions** (generated by CLI): - App Router: `app/api/auth/*` routes + `src/actions/auth.ts` server actions - Pages Router: `pages/api/auth/*` routes - All routes import from `codalware-auth/server` and work immediately 4. **Email Flows**: - Verification emails, magic links, password reset Use `emailService` from server package - Templates use your `EMAIL_FROM` and SMTP config from `.env` 5. **Auth Policies**: - Components call `GET /api/auth/policy` Returns tenant-specific rules - Forms adapt UI based on: `requiresMagicLink`, `enforces2FA`, `requiresEmailVerification`, etc. - No prop drilling or manual config ### How It Works ```tsx // 1. Install and init npm install codalware-auth npx authcore init --with-api=app // 2. Import and use - components auto-connect! import { AuthForm, useAuth } from 'codalware-auth'; function LoginPage() { const { user, loading } = useAuth(); // Automatically uses NextAuth session return ( <AuthForm mode="login" onSuccess={(user) => router.push('/dashboard')} // Component automatically: // - Fetches /api/auth/policy // - Shows/hides password/magic link based on tenant // - Handles 2FA if enforced // - Sends verification emails /> ); } // 3. Server actions work too (App Router) import { loginAction } from '@/actions/auth'; // Generated by CLI async function handleLogin(formData: FormData) { const result = await loginAction(formData); if (result.success) { // Auto-wired with AuthService from codalware-auth/server } } ``` ### Verification After installation, verify everything is wired correctly: ```bash npm run dev npx authcore verify # Output: # POST /api/auth/register - 200 OK # POST /api/auth/check-2fa - 200 OK # GET /api/auth/policy - 200 OK # POST /api/waitlist - 200 OK # GET /api/organizations - 200 OK ``` ### Customization While components auto-wire, you can still customize behavior: ```tsx // Override policy fetching <AuthForm customPolicyUrl="/custom-policy-endpoint" mode="login" /> // Use your own API endpoints <WaitlistForm apiEndpoint="/api/v2/waitlist" /> // Fully custom components with exported hooks import { useLogin } from 'codalware-auth'; function CustomLogin() { const { login, isLoading, error } = useLogin(); // Build your own UI using the hook } ``` See [Component Documentation](https://authcore-liard.vercel.app/components) for all props and customization options. --- ### Environment variables overview ```env # Database # DATABASE_URL=postgresql://... # Email (choose SMTP or provider helpers) EMAIL_SERVER_HOST="smtp.gmail.com" EMAIL_SERVER_PORT="587" EMAIL_FROM="AuthCore <noreply@yourapp.com>" # Auth NEXTAUTH_URL="http://localhost:3000" # Billing (optional) # BILLING_WEBHOOK_SECRET=... ``` > Need deeper guidance? Follow the dedicated [Email Setup guide](https://authcore-liard.vercel.app/guides/email-setup) for step-by-step SMTP troubleshooting, deployment tips, and examples for Gmail, Resend, and other providers. ### 5. Import the Theme & Start Using Components ```tsx // app/layout.tsx or pages/_app.tsx import 'codalware-auth/styles/theme.css' import { AuthForm, CreateOrganization } from 'codalware-auth' export default function LoginPage() { return ( <div className="space-y-10"> <AuthForm mode="login" onSuccess={(user) => console.log('Logged in:', user)} /> <CreateOrganization onOrganizationCreate={(org) => console.log('New org:', org)} /> </div> ) } ``` > **Note:** The post-install script injects the theme import automatically. If your entry file changes, re-run `npx authcore styles:install` to reapply the import and Tailwind preset. > Registrations now return a step-by-step follow-up (verification emails, 2FA setup, approval messaging) so you can redirect immediately or keep the guidance inside the modal. ### Configure Social Login Providers AuthCore renders Google, GitHub, and Facebook buttons whenever social login is enabled. Control which logos appear globally via `configure`, or override the list for a single form. > The `AuthForm` component automatically calls `/api/auth/policy` so tenants only see the sign-in options you allow (password, magic link, authenticator, email OTP, and approval messaging) without extra plumbing. ```ts import { configure } from 'codalware-auth' configure({ enableSocial: true, providerSettings: { socialProviders: { google: { enabled: true }, github: { enabled: true }, facebook: { enabled: false }, // remove Facebook everywhere }, }, }) ``` Override per form using the new `socialProviders` prop: ```tsx <AuthForm showSocial socialProviders={[ 'google', { id: 'github', label: 'GitHub' }, { id: 'facebook', enabled: false }, ]} /> ``` Providers marked `enabled: false` (or omitted entirely) are not rendered, letting you mirror whichever OAuth integrations are active in your app. ### 6. Accept Logo Uploads in Your API The `CreateOrganization` component now includes a drag-and-drop uploader that posts a Base64 `logoUrl` payload. Your handler can persist the file however you like: ```ts // app/api/organizations/route.ts (Next.js example) import { NextResponse } from 'next/server' export async function POST(req: Request) { const body = await req.json() // body.logoUrl will contain a data URL when a logo is uploaded // Store it in S3, upload to a CDN, or keep the data URL for mock/demo environments return NextResponse.json({ organization: { id: crypto.randomUUID(), name: body.name, slug: body.slug, logoUrl: body.logoUrl, // Base64 data URL or external URL }, }) } ``` > **Tip:** The logo uploader supports drag-and-drop and file picker. The API receives a Base64 data URL in `logoUrl`store it as-is for demos, or upload to S3/CDN and save the resulting URL. --- ## Documentation **Complete documentation and live demos:** ### [https://authcore-liard.vercel.app/](https://authcore-liard.vercel.app/) The documentation includes: - **Getting Started** Step-by-step setup for Next.js, React, and Vite - **Component Reference** All UI components with live demos - **Hooks API** React hooks documentation - **Configuration** Environment setup, customization, and advanced options - **Security Features** Account lockout, email restrictions, 2FA, and more - **Examples** Next.js App Router and Pages Router implementations - **API Reference** Complete API documentation (all endpoints, request/response shapes) - **Guides** Custom styling, translations, multi-tenancy, and more --- ## Quick Links - [NPM Package](https://www.npmjs.com/package/codalware-auth) Install from npm - [Documentation](https://authcore-liard.vercel.app/) Complete documentation with live demos - [Next.js App Router Example](https://authcore-liard.vercel.app/examples/app-router) Modern App Router implementation - [Next.js Pages Router Ex