A secure, enterprise-grade password management system built with modern web technologies. TrustVault provides encrypted credential storage, role-based access control, audit logging, and team collaboration features.
- Overview
- Features
- Technology Stack
- Security Architecture
- System Requirements
- Installation & Setup
- Configuration
- API Documentation
- User Roles & Permissions
- Project Structure
- Development Guide
- Deployment Guide
- Security Best Practices
- Troubleshooting
- Contributing
- License
TrustVault is a full-stack password management application designed for teams and organizations that need secure credential storage with enterprise features. It implements industry-standard encryption practices with a two-tier key management system (Master Key + Data Encryption Key), comprehensive audit logging, and fine-grained access controls.
- π Military-Grade Encryption: AES-256-GCM encryption for all sensitive data
- π₯ Team Collaboration: Share credentials securely with users and groups
- π Audit Logging: Complete audit trail of all vault operations
- π Key Rotation: Automatic re-encryption during master key rotation
- π Modern Tech Stack: React 19, Node.js, MongoDB, Docker
- β‘ Real-time Updates: React Query for optimized data fetching
- π¨ Beautiful UI: Tailwind CSS with responsive design
-
Secure Credential Storage
- Store passwords, usernames, URLs, and notes with end-to-end encryption
- Organize credentials with tags and categories
- Quick search and filter capabilities
- Password reveal with audit logging
-
Sharing & Collaboration
- Share credentials with individual users or groups
- Two access levels: View-only and Edit permissions
- Granular permission management per item
-
Advanced Encryption
- AES-256-GCM encryption algorithm
- Two-tier key management (Master Key + DEK)
- Secure key wrapping and unwrapping
- Key rotation with automatic re-encryption
-
Authentication & Authorization
- JWT-based authentication with access and refresh tokens
- Argon2 password hashing
- Role-based access control (RBAC)
- Rate limiting to prevent brute force attacks
- Secure session management with HTTP-only cookies
-
Password Recovery
- Forgot password flow with OTP verification
- Time-limited OTP codes (5 minutes expiry)
- Secure password reset mechanism
-
User Management
- Create, update, and deactivate user accounts
- Assign roles (User, Admin)
- Monitor user activity and last login
- Bulk user operations
-
Group Management
- Create and manage user groups
- Assign users to multiple groups
- Share credentials with entire groups
- Group-based permissions
-
Audit Logging
- Comprehensive audit trail for all operations
- Track who accessed what and when
- Filter logs by user, action type, and date range
- Export audit logs for compliance
-
Security Settings
- Master key rotation interface
- View security status and key information
- Monitor encryption key versions
-
My Vault Dashboard
- View all accessible credentials
- Create and manage personal vault items
- Access shared credentials
- Quick search and filtering
-
Activity Tracking
- Personal activity log
- View recent actions
- Track credential access history
- Runtime: Node.js (v18+)
- Framework: Express.js v5
- Database: MongoDB (Mongoose ODM)
- Authentication: JWT (jsonwebtoken)
- Encryption: Node.js Crypto (AES-256-GCM)
- Password Hashing: Argon2
- Security Headers: Helmet
- Rate Limiting: rate-limiter-flexible
- Logging: Winston
- Validation: Joi
- Framework: React 19
- Build Tool: Vite 7
- Routing: React Router DOM v7
- State Management: React Query (TanStack Query v5)
- HTTP Client: Axios
- Styling: Tailwind CSS v4
- UI Components: Custom components with Lucide icons
- Form Validation: Zod v4
- Containerization: Docker & Docker Compose
- Web Server: Nginx (for frontend static files)
- Process Management: PM2 (optional for production)
- Environment Management: dotenv
TrustVault uses a two-tier key management system:
-
Master Encryption Key (MEK)
- 32-byte key stored as base64 in environment variables
- Never stored in the database
- Used to encrypt/decrypt the Data Encryption Key (DEK)
-
Data Encryption Key (DEK)
- 32-byte key generated on first initialization
- Encrypted (wrapped) with the Master Key and stored in database
- Loaded into memory on server startup
- Used to encrypt/decrypt all vault items
Plaintext Data β Encrypt with DEK β Ciphertext + IV + AuthTag β Store in DB
DB β Ciphertext + IV + AuthTag β Decrypt with DEK β Plaintext Data
When a master key rotation is initiated:
- Generate new Data Encryption Key (DEK)
- Re-encrypt all vault items with new DEK
- Wrap new DEK with Master Key
- Archive old key version
- Update security settings with new key version
- User logs in with email/password
- Server validates credentials (Argon2 hash verification)
- Server generates access token (2 min expiry) and refresh token (7 days)
- Access token sent in response, refresh token in HTTP-only cookie
- Client includes access token in Authorization header
- When access token expires, client uses refresh token to get new access token
- Node.js: v18.0.0 or higher
- npm: v8.0.0 or higher
- MongoDB: v5.0 or higher
- RAM: 2GB minimum, 4GB recommended
- Disk Space: 1GB minimum
- Linux (Ubuntu 20.04+, Debian 11+, CentOS 8+)
- macOS (10.15+)
- Windows 10/11 (with WSL2 for Docker)
git clone https://github.com/sahanRanasingha/TrustVault.git
cd TrustVaultcd server
# Install dependencies
npm install
# Generate a 32-byte master key (base64 encoded)
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
# Copy .env.example to .env
cp .env.example .env
# Edit .env and set your values:
# - MASTER_KEY: Use the generated key from above
# - JWT_SECRET: Any secure random string
# - MONGO_URI: Your MongoDB connection string
nano .envMake sure MongoDB is running:
# If using local MongoDB
sudo systemctl start mongod
# Or using Docker
docker run -d -p 27017:27017 --name mongodb mongo:latestSeed the database with initial admin user:
cd server
npm run seedDefault admin credentials:
- Email: admin@trustvault.com
- Password: Admin@123
cd ../client
# Install dependencies
npm install
# Copy .env.example if exists, or create .env
echo "VITE_API_URL=http://localhost:5000/api" > .envTerminal 1 - Backend:
cd server
npm run devTerminal 2 - Frontend:
cd client
npm run devThe application will be available at:
- Frontend: http://localhost:5173
- Backend API: http://localhost:5000
- MongoDB: localhost:27017
Docker deployment is the recommended way to run TrustVault in production.
- Docker (v20.10+)
- Docker Compose (v2.0+)
# Generate a 32-byte master key
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"Create a .env file in the root directory (where docker-compose.yml is):
# Create .env file
cat > .env << EOF
MASTER_KEY=YOUR_GENERATED_KEY_HERE
EOFReplace YOUR_GENERATED_KEY_HERE with the key generated in step 2.
# Build and start all services
docker-compose up --build -d
# View logs
docker-compose logs -f
# Check service status
docker-compose ps# Seed the database with initial admin user
docker-compose exec server npm run seedThe application will be available at:
- Frontend: http://localhost (port 80)
- Backend API: http://localhost:5000
- MongoDB: localhost:27017
# Stop all services
docker-compose down
# Stop and remove volumes (WARNING: Deletes all data)
docker-compose down -v
# Restart a specific service
docker-compose restart server
# View logs for specific service
docker-compose logs -f server
# Execute command in container
docker-compose exec server npm run seed
# Rebuild specific service
docker-compose up -d --build server# Server Settings
PORT=5000
NODE_ENV=development # or 'production'
# Database
MONGO_URI=mongodb://localhost:27017/trustvault
# JWT Settings
JWT_SECRET=your_jwt_secret_key_here
JWT_ACCESS_EXPIRY=2m # Access token expiry (2 minutes)
JWT_REFRESH_EXPIRY=7d # Refresh token expiry (7 days)
# Encryption
MASTER_KEY=base64_encoded_32_byte_key_here
# CORS
CLIENT_URL=http://localhost:5173 # Frontend URL# API Endpoint
VITE_API_URL=http://localhost:5000/apiFor production deployment, ensure:
- Strong JWT Secret: Use a cryptographically secure random string
- Secure Master Key: Keep the master key in a secure vault (e.g., AWS Secrets Manager, Azure Key Vault)
- HTTPS: Use SSL/TLS certificates (Let's Encrypt recommended)
- Environment: Set
NODE_ENV=production - Database: Use MongoDB Atlas or a secured MongoDB cluster
- CORS: Set
CLIENT_URLto your production domain - Rate Limiting: Adjust rate limits based on your needs
- Logging: Configure Winston to write logs to files
Login with email and password.
Request Body:
{
"email": "user@example.com",
"password": "SecurePassword123!"
}Response:
{
"success": true,
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "user_id",
"email": "user@example.com",
"firstName": "John",
"lastName": "Doe",
"role": "user"
}
}Logout and clear refresh token.
Headers: Authorization: Bearer {accessToken}
Get current user information.
Headers: Authorization: Bearer {accessToken}
Refresh access token using refresh token cookie.
Initiate password recovery.
Request Body:
{
"email": "user@example.com"
}Verify OTP code.
Request Body:
{
"email": "user@example.com",
"otp": "123456"
}Reset password after OTP verification.
Request Body:
{
"email": "user@example.com",
"otp": "123456",
"newPassword": "NewSecurePassword123!"
}All vault endpoints require authentication (Authorization: Bearer {token}).
Get all vault items accessible to the user.
Query Parameters:
search: Search in title, url, tags (optional)
Create a new vault item.
Request Body:
{
"title": "Gmail Account",
"url": "https://mail.google.com",
"username": "user@gmail.com",
"password": "securepassword",
"notes": "Personal email account",
"tags": ["email", "personal"],
"sharedWithUsers": [
{
"user": "user_id",
"accessLevel": "view"
}
],
"sharedWithGroups": [
{
"group": "group_id",
"accessLevel": "edit"
}
]
}Get vault item metadata (without sensitive data).
Reveal encrypted data (username, password, notes).
Update a vault item.
Delete a vault item.
Get all users.
Create a new user.
Update user information.
Deactivate a user.
Get all groups.
Create a new group.
Update group information.
Delete a group.
Update group members.
Get audit logs (admin: all logs, user: own logs).
Query Parameters:
userId: Filter by useraction: Filter by action typestartDate: Filter by start dateendDate: Filter by end date
Get current security status and key information.
Rotate the Data Encryption Key (DEK).
Permissions:
- View own vault items
- Create vault items
- Edit own vault items
- Delete own vault items
- Access shared vault items (based on permission level)
- View own activity logs
Restrictions:
- Cannot access admin panel
- Cannot manage other users
- Cannot manage groups
- Cannot view all audit logs
- Cannot rotate encryption keys
All User Permissions, plus:
- Access admin panel
- Manage all users (create, edit, deactivate)
- Manage all groups
- View all audit logs
- Access security settings
- Rotate encryption keys
- View system security status
TrustVault/
βββ client/ # Frontend React application
β βββ public/ # Static assets
β βββ src/
β β βββ components/ # Reusable React components
β β β βββ ConfirmModal.jsx
β β β βββ GroupModal.jsx
β β β βββ Layout.jsx
β β β βββ ProtectedRoute.jsx
β β β βββ VaultDetailModal.jsx
β β β βββ VaultModal.jsx
β β βββ context/ # React Context providers
β β β βββ AuthContext.jsx
β β βββ lib/ # Utility libraries
β β β βββ axios.js # Axios configuration
β β β βββ utils.js # Helper functions
β β βββ pages/ # Page components
β β β βββ Admin/ # Admin pages
β β β β βββ AuditLogList.jsx
β β β β βββ GroupList.jsx
β β β β βββ SecuritySettings.jsx
β β β β βββ UserList.jsx
β β β βββ ForgotPasswordPage.jsx
β β β βββ LoginPage.jsx
β β β βββ MyActivity.jsx
β β β βββ UnauthorizedPage.jsx
β β β βββ VaultList.jsx
β β βββ App.jsx # Main App component
β β βββ main.jsx # Entry point
β βββ .dockerignore
β βββ Dockerfile
β βββ nginx.conf # Nginx configuration for Docker
β βββ package.json
β βββ tailwind.config.js
β βββ vite.config.js
β
βββ server/ # Backend Node.js application
β βββ controllers/ # Route controllers
β β βββ auditController.js
β β βββ authController.js
β β βββ groupController.js
β β βββ securityController.js
β β βββ userController.js
β β βββ vaultController.js
β βββ crypto/ # Encryption utilities
β β βββ encryption.js # AES-256-GCM encryption
β β βββ keyManager.js # Key management (DEK/MEK)
β βββ middleware/ # Express middleware
β β βββ auth.js # JWT authentication
β β βββ errorHandler.js # Global error handler
β β βββ rbac.js # Role-based access control
β βββ models/ # Mongoose models
β β βββ AuditLog.js
β β βββ Group.js
β β βββ KeyHistory.js
β β βββ SecuritySettings.js
β β βββ User.js
β β βββ VaultItem.js
β βββ routes/ # API routes
β β βββ audit.js
β β βββ auth.js
β β βββ groups.js
β β βββ security.js
β β βββ users.js
β β βββ vault.js
β βββ services/ # Business logic services
β βββ utils/ # Utility functions
β β βββ logger.js # Winston logger
β βββ .dockerignore
β βββ .env.example # Environment template
β βββ app.js # Express app configuration
β βββ db.js # MongoDB connection
β βββ Dockerfile
β βββ package.json
β βββ seed.js # Database seeding script
β βββ server.js # Server entry point
β
βββ .gitignore
βββ docker-compose.yml # Docker Compose configuration
βββ README-DOCKER.md # Docker-specific instructions
βββ README.md # This file
# Backend tests (if configured)
cd server
npm test
# Frontend tests (if configured)
cd client
npm test# Backend linting
cd server
npm run lint
# Frontend linting
cd client
npm run lintTo reset the database with fresh seed data:
cd server
npm run seedThis creates:
- Default admin user (admin@trustvault.com / Admin@123)
- Sample user (user@example.com / User@123)
- Sample groups
- Sample vault items
-
Backend API Endpoint
- Create controller in
server/controllers/ - Define route in
server/routes/ - Add validation with Joi
- Update audit logging if needed
- Create controller in
-
Frontend Component
- Create component in
client/src/components/orclient/src/pages/ - Add routing in
App.jsx - Use React Query for data fetching
- Follow existing patterns for consistency
- Create component in
- JavaScript: ESLint configuration provided
- React: Functional components with hooks
- CSS: Tailwind CSS utility classes
- Naming: camelCase for variables, PascalCase for components
- File Structure: Group related files together
-
Prepare Server
# Update system sudo apt update && sudo apt upgrade -y # Install Docker and Docker Compose curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh sudo usermod -aG docker $USER
-
Clone and Configure
git clone https://github.com/sahanRanasingha/TrustVault.git cd TrustVault # Generate and set master key node -e "console.log(require('crypto').randomBytes(32).toString('base64'))" > master_key.txt echo "MASTER_KEY=$(cat master_key.txt)" > .env # Secure the key file chmod 600 .env master_key.txt
-
Configure Production Settings
Edit
docker-compose.ymlto use production environment:environment: - NODE_ENV=production - CLIENT_URL=https://your-domain.com
-
Setup SSL/TLS
Use Let's Encrypt with Nginx:
sudo apt install certbot python3-certbot-nginx sudo certbot --nginx -d your-domain.com
-
Deploy
docker-compose up -d --build docker-compose exec server npm run seed -
Setup Monitoring
# View logs docker-compose logs -f # Monitor container health docker-compose ps
-
Install Dependencies
# Node.js curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt install -y nodejs # MongoDB # Follow: https://docs.mongodb.com/manual/installation/ # PM2 sudo npm install -g pm2
-
Setup Application
git clone https://github.com/sahanRanasingha/TrustVault.git cd TrustVault # Backend cd server npm install cp .env.example .env # Edit .env with production values # Frontend cd ../client npm install npm run build
-
Start Services
# Start backend with PM2 cd server pm2 start server.js --name trustvault-api pm2 save pm2 startup # Setup Nginx for frontend sudo cp client/nginx.conf /etc/nginx/sites-available/trustvault sudo ln -s /etc/nginx/sites-available/trustvault /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl restart nginx
- Debug logging enabled
- Hot reload for both frontend and backend
- CORS allows localhost origins
- Short JWT expiry for testing
- Error logging only
- Optimized builds
- CORS restricted to production domain
- Longer JWT expiry
- Rate limiting enforced
- Security headers enabled
-
Master Key Security
- Never commit master key to version control
- Store in secure vault (AWS Secrets Manager, Azure Key Vault)
- Rotate periodically (every 90 days recommended)
- Use strong, random 32-byte keys
-
Database Security
- Use strong MongoDB credentials
- Enable MongoDB authentication
- Use encrypted connections (TLS/SSL)
- Regular backups with encryption
- Restrict network access
-
Application Security
- Keep dependencies updated
- Use HTTPS in production
- Enable HSTS headers
- Regular security audits
- Monitor audit logs
-
User Management
- Enforce strong password policies
- Regularly review user permissions
- Deactivate unused accounts
- Monitor suspicious activity
-
Strong Passwords
- Use unique passwords for TrustVault
- Minimum 12 characters
- Mix of uppercase, lowercase, numbers, symbols
-
Account Security
- Don't share credentials
- Log out when finished
- Report suspicious activity
- Regularly review shared items
-
Sharing Practices
- Only share when necessary
- Use view-only when possible
- Regularly audit shared items
- Remove access when no longer needed
Error: MongooseServerSelectionError
Solutions:
- Ensure MongoDB is running:
sudo systemctl status mongod - Check MONGO_URI in .env
- Verify network connectivity
- Check MongoDB logs:
/var/log/mongodb/mongod.log
Error: MASTER_KEY must be 32 bytes
Solutions:
- Generate new key:
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))" - Ensure key is base64 encoded
- No spaces or newlines in key
Error: Access-Control-Allow-Origin
Solutions:
- Check CLIENT_URL in server .env
- Ensure URL includes protocol (http:// or https://)
- No trailing slash in URL
Error: Token expired
Solutions:
- Access token expires in 2 minutes (by design)
- Refresh token should automatically renew it
- If refresh token expired, log in again
- Check JWT_REFRESH_EXPIRY in .env
Solutions:
- Check Docker daemon is running
- Ensure sufficient disk space
- Clear Docker cache:
docker system prune -a - Check Dockerfile syntax
Error: EADDRINUSE
Solutions:
# Find process using port
sudo lsof -i :5000
# Kill process
sudo kill -9 <PID>If you encounter issues:
-
Check the logs:
# Docker logs docker-compose logs -f server # Server logs tail -f server/combined.log tail -f server/error.log
-
Enable debug mode:
NODE_ENV=development
-
Verify configuration:
# Check environment variables cd server node -e "require('dotenv').config(); console.log(process.env)"
We welcome contributions! Please follow these guidelines:
- 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
- Follow existing code style
- Add comments for complex logic
- Update documentation
- Write tests for new features
- Ensure all tests pass
This project is licensed under the ISC License.
Sahan Ranasingha
- GitHub: @sahanRanasingha
- React team for amazing frontend framework
- Express.js for robust backend framework
- MongoDB for flexible database
- All open-source contributors
π§ Support: For issues and questions, please open an issue on GitHub.
π Star this repository if you find it useful!