# AeThex Passport Domain Verification - Setup Guide

## Quick Start (5 Minutes)

### 1. Install Dependencies

```bash
# Root dependencies (backend)
npm install

# Frontend dependencies
cd src/frontend && npm install && cd ../..
```

### 2. Setup PostgreSQL Database

#### Option A: Local PostgreSQL

```bash
# Install PostgreSQL (Ubuntu/Debian)
sudo apt update
sudo apt install postgresql postgresql-contrib

# Start PostgreSQL
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Create database and user
sudo -u postgres psql
```

In PostgreSQL shell:
```sql
CREATE DATABASE aethex_passport;
CREATE USER aethex_user WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE aethex_passport TO aethex_user;
\q
```

#### Option B: Docker PostgreSQL

```bash
docker run --name aethex-postgres \
  -e POSTGRES_DB=aethex_passport \
  -e POSTGRES_USER=aethex_user \
  -e POSTGRES_PASSWORD=your_password \
  -p 5432:5432 \
  -d postgres:14
```

### 3. Configure Environment

```bash
# Copy environment template
cp .env.example .env

# Edit configuration
nano .env
```

Update these values in `.env`:
```env
DATABASE_URL=postgresql://aethex_user:your_password@localhost:5432/aethex_passport
PORT=3000
JWT_SECRET=your-super-secret-key-change-this
NODE_ENV=development
```

### 4. Run Database Migrations

```bash
npm run migrate
```

You should see:
```
Starting database migrations...
Running migration: 001_domain_verifications.sql
✓ Completed: 001_domain_verifications.sql
✓ All migrations completed successfully
```

### 5. Start Development Servers

Open two terminal windows:

**Terminal 1 - Backend:**
```bash
npm run dev
```

**Terminal 2 - Frontend:**
```bash
cd src/frontend && npm run dev
```

### 6. Access the Application

- **Frontend**: http://localhost:5173
- **Backend API**: http://localhost:3000
- **Health Check**: http://localhost:3000/health

## Testing Domain Verification

### Test with Your Own Domain

1. **Request Verification**:
   - Go to http://localhost:5173
   - Enter your domain (e.g., `dev.aethex.dev`)
   - Click "Request Verification"

2. **Add DNS Record**:
   - Copy the TXT record value shown
   - Go to your DNS provider (Cloudflare, Google Domains, etc.)
   - Add new TXT record:
     - **Name**: `_aethex-verify`
     - **Type**: `TXT`
     - **Value**: `aethex-verification=...` (the copied value)

3. **Verify**:
   - Wait 5-10 minutes for DNS to propagate
   - Click "Verify Domain" in the app
   - Success! Your domain badge appears

### Check DNS Propagation

```bash
# Check if DNS record is live
dig _aethex-verify.yourdomain.com TXT +short

# Alternative method
nslookup -type=TXT _aethex-verify.yourdomain.com
```

Expected output:
```
"aethex-verification=abc123def456..."
```

## Common Issues & Solutions

### Issue: "Connection refused" to database

**Solution 1**: Check PostgreSQL is running
```bash
sudo systemctl status postgresql
```

**Solution 2**: Verify connection string in `.env`
```bash
# Test connection manually
psql postgresql://aethex_user:your_password@localhost:5432/aethex_passport
```

### Issue: "Port 3000 already in use"

**Solution**: Find and kill the process
```bash
# Find process using port 3000
lsof -i :3000

# Kill it
kill -9 <PID>
```

### Issue: DNS verification always fails

**Checklist**:
1. ✓ DNS record added correctly?
2. ✓ Waited 10+ minutes?
3. ✓ Record name is `_aethex-verify` (not `_aethex-verify.yourdomain.com`)?
4. ✓ Record value matches exactly (no extra quotes)?

**Debug DNS**:
```bash
# Check what DNS server sees
dig _aethex-verify.yourdomain.com TXT @8.8.8.8

# Flush local DNS cache
sudo systemd-resolve --flush-caches
```

## Environment Variables Reference

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `DATABASE_URL` | ✅ Yes | - | PostgreSQL connection string |
| `PORT` | No | 3000 | Backend server port |
| `NODE_ENV` | No | development | Environment mode |
| `JWT_SECRET` | ✅ Yes | - | Secret for JWT tokens |
| `RPC_ENDPOINT` | For .aethex | - | Blockchain RPC URL |
| `FREENAME_REGISTRY_ADDRESS` | For .aethex | - | Contract address |
| `FRONTEND_URL` | No | http://localhost:5173 | CORS origin |
| `RATE_LIMIT_WINDOW_MS` | No | 900000 | Rate limit window (15 min) |
| `RATE_LIMIT_MAX_REQUESTS` | No | 100 | Max requests per window |

## Production Deployment

### 1. Build Frontend

```bash
cd src/frontend
npm run build
cd ../..
```

### 2. Environment Configuration

```bash
# Create production .env
cp .env.example .env.production

# Edit with production values
nano .env.production
```

Set:
```env
NODE_ENV=production
DATABASE_URL=postgresql://user:pass@production-host:5432/aethex_passport
JWT_SECRET=<strong-random-secret>
FRONTEND_URL=https://yourdomain.com
```

### 3. Start Production Server

```bash
NODE_ENV=production node src/backend/server.js
```

### 4. Serve Frontend

Use nginx or serve built files:
```bash
# Using serve
npm install -g serve
serve -s src/frontend/dist -l 5173
```

Or configure nginx:
```nginx
server {
    listen 80;
    server_name yourdomain.com;
    
    location / {
        root /path/to/src/frontend/dist;
        try_files $uri /index.html;
    }
    
    location /api {
        proxy_pass http://localhost:3000;
    }
}
```

## Database Backup

### Manual Backup

```bash
# Backup database
pg_dump -U aethex_user aethex_passport > backup_$(date +%Y%m%d).sql

# Restore from backup
psql -U aethex_user aethex_passport < backup_20260109.sql
```

### Automated Daily Backups

Create `/etc/cron.daily/aethex-backup`:
```bash
#!/bin/bash
pg_dump -U aethex_user aethex_passport | gzip > /backups/aethex_$(date +%Y%m%d).sql.gz
find /backups -name "aethex_*.sql.gz" -mtime +30 -delete
```

Make executable:
```bash
chmod +x /etc/cron.daily/aethex-backup
```

## Monitoring

### Health Check Endpoint

```bash
# Check if server is running
curl http://localhost:3000/health
```

Response:
```json
{"status":"ok","timestamp":"2026-01-09T12:00:00.000Z"}
```

### Database Connection Test

```bash
# Test query
psql -U aethex_user -d aethex_passport -c "SELECT COUNT(*) FROM domain_verifications;"
```

### Log Files

Backend logs to stdout. Capture with:
```bash
# Development
npm run dev 2>&1 | tee logs/app.log

# Production (with pm2)
npm install -g pm2
pm2 start src/backend/server.js --name aethex-passport
pm2 logs aethex-passport
```

## Next Steps

1. ✅ Setup complete? Test verification flow
2. 📱 Integrate into your main application
3. 🔐 Set up proper JWT authentication
4. 📊 Add analytics and monitoring
5. 🚀 Deploy to production

## Need Help?

- 📖 [Full Documentation](README.md)
- 🐛 [Report Issues](https://github.com/AeThex-Corporation/AeThex-Connect/issues)
- 💬 Email: support@aethex.dev

---

**Setup Guide v1.0** | Last Updated: January 10, 2026
