Backend:
- Add migrations/075_create_webhooks.sql: webhooks + webhook_failures tables
- Fixes GET /webhooks 500 (relation "webhooks" did not exist)
Frontend:
- Skip toast for 5xx on /webhooks so developer portal shows empty state
instead of 'Une erreur serveur s'est produite' when table is missing
Co-authored-by: Cursor <cursoragent@cursor.com>
- csrf: no log when backend returns HTML (wrong server / not running)
- webhookService: no log for 5xx on list webhooks
- api client: no log for 5xx on /webhooks (main + queued request)
Co-authored-by: Cursor <cursoragent@cursor.com>
- CSRF: hint uses VITE_BACKEND_PORT instead of hardcoded 8080
- Proxy: add /swagger to Vite dev server for Swagger doc.json (fixes YAMLException)
- playerService: validate media URL before load to avoid Invalid URI errors
- usePlayer: log invalid URL/network audio errors at DEBUG level
- SwaggerUI: log HTML-instead-of-JSON parse errors at DEBUG
- webhookService: log 5xx backend errors at DEBUG
- api client: log 5xx /webhooks errors at DEBUG (reduces duplicate noise)
Co-authored-by: Cursor <cursoragent@cursor.com>
- Skip retry for ERR_BAD_RESPONSE / HTML instead of JSON (wrong server)
- Log only first API retry attempt instead of all 3
- CSRF: friendly warn when wrong server, avoid duplicate logs
- App init: skip CSRF warn when wrong server (already shown)
- API client: skip CSRF refresh error log when wrong server
- ReactQuerySync: INFO → DEBUG for enable/disable messages
Co-authored-by: Cursor <cursoragent@cursor.com>
- Detect when API returns HTML (e.g. another app on port 8080): show clear
toast and reject so callers get an error instead of broken state
- Gate verbose API request/response/slow/error logs on VITE_DEBUG so
console is quiet by default in dev; set VITE_DEBUG=true for full logs
- Avoid double toast and HTML dump in logs for wrong-server errors
- .env.example: clarify VITE_DEBUG enables API request/response logging
Co-authored-by: Cursor <cursoragent@cursor.com>
Added response interceptor to handle 403 errors caused by expired or
invalid CSRF tokens. When a mutation fails with 403, the interceptor:
1. Detects if error is CSRF-related (checks error message for csrf/token/forbidden)
2. Refreshes the CSRF token via csrfService.ensureToken()
3. Updates request headers with new token
4. Retries the request once
Features:
- Only retries once per request (via _csrfRetry flag)
- Skips retry for /csrf-token and /auth/* endpoints
- Logs all CSRF refresh attempts for debugging
- Falls through to original error if refresh fails
- Handles both error.error and error.message formats
TypeScript fixes:
- Cast originalRequest to any for _csrfRetry property
- Safely access error data with type checking
Impact: Eliminates 403 errors on POST/PUT/DELETE when CSRF token expires.
Users no longer need to manually refresh page to get new CSRF token.
Fixes: P1.3 from audit AUDIT_TEMP_29_01_2026.md
Added refresh attempt counter with MAX_REFRESH_ATTEMPTS=3 to prevent
infinite refresh loops when token refresh repeatedly fails.
Changes:
- Added refreshAttempts counter and MAX_REFRESH_ATTEMPTS constant
- Check counter before attempting refresh, logout if max reached
- Increment counter on each refresh attempt
- Reset counter to 0 on successful refresh
- Log attempt number in all refresh-related logs
- Show user-friendly error message after max attempts
Behavior:
- After 3 failed refresh attempts, user is logged out automatically
- Prevents infinite 401 → refresh → 401 loops
- Uses logoutLocal() to avoid triggering another API call
- Displays clear error message: "Session expired after multiple attempts"
Impact: Eliminates infinite refresh loops, improves UX on persistent auth failures.
Fixes: P1.4 from audit AUDIT_TEMP_29_01_2026.md
- Ajouter padding-top au contenu principal pour compenser le header fixe
- Ajouter bouton toggle pour plier/déplier le sidebar (desktop et mobile)
- Corriger z-index pour éviter chevauchement header/sidebar
- Corriger routes du menu sidebar pour correspondre aux routes définies
- Améliorer gestion erreurs 500 marketplace (empty state au lieu d'erreur)
- Préserver httpStatus dans erreurs API pour détection correcte
- Added slow request detection with 1 second threshold
- Tracks request timing in request interceptor
- Detects and marks slow requests (> SLOW_REQUEST_THRESHOLD)
- Logs slow requests in dev mode with duration
- Provides utility functions:
- isSlowRequest() - check if request is slow
- getRequestDuration() - get request duration in ms
- Components can use these utilities to show additional loading feedback
- React Query already provides isLoading/isFetching for loading states
Backend changes (Action 5.1.1.1):
- Set access_token cookie in Login, Register, and Refresh handlers
- Cookie uses same configuration as refresh_token (httpOnly, Secure, SameSite)
- Expiry matches AccessTokenTTL (5 minutes)
- Update logout handler to clear access_token cookie
Backend middleware (Action 5.1.1.1):
- Update auth middleware to read access token from cookie first
- Fallback to Authorization header for backward compatibility
- Update OptionalAuth with same cookie-first logic
Frontend changes (Actions 5.1.1.2 & 5.1.1.3):
- Remove localStorage token storage from TokenStorage service
- TokenStorage now returns null for getAccessToken/getRefreshToken (httpOnly cookies not accessible)
- Remove Authorization header logic from API client
- Remove token expiration checks (can't check httpOnly cookies from JS)
- Update AuthContext to remove localStorage usage
- Update tokenRefresh to work without reading tokens from JS
- Simplify refresh logic: periodic refresh every 4 minutes (no expiration checks)
Security improvements:
- Access tokens no longer exposed to XSS attacks (httpOnly cookies)
- Tokens automatically sent with requests via withCredentials: true
- Backend reads tokens from cookies, not Authorization headers
- All users will need to re-login after deployment (breaking change)
Breaking change: All users must re-login after deployment
- Created rate limit store (apps/web/src/stores/rateLimit.ts) to store parsed headers
- Added header parsing in success response interceptor:
- X-RateLimit-Limit: Maximum requests allowed
- X-RateLimit-Remaining: Requests remaining
- X-RateLimit-Reset: Unix timestamp when limit resets
- Added header parsing in error response interceptor:
- Includes Retry-After header for 429 errors
- All rate limit headers parsed from both lowercase and uppercase variants
- Store automatically updated on every API response
- Store includes isLimited flag calculated from remaining/retryAfter
- Uses Zustand with persistence for cross-tab state
- Actions 5.4.1.1 and 5.4.1.6 complete
- Removed direct format handling code (110+ lines)
- Removed validation and recovery logic for direct format responses
- Added safety check to log warning if non-wrapped response received
- Client now only handles wrapped format {success, data} or {success: false, error}
- Graceful degradation: non-wrapped responses still returned with warning
- TypeScript compilation successful, no linter errors
- Action 1.3.2.2 complete - frontend simplified to wrapped format only
- Added cache fallback: uses cached response for GET requests when validation fails
- Added optional retry mechanism (disabled by default, enabled via config)
- Added user notifications for recovery actions (configurable)
- Recovery config: { useCache, retry, notifyUser } on request config
- Prevents infinite retry loops with _validationRetryAttempted flag
- Validates cached responses before using them
- Handles both wrapped and direct format responses
- Graceful degradation: falls back to unvalidated data if recovery fails
- Applied to both validation sections (wrapped and direct formats)
- Action 1.2.2.5 complete - validation errors now handled gracefully
- Created ValidationAlerting class to monitor validation metrics
- Alerts when failure rate exceeds threshold (default 5%)
- Periodic checks every 5 minutes (configurable)
- Cooldown period (15 min) to prevent alert spam
- Minimum validations required (10) before alerting
- Structured alert logging with full metrics context
- Automatically starts in production (can be disabled via env var)
- Alerts sent to backend logging and Sentry
- Action 1.2.2.4 complete - validation alerting now active for monitoring
- Created ValidationMetricsTracker class to track validation metrics
- Tracks total, successful, and failed validations
- Calculates failure rate percentage
- Tracks failures by normalized endpoint patterns
- Records last failure and success timestamps
- Integrated into both validation points (wrapped and direct formats)
- Exported singleton for metrics access and monitoring
- Action 1.2.2.3 complete - validation metrics now tracked for monitoring
- Enhanced validation error logging with production monitoring context
- Added error_type field for easy filtering in monitoring systems
- Added timestamp and schema_provided flag for correlation
- Logs automatically sent to backend endpoint and Sentry in production
- Structured JSON format for easy aggregation and alerting
- Action 1.2.2.2 complete - validation failures now fully logged for production monitoring
- Enhanced response validation logging (wrapped and direct formats)
- Changed validation failures from warn to error level for better visibility
- Added structured error details (path, message, code, received, expected)
- Added response data preview for debugging
- Added success logging in debug mode
- Maintains graceful degradation (continues with unvalidated data) to avoid breaking app
- Action 1.2.2.1 complete - validation now comprehensive for all responses with schemas
- Backend: Add X-API-Deprecated header alongside existing X-API-Version-Deprecated
- Frontend: Show deprecation warning toast when deprecated API version detected
- Warning shown only once per session to avoid spam
- Includes sunset date in warning message if available
- Completed Action 1.2.1.5: Enhanced request validation logic
- Improved error messages with field paths and detailed validation errors
- Added structured logging for validation failures with request context
- Validation infrastructure was already in place, now ensures robust error handling
- All requests with _requestSchema are validated before sending
- FormData requests are skipped (validated separately)
- Type safety verified, no regressions
- Completed Action 1.4.1.1: Added X-API-Version header to all requests
- Completed Action 1.4.1.4: Added API_VERSION to env config (defaults to 'v1')
- Header added in request interceptor before other headers
- Version configurable via VITE_API_VERSION environment variable
Frontend fixes:
- Stop retrying 429 rate limit errors to prevent infinite loops
- Show user-friendly error message for rate limit with retry-after duration
- Remove 429 from retryable status codes
- Clean up rate limit error handling logic
Backend fixes:
- Fix Swagger /docs route to use same handler as /swagger/*any
- Remove redirect that was causing 404 errors
- Created comprehensive Zod schemas (apiRequestSchemas.ts) for:
* LoginRequest, RegisterRequest, CreateUserRequest
* UpdateUserRequest, UpdateProfileRequest
* SendMessageRequest, UpdateMessageRequest
* CreateConversationRequest, UpdateConversationRequest
* UploadTrackRequest, UpdateTrackRequest
* PaginationParams and list/search request types
- Added validation utilities:
* validateApiRequest: Validate requests before sending
* safeValidateApiRequest: Safe validation with error handling
* validateApiRequestWithError: Validation with custom error handler
- Integrated validation into API client request interceptor
- Enhanced validatedApiClient with request validation support
- Automatic validation prevents invalid requests from being sent
- Comprehensive test suite (19 tests, all passing)
- Ensures runtime type safety for all API requests
- Created comprehensive Zod schemas (apiSchemas.ts) for:
* User, Track, Playlist, Conversation, Message
* Session, AuditLog, Notification
* PaginationData, ApiError, ApiResponse
- Added validation utilities:
* validateApiResponse: Validate and normalize responses
* safeValidateApiResponse: Safe validation with error handling
* validateApiResponseArray: Validate arrays of items
* validatePaginatedResponse: Validate paginated responses
- Integrated validation into API client interceptor
- Created validatedApiClient for type-safe API calls
- Automatic ID normalization during validation
- Comprehensive test suite (13 tests, all passing)
- Ensures runtime type safety for all API responses