# Changelog ## [Unreleased] - Branch: feature/security ### πŸ” Session-Based Admin Authentication & Multi-Admin Support (November 23, 2025) #### Backend - βœ… **Server-Side Sessions + CSRF**: Replaced Bearer-token auth with HttpOnly session cookies backed by SQLite, added `requireAdminAuth` + `requireCsrf` middlewares, and exposed `GET /auth/csrf-token` for clients. - βœ… **New Auth Lifecycle**: Added `GET /auth/setup/status`, `POST /auth/setup/initial-admin`, `POST /auth/login`, `POST /auth/logout`, `POST /auth/change-password`, and `POST /api/admin/users` to support onboarding, login, rotation, and creating additional admins. - βœ… **Admin Directory**: Introduced `admin_users` table, repository, and `AdminAuthService` (hash/verify, forced password change flag, audit-friendly responses) plus Jest coverage for the new flows. - βœ… **OpenAPI & Swagger Stability**: Regenerate spec on dev start only, ignore `docs/openapi.json` in nodemon watches, and expose Swagger UI reliably at `http://localhost:5001/api/docs/`. #### Frontend - βœ… **Admin Session Context**: New `AdminSessionProvider` manages setup/login state, CSRF persistence, and guards moderation routes via `AdminSessionGate`. - βœ… **Force Password Change UX**: Added `ForcePasswordChangeForm`, change-password API helper, and conditional gate that blocks moderation access until the first login password is rotated. - βœ… **Management UI Updates**: Moderation/management pages now assume cookie-based auth, automatically attach CSRF headers, and gracefully handle session expiry. #### Tooling & Scripts - βœ… **API-Driven CLI**: Replaced the legacy Node-only helper with `scripts/create_admin_user.sh`, which can bootstrap the first admin or log in via API to add additional admins from any Linux machine. - βœ… **Docker & Docs Alignment**: Updated dev/prod compose files, Nginx configs, and `README*`/`AUTHENTICATION.md`/`frontend/MIGRATION-GUIDE.md` to describe the new security model and CLI workflow. - βœ… **Feature Documentation**: Added `FeatureRequests/FEATURE_PLAN-security.md` + `FEATURE_TESTPLAN-security.md` outlining design, validation steps, and residual follow-ups. --- ## [Unreleased] - Branch: feature/SocialMedia ### πŸ§ͺ Comprehensive Test Suite & Admin API Security (November 16, 2025) #### Testing Infrastructure - βœ… **Jest + Supertest Framework**: 45 automated tests covering all API endpoints - Unit tests: 5 tests for authentication middleware (100% coverage) - Integration tests: 40 tests for API endpoints - Test success rate: 100% (45/45 passing) - Execution time: ~10 seconds for full suite - βœ… **Test Organization**: - `tests/unit/` - Unit tests (auth.test.js) - `tests/api/` - Integration tests (admin, consent, migration, upload) - `tests/setup.js` - Global configuration with singleton server pattern - `tests/testServer.js` - Test server helper utilities - βœ… **Test Environment**: - In-memory SQLite database (`:memory:`) for isolation - Temporary upload directories (`/tmp/test-image-uploader/`) - Singleton server pattern for fast test execution - Automatic cleanup after test runs - `NODE_ENV=test` environment detection - βœ… **Code Coverage**: - Statements: 26% (above 20% threshold) - Branches: 15% - Functions: 16% - Lines: 26% #### Admin API Authentication - βœ… **Bearer Token Security**: Protected all admin and dangerous system endpoints - `requireAdminAuth` middleware for Bearer token validation - Environment variable: `ADMIN_API_KEY` for token configuration - Protected routes: All `/api/admin/*`, `/api/system/migration/migrate`, `/api/system/migration/rollback` - HTTP responses: 403 for invalid/missing tokens, 500 if ADMIN_API_KEY not configured - βœ… **Authentication Documentation**: - Complete setup guide in `AUTHENTICATION.md` - Example token generation commands (openssl, Node.js) - curl and Postman usage examples - Security best practices and production checklist #### API Route Documentation - βœ… **Single Source of Truth**: `backend/src/routes/routeMappings.js` - Centralized route configuration for server and OpenAPI generation - Comprehensive API overview in `backend/src/routes/README.md` - Critical Express routing order documented and enforced - βœ… **Route Order Fix**: Fixed Express route matching bug - Problem: Generic routes (`/groups/:groupId`) matched before specific routes (`/groups/by-consent`) - Solution: Mount consent router before admin router on `/api/admin` prefix - Documentation: Added comments explaining why order matters - βœ… **OpenAPI Auto-Generation**: - Automatic spec generation on backend start (dev mode) - Swagger UI available at `/api/docs/` in development - Skip generation in test and production modes #### Bug Fixes - πŸ› Fixed: SQLite connection callback not properly awaited (caused test hangs) - Wrapped `new sqlite3.Database()` in Promise for proper async/await - πŸ› Fixed: Upload endpoint file validation checking `req.files.file` before `req.files` existence - Added `!req.files` check before accessing `.file` property - πŸ› Fixed: Test uploads failing with EACCES permission denied - Use `/tmp/` directory in test mode instead of `data/images/` - Dynamic path handling with `path.isAbsolute()` check - πŸ› Fixed: Express route order causing consent endpoints to return 404 - Reordered routers: consent before admin in routeMappings.js #### Frontend Impact **⚠️ Action Required**: Frontend needs updates for new authentication system 1. **Admin API Calls**: Add Bearer token header ```javascript headers: { 'Authorization': `Bearer ${ADMIN_API_KEY}` } ``` 2. **Route Verification**: Check all API paths against `routeMappings.js` - Consent routes: `/api/admin/groups/by-consent`, `/api/admin/consents/export` - Migration routes: `/api/system/migration/*` (not `/api/migration/*`) 3. **Error Handling**: Handle 403 responses for missing/invalid authentication 4. **Environment Configuration**: Add `REACT_APP_ADMIN_API_KEY` to frontend `.env` #### Technical Details - **Backend Changes**: - New files: `middlewares/auth.js`, `tests/` directory structure - Modified files: All admin routes now protected, upload.js validation improved - Database: Promisified SQLite connection in DatabaseManager.js - Constants: Test-mode path handling in constants.js - **Configuration Files**: - `jest.config.js`: Test configuration with coverage thresholds - `.env.example`: Added ADMIN_API_KEY documentation - `package.json`: Added Jest and Supertest dependencies --- ### 🎨 Modular UI Architecture (November 15, 2025) #### Features - βœ… **Reusable Component System**: Created modular components for all pages - `ConsentManager.js` (263 lines): Workshop + Social Media consents with edit/upload modes - `GroupMetadataEditor.js` (146 lines): Metadata editing with edit/upload/moderate modes - `ImageDescriptionManager.js` (175 lines): Batch image descriptions with manage/moderate modes - `DeleteGroupButton.js` (102 lines): Standalone group deletion component - βœ… **Multi-Mode Support**: Components adapt behavior based on context - `mode="upload"`: External state, no save buttons (MultiUploadPage) - `mode="edit"`: Management API endpoints (ManagementPortalPage) - `mode="moderate"`: Admin API endpoints (ModerationGroupImagesPage) - βœ… **Code Reduction**: Massive reduction in code duplication - ManagementPortalPage: 1000β†’400 lines (-60%) - ModerationGroupImagesPage: 281β†’107 lines (-62%) - MultiUploadPage: Refactored to use modular components - Net result: +288 lines added, -515 lines removed = **-227 lines total** #### UI Consistency - 🎨 **Design System**: Established consistent patterns across all pages - Paper boxes with headings inside (not outside) - HTML `