# 🔐 LockNKey - Quantum-Resistant Password Manager

A next-generation password management system built with post-quantum cryptography (CRYSTALS-Kyber-768) to protect against future quantum computing threats.

![Security](https://img.shields.io/badge/Security-Quantum%20Resistant-green)
![Status](https://img.shields.io/badge/Status-MVP-blue)
![License](https://img.shields.io/badge/License-MIT-yellow)

---

## 🌟 Features

### ✅ Core Functionality (Implemented)
- **Quantum-Resistant Encryption**: CRYSTALS-Kyber-768 KEM + AES-256-GCM
- **Full CRUD Operations**: Add, view, copy, and delete passwords
- **User Authentication**: Supabase JWT-based auth with row-level security
- **Real-time Decryption**: 8-19ms decryption performance
- **Audit Logging**: Complete activity trail for accountability
- **Security Dashboard**: Visual quantum protection indicators

### 🚧 In Development
- Password sharing and collaboration
- Password strength analysis
- Browser extension (Chrome/Firefox)
- Password generation with quantum entropy
- Multi-factor authentication

---

## 🏗️ Architecture

### Technology Stack

#### Frontend
- **Framework**: Next.js 14 (App Router)
- **UI Components**: shadcn/ui + TailwindCSS
- **State Management**: Zustand
- **API Client**: React Query (TanStack Query)
- **Language**: TypeScript

#### Backend Services
- **Vault Service**: Node.js + Express + TypeScript
- **Quantum Service**: Python FastAPI
- **Database**: PostgreSQL (via Supabase)
- **Cache/Queue**: Redis
- **Auth**: Supabase Auth

#### Quantum Cryptography
- **Key Encapsulation**: CRYSTALS-Kyber-768 (NIST approved)
- **Symmetric Encryption**: AES-256-GCM
- **Performance**: <100ms encryption/decryption target
- **Library**: liboqs (Open Quantum Safe)

### System Diagram

```
┌─────────────┐
│   Browser   │
│  (Next.js)  │
└──────┬──────┘
       │
       ├─────────────────────────────────┐
       │                                 │
       ▼                                 ▼
┌──────────────┐                 ┌──────────────┐
│ Vault Service│◄────────────────┤Quantum Service│
│   (Node.js)  │  Encrypt/Decrypt│   (Python)   │
└──────┬───────┘                 └──────────────┘
       │
       ▼
┌──────────────┐                 ┌──────────────┐
│  PostgreSQL  │                 │    Redis     │
│  (Supabase)  │                 │  (Caching)   │
└──────────────┘                 └──────────────┘
```

---

## 🚀 Quick Start

### Prerequisites

You only need **2 things** installed:

| Requirement | Version | Download |
|-------------|---------|----------|
| **Docker Desktop** | Latest | [docker.com/products/docker-desktop](https://www.docker.com/products/docker-desktop/) |
| **Node.js** | 18+ | [nodejs.org](https://nodejs.org/) |

> **Note**: Python is NOT required to run the app. It's only needed if you want to develop the quantum service locally.

#### Verify Installation
```bash
docker --version    # Should show Docker version 20+
node --version      # Should show v18+ or v20+
```

### 1. Clone Repository
```bash
git clone https://github.com/CD0minguez/Lock-and-Key-Encrypted-Password-Management-and-Collaboration-System.git
cd Lock-and-Key-Encrypted-Password-Management-and-Collaboration-System
```

### 2. Start the Application (Single Command)
```bash
./start-app.sh
```

This unified script will:
1. **Start Supabase** (PostgreSQL database + Auth) - runs all migrations automatically
2. **Wait for database** to be healthy before proceeding
3. **Start backend services** (Vault, Quantum, Auth via Docker Compose)
4. **Start frontend** (Next.js development server)
5. **Display service URLs** when ready

**Service URLs**:
- **Frontend**: http://localhost:3000
- **Vault Service**: http://localhost:8002
- **Quantum Service**: http://localhost:8001
- **Auth Service**: http://localhost:8003
- **Supabase Studio**: http://localhost:54323
- **Email Testing**: http://localhost:54324

### 3. Stop the Application
```bash
./stop-app.sh
```

### 4. Other Management Commands
```bash
./restart-app.sh    # Restart all services
./status.sh         # Check service status
```

### Manual Startup (Alternative)

If you prefer to start services separately:

**1. Start Supabase First (REQUIRED):**
```bash
cd supabase
npx supabase start
# Wait for all services to be ready
# Note the API URL and keys displayed
```

**2. Backend Services:**
```bash
cd backend
docker-compose up -d
docker ps | grep lockkey  # Verify services
```

**3. Frontend:**
```bash
cd frontend
npm install
npm run dev
```

> ⚠️ **Important**: Supabase must be running before starting backend services, as they depend on the PostgreSQL database and authentication.

---

## 🎮 Starting, Stopping, and Restarting the Application

### Cross-Platform Commands

The application includes unified management scripts that work on **Linux, macOS, and Windows** (with Git Bash or WSL).

#### Start the Application
```bash
./start-app.sh
```

**What it does:**
- Starts all backend Docker containers (Kong, Vault, Quantum, Auth, Redis)
- Starts the frontend Next.js development server
- Displays service URLs and status
- Shows real-time frontend logs

**Expected Output:**
```
🔐 Starting LockNKey Password Manager...
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📦 Starting Backend Services (Docker Compose)...
✅ Backend services starting...

⚛️  Starting Frontend (Next.js Dev Server)...
✅ LockNKey is Running!

🌐 Service URLs:
   Frontend:          http://localhost:3000
   Vault Service:     http://localhost:8002
   ...
```

#### Stop the Application
```bash
./stop-app.sh
```

**What it does:**
- Gracefully stops the frontend server (if running)
- Stops all Docker containers
- Removes containers (preserves data)
- Removes the Docker network

**When to use:**
- End of work session
- Before system shutdown
- Freeing up system resources

#### Restart the Application
```bash
./restart-app.sh
```

**What it does:**
- Stops all services (frontend + backend)
- Waits for graceful shutdown (3 seconds)
- Starts all services fresh
- Re-initializes connections

**When to use:**
- After changing environment variables (`frontend/.env.local`)
- After code changes requiring fresh state
- When services become unresponsive
- After Docker container updates

#### Check Service Status
```bash
./status.sh
```

**What it displays:**
- All running Docker containers with health status
- Frontend server status (port 3000)
- Container ports and mappings
- Quick diagnostic information

### Platform-Specific Instructions

#### Linux & macOS

**Prerequisites:**
- Bash shell (default on Linux/macOS)
- Docker Desktop or Docker Engine
- Execute permissions on scripts

**Setup (first time):**
```bash
# Make scripts executable
chmod +x start-app.sh stop-app.sh restart-app.sh status.sh

# Start application
./start-app.sh
```

**Commands:**
```bash
./start-app.sh      # Start all services
./stop-app.sh       # Stop all services
./restart-app.sh    # Restart all services
./status.sh         # Check status
```

#### Windows

**Option 1: Git Bash (Recommended)**

1. Install [Git for Windows](https://gitforwindows.org/) (includes Git Bash)
2. Open **Git Bash** (not CMD or PowerShell)
3. Navigate to project directory:
   ```bash
   cd /c/path/to/Lock-and-Key-Encrypted-Password-Management-and-Collaboration-System
   ```
4. Run scripts:
   ```bash
   ./start-app.sh
   ./stop-app.sh
   ./restart-app.sh
   ./status.sh
   ```

**Option 2: WSL (Windows Subsystem for Linux)**

1. Install WSL2 from Microsoft Store
2. Install Ubuntu from Microsoft Store
3. Open Ubuntu terminal
4. Navigate to project:
   ```bash
   cd /mnt/c/path/to/Lock-and-Key-Encrypted-Password-Management-and-Collaboration-System
   ```
5. Run scripts:
   ```bash
   ./start-app.sh
   ./stop-app.sh
   ./restart-app.sh
   ./status.sh
   ```

**Option 3: PowerShell (Manual Commands)**

If you prefer PowerShell, use these manual commands:

**Start Backend:**
```powershell
cd backend
docker-compose up -d
docker ps | Select-String "lockkey"
```

**Start Frontend:**
```powershell
cd frontend
npm install
npm run dev
```

**Stop Backend:**
```powershell
cd backend
docker-compose down
```

**Stop Frontend:**
```powershell
# Press Ctrl+C in the frontend terminal
```

### Troubleshooting Script Execution

#### Linux/macOS: Permission Denied
```bash
# Fix: Make scripts executable
chmod +x *.sh

# Verify permissions
ls -la *.sh
```

#### Windows: Script Not Found
```bash
# Fix: Use forward slashes in Git Bash
./start-app.sh  # ✅ Correct
.\start-app.sh  # ❌ Wrong (PowerShell syntax)
```

#### Windows: Docker Not Found in Git Bash
```bash
# Fix: Add Docker to PATH in Git Bash
export PATH="$PATH:/c/Program Files/Docker/Docker/resources/bin"

# Or use Docker Desktop's WSL integration
```

#### All Platforms: Port Already in Use
```bash
# Check which process is using the port
# Linux/macOS:
lsof -i :3000
lsof -i :8002

# Windows PowerShell:
netstat -ano | findstr :3000
netstat -ano | findstr :8002

# Kill the process or change ports in docker-compose.yml
```

### Advanced: Running Services Individually

If you need more control, start services separately:

**Backend Only (All Platforms):**
```bash
cd backend
docker-compose up -d

# View logs
docker-compose logs -f
```

**Frontend Only (All Platforms):**
```bash
cd frontend
npm run dev

# Or with custom port
npm run dev -- --port 3001
```

**Specific Service (All Platforms):**
```bash
cd backend
docker-compose up -d vault-service
docker-compose up -d quantum-service
```

### Quick Reference

| Command | Purpose | When to Use |
|---------|---------|-------------|
| `./start-app.sh` | Start everything | First time, after stop |
| `./stop-app.sh` | Stop everything | End of session |
| `./restart-app.sh` | Restart all services | After changes, if unresponsive |
| `./status.sh` | Check what's running | Debugging, verification |
| `docker-compose logs -f` | View backend logs | Debugging backend issues |
| `docker ps` | List containers | Verify services running |

---

## 📖 Usage

### Creating an Account
1. Navigate to http://localhost:3000
2. Click "Sign Up"
3. Enter email and password
4. Verify email (check Supabase inbox at http://localhost:54324)

### Adding a Password
1. Login to your account
2. Click "Add Password" button
3. Enter:
   - Website/service name
   - Username
   - Password
   - Category (optional)
4. Click "Save"
5. Password is encrypted with CRYSTALS-Kyber-768

### Copying a Password
1. Find your password in the vault
2. Click the copy icon
3. Password is decrypted and copied to clipboard
4. Paste into login form

### Deleting a Password
1. Click the trash icon on a password entry
2. Confirm deletion
3. Entry is permanently removed

---

## 🔧 Development

### Project Structure
```
Lock-and-Key-Encrypted-Password-Management-and-Collaboration-System/
├── frontend/                   # Next.js application
│   ├── src/
│   │   ├── app/               # App Router pages
│   │   ├── components/        # React components
│   │   ├── hooks/             # Custom hooks
│   │   ├── lib/               # Utilities & API clients
│   │   └── stores/            # Zustand state stores
│   └── package.json
├── backend/
│   ├── vault-service/         # Node.js vault API
│   │   ├── src/
│   │   │   ├── routes/        # Express routes
│   │   │   ├── services/      # Business logic
│   │   │   └── middleware/    # Auth & error handling
│   │   └── Dockerfile
│   ├── quantum-service/       # Python quantum crypto API
│   │   ├── app/
│   │   │   ├── api/           # FastAPI endpoints
│   │   │   ├── core/          # Crypto implementation
│   │   │   └── models/        # Pydantic schemas
│   │   └── Dockerfile
│   └── docker-compose.yml
├── supabase/
│   └── migrations/            # Database schema migrations
├── .claude/                   # Claude Code documentation
│   └── task/                  # Task plans and handoffs
├── CLAUDE.md                  # Developer guidelines
└── README.md                  # This file
```

### Key Development Commands

#### Frontend
```bash
cd frontend

npm run dev              # Start dev server
npm run build            # Build for production
npm run typecheck        # TypeScript type checking
npx biome check .        # Lint and format
npm test                 # Run tests (when implemented)
```

#### Backend - Vault Service
```bash
cd backend/vault-service

npm run dev              # Start dev server
npm run build            # Compile TypeScript
npm test                 # Run tests (when implemented)
npx biome check .        # Lint and format

# Docker rebuild (IMPORTANT: See Docker section below)
docker stop lockkey-vault-service
docker rm lockkey-vault-service
docker rmi backend-vault-service
docker-compose build --no-cache vault-service
docker-compose up -d vault-service
```

#### Backend - Quantum Service
```bash
cd backend/quantum-service

python -m pytest         # Run tests
ruff check .             # Lint
ruff format .            # Format code

# Docker rebuild
docker stop lockkey-quantum-service
docker rm lockkey-quantum-service
docker rmi backend-quantum-service
docker-compose build --no-cache quantum-service
docker-compose up -d quantum-service
```

### ⚠️ Docker Development Protocol (CRITICAL)

**When updating backend code in Docker containers**, you MUST follow this complete rebuild sequence:

```bash
# Step 1: Stop the container
docker stop <container-name>

# Step 2: Remove the container
docker rm <container-name>

# Step 3: Remove the image (CRITICAL - prevents cached layers)
docker rmi <image-name>

# Step 4: Rebuild without cache
docker-compose build --no-cache <service-name>

# Step 5: Start fresh container
docker-compose up -d <service-name>
```

**Why**: Docker caches build layers. Simply restarting or rebuilding may use cached layers with old compiled code, causing the container to run outdated JavaScript/Python even after source files were updated.

**Example for vault-service**:
```bash
docker stop lockkey-vault-service && \
docker rm lockkey-vault-service && \
docker rmi backend-vault-service && \
docker-compose build --no-cache vault-service && \
docker-compose up -d vault-service
```

---

## 🔒 Security

### Quantum Cryptography Implementation

#### Hybrid Encryption Approach
```
User Password (plaintext)
    ↓
[CRYSTALS-Kyber-768 KEM]
    ↓
Shared Secret (32 bytes)
    ↓
[AES-256-GCM Encryption]
    ↓
Encrypted Password (stored in database)
```

**Why Hybrid?**
- **CRYSTALS-Kyber**: Quantum-resistant key encapsulation
- **AES-256-GCM**: Fast symmetric encryption for data
- **Best of Both**: Quantum security + performance

#### Performance Metrics
- **Encryption**: 10-15ms per password
- **Decryption**: 8-19ms per password
- **Target**: <100ms (✅ Achieved)
- **Encrypted Size**: ~1200 bytes per password

### Row-Level Security (RLS)
All vault entries enforce PostgreSQL Row-Level Security:
```sql
-- Users can only access their own passwords
CREATE POLICY "Users can only see own entries"
ON vault_entries FOR SELECT
USING (auth.uid() = user_id);
```

### Audit Logging
Every vault operation is logged:
- Entry creation
- Entry deletion
- Password access
- User authentication

View logs in Supabase:
```sql
SELECT * FROM activity_logs
WHERE user_id = 'your-user-id'
ORDER BY created_at DESC;
```

---

## 📊 Current Status

### ✅ Working Features
| Feature | Status | Performance |
|---------|--------|-------------|
| User Registration | ✅ Working | - |
| User Login | ✅ Working | - |
| Add Password | ✅ Working | 10-15ms encryption |
| View Passwords | ✅ Working | <100ms load |
| Copy Password | ✅ Working | 8-19ms decryption |
| Delete Password | ✅ Working | <20ms |
| Quantum Encryption | ✅ Working | CRYSTALS-Kyber-768 |
| Row-Level Security | ✅ Working | Supabase RLS |
| Audit Logging | ✅ Working | All operations tracked |

### 🚧 Known Issues
- **UI Warning Badge**: "7 issues" badge in vault UI is from stale console errors (refresh browser to clear)
- **Supabase Security Warnings**: 6 function search_path warnings (see `.claude/task/FUTURE-2025-09-29-supabase-search-path-strict-fix.md`)
  - **Impact**: Low - functions are secure per PostgreSQL standards
  - **Fix**: Documented for future implementation

### 📈 Database Statistics
```sql
-- Current vault state
Entries: 3
Quantum Protected: 100%
Algorithm: CRYSTALS-Kyber-768
Average Encrypted Size: 1200 bytes
```

---

## 🧪 Testing

### Manual Testing
See `.claude/task/HANDOFF-2025-09-29-delete-button-fix.md` for comprehensive testing checklist.

#### Quick Smoke Test
```bash
# 1. Start all services
docker-compose up -d
cd frontend && npm run dev

# 2. Open browser: http://localhost:3000
# 3. Register new account
# 4. Add test password
# 5. Copy password (verify clipboard)
# 6. Delete password
# 7. Verify database
docker exec supabase_db_Lock-and-Key-Encrypted-Password-Manageme \
  psql -U postgres -d postgres -c \
  "SELECT COUNT(*) FROM vault_entries;"
```

### Integration Testing (Future)
```bash
# When tests are implemented
npm test                 # Frontend tests
cd backend/vault-service && npm test
cd backend/quantum-service && pytest
```

---

## 📚 Documentation

### For Developers
- **`CLAUDE.md`**: Project guidelines, TDD workflow, 1% Solution methodology
- **`.claude/task/`**: Detailed task plans, handoff docs, and implementation notes

### Key Documentation Files
| File | Description |
|------|-------------|
| `CLAUDE.md` | Developer guidelines & project overview |
| `.claude/task/HANDOFF-2025-09-29-delete-button-fix.md` | Latest implementation handoff |
| `.claude/task/HANDOFF-2025-09-29-copy-button-fix-complete.md` | Copy button fix details |
| `.claude/task/FUTURE-2025-09-29-supabase-search-path-strict-fix.md` | Future security enhancement |
| `.claude/task/2025-09-29-delete-button-fix-plan.md` | Delete functionality plan |

### API Documentation
- **Vault Service**: http://localhost:8002/api/v1/docs (when implemented)
- **Quantum Service**: http://localhost:8001/api/v1/docs (when implemented)

---

## 🤝 Contributing

### Development Workflow
1. Read `CLAUDE.md` for project guidelines
2. Follow TDD approach with 1% Solution methodology
3. Use Docker rebuild protocol for backend changes
4. Run linters before committing:
   ```bash
   # Frontend
   npx biome check . --write

   # Backend Python
   ruff format . && ruff check .
   ```
5. Update documentation for significant changes

### Git Workflow
```bash
# Create feature branch
git checkout -b feature/your-feature-name

# Make changes and commit
git add .
git commit -m "feat: description of changes

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>"

# Push and create PR
git push origin feature/your-feature-name
```

---

## 🎯 Roadmap

### Phase 1: MVP (Current) ✅
- [x] User authentication
- [x] Password CRUD operations
- [x] Quantum encryption (CRYSTALS-Kyber-768)
- [x] Copy to clipboard
- [x] Security dashboard

### Phase 2: Enhanced Security (Q1 2026)
- [ ] Password sharing with encryption
- [ ] Two-factor authentication (TOTP)
- [ ] Security audit logging dashboard
- [ ] Password strength analyzer
- [ ] Breach monitoring

### Phase 3: Browser Integration (Q2 2026)
- [ ] Chrome extension
- [ ] Firefox extension
- [ ] Auto-fill functionality
- [ ] Password generation
- [ ] Import from other password managers

### Phase 4: Advanced Features (Q3 2026)
- [ ] Team collaboration
- [ ] Role-based access control
- [ ] Backup and recovery
- [ ] Mobile apps (iOS/Android)
- [ ] API for third-party integrations

---

## 🐛 Troubleshooting

### Common Issues

#### 1. Docker Containers Won't Start
```bash
# Check container logs
docker logs lockkey-vault-service
docker logs lockkey-quantum-service

# Verify ports are not in use
lsof -i :8001
lsof -i :8002
lsof -i :3002
```

#### 2. Frontend Can't Connect to Backend
```bash
# Verify backend services are running
docker ps | grep lockkey

# Check environment variables
cat frontend/.env.local

# Verify URLs match:
# NEXT_PUBLIC_VAULT_SERVICE_URL=http://localhost:8002
```

#### 3. Database Connection Issues
```bash
# Check Supabase is running
docker ps | grep supabase

# Test connection
docker exec supabase_db_Lock-and-Key-Encrypted-Password-Manageme \
  psql -U postgres -d postgres -c "SELECT 1;"
```

#### 4. Code Changes Not Appearing
**Problem**: Updated code but container still runs old version

**Solution**: Follow Docker rebuild protocol (see Development section)

---

## 📄 License

MIT License - See LICENSE file for details

---

## 👥 Authors

### Development Team
- **Christian Dominguez** (6353620) - Team Leader - cdomi090@fiu.edu
- **Mauricio Ballart Alvarez** (6364456) - Product Owner - mball074@fiu.edu
- **Alexis Henkel** (6449093) - ahenk004@fiu.edu
- **Isaac Quintero** (6053248) - iquin024@fiu.edu
- **Alberto Espinoza** (6454155) - aespi237@fiu.edu

### AI Assistance
- **Claude Code** (Anthropic Sonnet 4.5) - Development assistance and documentation

---

## 🙏 Acknowledgments

- **Open Quantum Safe (liboqs)**: Quantum cryptography implementation
- **NIST**: CRYSTALS-Kyber standardization
- **Supabase**: Database and authentication infrastructure
- **shadcn/ui**: UI component library

---

## 📬 Contact & Support

- **GitHub Issues**: https://github.com/CD0minguez/Lock-and-Key-Encrypted-Password-Management-and-Collaboration-System/issues
- **Documentation**: See `.claude/task/` directory for detailed implementation docs

---

## 🔗 Quick Links

- [Supabase Dashboard](http://localhost:54323)
- [Frontend](http://localhost:3000)
- [Vault Service](http://localhost:8002)
- [Quantum Service](http://localhost:8001)
- [Email Testing](http://localhost:54324) (Mailpit)

---

**Built with 💙 using quantum-resistant cryptography to protect your passwords from future threats.**

Last Updated: 2025-09-29