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,77 @@
# Quick Start
Get Mosaic Stack running in 5 minutes with Docker.
## Prerequisites
- Docker 24+ and Docker Compose 2.20+
- Git 2.x
## Installation
```bash
# Clone repository
git clone https://git.mosaicstack.dev/mosaic/stack mosaic-stack
cd mosaic-stack
# Copy environment file
cp .env.example .env
# Start all services
docker compose up -d
# Run migrations
docker compose exec api pnpm prisma migrate deploy
# Seed development data (optional)
docker compose exec api pnpm prisma:seed
```
## Verify Installation
```bash
# Check API health
curl http://localhost:3001/health
# Expected response:
# {"status":"ok","timestamp":"...","uptime":...}
# View logs
docker compose logs -f api
```
## What's Running?
| Service | Port | Purpose |
|---------|------|---------|
| API | 3001 | NestJS backend |
| PostgreSQL | 5432 | Database |
| Valkey | 6379 | Cache (Redis-compatible) |
## Next Steps
1. **Configure Authentication** — See [Configuration → Authentik](../3-configuration/2-authentik.md)
2. **Explore the API** — Check [API Reference](../../4-api/README.md)
3. **Start Developing** — Read [Development → Workflow](../../2-development/1-workflow/1-branching.md)
## Troubleshooting
**Port already in use:**
```bash
# Stop existing services
docker compose down
# Check what's using the port
lsof -i :3001
```
**Database connection failed:**
```bash
# Check PostgreSQL is running
docker compose ps postgres
# View PostgreSQL logs
docker compose logs postgres
```
For detailed installation options, see [Installation → Local Setup](../2-installation/2-local-setup.md).

View File

@@ -0,0 +1,172 @@
# Prerequisites
Required and optional software for Mosaic Stack development.
## Required
### Node.js 20+
```bash
# Install using nvm (recommended)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install 20
nvm use 20
# Verify installation
node --version # Should be v20.x.x
```
### pnpm 9+
```bash
# Install globally
npm install -g pnpm@9
# Verify installation
pnpm --version # Should be 9.x.x
```
### PostgreSQL 17+
**Option 1: Native Installation (Linux)**
```bash
# Ubuntu/Debian
sudo apt update
sudo apt install postgresql-17 postgresql-contrib postgresql-17-pgvector
# Start PostgreSQL
sudo systemctl start postgresql
sudo systemctl enable postgresql
# Verify installation
sudo -u postgres psql --version
```
**Option 2: macOS (Homebrew)**
```bash
brew install postgresql@17
brew services start postgresql@17
```
**Option 3: Docker (Recommended for Development)**
```bash
# PostgreSQL will be started via docker compose
# No native installation required
```
### Git 2+
```bash
# Ubuntu/Debian
sudo apt install git
# macOS
brew install git
# Verify installation
git --version
```
## Optional
### Docker & Docker Compose
Required for containerized deployment and recommended for development.
**Linux:**
```bash
# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# Add user to docker group
sudo usermod -aG docker $USER
newgrp docker
# Install Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
# Verify installation
docker --version
docker compose version
```
**macOS:**
```bash
# Install Docker Desktop
# Download from: https://www.docker.com/products/docker-desktop
# Verify installation
docker --version
docker compose version
```
### Authentik
Required for OIDC authentication in production.
**Docker Installation:**
```bash
# Download Authentik compose file
curl -o authentik-compose.yml https://goauthentik.io/docker-compose.yml
# Start Authentik
docker compose -f authentik-compose.yml up -d
# Access at http://localhost:9000
```
**Or use an existing Authentik instance**
See [Configuration → Authentik](../3-configuration/2-authentik.md) for setup instructions.
### Ollama
Required for AI features (optional for core functionality).
**Linux:**
```bash
curl -fsSL https://ollama.com/install.sh | sh
# Pull a model
ollama pull llama2
```
**macOS:**
```bash
brew install ollama
# Pull a model
ollama pull llama2
```
**Or use remote Ollama instance**
Configure `OLLAMA_MODE=remote` and `OLLAMA_ENDPOINT` in `.env`.
## Verification
Check all required tools are installed:
```bash
node --version # v20.x.x or higher
pnpm --version # 9.x.x or higher
git --version # 2.x.x or higher
docker --version # 24.x.x or higher (if using Docker)
psql --version # 17.x.x or higher (if using native PostgreSQL)
```
## Next Steps
Proceed to:
- [Local Setup](2-local-setup.md) for native development
- [Docker Setup](3-docker-setup.md) for containerized deployment

View File

@@ -0,0 +1,259 @@
# Local Setup
Native installation for active development with hot reload and debugging.
## Prerequisites
Complete [Prerequisites](1-prerequisites.md) first.
## Step 1: Clone Repository
```bash
git clone https://git.mosaicstack.dev/mosaic/stack mosaic-stack
cd mosaic-stack
```
## Step 2: Install Dependencies
```bash
pnpm install
```
This installs dependencies for:
- Root workspace
- `apps/api` (NestJS backend)
- `apps/web` (Next.js frontend - when implemented)
- `packages/shared` (Shared types and utilities)
## Step 3: Configure Environment
```bash
# Copy environment template
cp .env.example .env
# Edit configuration
nano .env # or use your preferred editor
```
**Minimum required configuration:**
```bash
# Database
DATABASE_URL=postgresql://mosaic:mosaic@localhost:5432/mosaic
# JWT Session
JWT_SECRET=$(openssl rand -base64 32)
JWT_EXPIRATION=24h
# Application
NEXT_PUBLIC_APP_URL=http://localhost:3000
```
See [Configuration → Environment](../3-configuration/1-environment.md) for complete reference.
## Step 4: Setup PostgreSQL Database
### Create Database and User
```bash
sudo -u postgres psql <<EOF
CREATE USER mosaic WITH PASSWORD 'mosaic';
CREATE DATABASE mosaic OWNER mosaic;
\c mosaic
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
GRANT ALL PRIVILEGES ON DATABASE mosaic TO mosaic;
EOF
```
### Or Use Docker PostgreSQL
```bash
# Start only PostgreSQL
docker compose up -d postgres
# Wait for it to be ready
sleep 5
```
## Step 5: Run Database Migrations
```bash
# Generate Prisma client
pnpm prisma:generate
# Run migrations
cd apps/api
pnpm prisma migrate deploy
# Seed development data (optional)
pnpm prisma:seed
# Return to project root
cd ../..
```
## Step 6: Start Development Servers
```bash
# Start all services
pnpm dev
# This starts:
# - API on http://localhost:3001
# - Web on http://localhost:3000 (when implemented)
```
**Or start individually:**
```bash
# API only
pnpm dev:api
# Web only (when implemented)
pnpm dev:web
```
## Step 7: Verify Installation
### Check API Health
```bash
curl http://localhost:3001/health
```
**Expected response:**
```json
{
"status": "ok",
"timestamp": "2026-01-28T...",
"uptime": 1234
}
```
### Run Tests
```bash
pnpm test
```
**Expected output:**
```
Test Files 5 passed (5)
Tests 26 passed (26)
```
### Open Prisma Studio
```bash
cd apps/api
pnpm prisma:studio
# Opens at http://localhost:5555
```
## Development Workflow
### File Watching
The development servers automatically reload when you make changes:
```bash
# API watches src/**/*.ts
pnpm dev:api
# Changes trigger automatic restart
```
### Running Specific Tests
```bash
# All tests
pnpm test
# Watch mode (re-runs on file changes)
pnpm test:watch
# Specific test file
pnpm test apps/api/src/auth/auth.service.spec.ts
# Coverage report
pnpm test:coverage
```
### Database Management
```bash
cd apps/api
# Open Prisma Studio GUI
pnpm prisma:studio
# Create migration after schema changes
pnpm prisma migrate dev --name your_migration_name
# Reset database (WARNING: deletes data)
pnpm prisma migrate reset
```
## Troubleshooting
### Port Already in Use
```bash
# Find process using port
lsof -i :3001
# Kill process
kill -9 <PID>
# Or use different port
PORT=3002 pnpm dev:api
```
### PostgreSQL Connection Failed
```bash
# Check if PostgreSQL is running
sudo systemctl status postgresql
# Test connection
psql -U mosaic -d mosaic -h localhost -W
# Password: mosaic
# Check DATABASE_URL in .env
cat .env | grep DATABASE_URL
```
### Prisma Client Not Generated
```bash
cd apps/api
pnpm prisma:generate
# If still failing, clean and reinstall
rm -rf node_modules
cd ../..
pnpm install
pnpm prisma:generate
```
### Build Errors
```bash
# Clean build cache
rm -rf apps/*/dist packages/*/dist
# Rebuild
pnpm build
# Type check
pnpm typecheck
```
## Next Steps
1. **Configure Authentication** — [Authentik Setup](../3-configuration/2-authentik.md)
2. **Learn the Workflow** — [Development → Workflow](../../2-development/1-workflow/1-branching.md)
3. **Explore the Database** — [Development → Database](../../2-development/2-database/1-schema.md)
4. **Review API Docs** — [API → Conventions](../../4-api/1-conventions/1-endpoints.md)

View File

@@ -0,0 +1,361 @@
# Docker Setup
Containerized deployment for production or quick testing.
## Prerequisites
- Docker 24+ and Docker Compose 2.20+
- Git 2.x
See [Prerequisites](1-prerequisites.md) for installation instructions.
## Step 1: Clone Repository
```bash
git clone https://git.mosaicstack.dev/mosaic/stack mosaic-stack
cd mosaic-stack
```
## Step 2: Configure Environment
```bash
cp .env.example .env
nano .env # Configure as needed
```
**Key variables for Docker deployment:**
```bash
# Database (Docker internal networking)
DATABASE_URL=postgresql://mosaic:mosaic@postgres:5432/mosaic
# Redis (Docker internal networking)
REDIS_URL=redis://valkey:6379
# Application URLs
NEXT_PUBLIC_APP_URL=http://localhost:3000
# JWT
JWT_SECRET=$(openssl rand -base64 32)
JWT_EXPIRATION=24h
```
## Step 3: Start Services
```bash
# Start entire stack
docker compose up -d
# View startup logs
docker compose logs -f
# Check service status
docker compose ps
```
**Services started:**
| Service | Container | Port | Purpose |
|---------|-----------|------|---------|
| API | mosaic-api | 3001 | NestJS backend |
| Web | mosaic-web | 3000 | Next.js frontend |
| PostgreSQL | mosaic-postgres | 5432 | Database |
| Valkey | mosaic-valkey | 6379 | Cache |
## Step 4: Run Database Migrations
```bash
# Enter API container
docker compose exec api sh
# Run migrations
pnpm prisma migrate deploy
# Seed development data (optional)
pnpm prisma:seed
# Exit container
exit
```
## Step 5: Verify Deployment
### Check API Health
```bash
curl http://localhost:3001/health
```
### View Logs
```bash
# All services
docker compose logs -f
# Specific service
docker compose logs -f api
# Last 100 lines
docker compose logs --tail=100 api
```
### Access Containers
```bash
# API container shell
docker compose exec api sh
# PostgreSQL client
docker compose exec postgres psql -U mosaic -d mosaic
# Redis CLI
docker compose exec valkey redis-cli
```
## Management Commands
### Start/Stop Services
```bash
# Start all
docker compose up -d
# Stop all
docker compose stop
# Stop and remove containers
docker compose down
# Stop and remove containers + volumes (WARNING: deletes data)
docker compose down -v
```
### Restart Services
```bash
# Restart all
docker compose restart
# Restart specific service
docker compose restart api
```
### View Service Status
```bash
# List running containers
docker compose ps
# View resource usage
docker stats
# View logs
docker compose logs -f [service_name]
```
### Rebuild After Code Changes
```bash
# Rebuild and restart
docker compose up -d --build
# Rebuild specific service
docker compose build api
docker compose up -d api
```
## Production Deployment
### Environment Configuration
Create a production `.env` file:
```bash
# Production database
DATABASE_URL=postgresql://user:pass@prod-db-host:5432/mosaic
# Production Redis
REDIS_URL=redis://prod-redis-host:6379
# Production URLs
NEXT_PUBLIC_APP_URL=https://mosaic.example.com
# Secure JWT secret
JWT_SECRET=$(openssl rand -base64 64)
JWT_EXPIRATION=24h
# Authentik OIDC
OIDC_ISSUER=https://auth.example.com/application/o/mosaic/
OIDC_CLIENT_ID=prod-client-id
OIDC_CLIENT_SECRET=prod-client-secret
OIDC_REDIRECT_URI=https://mosaic.example.com/auth/callback
```
### Compose Override for Production
Create `docker-compose.prod.yml`:
```yaml
services:
api:
restart: always
environment:
NODE_ENV: production
deploy:
replicas: 2
resources:
limits:
cpus: '1.0'
memory: 1G
web:
restart: always
environment:
NODE_ENV: production
deploy:
replicas: 2
resources:
limits:
cpus: '0.5'
memory: 512M
```
**Deploy:**
```bash
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
```
## Troubleshooting
### Containers Won't Start
```bash
# Check logs for errors
docker compose logs api
docker compose logs postgres
# Check container status
docker compose ps
# Restart specific service
docker compose restart api
```
### Database Connection Failed
```bash
# Check PostgreSQL is running
docker compose ps postgres
# Check PostgreSQL logs
docker compose logs postgres
# Test connection from API container
docker compose exec api sh
nc -zv postgres 5432
```
### Port Already in Use
```bash
# Find what's using the port
lsof -i :3001
# Kill the process or change port in docker-compose.yml
```
### Out of Disk Space
```bash
# Remove unused containers/images
docker system prune -a
# Remove unused volumes (WARNING: may delete data)
docker volume prune
```
### Permission Errors
```bash
# Add user to docker group
sudo usermod -aG docker $USER
# Log out and back in, or
newgrp docker
```
## Monitoring
### Resource Usage
```bash
# Live resource stats
docker stats
# Container logs
docker compose logs -f --tail=100
```
### Health Checks
```bash
# API health endpoint
curl http://localhost:3001/health
# PostgreSQL connection
docker compose exec postgres pg_isready -U mosaic
# Redis ping
docker compose exec valkey redis-cli ping
```
## Updating
### Pull Latest Changes
```bash
git pull origin develop
# Rebuild and restart
docker compose up -d --build
```
### Update Docker Images
```bash
# Pull latest base images
docker compose pull
# Rebuild
docker compose up -d --build
```
## Backup and Restore
### Database Backup
```bash
# Backup database
docker compose exec postgres pg_dump -U mosaic -d mosaic > backup-$(date +%Y%m%d).sql
# Restore database
cat backup-20260128.sql | docker compose exec -T postgres psql -U mosaic -d mosaic
```
### Volume Backup
```bash
# Backup PostgreSQL volume
docker run --rm \
-v mosaic-stack_postgres-data:/data \
-v $(pwd):/backup \
alpine tar czf /backup/postgres-backup.tar.gz /data
```
## Next Steps
1. **Configure Authentication** — [Authentik Setup](../3-configuration/2-authentik.md)
2. **Monitor Logs** — Set up log aggregation for production
3. **Set up Backups** — Automate database backups
4. **Configure SSL** — Add reverse proxy (Traefik/Nginx) for HTTPS

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)

View File

@@ -0,0 +1,23 @@
# Getting Started
Complete guide to getting Mosaic Stack installed and configured.
## Chapters
1. **Quick Start** — Get up and running in 5 minutes
2. **Installation** — Detailed installation instructions for different environments
3. **Configuration** — Environment setup and authentication configuration
## Prerequisites
Before you begin, ensure you have:
- Node.js 20+ and pnpm 9+
- PostgreSQL 17+ (or Docker)
- Basic familiarity with TypeScript and NestJS
## Next Steps
After completing this book, proceed to:
- **Development** — Learn the development workflow
- **Architecture** — Understand the system design
- **API** — Explore the API documentation