A comprehensive, production-ready authentication application built with cutting-edge web technologies. ShieldAuth provides secure user authentication, role-based access control, a beautiful modern interface with advanced admin capabilities, and an integrated AI chatbot assistant with RAG (Retrieval Augmented Generation) capabilities for enhanced cybersecurity guidance.
- Frontend: SvelteKit with Svelte 5
- Authentication: Auth.js with PostgreSQL Database Sessions (No JWT)
- Styling: TailwindCSS with custom dark theme
- Database: PostgreSQL with pgvector extension for vector embeddings
- AI Integration: Google Gemini AI with streaming responses and RAG
- Vector Database: pgvector for semantic search and embeddings
- Embedding Service: Python FastAPI microservice with Gemini Embeddings API
- Security: CSRF protection, bcrypt hashing, secure sessions
- Deployment: Docker-ready with comprehensive configuration
- Real-time AI Chat - Interactive conversation with ShieldBot AI assistant
- Word-by-Word Streaming - Natural typing effect with streaming responses
- Context-Aware Responses - AI responses enhanced with retrieved document context
- Citation Display - Shows which documents informed the AI's answer
- File Upload Support - Upload documents (.txt, .doc, .docx, .pdf) for AI analysis
- Multiple AI Models - Support for Gemini 2.5 Pro, 2.5 Flash, 1.5 Pro, and 1.5 Flash
- Chat Management - Create, rename, delete, and organize chat conversations
- Auto-Rename - Automatic chat naming based on first message topic
- Responsive Design - Full-screen chat interface with collapsible sidebar
- Document Ingestion - Upload and process documents for AI context
- Semantic Search - Vector-based similarity search for relevant content
- Context Retrieval - Automatic retrieval of relevant document snippets
- Citation System - Track and display source documents with relevance scores
- Chunking Strategy - Intelligent document chunking for optimal context
- Embedding Generation - Automatic vector embeddings using Gemini API
- Vector Storage - pgvector database for efficient similarity search
- Relevance Gating - Only use document context when similarity is strong enough; otherwise answer from general knowledge
- Streaming Responses - Real-time word-by-word AI response streaming
- Model Selection - Choose between different Gemini AI models
- Chat History - Persistent chat conversations with timestamps
- Security Guidance - Expert advice on password security, phishing protection, 2FA, and network security
- Interactive Prompts - Pre-built conversation starters for common security topics
- Markdown Rendering - Rich text formatting with syntax highlighting
- Code Highlighting - Syntax highlighting for code blocks using Shiki
- Citations in UI - Assistant messages show sources when document context is used
- Message Versioning - Complete forking system for message editing and branching
- Edit Messages - Edit any user message to create conversation branches
- Regenerate Responses - Generate new AI responses with streaming updates
- Version Control - Track message versions with
isActiveflags andversionGroupId - Smart Context - AI maintains proper conversation context for versioned messages
- First Message Protection - Prevents forking of initial messages with user-friendly popup
- Editing UX - While saving an edit or regenerating, the chat disables send/regenerate and shows โGenerating responseโฆโ
- Email/Password Registration - Secure account creation with email verification
- Google OAuth Integration - One-click sign-in with Google accounts
- GitHub OAuth Integration - Seamless GitHub authentication
- Email Verification - 6-digit verification codes with spam folder alerts
- Password Reset - Secure password recovery with email codes
- Database Sessions Only - No JWT tokens, secure server-side sessions
- Bcrypt Password Hashing - Industry-standard password encryption
- CSRF Protection - Built-in cross-site request forgery protection
- Input Validation - Comprehensive server-side validation
- Secure Headers - Security-focused HTTP headers
- Profile Image Persistence - OAuth profile image/name synced on link/sign-in; DB image preferred to prevent flicker; avatars use
referrerpolicy="no-referrer"
- User Analytics - Real-time user statistics and metrics
- System Overview - Complete system health and activity monitoring
- Quick Actions - Fast access to common admin tasks
- Modern UI - Beautiful gradient-based interface with dark theme
- Search & Filter - Real-time search by name/email with role filtering
- User Statistics - Dynamic user counts by role (Admin/Regular users)
- Role Management - Promote/demote users between user and admin roles
- Account Control - Delete user accounts with comprehensive data removal
- Self-Protection - Admins cannot modify their own accounts
- Activity Tracking - User registration and update timestamps
- Consistent Dark Mode - Beautiful black theme with blue accents throughout
- Gradient Backgrounds - Modern gradient overlays and textures
- Responsive Design - Perfect display on all devices and screen sizes
- Professional Navigation - Role-based navigation with smooth transitions
- Slide-up Animations - Smooth text animations on About and Contact pages
- Interactive Elements - Hover effects, scale transforms, and smooth transitions
- Form Validation - Real-time validation with user-friendly error messages
- Loading States - Visual feedback during form submissions and API calls
- Accessibility - ARIA labels, keyboard navigation, and screen reader support
- Hero Section - Engaging landing page with feature showcase
- Feature Cards - Interactive cards highlighting system capabilities
- ShieldBot Integration - AI chatbot card with purple theme and functional buttons
- Call-to-Action - Beautiful gradient buttons for user engagement
- Professional Footer - Complete site navigation and social links
- Full-Screen Chat - Immersive chat experience without navbar distractions
- Collapsible Sidebar - Chat history and management with toggle functionality
- Model Selection - Dropdown to choose AI model with real-time switching
- Streaming Responses - Word-by-word AI response streaming for natural conversation
- Chat Prompts - Pre-built conversation starters for security topics
- Auto-Rename - Intelligent chat naming based on conversation topics
- File Upload - Drag-and-drop file upload with validation
- Citation Display - Show source documents with relevance scores
- Doc-first Title - If the first message includes a file, the chat auto-renames to that documentโs name
- Professional Rename Modal - Beautiful modal form for chat renaming with keyboard shortcuts
- Smart Auto-Scroll - Automatic scrolling to bottom on new messages and page reload
- Empty State UI - Beautiful interface when no conversations exist
- Chat Deletion - Complete cleanup of messages and conversations with confirmation
- Page Refresh Continuity - Resume last active chat after page reload
- Hidden Scrollbars - Clean UI with custom scrollbar hiding throughout the interface
- Keyboard Navigation - Enter/Escape key support for all modals and forms
- Modern Login/Register - Purple-blue gradient themes with pattern backgrounds
- Email Verification - 6-digit code input with individual digit fields
- Password Management - Secure password change and reset workflows
- Forgot Password - Email-based password recovery system
- Alert Messages - "Check Spam Section" alerts for email verification
- Profile Management - Complete user profile with picture upload
- Settings Panel - User preferences and account settings
- Activity Overview - User activity and account information
- Change Password - Secure password update with modern lock icon
- Dashboard Analytics - User statistics and system metrics
- User Management - Advanced search, filtering, and user control
- Role Administration - User role management and permissions
- System Monitoring - Real-time system health and activity
Create a .env file in the root directory:
# Database Configuration (Required)
DATABASE_URL="postgresql://postgres:password@localhost:5433/authapp"
# Authentication Secret (Required)
AUTH_SECRET="your-super-secret-auth-key-here"
# AI Configuration (Required for ShieldBot)
GOOGLE_AI_API_KEY="your-google-ai-api-key"
# Embedding Service Configuration (Required for RAG)
EMBEDDING_API_URL="http://localhost:8000"
# Embedding target dimension (must match DB vector column; defaults to 3072)
EMBEDDING_TARGET_DIM="3072"
# OAuth Configuration (Optional)
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
GITHUB_CLIENT_ID="your-github-client-id"
GITHUB_CLIENT_SECRET="your-github-client-secret"
# Environment
NODE_ENV="development"Important Notes:
- Uses PostgreSQL with pgvector - no SQLite fallback
- Custom port
5433to avoid conflicts - Generate secure AUTH_SECRET:
openssl rand -base64 32 - Google AI API Key required for ShieldBot functionality
- Embedding API URL required for RAG functionality
- OAuth credentials are optional
src/
โโโ lib/
โ โโโ components/ # Reusable UI components
โ โ โโโ Button.svelte
โ โ โโโ Card.svelte
โ โ โโโ Input.svelte
โ โ โโโ Notification.svelte
โ โ โโโ EnhancedMessageRenderer.svelte
โ โ โโโ MarkdownRenderer.svelte # Markdown with syntax highlighting
โ โโโ server/ # Server-side utilities
โ โ โโโ auth.ts # Auth.js configuration
โ โ โโโ ai.ts # AI service integration
โ โ โโโ db/ # Database schema and connection
โ โ โ โโโ schema.ts # Main database schema
โ โ โ โโโ rag.schema.ts # RAG-specific tables
โ โ โโโ email.ts # Email service
โ โ โโโ security.ts # Security utilities
โ โโโ services/ # Client-side services
โ โ โโโ clientChatService.ts # AI chat service
โ โ โโโ databaseChatService.ts # Database chat operations
โ โโโ stores/ # Svelte stores
โ โโโ chatStore.ts # Chat state management
โโโ routes/ # Application routes
โ โโโ api/ # API endpoints
โ โ โโโ auth/ # Authentication endpoints
โ โ โโโ chat/ # AI chat streaming endpoints
โ โ โโโ rag/ # RAG endpoints
โ โ โโโ ingest/ # Document ingestion
โ โ โโโ retrieve/ # Context retrieval
โ โโโ admin/ # Admin-only pages
โ โโโ auth/ # Authentication pages
โ โโโ chatbot/ # ShieldBot AI chat interface
โ โโโ (pages)/ # Public and protected pages
โโโ static/ # Static assets
embedding-service/ # Python microservice
โโโ app.py # FastAPI embedding service
โโโ Dockerfile # Container configuration
โโโ requirements.txt # Python dependencies
git clone https://github.com/Vanar-AI-Excellence-Program/Assignment-3-Ahmed-Asghar-and-Aatiqa-Hussain
cd Assignment-3-Ahmed-Asghar-and-Aatiqa-Hussain
npm install# Start PostgreSQL with pgvector (custom port 5433)
docker-compose up -d
# Push database schema
npm run db:pushCreate a .env file in the root directory with the following variables:
# Database Configuration
DATABASE_URL="postgresql://postgres:password@localhost:5433/Authapp"
# Authentication Configuration
AUTH_SECRET="your-auth-secret-here-generate-a-long-random-string"
AUTH_TRUST_HOST=true
# OAuth Configuration (Optional)
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
GITHUB_CLIENT_ID="your-github-client-id"
GITHUB_CLIENT_SECRET="your-github-client-secret"
# AI Configuration (Required for ShieldBot)
GOOGLE_AI_API_KEY="your-google-ai-api-key"
# Embedding Service Configuration (Required for RAG)
EMBEDDING_API_URL="http://localhost:8000"
# Optional: override embedding dimension exposed by the Python service
EMBEDDING_TARGET_DIM="3072"
# Email Configuration (Optional - for email verification and password reset)
SENDGRID_API_KEY="your-sendgrid-api-key"
FROM_EMAIL="noreply@yourdomain.com"
# Application Configuration
NODE_ENV="development"Important: Both GOOGLE_AI_API_KEY and EMBEDDING_API_URL are required for full ShieldBot functionality.
# Start the embedding service
docker-compose up embedding-service -d
# Verify embedding service
curl http://localhost:8000/health
# Start the main application
npm run devVisit http://localhost:5173 to see your application!
- Navigate to Chatbot - Click "Start Chat" on the homepage or visit
/chatbot - Choose AI Model - Select from Gemini 2.5 Pro, 2.5 Flash, 1.5 Pro, or 1.5 Flash
- Start Conversation - Use pre-built prompts or ask your own security questions
- Upload Documents - Upload files for AI to analyze and reference
- Streaming Responses - Watch AI responses appear word-by-word in real-time
- View Citations - See which documents informed the AI's answer
- Out-of-Doc Questions - If retrieval is not relevant enough, ShieldBot answers from its general knowledge
- Document Analysis - Upload and analyze security documents, policies, and guides
- Context-Aware Responses - AI responses enhanced with relevant document content
- Citation Tracking - See exactly which documents and sections informed each answer
- Semantic Search - Find relevant content using vector similarity
- Multi-Format Support - Support for .txt, .doc, .docx, and .pdf files
- Configurable Relevance - Document context is only attached when similarity passes an internal threshold (default ~0.62 cosine-like). You can raise/lower this threshold in
src/lib/server/ai.tsif needed.
- Password Security - Best practices for strong passwords
- Phishing Protection - How to identify and avoid phishing scams
- Two-Factor Authentication - Benefits and setup guidance
- Network Security - Securing home Wi-Fi and devices
- General Cybersecurity - Comprehensive security advice
- Document-Specific Guidance - AI responses based on uploaded documents
- Auto-Rename - Chats automatically named based on first message
- Manual Rename - Custom chat titles for organization
- Chat History - Persistent conversation storage
- Delete Chats - Remove unwanted conversations
- New Chat - Start fresh conversations anytime
- File Attachments - Upload and reference documents in conversations
npm run promote-admin your-email@example.com- Dashboard:
/admin- System analytics and overview - User Management:
/admin/users- Advanced user administration - Search & Filter: Real-time user search by name/email
- Role Management: Promote/demote users between roles
- Account Control: Delete user accounts with full data removal
- Statistics: Dynamic user counts and activity metrics
- Google OAuth - Sign in with Google account
- GitHub OAuth - Sign in with GitHub account
- Email/Password - Traditional authentication
- Seamless Integration - One-click social authentication
- Account Linking - OAuth accounts linked to email accounts
- Profile Sync - Automatic name and picture sync from providers
- Flexible Authentication - Multiple authentication methods per user
/- Homepage with feature showcase and ShieldBot card/about- About page with slide-up animations/contact- Contact page with modern UI/register- User registration with email verification/login- User login with OAuth options
/chatbot- ShieldBot AI chat interface with streaming responses and RAG
/verify-code- Email verification with 6-digit codes/forgot-password- Password recovery request/reset-password-code- Password reset code entry/reset-password- New password creation/change-password-code- Password change verification/change-password- Password update
/dashboard- User dashboard with profile overview/profile- Profile management with picture upload/change-password- Secure password change
/admin- Admin dashboard with analytics/admin/users- User management with search/filter
/api/auth/*- Authentication endpoints/api/profile/*- Profile management/api/admin/users/*- Admin user management/api/chat/stream- AI chat streaming endpoint/api/rag/ingest- Document ingestion endpoint/api/rag/retrieve- Context retrieval endpoint
/api/chat/conversations- Create and list conversations/api/chat/conversations/[id]/delete- Delete conversation with message cleanup/api/chat/conversations/[id]/rename- Rename conversation/api/chat/messages/[id]/edit- Edit message with versioning/api/chat/messages/[id]/regenerate- Regenerate AI response with streaming/api/chat/messages/[id]/versions- Get message versions
npm run dev # Start development server
npm run build # Build for production
npm run preview # Preview production build
npm run check # Type checking and lintingnpm run db:up # Start PostgreSQL database
npm run db:down # Stop PostgreSQL database
npm run db:push # Push database schema changes
npm run db:studio # Open Drizzle Studio
npm run seed # Seed database with sample datanpm run promote-admin <email> # Promote user to admin roledocker-compose up -d # Start all services
docker-compose up embedding-service -d # Start only embedding service
docker-compose down # Stop all services- Document Upload โ File validation โ Text extraction โ Chunking
- Embedding Generation โ Python service โ Gemini API โ Vector storage
- Context Retrieval โ User query โ Vector similarity โ Relevant chunks
- AI Enhancement โ Context + query โ Enhanced AI response โ Citations
- Model Selection โ Choose AI model โ Start conversation
- Streaming Response โ Word-by-word streaming โ Real-time display
- Context Integration โ RAG context โ Enhanced responses โ Citations
- Chat Management โ Auto-rename โ Manual organization
- Security Guidance โ Expert advice โ Interactive learning
- Edit Message โ Click edit button โ Modify content โ Save changes
- Version Creation โ New message version created โ Previous version deactivated
- AI Regeneration โ Regenerate AI response โ Streaming update โ Context preserved
- Version Navigation โ View message history โ Switch between versions
- Context Maintenance โ AI maintains conversation context across versions
- Registration โ Email verification โ Account activation
- Login โ Database session creation โ Protected access
- Password Reset โ Email code โ New password creation
- OAuth Login โ Provider authentication โ Account linking
- User Search โ Real-time filtering โ Role management
- Account Control โ User deletion โ Complete data removal
- Analytics โ User statistics โ System monitoring
- Security โ Self-protection โ Audit trail
- Dark Theme โ Consistent black theme with blue accents
- Animations โ Slide-up text animations and smooth transitions
- Responsive โ Perfect display on all devices
- Accessibility โ ARIA labels and keyboard navigation
- Streaming โ Real-time AI response streaming
- Markdown โ Rich text formatting with syntax highlighting
- Auto-Scroll โ Automatic scrolling to bottom on new messages
- Hidden Scrollbars โ Clean UI with custom scrollbar hiding
- Keyboard Shortcuts โ Enter/Escape key support for all modals
- Professional Modals โ Beautiful modal forms instead of browser prompts
- Empty States โ Beautiful UI when no conversations exist
- Page Continuity โ Resume last active chat after page reload
- File Upload โ Drag-and-drop file upload with validation
- Citation Display โ Source documents with relevance scores
- Database Sessions - Server-side session storage
- 30-day Expiration - Automatic session cleanup
- Secure Cookies - HttpOnly, Secure, SameSite attributes
- CSRF Protection - Built-in cross-site request forgery protection
- Version Control - Secure message versioning with
versionGroupIdandisActiveflags - Context Integrity - AI maintains proper conversation context for versioned messages
- Data Consistency - Proper cleanup of related messages when conversations are deleted
- First Message Protection - Prevents forking of initial messages to maintain conversation integrity
- Bcrypt Hashing - Industry-standard password encryption
- Salt Rounds - Configurable encryption strength
- Password Validation - Strong password requirements
- Secure Reset - Email-based password recovery
- Server-side Validation - All inputs validated on server
- Type Safety - TypeScript implementation throughout
- SQL Injection Protection - Drizzle ORM parameterized queries
- XSS Protection - Input sanitization and output encoding
- API Key Protection - Secure server-side AI API key handling
- Input Sanitization - All user inputs sanitized before AI processing
- Rate Limiting - Protection against AI API abuse
- Error Handling - Graceful AI service error management
- File Validation - Strict file type and size validation
- Content Sanitization - All uploaded content sanitized before processing
- Vector Security - Secure embedding generation and storage
- Access Control - User-specific document access and retrieval
- Thresholding - Irrelevant context is ignored to avoid data leakage from unrelated documents
- Embeddings not saved:
- Ensure the embedding service is running:
curl http://localhost:8000/healthshould return status ok andtarget_dim: 3072. - Confirm your DB has pgvector and the embeddings column dimensions match 3072.
- Check server logs for
Saved embedding for chunkmessages.
- Ensure the embedding service is running:
- Always citing docs for out-of-scope questions:
- The system now gates context by similarity. If it still feels too eager, increase the threshold in
src/lib/server/ai.ts.
- The system now gates context by similarity. If it still feels too eager, increase the threshold in
- OAuth avatar missing or late:
- We persist the provider image on link/sign-in and prefer the DB image in session. Clear cache and refresh.
- Edit/regenerate buttons clickable during generation:
- The UI disables these while generating and shows a status label. If you donโt see this, rebuild the app.
- โ
Set
NODE_ENV=production - โ Configure production database URL
- โ
Set secure
AUTH_SECRET - โ
Configure
GOOGLE_AI_API_KEYfor ShieldBot - โ
Configure
EMBEDDING_API_URLfor RAG - โ Enable SSL for database connections
- โ Configure reverse proxy
- โ Set up monitoring and logging
# Build and run with Docker Compose
docker-compose up -d
# Check service status
docker-compose ps
# View logs
docker-compose logs -f- Code Splitting - Automatic bundle optimization
- Component Library - Reusable, optimized components
- TailwindCSS Purging - Optimized CSS for production
- Image Optimization - Compressed and optimized assets
- Streaming Optimization - Efficient AI response streaming
- Markdown Rendering - Optimized syntax highlighting
- Connection Pooling - Efficient database connections
- Query Optimization - Optimized database queries
- Caching - Strategic caching implementation
- Error Handling - Graceful error management
- AI Response Caching - Optimized AI service calls
- Vector Indexing - Optimized vector similarity search
- Chunking Strategy - Optimal document chunking for context
- Vector Indexing - Efficient similarity search with pgvector
- Embedding Caching - Cached embeddings for performance
- Context Filtering - Smart context selection and ranking
- Tree Structure - Messages organized in tree structure with
parentIdrelationships - Version Groups - Messages grouped by
versionGroupIdfor easy version tracking - Active Flags -
isActiveflag to identify current version of each message - Version Numbers - Sequential
versionNumberfor version ordering - Context Preservation - AI maintains conversation context across message versions
- Data Integrity - Proper cleanup of related messages when conversations are deleted
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- SvelteKit - The web framework
- Auth.js - Authentication for the web
- TailwindCSS - Utility-first CSS framework
- Drizzle ORM - TypeScript ORM
- PostgreSQL - Advanced open source database
- pgvector - Vector similarity search
- Google Gemini AI - Advanced AI capabilities
- Shiki - Syntax highlighting
- FastAPI - Python web framework
ShieldAuth - Built with โค๏ธ using modern web technologies for secure, scalable authentication with intelligent AI assistance and advanced RAG capabilities.
- โ Document Ingestion - Upload and process documents for AI context
- โ Vector Embeddings - Automatic embedding generation using Gemini API
- โ Semantic Search - Vector-based similarity search with pgvector
- โ Context Retrieval - Automatic retrieval of relevant document snippets
- โ Citation System - Track and display source documents with relevance scores
- โ Python Microservice - Containerized embedding service with FastAPI
- โ Context-Aware Responses - AI responses enhanced with retrieved document context
- โ File Upload Support - Upload .txt, .doc, .docx, .pdf files for analysis
- โ Citation Display - Show which documents informed the AI's answer
- โ Markdown Rendering - Rich text formatting with syntax highlighting
- โ Code Highlighting - Syntax highlighting for code blocks using Shiki
- โ Streaming Integration - Real-time streaming with context integration
- โ pgvector Integration - PostgreSQL with vector similarity search
- โ Embedding Service - Python FastAPI microservice for embeddings
- โ Database Schema - RAG tables for documents, chunks, and embeddings
- โ API Endpoints - Document ingestion and context retrieval endpoints
- โ Error Handling - Comprehensive error handling for RAG operations
- โ Performance - Optimized vector search and context retrieval
- โ Message Versioning - Complete message forking and versioning system
- โ Edit & Regenerate - Edit any message or regenerate AI responses
- โ Smart Context Handling - AI maintains proper conversation context for versioned messages
- โ Streaming Regeneration - Real-time streaming for regenerated responses
- โ First Message Protection - Prevents forking of first messages with user-friendly popup
- โ Professional Rename Modal - Beautiful modal form instead of browser prompts
- โ Smart Auto-Rename - Automatic chat naming based on conversation topics
- โ Chat Deletion - Complete cleanup of messages and conversations
- โ Empty State Handling - Beautiful UI when no conversations exist
- โ Page Refresh Continuity - Resume last active chat after page reload
- โ Auto-Scroll Functionality - Smooth scrolling to bottom on new messages
- โ Hidden Scrollbars - Clean UI with custom scrollbar hiding
- โ Keyboard Shortcuts - Enter/Escape key support for all modals
- โ Responsive Design - Perfect display on all devices
- โ Dark Theme Consistency - Unified dark theme throughout
- โ Error Handling - Comprehensive error handling and user feedback
- โ State Management - Enhanced chat store with proper state management
- โ API Optimization - Improved API endpoints for better performance
- โ Database Integrity - Proper message cleanup and data consistency
- โ Real-time Updates - Immediate UI updates for all chat operations
- โ AI Chat Interface - Full-screen chat with ShieldBot AI assistant
- โ Streaming Responses - Word-by-word AI response streaming
- โ Model Selection - Support for multiple Gemini AI models
- โ Chat Management - Auto-rename, manual rename, and chat organization
- โ Security Focus - Specialized cybersecurity guidance and advice
- โ Responsive Design - Mobile-optimized chat interface
- โ UI Improvements - Fixed ShieldBot card styling and dashboard icons
- โ Performance - Optimized streaming and error handling