---
name: standard-architecture
description: Automatically setup secure deployment architecture with Nginx + Unix Socket + Cloudflare Tunnel. Use when creating new applications, backends, APIs, or any web service. Triggers on "create app", "deploy service", "new backend", "setup architecture".
---

# Standard Security Architecture

Automatically deploys applications using the **most secure architecture pattern**:
- **Zero public ports** for backend services
- **Unix Domain Sockets** for inter-process communication  
- **Nginx reverse proxy** for security and performance
- **Cloudflare Tunnel** for zero-trust network access
- **Docker isolation** with proper security boundaries

## When to Use

- Creating new web applications, APIs, or backend services
- Migrating existing services to secure architecture
- Setting up development/staging/production environments
- Any application requiring internet access

## Architecture Pattern

```
Internet → Cloudflare Edge → CF Tunnel → Nginx → Unix Socket → Docker App
```

**Security Benefits:**
- ✅ Zero network ports exposed to internet
- ✅ File-based permissions for socket access
- ✅ Nginx security layer (rate limiting, headers)
- ✅ Container isolation boundaries
- ✅ DDoS protection via Cloudflare

## Quick Start

The skill automatically:
1. **Generate Docker setup** with Unix socket support
2. **Create Nginx config** with security hardening
3. **Setup Cloudflare Tunnel** configuration
4. **Configure systemd services** for auto-restart
5. **Apply security policies** and file permissions
6. **Test deployment** end-to-end

## Implementation

### Application Requirements
- Must support Unix Domain Socket binding (most modern frameworks do)
- Should have health check endpoint
- Environment variable configuration

### Generated Files
```
project/
├── docker-compose.yml       # Docker with Unix socket volume
├── nginx/
│   └── app.conf            # Nginx reverse proxy config
├── cloudflared/
│   └── config.yml          # CF tunnel configuration  
├── systemd/
│   └── app.service         # Auto-restart service
└── scripts/
    ├── deploy.sh           # Full deployment script
    └── health-check.sh     # Service validation
```

### Nginx Security Features
- Rate limiting per IP
- Security headers (HSTS, CSP, etc)
- Request size limits
- Bad bot blocking
- SSL/TLS hardening

### Unix Socket Configuration
- Proper file permissions (660)
- Owner/group management
- Socket cleanup on restart
- Performance optimizations

## Usage Examples

### Backend API
```bash
./scripts/deploy.sh --type=api --port=8080 --domain=api.example.com
```

### Full-Stack App  
```bash
./scripts/deploy.sh --type=webapp --frontend=3000 --backend=8080 --domain=app.example.com
```

### Database Service
```bash
./scripts/deploy.sh --type=database --port=5432 --internal-only
```

## Advanced Configuration

### Multi-Service Setup
Handle applications with multiple components (frontend, backend, workers) using unified socket directory and Nginx upstream configuration.

### Load Balancing
Configure multiple backend instances behind single Unix socket proxy for horizontal scaling.

### Monitoring Integration
Automatic setup of:
- Health check endpoints
- Prometheus metrics exposure
- Log aggregation configuration
- Alert manager integration

## Security Hardening

### File System
- Unix socket permissions: `660` (owner + group only)
- Service user isolation
- Read-only container filesystem where possible
- Volume mount restrictions

### Network
- Container network isolation (`network_mode: none` for pure socket communication)
- Firewall rules via iptables
- CrowdSec integration for threat detection

### Process
- Non-root container execution
- Resource limits (CPU, memory)
- Capability dropping
- Systemd service isolation

## Troubleshooting

### Common Issues
- **Socket permission denied**: Check file ownership and permissions
- **Connection refused**: Verify socket file exists and service is running
- **502 Bad Gateway**: Check socket path in Nginx config matches application
- **CF Tunnel not connecting**: Verify tunnel token and domain DNS

### Debug Commands
```bash
# Check socket file
ls -la /var/run/sockets/

# Test socket connectivity  
curl --unix-socket /var/run/sockets/app.sock http://localhost/health

# Nginx config test
nginx -t

# Service status
systemctl status app
```

## Best Practices

### Development Workflow
1. Start with localhost development
2. Test Unix socket locally  
3. Add Nginx layer
4. Configure CF tunnel
5. Deploy with monitoring

### Production Checklist
- [ ] Unix socket permissions verified
- [ ] Nginx security headers enabled
- [ ] CF tunnel authenticated
- [ ] Health checks responding
- [ ] Log rotation configured
- [ ] Backup strategy in place
- [ ] Monitoring alerts active

### Security Review
- [ ] No network ports in application containers
- [ ] Socket files protected (not world-readable)
- [ ] Nginx rate limiting configured
- [ ] CF WAF rules enabled
- [ ] Container runs as non-root
- [ ] Resource limits applied

## Integration with Existing Services

Works seamlessly with:
- **Databases**: PostgreSQL, Redis, MongoDB via Unix sockets
- **Message Queues**: RabbitMQ, Apache Kafka
- **Monitoring**: Prometheus, Grafana, ELK stack
- **CI/CD**: GitHub Actions, GitLab CI, Jenkins
- **Container Orchestration**: Docker Swarm, basic Kubernetes

---

**Note:** This pattern provides maximum security with minimal complexity. Every new application should follow this architecture unless specific requirements dictate otherwise.