docs: Restructure documentation with Bookstack-compatible hierarchy

- Organized docs into numbered shelf/book/chapter/page structure
- Created comprehensive README.md with project overview
- Added Getting Started book (quick start, installation, configuration)
- Added Development book (workflow, testing, type sharing)
- Added Architecture book (design principles, PDA-friendly patterns)
- Added API Reference book (conventions, authentication)
- Moved TYPE-SHARING.md to proper location
- Updated all cross-references in main README
- Created docs/README.md as master index
- Removed old QA automation reports
- Removed deprecated SETUP.md (content split into new structure)

Documentation structure follows Bookstack best practices:
- Numbered books: 1-getting-started, 2-development, 3-architecture, 4-api
- Numbered chapters and pages for ordering
- Clear hierarchy and navigation
- Cross-referenced throughout

Complete documentation available at: docs/README.md

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Jason Woltje
2026-01-28 17:46:33 -06:00
parent 6a038d093b
commit dd5b3117a7
18 changed files with 3846 additions and 0 deletions

View File

@@ -0,0 +1,305 @@
# Environment Configuration
Complete reference for all environment variables in Mosaic Stack.
## Configuration File
All environment variables are defined in `.env` at the project root.
```bash
# Copy template
cp .env.example .env
# Edit configuration
nano .env
```
## Core Settings
### Database
```bash
# PostgreSQL connection string
DATABASE_URL=postgresql://user:password@host:port/database
# Examples:
# Local: postgresql://mosaic:mosaic@localhost:5432/mosaic
# Docker: postgresql://mosaic:mosaic@postgres:5432/mosaic
# Production: postgresql://user:pass@prod-host:5432/mosaic
```
**Format:** `postgresql://[user[:password]@][host][:port][/database][?options]`
### Application URLs
```bash
# Frontend URL (used for CORS and redirects)
NEXT_PUBLIC_APP_URL=http://localhost:3000
# API URL (if different from default)
API_URL=http://localhost:3001
```
### Node Environment
```bash
# Development, production, or test
NODE_ENV=development
# API port (default: 3001)
PORT=3001
```
## Authentication
### JWT Session Management
```bash
# Secret key for signing JWT tokens (REQUIRED)
# Generate with: openssl rand -base64 32
JWT_SECRET=your-secret-key-here
# Token expiration time
JWT_EXPIRATION=24h
# Accepted formats: 60 (seconds), 60s, 5m, 2h, 7d
```
**⚠️ Security Warning:** Never commit `JWT_SECRET` to version control. Use a strong, randomly generated secret in production.
### Authentik OIDC (Optional)
```bash
# Authentik instance URL with application path
OIDC_ISSUER=https://auth.example.com/application/o/mosaic-stack/
# OAuth2 client credentials
OIDC_CLIENT_ID=your-client-id
OIDC_CLIENT_SECRET=your-client-secret
# Callback URL (must match Authentik configuration)
OIDC_REDIRECT_URI=http://localhost:3001/auth/callback
```
See [Authentik Setup](2-authentik.md) for complete OIDC configuration.
## Cache and Storage
### Redis/Valkey
```bash
# Redis connection string
REDIS_URL=redis://localhost:6379
# With password
REDIS_URL=redis://:password@localhost:6379
# Docker
REDIS_URL=redis://valkey:6379
```
### File Storage (Future)
```bash
# Local file storage path
FILE_STORAGE_PATH=./storage/uploads
# S3-compatible storage
S3_ENDPOINT=https://s3.amazonaws.com
S3_BUCKET=mosaic-uploads
S3_ACCESS_KEY=your-access-key
S3_SECRET_KEY=your-secret-key
```
## AI Features (Optional)
### Ollama
```bash
# Local or remote Ollama instance
OLLAMA_MODE=local # or 'remote'
# Ollama API endpoint
OLLAMA_ENDPOINT=http://localhost:11434
# Default model for text generation
OLLAMA_MODEL=llama2
# Default model for embeddings
OLLAMA_EMBEDDING_MODEL=nomic-embed-text
```
## Logging and Monitoring
### Log Level
```bash
# Log verbosity: error, warn, info, debug, verbose
LOG_LEVEL=info
# Production recommended: warn
# Development recommended: debug
```
### Sentry (Optional)
```bash
# Sentry DSN for error tracking
SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id
# Environment name
SENTRY_ENVIRONMENT=production
# Release version
SENTRY_RELEASE=v0.0.1
```
## Testing
```bash
# Test database (separate from development)
TEST_DATABASE_URL=postgresql://mosaic:mosaic@localhost:5432/mosaic_test
# Disable external services during testing
SKIP_EXTERNAL_SERVICES=true
```
## Development Tools
### Prisma
```bash
# Prisma Studio port (default: 5555)
PRISMA_STUDIO_PORT=5555
# Enable query logging
PRISMA_LOG_QUERIES=true
```
### Hot Reload
```bash
# Disable hot reload (if causing issues)
NO_WATCH=true
# Polling interval for file watching (ms)
WATCH_POLL_INTERVAL=1000
```
## Complete Example
**.env.example:**
```bash
# ======================
# Core Settings
# ======================
NODE_ENV=development
PORT=3001
NEXT_PUBLIC_APP_URL=http://localhost:3000
# ======================
# Database
# ======================
DATABASE_URL=postgresql://mosaic:mosaic@localhost:5432/mosaic
TEST_DATABASE_URL=postgresql://mosaic:mosaic@localhost:5432/mosaic_test
# ======================
# Authentication
# ======================
JWT_SECRET=change-this-to-a-random-secret-in-production
JWT_EXPIRATION=24h
# Authentik OIDC (Optional)
OIDC_ISSUER=https://auth.example.com/application/o/mosaic-stack/
OIDC_CLIENT_ID=your-client-id
OIDC_CLIENT_SECRET=your-client-secret
OIDC_REDIRECT_URI=http://localhost:3001/auth/callback
# ======================
# Cache
# ======================
REDIS_URL=redis://localhost:6379
# ======================
# AI Features (Optional)
# ======================
OLLAMA_MODE=local
OLLAMA_ENDPOINT=http://localhost:11434
OLLAMA_MODEL=llama2
OLLAMA_EMBEDDING_MODEL=nomic-embed-text
# ======================
# Logging
# ======================
LOG_LEVEL=info
# ======================
# Development
# ======================
PRISMA_STUDIO_PORT=5555
PRISMA_LOG_QUERIES=false
```
## Validation
Environment variables are validated at application startup. Missing required variables will cause the application to fail with a clear error message.
**Required variables:**
- `DATABASE_URL`
- `JWT_SECRET`
- `NEXT_PUBLIC_APP_URL`
**Optional variables:**
- All OIDC settings (if using Authentik)
- All Ollama settings (if using AI features)
- Logging and monitoring settings
## Security Best Practices
1. **Never commit secrets** to version control
2. **Use strong JWT secrets** (min 32 characters, randomly generated)
3. **Rotate secrets regularly** in production
4. **Use different secrets per environment** (dev, staging, prod)
5. **Restrict database user permissions** in production
6. **Enable SSL for database connections** in production
7. **Use environment-specific .env files** (`.env.local`, `.env.production`)
## Troubleshooting
### Application Won't Start
```bash
# Check for syntax errors in .env
cat .env
# Ensure no quotes around values (unless they contain spaces)
# ✅ Good: JWT_SECRET=abc123
# ❌ Bad: JWT_SECRET="abc123"
```
### Database Connection Failed
```bash
# Test connection string
psql "postgresql://mosaic:mosaic@localhost:5432/mosaic"
# Check if PostgreSQL is running
sudo systemctl status postgresql
```
### OIDC Authentication Fails
```bash
# Verify OIDC_ISSUER ends with /
# ✅ Good: https://auth.example.com/application/o/mosaic-stack/
# ❌ Bad: https://auth.example.com/application/o/mosaic-stack
# Check OIDC_REDIRECT_URI matches Authentik configuration exactly
```
## Next Steps
- **Configure Authentik** — [Authentik Setup](2-authentik.md)
- **Review Database Schema** — [Development → Database](../../2-development/2-database/1-schema.md)
- **Start Development** — [Development → Workflow](../../2-development/1-workflow/1-branching.md)

View File

@@ -0,0 +1,324 @@
# Authentik OIDC Setup
Complete guide to configuring Authentik OIDC authentication for Mosaic Stack.
## Overview
Mosaic Stack uses **BetterAuth** with **OpenID Connect (OIDC)** for authentication. Authentik serves as the identity provider for SSO capabilities.
## Prerequisites
- Authentik instance (self-hosted or cloud)
- Admin access to Authentik
- Mosaic Stack installed and running
## Step 1: Install Authentik (Optional)
If you don't have an existing Authentik instance:
### Docker Compose Method
```bash
# Create Authentik directory
mkdir ~/authentik && cd ~/authentik
# Download compose file
curl -o docker-compose.yml https://goauthentik.io/docker-compose.yml
# Generate secret key
echo "AUTHENTIK_SECRET_KEY=$(openssl rand -base64 60)" >> .env
# Start Authentik
docker compose up -d
# Wait for startup (~30 seconds)
docker compose logs -f
```
**Access Authentik:**
- URL: http://localhost:9000/if/flow/initial-setup/
- Create admin account during initial setup
### Alternative: Use Hosted Authentik
Sign up at [goauthentik.io](https://goauthentik.io) for managed Authentik.
## Step 2: Create OAuth2 Provider
1. **Log in to Authentik** as admin
2. **Navigate to Applications****Providers**
3. **Click "Create"** and select **OAuth2/OpenID Provider**
4. **Configure Provider:**
| Field | Value |
|-------|-------|
| **Name** | Mosaic Stack |
| **Authorization flow** | default-provider-authorization-implicit-consent |
| **Client type** | Confidential |
| **Client ID** | (auto-generated, save this) |
| **Client Secret** | (auto-generated, save this) |
| **Redirect URIs** | `http://localhost:3001/auth/callback` |
| **Scopes** | `openid`, `email`, `profile` |
| **Subject mode** | Based on User's UUID |
| **Include claims in id_token** | ✅ Enabled |
5. **Click "Create"**
6. **Save** the Client ID and Client Secret for Step 4
## Step 3: Create Application
1. **Navigate to Applications****Applications**
2. **Click "Create"**
3. **Configure Application:**
| Field | Value |
|-------|-------|
| **Name** | Mosaic Stack |
| **Slug** | mosaic-stack |
| **Provider** | Select "Mosaic Stack" (created in Step 2) |
| **Launch URL** | `http://localhost:3000` |
4. **Click "Create"**
## Step 4: Configure Mosaic Stack
Update your `.env` file:
```bash
# Authentik OIDC Configuration
OIDC_ISSUER=http://localhost:9000/application/o/mosaic-stack/
OIDC_CLIENT_ID=<your-client-id-from-step-2>
OIDC_CLIENT_SECRET=<your-client-secret-from-step-2>
OIDC_REDIRECT_URI=http://localhost:3001/auth/callback
```
**Important Notes:**
- `OIDC_ISSUER` must end with a trailing slash `/`
- Replace `<your-client-id>` and `<your-client-secret>` with actual values from Step 2
- `OIDC_REDIRECT_URI` must exactly match what you configured in Authentik
### Production Configuration
For production deployments:
```bash
OIDC_ISSUER=https://auth.example.com/application/o/mosaic-stack/
OIDC_CLIENT_ID=prod-client-id
OIDC_CLIENT_SECRET=prod-client-secret
OIDC_REDIRECT_URI=https://mosaic.example.com/auth/callback
```
Update Authentik redirect URIs to match your production URL.
## Step 5: Restart Mosaic Stack
```bash
# Local development
pnpm dev:api
# Docker
docker compose restart api
```
## Step 6: Test Authentication
### Method 1: Web UI (when implemented)
1. Navigate to `http://localhost:3000`
2. Click "Sign In"
3. You'll be redirected to Authentik
4. Log in with your Authentik credentials
5. Authorize the application
6. You'll be redirected back to Mosaic Stack
### Method 2: API Endpoint
```bash
# Initiate OIDC flow
curl http://localhost:3001/auth/callback/authentik
# This will return a redirect URL to Authentik
```
### Method 3: Direct Email/Password (Development)
```bash
# Create user via API (development only)
curl -X POST http://localhost:3001/auth/sign-up \
-H "Content-Type: application/json" \
-d '{
"email": "test@example.com",
"password": "SecurePass123!",
"name": "Test User"
}'
# Sign in
curl -X POST http://localhost:3001/auth/sign-in \
-H "Content-Type: application/json" \
-d '{
"email": "test@example.com",
"password": "SecurePass123!"
}'
# Response includes session token
{
"user": {
"id": "...",
"email": "test@example.com",
"name": "Test User"
},
"session": {
"token": "eyJhbGc...",
"expiresAt": "..."
}
}
```
## Advanced Configuration
### Custom Scopes
To request additional user information:
1. In Authentik, navigate to **Customization****Property Mappings**
2. Create custom **Scope Mapping**
3. Add scope to provider configuration
4. Update Mosaic Stack to request the scope
### Multi-Factor Authentication (MFA)
Enable MFA in Authentik:
1. **Navigate to Flows & Stages****Flows**
2. Edit **default-authentication-flow**
3. Add **Multi-Factor Authentication** stage
4. Configure MFA methods (TOTP, WebAuthn, etc.)
Users will be prompted for MFA during login.
### Custom Login Page
Customize Authentik's login page:
1. **Navigate to Customization****Brands**
2. Edit default brand
3. Customize logo, title, and theme
4. Save changes
## Troubleshooting
### Error: "Invalid redirect URI"
**Cause:** Redirect URI in `.env` doesn't match Authentik configuration
**Fix:**
```bash
# Ensure exact match (including http vs https)
# In Authentik: http://localhost:3001/auth/callback
# In .env: OIDC_REDIRECT_URI=http://localhost:3001/auth/callback
```
### Error: "Invalid client credentials"
**Cause:** Incorrect client ID or secret
**Fix:**
1. Double-check Client ID and Secret in Authentik provider
2. Copy values exactly (no extra spaces)
3. Update `.env` with correct values
4. Restart API
### Error: "OIDC discovery failed"
**Cause:** `OIDC_ISSUER` incorrect or Authentik not accessible
**Fix:**
```bash
# Ensure OIDC_ISSUER ends with /
# Test discovery endpoint
curl http://localhost:9000/application/o/mosaic-stack/.well-known/openid-configuration
# Should return JSON with OIDC configuration
```
### Users Can't Access Application
**Cause:** User doesn't have permission in Authentik
**Fix:**
1. In Authentik, go to **Directory****Users**
2. Select user
3. Click **Assigned to applications**
4. Add "Mosaic Stack" application
Or enable **Superuser privileges** for the user (development only).
### Session Expires Too Quickly
**Cause:** JWT expiration set too low
**Fix:**
```bash
# In .env, increase expiration
JWT_EXPIRATION=7d # 7 days instead of 24h
# Restart API
```
## Security Considerations
### Production Checklist
- [ ] Use HTTPS for all URLs
- [ ] Configure CORS properly
- [ ] Use strong client secret (rotate regularly)
- [ ] Enable MFA for admin accounts
- [ ] Review Authentik audit logs regularly
- [ ] Limit redirect URIs to exact matches
- [ ] Use environment-specific client credentials
- [ ] Enable rate limiting on auth endpoints
### Recommended Authentik Settings
```yaml
# In Authentik provider configuration:
- Access token validity: 30 minutes
- Refresh token validity: 30 days
- Include claims in ID token: Enabled
- Subject mode: Based on User's UUID
- Signing algorithm: RS256
```
## User Management
### Create User in Authentik
1. **Navigate to Directory****Users**
2. **Click "Create"**
3. Fill in user details:
- Username
- Email (required for OIDC)
- Name
4. **Click "Create"**
5. User can now log in to Mosaic Stack
### Assign Users to Application
1. Go to **Applications****Applications**
2. Select "Mosaic Stack"
3. Click **Policy / Group / User Bindings**
4. **Click "Bind existing policy"**
5. Select users or groups
6. **Click "Create"**
## Next Steps
- **Review Authentication Flow** — [Architecture → Authentication](../../3-architecture/2-authentication/1-betterauth.md)
- **Start Development** — [Development → Workflow](../../2-development/1-workflow/1-branching.md)
- **Explore API** — [API → Authentication](../../4-api/2-authentication/1-endpoints.md)