Skip to content

Latest commit

 

History

History
763 lines (534 loc) · 24.6 KB

File metadata and controls

763 lines (534 loc) · 24.6 KB

Caddyshack Task List

Check off tasks as completed. Each task should result in working, testable code.


Phase 0: Project Setup

Task 0.1: Initialize Go Module and Project Structure

  • Create go.mod with module github.com/djedi/caddyshack
  • Create directory structure: cmd/caddyshack/, internal/, templates/, static/
  • Create minimal cmd/caddyshack/main.go that starts an HTTP server on port 8080
  • Verify with go run ./cmd/caddyshack - should respond to requests

Task 0.2: Open Source Files

  • Create LICENSE file (MIT)
  • Create README.md with project description, features, and installation instructions
  • Create .gitignore for Go projects (binaries, .env, *.db, node_modules)

Task 0.3: Docker Setup

  • Create Dockerfile (multi-stage build: Go build + minimal runtime)
  • Create docker-compose.dev.yml for local development (caddyshack + caddy container)
  • Add Makefile with common commands (build, run, docker-build, docker-up)

Task 0.4: Tailwind CSS Setup

  • Create package.json with tailwindcss as dev dependency
  • Create tailwind.config.js configured for Go templates
  • Create static/css/input.css with Tailwind directives
  • Generate static/css/output.css
  • Add npm scripts for watch and build

Phase 1: Basic UI Shell

Task 1.1: Base Template Layout

  • Create templates/layouts/base.html with:
    • HTML5 boilerplate
    • Tailwind CSS link
    • HTMX script (CDN)
    • Alpine.js script (CDN)
    • Sidebar navigation placeholder
    • Main content area with {{ block "content" . }}{{ end }}
  • Create internal/templates/templates.go to load and render templates
  • Update main.go to serve a test page using the base layout

Task 1.2: Static File Serving

  • Add route to serve /static/ files from static/ directory
  • Embed static files in binary using embed.FS for production

Task 1.3: Dashboard Page

  • Create templates/pages/dashboard.html extending base layout
  • Create internal/handlers/dashboard.go with handler
  • Display placeholder cards for: "Sites", "Snippets", "Status"
  • Style with Tailwind (clean, minimal admin UI)

Phase 2: Configuration Management

Task 2.1: Environment Configuration

  • Create internal/config/config.go
  • Load config from environment variables (see CLAUDE.md for list)
  • Provide sensible defaults for local development
  • Pass config to handlers via dependency injection

Task 2.2: SQLite Database Setup

  • Add modernc.org/sqlite dependency (pure Go SQLite)
  • Create internal/store/store.go with database initialization
  • Create schema for config_history table (id, timestamp, content, comment)
  • Add migration system (simple version table + SQL files or embedded strings)

Phase 3: Caddyfile Parsing

Task 3.1: Basic Caddyfile Reader

  • Create internal/caddy/reader.go
  • Function to read Caddyfile from configured path
  • Return raw content as string
  • Handle file not found gracefully

Task 3.2: Site Block Parser

  • Create internal/caddy/parser.go
  • Define Site struct: Domain, Directives []Directive, Imports []string
  • Parse site blocks (domain { ... }) from Caddyfile
  • Extract domain name and raw content of each site
  • Write unit tests with example Caddyfile from prompt.md

Task 3.3: Snippet Parser

  • Define Snippet struct: Name, Content
  • Parse snippet definitions (name) { ... }
  • Store snippets separately from sites
  • Write unit tests

Task 3.4: Global Options Parser

  • Define GlobalOptions struct: Email, LogConfig, etc.
  • Parse the global options block { ... } at start of file
  • Write unit tests

Phase 4: Sites List UI

Task 4.1: Sites Index Page

  • Create templates/pages/sites.html
  • Create internal/handlers/sites.go with List handler
  • Display all parsed sites as cards showing domain and basic info
  • Add navigation link to sidebar

Task 4.2: Site Card Partial

  • Create templates/partials/site-card.html
  • Display: domain, reverse proxy target (if applicable), imported snippets
  • Add Edit and Delete buttons (non-functional for now)
  • Style with Tailwind

Task 4.3: Site Detail View

  • Create templates/pages/site-detail.html
  • Show full configuration for a single site
  • Display raw Caddyfile block with syntax highlighting (optional)
  • Link from site card to detail view

Phase 5: Caddyfile Generation

Task 5.1: Site Block Writer

  • Create internal/caddy/writer.go
  • Function to generate Caddyfile site block from Site struct
  • Maintain proper indentation and formatting
  • Write unit tests (parse -> write -> compare)

Task 5.2: Full Caddyfile Writer

  • Function to generate complete Caddyfile from all components
  • Order: global options, snippets, sites
  • Preserve comments where possible

Task 5.3: Caddyfile Validator

  • Create internal/caddy/validator.go
  • Shell out to caddy validate --config /path or use Admin API
  • Return validation errors in structured format
  • Write integration test

Phase 6: Site CRUD Operations

Task 6.1: Add Site Form

  • Create templates/partials/site-form.html
  • Form fields: domain, type (reverse_proxy/static/redirect), target
  • Use Alpine.js to show/hide fields based on type selection
  • HTMX form submission to POST /sites

Task 6.2: Create Site Handler

  • Add POST /sites handler
  • Validate input
  • Add site to parsed config
  • Regenerate and validate Caddyfile
  • Save to file
  • Return updated site list (HTMX swap)

Task 6.3: Edit Site

  • Create edit form (reuse site-form partial)
  • GET /sites/{domain}/edit returns form with current values
  • PUT /sites/{domain} updates the site
  • Validate and save

Task 6.4: Delete Site

  • Add DELETE /sites/{domain} handler
  • Confirmation modal using Alpine.js
  • Remove site from config
  • Regenerate Caddyfile
  • Return updated site list

Phase 7: Caddy Integration

Task 7.1: Caddy Admin API Client

  • Create internal/caddy/admin.go
  • Function to reload config: POST to /load endpoint
  • Function to get current config: GET /config/
  • Function to check Caddy status
  • Handle connection errors gracefully

Task 7.2: Reload After Changes

  • After successful Caddyfile save, trigger reload
  • Display reload status in UI (success/failure)
  • Show error details if reload fails

Task 7.3: Status Dashboard Widget

  • Add Caddy status to dashboard
  • Show: running/stopped, uptime, version
  • Auto-refresh with HTMX polling (every 30s)

Phase 8: Config History

Task 8.1: Save Config History

  • Before each Caddyfile change, save current version to SQLite
  • Store: timestamp, full content, change description
  • Limit history to last 50 versions (configurable)

Task 8.2: History View

  • Create templates/pages/history.html
  • List recent config changes with timestamps
  • Show diff between versions (simple text diff)

Task 8.3: Rollback Feature

  • Add "Restore" button to history entries
  • Restore selected version as current Caddyfile
  • Validate before applying
  • Reload Caddy

Phase 9: Authentication

Task 9.1: Basic Auth Middleware

  • Create internal/middleware/auth.go
  • Implement HTTP Basic Auth
  • Read credentials from config
  • Apply to all routes except /health

Task 9.2: Login Page

  • Create login form as alternative to browser basic auth prompt
  • Session-based auth with secure cookie
  • Logout functionality

Phase 10: Polish and Production

Task 10.1: Error Handling

  • Create error page template
  • Consistent error responses for HTMX (swap error message)
  • Log errors appropriately

Task 10.2: Loading States

  • Add HTMX loading indicators
  • Disable buttons during form submission
  • Skeleton loaders for async content

Task 10.3: Production Build

  • Embed templates and static files in binary
  • Optimize Tailwind for production (purge unused)
  • Add health check endpoint
  • Document deployment process in README

Task 10.4: Testing

  • Unit tests for parser and writer (80%+ coverage)
  • Integration tests for handlers
  • End-to-end test with real Caddy container

Phase 11: Snippet Management UI (V2)

Task 11.1: Snippets Index Page

  • Create templates/pages/snippets.html
  • Create internal/handlers/snippets.go with List handler
  • Display all parsed snippets as cards showing name and preview
  • Add navigation link to sidebar
  • Wire up routes in main.go

Task 11.2: Snippet Card Partial

  • Create templates/partials/snippet-card.html
  • Display: name, content preview (first few lines), usage count
  • Add Edit and Delete buttons
  • Style with Tailwind consistent with site cards

Task 11.3: Snippet Detail View

  • Create templates/pages/snippet-detail.html
  • Show full snippet content with syntax highlighting
  • List sites that use this snippet (via import)
  • Link from snippet card to detail view

Task 11.4: Add Snippet Form

  • Create templates/partials/snippet-form.html
  • Form fields: name (identifier), content (textarea)
  • Syntax validation on submit
  • HTMX form submission to POST /snippets

Task 11.5: Snippet CRUD Handlers

  • Add POST /snippets handler (create)
  • Add GET /snippets/{name}/edit handler (edit form)
  • Add PUT /snippets/{name} handler (update)
  • Add DELETE /snippets/{name} handler
  • Validate snippet syntax before saving
  • Regenerate Caddyfile and reload Caddy

Task 11.6: Snippet Tests

  • Unit tests for snippet CRUD handlers
  • Integration tests for snippet routes
  • Test snippet creation, editing, deletion flow

Phase 12: Import/Export Configuration

Task 12.1: Export Caddyfile

  • Create internal/handlers/export.go with export handler
  • Add GET /export route that downloads current Caddyfile as file
  • Add GET /export/json route that returns config as JSON (using Caddy Admin API)
  • Create export button in dashboard or settings area
  • Include timestamp in filename (e.g., caddyfile-2024-01-15.txt)

Task 12.2: Import Caddyfile UI

  • Create templates/pages/import.html with file upload form
  • Create internal/handlers/import.go with import handler
  • Add navigation link to sidebar (under settings or tools section)
  • Support file upload or paste text content
  • Preview parsed config before applying

Task 12.3: Import Validation and Apply

  • Parse uploaded/pasted Caddyfile using existing parser
  • Validate syntax using caddy validate or Admin API
  • Show validation errors with line numbers
  • Show preview of sites and snippets that will be imported
  • Create "Apply Import" action that saves and reloads

Task 12.4: Backup All Configuration

  • Create handler to export full backup (Caddyfile + history)
  • Package as downloadable JSON or ZIP file
  • Include: current Caddyfile, config history, timestamps
  • Add backup button to history page or dashboard

Phase 13: Certificate Status Display

Task 13.1: Caddy PKI API Client

  • Extend internal/caddy/admin.go with certificate methods
  • GET /pki/ca/local for CA info (if using internal CA)
  • Parse certificate info from Caddy's config JSON
  • Handle cases where ACME/certificates aren't configured

Task 13.2: Certificate Status Page

  • Create templates/pages/certificates.html
  • Create internal/handlers/certificates.go with handler
  • Display: domain, issuer, expiry date, status (valid/expiring/expired)
  • Add navigation link to sidebar
  • Color code by status (green=valid, yellow=expiring soon, red=expired)

Task 13.3: Certificate Status Widget

  • Add certificate summary to dashboard
  • Show count of valid, expiring, and expired certificates
  • Link to full certificates page
  • Auto-refresh with HTMX polling

Task 13.4: Certificate Expiry Warnings

  • Highlight certificates expiring within 30 days
  • Add warning banner when certificates need attention
  • Show in site detail view if that site's cert is expiring

Phase 14: Global Options Editor

Task 14.1: Global Options Page

  • Create templates/pages/global-options.html
  • Create internal/handlers/global.go with handler
  • Display current global options (email, logging, admin, debug, etc.)
  • Add navigation link to sidebar

Task 14.2: Global Options Edit Form

  • Create form to edit common global options
  • Fields: email, admin address, debug mode, log format
  • Advanced section for raw block editing
  • Validate and save changes

Task 14.3: Log Configuration Editor

  • UI to configure global logging settings
  • Log output path, format (json/console), roll settings
  • Preview generated Caddyfile block
  • Save and reload

Phase 15: Log Viewer (Basic)

Task 15.1: Log File Reader

  • Create internal/handlers/logs.go with log handler
  • Read last N lines from configured Caddy log file
  • Support configurable log path (from config or auto-detect from Caddyfile)
  • Handle log file not found gracefully

Task 15.2: Logs Page

  • Create templates/pages/logs.html
  • Display recent log entries in scrollable view
  • Parse JSON log format for readable display
  • Show: timestamp, level, message, domain (if applicable)
  • Add navigation link to sidebar

Task 15.3: Log Filtering

  • Filter logs by level (error, warn, info)
  • Filter by domain/site
  • Search within log entries
  • HTMX partial refresh for filters

Task 15.4: Log Auto-Refresh

  • Add auto-refresh toggle (poll every 5 seconds)
  • Scroll to bottom on new entries (optional)
  • Pause auto-refresh when user scrolls up
  • Show "new entries" indicator

Phase 16: Docker Container Status

Task 16.1: Docker API Client

  • Create internal/docker/client.go with Docker client
  • Connect to Docker socket (configurable path)
  • Function to list running containers
  • Function to get container status by name or ID
  • Handle Docker not available gracefully (optional feature)

Task 16.2: Container Status Page

  • Create templates/pages/containers.html
  • Create internal/handlers/containers.go with handler
  • Display: container name, status (running/stopped), image, ports
  • Add navigation link to sidebar
  • Color code by status (green=running, red=stopped)

Task 16.3: Link Containers to Sites

  • Parse reverse_proxy targets to identify potential container hosts
  • Match container ports to proxy targets
  • Show container status in site detail view
  • Add indicator on site cards for container health (moved to Task 21.4)

Task 16.4: Container Status Widget

  • Add container summary to dashboard
  • Show count of running, stopped, and unhealthy containers
  • Link to full containers page
  • Auto-refresh with HTMX polling

Task 16.5: Container Actions (Optional)

  • Add start/stop/restart buttons for containers
  • Confirmation modal for container actions
  • Log output for container actions
  • Require admin permissions for container control

Phase 17: Notification System

Task 17.1: Notification Infrastructure

  • Create internal/notifications/notification.go with notification types and interfaces
  • Define Notification struct: Type, Severity, Title, Message, Timestamp, Acknowledged
  • Create notification storage in SQLite (notifications table with type, severity, data, created_at, ack_at)
  • Add notification service for creating, listing, and acknowledging notifications

Task 17.2: Notification UI

  • Create templates/pages/notifications.html for notification center
  • Create internal/handlers/notifications.go with handlers
  • Add notification bell icon to header with unread count badge
  • Create notification dropdown/panel showing recent notifications
  • Add "Mark as read" and "Mark all as read" functionality
  • Add navigation link to full notification history

Task 17.3: Certificate Expiry Notifications

  • Create background job to check certificate expiry daily
  • Generate notification when certificate expires within 30 days (warning)
  • Generate notification when certificate expires within 7 days (critical)
  • Generate notification when certificate has expired (error)
  • Link notification to certificate details page
  • Avoid duplicate notifications for same certificate/threshold

Task 17.4: Email Notification Support

  • Create internal/notifications/email.go with SMTP client
  • Add email configuration to config.go (SMTP host, port, user, password, from address)
  • Create email templates for notifications
  • Add email preferences per notification type (UI setting)
  • Send email for critical notifications (configurable)

Task 17.5: Webhook Notifications

  • Create internal/notifications/webhook.go for webhook delivery
  • Add webhook URL configuration (supports multiple endpoints)
  • POST notification data as JSON to configured webhooks
  • Support webhook headers for authentication
  • Retry failed webhook deliveries with exponential backoff

Phase 18: Domain Management

Task 18.1: Domain Tracking

  • Create domains table in SQLite (domain, registrar, expiry_date, notes, created_at)
  • Create internal/handlers/domains.go with CRUD handlers
  • Create templates/pages/domains.html for domain list
  • Auto-detect domains from Caddyfile sites
  • Allow manual domain entry with registrar and expiry info

Task 18.2: Domain Expiry Notifications

  • Add expiry tracking for registered domains
  • Background job to check domain expiry dates
  • Generate notification when domain expires within 60 days (warning)
  • Generate notification when domain expires within 14 days (critical)
  • Link notification to domain details

Task 18.3: WHOIS Integration (Optional)

  • Create internal/domains/whois.go for WHOIS lookups
  • Lookup domain expiry date automatically
  • Cache WHOIS results to avoid rate limiting
  • Button to refresh WHOIS data manually
  • Parse registrar and nameserver info

Phase 19: Multi-User Support

Task 19.1: User Model and Storage

  • Create users table in SQLite (id, username, email, password_hash, role, created_at, last_login)
  • Create internal/auth/user.go with User model and password hashing (bcrypt)
  • Define roles: admin, editor, viewer
  • Role permissions: admin (all), editor (CRUD sites/snippets), viewer (read-only)
  • Migrate from basic auth to session-based auth

Task 19.2: User Management UI

  • Create templates/pages/users.html for user list (admin only)
  • Create internal/handlers/users.go with CRUD handlers
  • Add user creation form with role selection
  • Add user edit form (change password, role)
  • Add user deletion with confirmation
  • Only admins can manage users

Task 19.3: Role-Based Access Control

  • Create internal/middleware/rbac.go for role checking
  • Protect routes based on required role
  • Hide UI elements based on user role
  • Viewer role: read-only access, no edit/delete buttons
  • Editor role: can edit sites/snippets, cannot manage users or global settings
  • Admin role: full access

Task 19.4: User Profile and Settings

  • Create templates/pages/profile.html for current user settings
  • Allow users to change their own password
  • Notification preferences per user
  • Theme preference (if dark mode is implemented) - skipped, dark mode not yet implemented
  • Session management (list active sessions, logout other sessions)

Task 19.5: Audit Log

  • Create audit_log table (user_id, action, resource_type, resource_id, details, timestamp)
  • Log all configuration changes with user attribution
  • Create templates/pages/audit.html to view audit log (admin only)
  • Filter by user, action type, date range
  • Link audit entries to relevant resources

Phase 20: UI Enhancements

Task 20.1: Dark Mode

  • Add dark mode CSS variants with Tailwind dark: modifier
  • Add theme toggle in header (light/dark/system)
  • Store preference in localStorage or user profile
  • Respect system preference by default

Task 20.2: Dashboard Customization

  • Allow reordering of dashboard widgets
  • Allow hiding/showing widgets
  • Collapsible widget sections
  • Store layout preference per user

Task 20.3: Keyboard Shortcuts

  • Add keyboard shortcuts for common actions
  • ? to show shortcuts help modal
  • n for new site, g s for sites, g d for dashboard
  • Escape to close modals
  • Use Alpine.js for shortcut handling

Task 20.4: Search

  • Add global search in header
  • Search across sites, snippets, logs
  • Quick navigation results (cmd+k style)
  • Recent searches history

Phase 21: API and Security Enhancements

Task 21.1: API Tokens

  • Create api_tokens table (id, user_id, token_hash, name, permissions, created_at, expires_at, last_used)
  • Create internal/auth/token.go with token generation and validation
  • Add API token management UI (create, revoke, list tokens)
  • Create middleware to authenticate API requests via Bearer token
  • Define API scopes/permissions (read, write, admin)

Task 21.2: Rate Limiting

  • Create internal/middleware/ratelimit.go for rate limiting
  • Rate limit login attempts (5 attempts per 15 minutes per IP)
  • Rate limit API requests (configurable per token/user)
  • Add lockout notification when rate limit exceeded
  • Store rate limit data in memory with configurable backend

Task 21.3: Two-Factor Authentication

  • Add TOTP support with pquerna/otp library
  • Create internal/auth/totp.go for TOTP handling
  • Add 2FA setup flow in user profile (QR code generation)
  • Add 2FA verification step in login flow
  • Add backup codes for account recovery
  • Allow admins to disable 2FA for users

Task 21.4: Container Health Indicators on Site Cards

  • Add container health check to site card partial
  • Display small status indicator (dot) on site cards for linked containers
  • Color code: green=running, red=stopped, yellow=unhealthy
  • Tooltip showing container name and status
  • Handle case where Docker integration is disabled

Phase 22: Monitoring and Metrics

Task 22.1: Prometheus Metrics Endpoint

  • Create internal/handlers/metrics.go with Prometheus handler
  • Export Caddy status metrics (uptime, config reloads)
  • Export certificate metrics (valid count, expiring count, expired count)
  • Export container metrics if Docker enabled
  • Add /metrics endpoint (optionally protected)

Task 22.2: Performance Monitoring Dashboard

  • Add request rate and latency charts to dashboard
  • Display error rate trends
  • Show bandwidth usage per site (from Caddy logs)
  • Add time range selector (1h, 24h, 7d, 30d)
  • Store aggregated metrics in SQLite

Task 22.3: Health Checks

  • Create comprehensive /health endpoint with component status
  • Check Caddy connectivity
  • Check database connectivity
  • Check Docker connectivity (if enabled)
  • Return structured JSON with component statuses

Phase 23: Configuration Management

Task 23.1: Git Integration

  • Create internal/git/git.go for git operations
  • Initialize git repo for Caddyfile directory (optional)
  • Auto-commit on Caddyfile changes with meaningful messages
  • View git history in UI
  • Diff between commits

Task 23.2: Scheduled Backups

  • Add backup schedule configuration (daily, weekly)
  • Create internal/backup/scheduler.go for scheduled tasks
  • Store backups in configurable location
  • Auto-cleanup old backups (configurable retention)
  • Add backup status to dashboard

Task 23.3: Configuration Import from Nginx

  • Create internal/caddy/nginx.go for nginx config parsing
  • Parse nginx.conf server blocks
  • Convert to equivalent Caddyfile configuration
  • Preview conversion before applying
  • Handle common nginx directives (proxy_pass, location, rewrite)

Future Ideas (V5+)

Ideas for future development:

  • Traefik configuration import
  • Mobile-responsive improvements
  • Caddy plugin management
  • Multi-server management (manage multiple Caddy instances)
  • Configuration templates/presets
  • API documentation (OpenAPI/Swagger)
  • WebSocket support for real-time log streaming
  • Site analytics integration