feat: add authentication, user management, and admin features

Added comprehensive authentication and authorization system:

Authentication System:
- Better Auth integration with session management
- Login/logout pages and API routes
- Middleware for route protection
- Auth utilities and client libraries

User Management:
- User list, detail, and invite pages
- User API endpoints (CRUD operations)
- Session management for users
- Profile settings page

Role-Based Access Control:
- Role management pages (list, create, edit)
- Permission system with granular controls
- Role assignment to users
- Role API endpoints

Admin Features:
- Audit log page for tracking system events
- Admin settings page
- Audit service for logging user actions

Additional Features:
- Quotes management pages and components
- SalesBldr API integration
- Email service for notifications

Configuration & Documentation:
- Updated docker-compose.yml
- MCP server configuration (mcp.json)
- CVE-2025-55182 security review documentation
- Standards guide and PRD documents
- Re-enabling authentication documentation

Database Migrations:
- 012: Auth tables (users, sessions, accounts, verifications)
- 013: Role tables (roles, permissions, role_permissions, user_roles)
- 014: Admin settings table

UI Updates:
- Updated dashboard layout
- Enhanced app layout with auth integration
This commit is contained in:
root 2026-01-31 12:43:14 -05:00
parent d8e6931b85
commit 9f912aed24
68 changed files with 7651 additions and 3 deletions

View file

@ -0,0 +1,405 @@
# PRD: Authentication & User Management Module
## 1. Introduction/Overview
Pulse currently has no authentication system, leaving all routes and data publicly accessible. This PRD defines the implementation of a comprehensive authentication and authorization system using **Better Auth** with a **User Management Module** for super-admins.
### Problem Statement
- No authentication protects the application
- Sensitive admin sections and data are exposed
- No role-based access control (RBAC) exists
- No user management capabilities
### Solution
Implement Better Auth with:
- Magic link and Microsoft 365 OAuth authentication
- Role-based access control with custom role creation
- User management module for super-admins
- Session management with security controls
- Two-factor authentication (2FA)
- Audit logging
---
## 2. Goals
1. **Secure all application routes** - No unauthenticated access to any part of Pulse
2. **Implement RBAC** - Protect admin sections and sensitive data based on user roles
3. **Enable user management** - Super-admins can create, edit, deactivate users and manage roles
4. **Support enterprise auth** - Magic link and Microsoft 365 SSO
5. **Provide security controls** - Session timeout, password policies, 2FA, audit logging
6. **Match existing UI** - Use existing shadcn/ui components for consistency
---
## 3. User Stories
### Authentication
- **As a user**, I want to sign in with a magic link so I don't need to remember a password
- **As a user**, I want to sign in with my Microsoft 365 account for seamless enterprise access
- **As a user**, I want to enable 2FA to secure my account
- **As a user**, I want to see and manage my active sessions
### Authorization
- **As an admin**, I want certain sections protected so only authorized users can access them
- **As a super-admin**, I want to define custom roles with specific permissions
### User Management
- **As a super-admin**, I want to invite new users via email
- **As a super-admin**, I want to view all users and their roles
- **As a super-admin**, I want to edit user profiles and change their roles
- **As a super-admin**, I want to deactivate/reactivate users
- **As a super-admin**, I want to reset a user's password/sessions
- **As a super-admin**, I want to create and manage custom roles
- **As a super-admin**, I want to view audit logs of user actions
---
## 4. Functional Requirements
### 4.1 Authentication System
| ID | Requirement |
|----|-------------|
| AUTH-01 | System must support magic link authentication via email |
| AUTH-02 | System must support Microsoft 365 OAuth authentication |
| AUTH-03 | System must support two-factor authentication (TOTP) |
| AUTH-04 | System must redirect unauthenticated users to sign-in page |
| AUTH-05 | System must maintain secure sessions with configurable timeout |
| AUTH-06 | System must allow users to view and revoke their active sessions |
| AUTH-07 | Magic links must expire after 5 minutes |
| AUTH-08 | System must support account linking (magic link + Microsoft) |
### 4.2 Authorization & RBAC
| ID | Requirement |
|----|-------------|
| RBAC-01 | System must implement role-based access control |
| RBAC-02 | System must have default roles: `super-admin`, `admin`, `user` |
| RBAC-03 | Super-admins must be able to create custom roles |
| RBAC-04 | Roles must define permissions for resources (e.g., `tickets:read`, `admin:access`) |
| RBAC-05 | `/app/admin/*` routes must require `admin` or `super-admin` role |
| RBAC-06 | User management must require `super-admin` role |
| RBAC-07 | API routes must validate permissions before returning data |
### 4.3 User Management Module
| ID | Requirement |
|----|-------------|
| USER-01 | Super-admins must be able to view a list of all users |
| USER-02 | Super-admins must be able to invite new users via email |
| USER-03 | Super-admins must be able to edit user profiles (name, email) |
| USER-04 | Super-admins must be able to assign/change user roles |
| USER-05 | Super-admins must be able to deactivate users (soft delete) |
| USER-06 | Super-admins must be able to reactivate deactivated users |
| USER-07 | Super-admins must be able to delete users permanently |
| USER-08 | Super-admins must be able to force password reset / revoke sessions |
| USER-09 | Super-admins must be able to view user session history |
### 4.4 Role Management
| ID | Requirement |
|----|-------------|
| ROLE-01 | Super-admins must be able to view all roles |
| ROLE-02 | Super-admins must be able to create new roles with custom permissions |
| ROLE-03 | Super-admins must be able to edit existing role permissions |
| ROLE-04 | Super-admins must be able to delete custom roles (not default roles) |
| ROLE-05 | System must prevent deletion of roles assigned to users |
### 4.5 Security & Audit
| ID | Requirement |
|----|-------------|
| SEC-01 | Sessions must expire after 1 hour by default (configurable) |
| SEC-02 | Session timeout must be configurable per source IP/subnet (trusted networks can have longer sessions) |
| SEC-03 | Sessions must refresh on activity (sliding expiration) |
| SEC-04 | System must log authentication events (sign-in, sign-out, failed attempts) |
| SEC-05 | System must log user management actions (create, edit, delete, role changes) |
| SEC-06 | Audit logs must be viewable by super-admins |
| SEC-07 | Audit logs must be retained for 120 days by default |
| SEC-08 | System must automatically purge audit logs older than retention period |
| SEC-09 | System must rate-limit authentication attempts |
### 4.6 Microsoft 365 Configuration
| ID | Requirement |
|----|-------------|
| MS-01 | Super-admins must be able to configure Microsoft tenant ID in admin settings |
| MS-02 | System must validate tenant ID format before saving |
| MS-03 | System must support both specific tenant and 'common' (any Microsoft account) modes |
### 4.8 Session Policies (Trusted Networks)
| ID | Requirement |
|----|-------------|
| NET-01 | Super-admins must be able to define trusted networks using CIDR notation |
| NET-02 | Each network policy must have: name, CIDR range, session timeout (seconds) |
| NET-03 | System must validate CIDR notation format before saving |
| NET-04 | System must match client IP against policies in priority order |
| NET-05 | Default policy (1 hour) applies when no CIDR matches |
| NET-06 | Example: `10.0.0.0/8` = 8 hours, `192.168.1.0/24` = 24 hours |
### 4.9 Email Templates
| ID | Requirement |
|----|-------------|
| EMAIL-01 | Super-admins must be able to customize magic link email template |
| EMAIL-02 | Super-admins must be able to customize user invitation email template |
| EMAIL-03 | Templates must support variables: `{{name}}`, `{{link}}`, `{{expires}}`, `{{app_name}}` |
| EMAIL-04 | System must provide default templates that can be reset |
| EMAIL-05 | Templates must support HTML formatting |
### 4.7 Initial Setup & Bootstrap
| ID | Requirement |
|----|-------------|
| BOOT-01 | System must create a default super-admin account on first run |
| BOOT-02 | Default super-admin credentials must be set via environment variables |
| BOOT-03 | System must force immediate password/auth method change on first login for default account |
| BOOT-04 | Default account must be clearly marked as "setup account" requiring reconfiguration |
---
## 5. Non-Goals (Out of Scope)
- **Password-based authentication** - Only magic link and Microsoft 365 OAuth
- **Self-registration** - Users must be invited by super-admins
- **Multi-tenancy / Organizations** - Single tenant for now
- **API key authentication** - Not in initial scope
- **SAML SSO** - Only OAuth (Microsoft 365)
- **Email verification for existing users** - Users are invited, not self-registered
---
## 6. Design Considerations
### UI Components
Use existing shadcn/ui components from `/components/ui/`:
- `button`, `input`, `label`, `form` for auth forms
- `card` for sign-in/settings cards
- `table` for user/role lists
- `dialog` for confirmations
- `dropdown-menu` for user actions
- `badge` for role/status display
- `tabs` for settings sections
- `alert-dialog` for destructive actions
### Pages to Create
| Route | Description |
|-------|-------------|
| `/auth/sign-in` | Sign-in page (magic link + Microsoft) |
| `/auth/verify` | Magic link verification |
| `/auth/2fa` | Two-factor verification |
| `/app/admin/users` | User management list |
| `/app/admin/users/[id]` | User detail/edit page |
| `/app/admin/users/invite` | Invite user form |
| `/app/admin/roles` | Role management |
| `/app/admin/audit-log` | Audit log viewer |
| `/app/admin/settings` | App settings (Microsoft tenant, session policies, email templates) |
| `/settings` | User settings (profile, sessions, 2FA) |
### Component Structure
```
/components/auth/
├── sign-in-form.tsx # Magic link + Microsoft buttons
├── magic-link-form.tsx # Email input for magic link
├── two-factor-form.tsx # TOTP input
└── session-list.tsx # Active sessions
/components/admin/users/
├── user-table.tsx # User list with actions
├── user-form.tsx # Create/edit user
├── invite-user-form.tsx # Invite via email
├── role-badge.tsx # Role display
└── user-actions.tsx # Dropdown actions
/components/admin/roles/
├── role-table.tsx # Role list
├── role-form.tsx # Create/edit role
└── permission-picker.tsx # Permission selection
```
---
## 7. Technical Considerations
### Dependencies
```json
{
"better-auth": "^1.x",
"@daveyplate/better-auth-ui": "^1.x"
}
```
### Database Schema (PostgreSQL)
Better Auth will create these tables:
- `user` - User accounts
- `session` - Active sessions
- `account` - OAuth accounts (Microsoft)
- `verification` - Magic link tokens
Additional tables:
- `role` - Custom roles
- `permission` - Role permissions
- `audit_log` - Security audit trail
- `session_policy` - IP/subnet-based session timeout rules (CIDR notation)
- `app_settings` - Application settings (Microsoft tenant, etc.)
- `email_template` - Customizable email templates
### File Structure
```
/lib/
├── auth.ts # Better Auth server config
├── auth-client.ts # Better Auth client
└── permissions.ts # RBAC definitions
/app/api/auth/[...all]/
└── route.ts # Better Auth API handler
/middleware.ts # Route protection
```
### Environment Variables
```env
# Better Auth
BETTER_AUTH_SECRET= # Random secret for signing
BETTER_AUTH_URL= # Base URL (e.g., http://localhost:3000)
# Microsoft OAuth (Tenant ID configurable in admin UI)
MICROSOFT_CLIENT_ID=
MICROSOFT_CLIENT_SECRET=
# SMTP Configuration (for magic links)
SMTP_HOST= # SMTP server hostname
SMTP_PORT=587 # SMTP port (587 for TLS, 465 for SSL)
SMTP_USER= # SMTP username
SMTP_PASS= # SMTP password
SMTP_FROM= # From email address
SMTP_SECURE=false # Use SSL (true for port 465)
# Default Super-Admin (for initial setup)
DEFAULT_ADMIN_EMAIL= # Email for default super-admin account
DEFAULT_ADMIN_NAME= # Display name for default super-admin
# Session Configuration
SESSION_TIMEOUT_SECONDS=3600 # Default 1 hour
# Audit Log Retention
AUDIT_LOG_RETENTION_DAYS=120 # Default 120 days
```
### Integration Points
- Integrate with existing PostgreSQL database (`pg` package)
- Use existing `Toaster` from sonner for notifications
- Protect existing `/app/admin/*` routes
- Add user context to existing components via `useSession()`
---
## 8. Success Metrics
| Metric | Target |
|--------|--------|
| All routes protected | 100% of routes require authentication |
| Admin routes secured | `/admin/*` only accessible to admin/super-admin |
| User management functional | Super-admins can perform all CRUD operations |
| Auth methods working | Magic link and Microsoft 365 both functional |
| 2FA adoption | Available and working for all users |
| Audit logging | All auth and user management events logged |
---
## 9. Resolved Questions
| Question | Resolution |
|----------|------------|
| Email provider | Pure SMTP - configurable via environment variables |
| Microsoft tenant | Configurable in admin UI - supports specific tenant or 'common' |
| Initial super-admin | Default account via env vars, forced reconfiguration on first login |
| Session duration | 1 hour default, configurable per source IP/subnet for trusted networks |
| Audit log retention | 120 days default, automatic purge of older records |
## 10. Resolved Questions (Continued)
| Question | Resolution |
|----------|------------|
| Trusted network configuration | CIDR notation (e.g., `192.168.1.0/24`, `10.0.0.0/8`) |
| Email templates | Customizable by admins in settings |
---
## 11. Implementation Phases
### Phase 1: Core Authentication
- Install and configure Better Auth
- Set up magic link authentication
- Set up Microsoft 365 OAuth
- Create sign-in page
- Implement middleware for route protection
### Phase 2: RBAC & Permissions
- Define permission structure
- Implement admin plugin with roles
- Protect admin routes
- Add role checking to API routes
### Phase 3: User Management
- Create user list page
- Implement invite user flow
- Create user edit page
- Add deactivate/delete functionality
### Phase 4: Role Management
- Create role list page
- Implement role creation/editing
- Add permission picker UI
### Phase 5: Security Features
- Implement 2FA
- Add session management UI
- Create audit log system
- Add audit log viewer
---
## Appendix: Permission Structure
```typescript
// Suggested permission structure
const permissions = {
// Ticket permissions
tickets: ["read", "create", "update", "delete"],
// Configuration items
configItems: ["read", "create", "update", "delete"],
// Admin sections
admin: ["access", "sync", "dataBrowser", "analytics"],
// User management (super-admin only)
users: ["read", "create", "update", "delete", "invite"],
// Role management (super-admin only)
roles: ["read", "create", "update", "delete"],
// Audit logs
auditLog: ["read"],
} as const;
// Default roles
const defaultRoles = {
"super-admin": {
// All permissions
},
"admin": {
tickets: ["read", "create", "update", "delete"],
configItems: ["read", "create", "update", "delete"],
admin: ["access", "sync", "dataBrowser", "analytics"],
},
"user": {
tickets: ["read", "create", "update"],
configItems: ["read"],
},
};
```

View file

@ -0,0 +1,209 @@
# Tasks: Authentication & User Management Module
## Relevant Files
### Core Auth Infrastructure
- `lib/auth.ts` - Better Auth server configuration with plugins
- `lib/auth-client.ts` - Better Auth client for React components
- `lib/auth-utils.ts` - Server-side auth utilities and permission checking
- `lib/permissions.ts` - RBAC permission definitions and access control
- `lib/bootstrap.ts` - Bootstrap and initial setup functions
- `lib/services/email.ts` - SMTP email service for magic links
- `lib/services/audit.ts` - Audit logging service
- `app/api/auth/[...all]/route.ts` - Better Auth API route handler
- `middleware.ts` - Route protection middleware
### Database Migrations
- `migrations/012_create_auth_tables.sql` - Better Auth core tables (user, session, account, verification, two_factor)
- `migrations/013_create_role_tables.sql` - Role and permission tables with default roles
- `migrations/014_create_admin_settings.sql` - App settings, session policies, email templates, and audit log tables
### Auth Pages
- `app/auth/sign-in/page.tsx` - Sign-in page with magic link and Microsoft options
- `app/auth/verify/page.tsx` - Magic link verification page
- `app/auth/2fa/page.tsx` - Two-factor authentication verification page
- `app/auth/setup/page.tsx` - Initial account setup page
- `app/auth/layout.tsx` - Auth pages layout (no navigation)
### Auth Components
- `components/auth/auth-provider.tsx` - Auth context provider for React
- `components/auth/sign-in-form.tsx` - Combined sign-in form with both auth methods
- `components/auth/magic-link-form.tsx` - Email input for magic link
- `components/auth/microsoft-button.tsx` - Microsoft 365 OAuth button
- `components/auth/two-factor-form.tsx` - TOTP code input form
### User Management Pages
- `app/admin/users/page.tsx` - User list page
- `app/admin/users/[id]/page.tsx` - User detail/edit page
- `app/admin/users/invite/page.tsx` - Invite user page
### User Management Components
- `components/admin/users/user-table.tsx` - User list table with actions
- `components/admin/users/user-form.tsx` - Create/edit user form
- `components/admin/users/invite-user-form.tsx` - Invite user via email form
- `components/admin/users/role-badge.tsx` - Role display badge
- `components/admin/users/user-actions.tsx` - User action dropdown menu
- `components/admin/users/user-sessions.tsx` - User session history
### Role Management Pages
- `app/admin/roles/page.tsx` - Role list page
- `app/admin/roles/[id]/page.tsx` - Role detail/edit page
- `app/admin/roles/new/page.tsx` - Create new role page
### Role Management Components
- `components/admin/roles/role-table.tsx` - Role list table
- `components/admin/roles/role-form.tsx` - Create/edit role form
- `components/admin/roles/permission-picker.tsx` - Permission selection UI
### Admin Settings Pages
- `app/admin/settings/page.tsx` - Admin settings page with tabs
- `app/admin/audit-log/page.tsx` - Audit log viewer page
### Admin Settings Components
- `components/admin/settings/microsoft-config.tsx` - Microsoft tenant configuration
- `components/admin/settings/session-policies.tsx` - CIDR session policy management
- `components/admin/settings/email-templates.tsx` - Email template editor
- `components/admin/audit/audit-log-table.tsx` - Audit log table with filters
### User Settings Pages
- `app/settings/page.tsx` - User settings page
- `app/settings/security/page.tsx` - Security settings (2FA, sessions)
### User Settings Components
- `components/settings/profile-form.tsx` - User profile edit form
- `components/settings/two-factor-setup.tsx` - 2FA setup wizard
- `components/settings/active-sessions.tsx` - Current user's active sessions
### API Routes
- `app/api/admin/users/route.ts` - User CRUD API
- `app/api/admin/users/[id]/route.ts` - Single user API
- `app/api/admin/users/invite/route.ts` - User invitation API
- `app/api/admin/roles/route.ts` - Role CRUD API
- `app/api/admin/roles/[id]/route.ts` - Single role API
- `app/api/admin/settings/route.ts` - App settings API
- `app/api/admin/settings/session-policies/route.ts` - Session policies API
- `app/api/admin/settings/email-templates/route.ts` - Email templates API
- `app/api/admin/audit-log/route.ts` - Audit log API
- `app/api/settings/profile/route.ts` - User profile API
### Notes
- Unit tests should typically be placed alongside the code files they are testing (e.g., `MyComponent.tsx` and `MyComponent.test.tsx` in the same directory).
- Use `npx jest [optional/path/to/test/file]` to run tests. Running without a path executes all tests found by the Jest configuration.
- Better Auth handles most auth logic internally; focus tests on custom business logic.
- Use existing shadcn/ui components from `/components/ui/` for consistency.
## Tasks
- [x] 1.0 Setup Better Auth Core Infrastructure
- [x] 1.1 Install Better Auth dependencies (`better-auth`, `@better-auth/cli`)
- [x] 1.2 Add required environment variables to `.env` and `.env.local` (BETTER_AUTH_SECRET, BETTER_AUTH_URL, SMTP_*, DEFAULT_ADMIN_*, SESSION_TIMEOUT_SECONDS, AUDIT_LOG_RETENTION_DAYS)
- [x] 1.3 Create database migration for Better Auth core tables (user, session, account, verification)
- [x] 1.4 Create `lib/auth.ts` with Better Auth server configuration
- [x] 1.5 Create `lib/auth-client.ts` with Better Auth client for React
- [x] 1.6 Create `app/api/auth/[...all]/route.ts` API route handler
- [x] 1.7 Create `middleware.ts` for route protection (redirect unauthenticated users to /auth/sign-in)
- [x] 1.8 Create `lib/services/email.ts` SMTP email service using environment variables
- [x] 1.9 Update `app/layout.tsx` to wrap app with auth session provider
- [x] 2.0 Implement Authentication Methods (Magic Link & Microsoft 365)
- [x] 2.1 Configure magic link plugin in `lib/auth.ts` with sendMagicLink callback using SMTP service
- [x] 2.2 Configure Microsoft OAuth provider in `lib/auth.ts` with client ID/secret from env
- [x] 2.3 Create `app/auth/layout.tsx` - minimal layout without main navigation
- [x] 2.4 Create `app/auth/sign-in/page.tsx` - sign-in page container
- [x] 2.5 Create `components/auth/magic-link-form.tsx` - email input with submit
- [x] 2.6 Create `components/auth/microsoft-button.tsx` - Microsoft 365 OAuth button
- [x] 2.7 Create `components/auth/sign-in-form.tsx` - combined form with both methods
- [x] 2.8 Create `app/auth/verify/page.tsx` - magic link verification handler
- [x] 2.9 Implement "check your email" success state in magic link form
- [x] 2.10 Add error handling for failed auth attempts with toast notifications
- [x] 3.0 Implement RBAC & Permission System
- [x] 3.1 Create database migration for role and permission tables
- [x] 3.2 Create `lib/permissions.ts` with permission definitions (tickets, configItems, admin, users, roles, auditLog)
- [x] 3.3 Define default roles (super-admin, admin, user) with their permissions
- [x] 3.4 Configure Better Auth admin plugin with access control in `lib/auth.ts`
- [x] 3.5 Update `lib/auth-client.ts` with admin client plugin
- [x] 3.6 Create helper function `hasPermission(user, resource, action)` for checking permissions
- [x] 3.7 Update `middleware.ts` to check roles for `/admin/*` routes (require admin or super-admin)
- [x] 3.8 Create API middleware helper for permission checking in route handlers
- [x] 3.9 Seed default roles into database on first run
- [x] 4.0 Build User Management Module
- [x] 4.1 Create `app/api/admin/users/route.ts` - GET (list users), POST (create user)
- [x] 4.2 Create `app/api/admin/users/[id]/route.ts` - GET, PATCH, DELETE single user
- [x] 4.3 Create `app/api/admin/users/invite/route.ts` - POST to send invitation email
- [x] 4.4 Create `components/admin/users/role-badge.tsx` - badge component for role display
- [x] 4.5 Create `components/admin/users/user-table.tsx` - table with columns: name, email, role, status, actions
- [x] 4.6 Create `components/admin/users/user-actions.tsx` - dropdown with edit, deactivate, delete, revoke sessions
- [x] 4.7 Create `app/admin/users/page.tsx` - user list page with search/filter
- [x] 4.8 Create `components/admin/users/user-form.tsx` - form for editing user (name, email, role)
- [x] 4.9 Create `app/admin/users/[id]/page.tsx` - user detail page with edit form and session history
- [x] 4.10 Create `components/admin/users/invite-user-form.tsx` - email input with role selection
- [x] 4.11 Create `app/admin/users/invite/page.tsx` - invite user page
- [x] 4.12 Create `components/admin/users/user-sessions.tsx` - table of user's sessions with revoke
- [x] 4.13 Implement soft delete (deactivate) and reactivate functionality
- [x] 4.14 Implement permanent delete with confirmation dialog
- [x] 4.15 Add super-admin role check to all user management routes
- [x] 5.0 Build Role Management Module
- [x] 5.1 Create `app/api/admin/roles/route.ts` - GET (list roles), POST (create role)
- [x] 5.2 Create `app/api/admin/roles/[id]/route.ts` - GET, PATCH, DELETE single role
- [x] 5.3 Create `components/admin/roles/permission-picker.tsx` - checkbox grid for selecting permissions
- [x] 5.4 Create `components/admin/roles/role-table.tsx` - table with columns: name, permissions count, users count, actions
- [x] 5.5 Create `app/admin/roles/page.tsx` - role list page
- [x] 5.6 Create `components/admin/roles/role-form.tsx` - form with name input and permission picker
- [x] 5.7 Create `app/admin/roles/new/page.tsx` - create new role page
- [x] 5.8 Create `app/admin/roles/[id]/page.tsx` - edit role page
- [x] 5.9 Prevent deletion of default roles (super-admin, admin, user)
- [x] 5.10 Prevent deletion of roles that are assigned to users (show error)
- [x] 5.11 Add super-admin role check to all role management routes
- [x] 6.0 Implement Admin Settings (Microsoft Tenant, Session Policies, Email Templates)
- [x] 6.1 Create database migration for app_settings table
- [x] 6.2 Create database migration for session_policy table (name, cidr, timeout_seconds, priority)
- [x] 6.3 Create database migration for email_template table (type, subject, body_html)
- [x] 6.4 Create `app/api/admin/settings/route.ts` - GET/PATCH app settings
- [x] 6.5 Create `app/api/admin/settings/session-policies/route.ts` - CRUD for session policies
- [x] 6.6 Create `app/api/admin/settings/email-templates/route.ts` - GET/PATCH email templates
- [x] 6.7 Create `components/admin/settings/microsoft-config.tsx` - tenant ID input with validation
- [x] 6.8 Create `components/admin/settings/session-policies.tsx` - table with add/edit/delete for CIDR policies
- [x] 6.9 Implement CIDR notation validation (e.g., `192.168.1.0/24`)
- [x] 6.10 Create `components/admin/settings/email-templates.tsx` - template editor with variable hints
- [x] 6.11 Create `app/admin/settings/page.tsx` - settings page with tabs (Microsoft, Sessions, Email)
- [x] 6.12 Seed default email templates (magic_link, invitation) on first run
- [x] 6.13 Update auth config to dynamically load Microsoft tenant from app_settings
- [x] 6.14 Update session creation to check CIDR policies and set appropriate timeout
- [x] 7.0 Implement Security Features (2FA, Session Management, Audit Logging)
- [x] 7.1 Configure two-factor plugin in `lib/auth.ts`
- [x] 7.2 Update `lib/auth-client.ts` with two-factor client plugin
- [x] 7.3 Create `components/auth/two-factor-form.tsx` - TOTP code input
- [x] 7.4 Create `app/auth/2fa/page.tsx` - 2FA verification page
- [x] 7.5 Create `components/settings/two-factor-setup.tsx` - QR code display and verification
- [x] 7.6 Create `components/settings/active-sessions.tsx` - current user's sessions with revoke
- [x] 7.7 Create `app/settings/page.tsx` - user settings with profile tab
- [x] 7.8 Create `app/settings/security/page.tsx` - security settings (2FA toggle, sessions)
- [x] 7.9 Create database migration for audit_log table (timestamp, user_id, action, resource, details, ip_address)
- [x] 7.10 Create `lib/services/audit.ts` - audit logging service with log() function
- [x] 7.11 Add audit logging to auth events (sign-in, sign-out, failed attempts)
- [x] 7.12 Add audit logging to user management actions (create, edit, delete, role change)
- [x] 7.13 Add audit logging to role management actions
- [x] 7.14 Create `app/api/admin/audit-log/route.ts` - GET with pagination and filters
- [x] 7.15 Create `components/admin/audit/audit-log-table.tsx` - table with filters (date range, user, action)
- [x] 7.16 Create `app/admin/audit-log/page.tsx` - audit log viewer page
- [x] 7.17 Implement audit log retention (delete records older than AUDIT_LOG_RETENTION_DAYS)
- [x] 7.18 Create scheduled job or API endpoint to purge old audit logs
- [x] 7.19 Implement rate limiting on auth endpoints (sign-in, magic-link)
- [x] 8.0 Implement Bootstrap & Initial Setup Flow
- [x] 8.1 Create bootstrap check function to detect if any users exist
- [x] 8.2 Create seed script to create default super-admin from DEFAULT_ADMIN_EMAIL and DEFAULT_ADMIN_NAME env vars
- [x] 8.3 Add `requires_setup` flag to user table for accounts needing reconfiguration
- [x] 8.4 Create setup detection in middleware - redirect setup accounts to `/auth/setup`
- [x] 8.5 Create `app/auth/setup/page.tsx` - forced setup page for default account
- [x] 8.6 Create `components/auth/setup-form.tsx` - form to link Microsoft account or set up magic link
- [x] 8.7 Clear `requires_setup` flag after successful setup completion
- [x] 8.8 Display warning banner for setup accounts until reconfigured
- [x] 8.9 Run bootstrap/seed on application startup if no users exist
- [x] 8.10 Add documentation for initial setup process in README