Imported from mrflory/contao-manager-api-browser (
AGENTS.md). Install upstream withnpx skills add mrflory/contao-manager-api-browser. Copyright stays with the author.
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Development Commands
npm start- Start production server (TypeScript backend serving React build)npm run dev- Start development server with TypeScript backend and auto-reloadnpm run dev:react- Start Vite development server for React frontendnpm run dev:full- Start both backend and frontend development servers concurrentlynpm run build- Build complete application (backend + frontend)npm run build:server- Build TypeScript backend onlynpm run lint- Run ESLint code quality checksnpm run test- Run Jest test suitenpm run test:watch- Run Jest tests in watch modenpm run test:coverage- Generate test coverage reportsnpm run mock:server- Start TypeScript mock server for testing
Database Commands (Phase 1)
npm run db:generate- Generate Prisma client from schemanpm run db:push- Push schema changes to databasenpm run db:studio- Open Prisma Studio for database managementnpm run db:migrate- Run database migrationsnpm run seed:database- Seed database with test datanpm run migrate:database- Migrate from JSON file to database storage
Architecture Overview
This is a Node.js proxy application that provides a modern web interface for interacting with Contao Manager APIs. The application uses a modular, service-oriented architecture with three main layers:
Server Layer (TypeScript Backend - src/server.ts)
- Express.js TypeScript server with modular service architecture
- Service-oriented design with dedicated services:
ConfigService- Site configuration with pluggable storage backendsAuthService- OAuth token validation and authenticationProxyService- API forwarding to Contao Manager instancesLoggingService- Request/response logging and audit trailsHistoryService- Workflow execution history trackingSnapshotService- System state capture and management
- Comprehensive API endpoints for site management, authentication, and workflow execution
- Middleware architecture with authentication, scope validation, and response logging
Frontend (React Application)
- React v19 single-page application with TypeScript and modular architecture
- Chakra UI v3 for component library and theming
- Service Layer Architecture:
- Centralized API management with
apiCallService - Authentication service for OAuth flows
- Specialized services (Expert, Task, Logs) with proper error handling
- Centralized API management with
- Custom Hooks:
useApiCallfor consistent API state managementuseAuthfor authentication flowsuseModalStatefor dialog managementuseToastNotificationsfor user feedback
- Modular Components:
- Pages: Sites overview, site details, add site
- Display: Loading states, empty states, version badges
- Forms: URL input, scope selector with validation
- Modals: API result display, confirmation dialogs
- Site Details: Dedicated tabs (Info, Expert, Logs, Management)
- Workflow: Timeline-based execution, step management, user confirmations
- Workflow Engine: Timeline-based execution system with:
- Generic workflow engine supporting multiple workflow types
- Timeline item abstraction for reusable workflow steps
- State management with execution history and context
- Event-driven architecture with pausable/resumable execution
- Integration with history service for audit trails
- Routing - React Router v7 for navigation between pages
- OAuth redirect flow - redirects to Contao Manager for token generation
- Token extraction - parses access token from URL fragment after OAuth redirect
- Server-side token storage - tokens stored in
data/config.jsonfile on server - Theme support - Dark/light mode toggle using next-themes integration
Storage Architecture (Pluggable Backends)
The application supports multiple storage backends through a unified abstraction layer:
JSON File Storage (Default - STORAGE_TYPE=json_file)
- Server-side storage in
data/config.json - Token encryption with
TOKEN_MASTER_KEY - Multi-site configuration support
- Automatic backup and migration handling
Database Storage (STORAGE_TYPE=database - Phase 1) ✅ COMPLETED
- PostgreSQL backend with Neon.tech cloud hosting for multi-tenant SaaS deployment
- Prisma ORM with full TypeScript integration for type-safe database operations
- Connection via
DATABASE_URLenvironment variable (Neon.tech connection string) - Multi-tenant support with user isolation and comprehensive relationships
- Backup and migration capabilities with JSON file to PostgreSQL migration tools
- Usage analytics foundation with detailed logging for SaaS metrics
- Hybrid architecture: database for configs, files for logs/history/snapshots
User Authentication (Better Auth)
The application uses Better Auth for user authentication with modern security features:
- Email/Password Authentication - bcrypt password hashing (12 rounds)
- Passkey/WebAuthn Support - Passwordless authentication with hardware keys
- Two-Factor Authentication - TOTP-based 2FA with backup codes
- Session Management - Secure HTTP-only cookies with configurable expiry
- Password Reset - Email-based password recovery flow
Key files:
src/lib/auth.ts- Better Auth server configurationsrc/lib/auth-client.ts- Better Auth React clientsrc/middleware/betterAuthMiddleware.ts- Express session validationsrc/contexts/AuthContext.tsx- React authentication context
Site Authentication (OAuth Token-based)
For connecting to Contao Manager instances:
- User enters Contao Manager URL and selects required permissions (scope)
- Application redirects to Contao Manager OAuth endpoint with parameters:
response_type=tokenscope(read, update, install, admin)client_id(application name)redirect_uri(callback URL with #token fragment)
- User authenticates with Contao Manager (including TOTP if required)
- Contao Manager redirects back with access token in URL fragment
- Frontend extracts token from URL and sends it to server for storage
- Server stores site configuration using selected storage backend
Key Technical Details
- Full TypeScript Stack - Both frontend and backend written in TypeScript with strict type safety
- Service-Oriented Architecture - Modular backend services with clear separation of concerns
- Workflow Engine - Generic timeline-based execution system for complex multi-step operations
- Storage Abstraction Layer - Pluggable storage backends (JSON file, PostgreSQL database)
- JSON File Storage - No database dependency, uses
data/config.jsonfor configuration (default) - PostgreSQL Database - Production-ready multi-tenant backend with Prisma ORM and Neon.tech hosting
- Better Auth - Modern authentication with passkeys, 2FA, and session management
- OAuth Token Authentication - Supports TOTP/2FA through Contao Manager integration (for sites)
- Request/Response Logging - Comprehensive audit trails with structured logging
- History Tracking - Workflow execution history with detailed step information
- Modern React Architecture - React v19 with Chakra UI v3 component system
- Build System - Vite for frontend, separate TypeScript compilation for backend
- Development Tooling - ESLint, Jest testing, multiple TypeScript configurations
Common Issues
- Token errors - "Invalid token" indicates expired/malformed tokens, requires OAuth re-authentication
- Connection timeouts - Target Contao Manager may be slow or unreachable
- TypeScript compilation - Ensure proper imports and type definitions across services
- Workflow execution - Check timeline state and execution history for debugging
- Build issues - Verify TypeScript configurations for backend vs frontend builds
Project Structure
Backend Services (src/services/)
configService.ts- Site configuration with pluggable storage backends (JSON file, PostgreSQL)authService.ts- OAuth token validation and authentication logicproxyService.ts- API forwarding to Contao Manager instancesloggingService.ts- Request/response logging and audit trailshistoryService.ts- Workflow execution history trackingsnapshotService.ts- System state capture and management
Storage Layer (src/storage/)
interfaces.ts- Storage abstraction interfaces and base classesJsonFileStorage.ts- JSON file storage implementation (default)DatabaseStorage.ts- PostgreSQL storage with Prisma ORM (Phase 1)storageFactory.ts- Factory pattern for storage backend selection
Workflow System (src/workflow/)
engine/- Generic timeline-based workflow execution engineitems/- Specific workflow step implementationshooks/- React hooks for workflow state managementui/- Workflow visualization and user interaction components
Frontend Components (src/components/)
ui/- Chakra UI v3 custom components (dialogs, timelines, etc.)workflow/- Workflow-specific UI componentssite-details/- Site management interface componentsmodals/- Dialog and confirmation components
Development Guidelines
- TypeScript First - All new code must be TypeScript with proper typing
- Service Architecture - Use dependency injection and service abstraction
- Storage Patterns - Use storage abstraction for all data persistence operations
- Database Operations - Use Prisma ORM with async/await patterns for database interactions
- Workflow Design - Extend timeline items for new workflow steps
- Component Patterns - Follow Chakra UI v3 composition patterns
- Error Handling - Implement proper error boundaries and user feedback
Database Development (Phase 1)
- Schema Changes - Use Prisma migrations (
npm run db:migrate) for schema updates - Data Seeding - Use
npm run seed:databasefor consistent test data - Database Studio - Use
npm run db:studiofor database inspection and debugging - Migration Strategy - Use
npm run migrate:databasefor JSON file to PostgreSQL migration - Connection Management - Database connections handled automatically by Prisma with connection pooling
Testing Infrastructure
Mock Server (src/test/mockServer/)
TypeScript-based mock server simulating the complete Contao Manager API:
- Command:
npm run mock:server(starts on http://localhost:3001) - Scenarios: JSON-based test scenarios (happy-path, error-scenarios, edge-cases)
- Features: OAuth simulation, realistic timing, web interface for scenario control
Testing Workflow
- Start mock server:
npm run mock:server - Add test site:
http://localhost:3001/contao-manager.phar.php - Use OAuth scope:
adminfor full testing coverage - Test complete workflows end-to-end
- Switch scenarios via API or web interface
Testing Commands
npm test- Run Jest test suitenpm run test:watch- Run tests in watch modenpm run test:coverage- Generate coverage reports
Scenario Management
# Load specific scenario
curl -X POST http://localhost:3001/mock/scenario -H "Content-Type: application/json" \
-d '{"scenario": "error-scenarios.composer-update-failure"}'
# Reset to default
curl -X POST http://localhost:3001/mock/reset