# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

Skybridge is an all-in-one "startup starterpack" monolith application designed to provide everything needed to start a software company with a single platform. Built with a microfrontend architecture, it combines multiple business-critical services including API key management, user authentication, permissions, and a modular plugin system for additional business applications.

**Key Technologies:**
- **Backend**: Go 1.23+ with Gin router, PostgreSQL, JWT tokens  
- **Frontend**: React 18+ with TypeScript, Mantine UI components
- **Module Federation**: Webpack 5 Module Federation for plugin architecture
- **Infrastructure**: Podman/Docker Compose, Nginx
- **Security**: HMAC token signing, RBAC permissions, rate limiting

## Startup Platform Architecture

### Business Applications (Microfrontends)
```
skybridge/
├── kms/                     - API Key Management System
│   ├── [Go backend files]   - Secure token lifecycle management
│   └── web/                 - KMS frontend (port 3002)
├── web/                     - Main Shell Dashboard (port 3000)
├── demo/                    - Plugin Development Template (port 3001)  
├── kms-frontend/           - Legacy KMS interface
└── [future modules]        - Additional business applications
```

### Plugin Architecture (Module Federation)
- **Shell Dashboard (port 3000)**: Central hub for all business applications
- **KMS Module (port 3002)**: API key and authentication management
- **Demo Module (port 3001)**: Template for building new business modules
- **Extensible Design**: Easy addition of new business applications (CRM, billing, analytics, etc.)

### Backend Architecture (KMS)
```
cmd/server/          - Application entry point  
internal/            - Go backend core logic
├── domain/          - Domain models and business logic
├── repository/      - Data access interfaces and PostgreSQL implementations  
├── services/        - Business logic layer
├── handlers/        - HTTP request handlers (Gin-based)
├── middleware/      - Authentication, logging, security middleware
├── auth/            - Multiple auth providers (header, JWT, OAuth2, SAML)
└── database/        - Database connection and migrations
```

## Development Commands

### Startup Platform Development

```bash
# Start complete platform in development mode (run in separate terminals)

# Terminal 1: Main Dashboard Shell
cd web
npm install
npm run dev        # Central dashboard on port 3000

# Terminal 2: KMS Business Module
cd kms/web
npm install  
npm run dev        # API Key Management on port 3002

# Terminal 3: Demo/Template Module
cd demo  
npm install
npm run dev        # Plugin template on port 3001

# Production build
npm run build      # In each business module directory
```

### Platform Backend Development

```bash
# Start core platform backend with authentication services
cd kms
INTERNAL_HMAC_KEY=test-hmac-key JWT_SECRET=test-jwt-secret AUTH_SIGNING_KEY=test-signing-key go run cmd/server/main.go

# Build platform backend
go build -o platform-server ./cmd/server

# Run platform tests
go test -v ./test/...

# Test specific business modules
go test -v ./test/ -run TestApplicationCRUD
go test -v ./test/ -run TestStaticTokenWorkflow
```

### Full Platform Deployment (Recommended)

**CRITICAL**: This project uses `podman-compose`, not `docker-compose`.

```bash
# Start complete startup platform (database, API, all business modules)
podman-compose up -d

# Start with forced rebuild after code changes  
podman-compose up -d --build

# View platform logs
podman-compose logs -f kms-api-service
podman-compose logs -f postgres

# Stop entire platform
podman-compose down

# Check platform health
curl http://localhost:8081/health
```

### Database Operations

**CRITICAL**: All database operations use `podman exec` commands.

```bash
# Access database shell
podman exec -it kms-postgres psql -U postgres -d kms

# Run SQL commands via exec
podman exec -it kms-postgres psql -U postgres -c "SELECT * FROM applications LIMIT 5;"

# Check tables
podman exec -it kms-postgres psql -U postgres -d kms -c "\dt"

# Reset test database  
podman exec -it kms-postgres psql -U postgres -c "DROP DATABASE IF EXISTS kms_test; CREATE DATABASE kms_test;"
```

## Key Architecture Patterns

### Business Module Plugin System
- **Shell Dashboard** (`web/webpack.config.js`): Central hub consuming all business modules
- **Business Modules** (`kms/web/webpack.config.js`, `demo/webpack.config.js`): Independent applications exposing functionality
- **Shared Infrastructure**: React, Mantine, icons shared across all business modules

### Startup Platform Routing
- **Central routing**: `/app/{businessModule}/*` handled by shell dashboard
- **Module autonomy**: Each business application handles internal navigation independently  
- **Isolated contexts**: No React Router conflicts between business modules

### Core Authentication System (KMS Module)
The platform's authentication system uses **exact permission names** (not wildcards):
- **Application management**: `app.read`, `app.write`, `app.delete`
- **Token operations**: `token.read`, `token.create`, `token.revoke` 
- **Repository access**: `repo.read`, `repo.write`, `repo.admin`
- **Permission management**: `permission.read`, `permission.write`, `permission.grant`, `permission.revoke`

### Business Application Types
Valid application configurations for the platform:
- `"static"` - Service-to-service authentication for business modules
- `"user"` - User authentication for startup team members

### Ownership Models
Platform supports different ownership structures:
- `"individual"` - Individual founder/employee ownership
- `"team"` - Team/department ownership

## Important Development Notes

### Business Module Development
- **Port allocation**: Dashboard:3000, Demo:3001, KMS:3002, [Future modules:3003+]
- **Environment variables**: All business modules require `webpack.DefinePlugin` for process.env
- **Shared dependencies**: Must match versions across all business modules
- **Navigation**: Use `window.history.pushState()` and custom events for inter-module routing

### Platform API Integration
- **Base URL**: `http://localhost:8080` (development)
- **Authentication**: Header-based with `X-User-Email: admin@example.com`
- **Duration format**: Convert human-readable formats like "24h" to seconds (86400) for API
- **Permission validation**: Use exact permission names from database, not wildcards

### Startup Platform UI Standards
- **UI Framework**: Mantine v7.0.0 (consistent across all business modules)
- **Icons**: Tabler Icons React (shared icon system)
- **Forms**: Mantine Form with validation (standardized form handling)
- **Notifications**: Mantine Notifications (unified notification system)

### Critical Platform Configuration
```bash
# Platform Backend Environment Variables (Required)
INTERNAL_HMAC_KEY=<secure-hmac-key-32-chars-min>
JWT_SECRET=<secure-jwt-secret-32-chars-min>  
AUTH_SIGNING_KEY=<secure-auth-key-32-chars-min>

# Platform Database
DB_HOST=postgres  # Use 'postgres' for containers
DB_PORT=5432
DB_NAME=kms
DB_USER=postgres  
DB_PASSWORD=postgres

# Startup Platform Authentication
AUTH_PROVIDER=header
AUTH_HEADER_USER_EMAIL=X-User-Email
```

### Testing & Debugging
- **Platform E2E Tests**: `./kms/test/e2e_test.sh` for core authentication system
- **Test Users**: `admin@example.com`, `test@example.com`, `limited@example.com`
- **Service Ports**: API:8080, Nginx:8081, Dashboard:3000, DB:5432
- **Debug Business Modules**: Check browser network tab for remoteEntry.js loading from each module

### Build & Deployment
- **Development**: Run dashboard shell + all business modules + platform backend
- **Container Issues**: Use `podman-compose build --no-cache` if changes don't appear
- **Module Federation**: All business modules must be running for dashboard to load them
- **Production**: Build all business modules and serve via nginx with proper CORS headers

## Security Considerations
- All platform tokens use HMAC signing with secure keys
- Permission validation at both API and UI levels across all business modules
- Rate limiting and comprehensive audit logging for startup compliance
- CORS configured for secure business module communication
- Never commit secrets or API keys to repository

## Adding New Business Modules
To extend the startup platform with new business applications (CRM, billing, analytics, etc.):

1. **Create new module directory** following the pattern of `demo/` or `kms/web/`
2. **Configure Module Federation** in webpack.config.js to expose the module
3. **Update shell dashboard** (`web/webpack.config.js`) to consume the new remote
4. **Add to navigation** in `web/src/components/Navigation.tsx`
5. **Follow UI standards** using Mantine components and shared dependencies
6. **Implement authentication** using the platform's permission system
7. **Test integration** ensuring the module loads properly in the dashboard