wulf-pulse/tasks/prd-auth-user-management.md
root 9f912aed24 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
2026-01-31 12:43:14 -05:00

14 KiB

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

{
  "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

# 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

// 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"],
  },
};