- 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
- Remove obsolete error logging in api/auth.ts that expected tokens in localStorage
- Fix tokenRefresh.ts periodic refresh to not check tokens (httpOnly cookies not accessible)
- Mark Actions 5.1.1.6-5.1.1.9 as complete in TODO list
Actions 5.1.1.7-5.1.1.9 were already completed in previous actions:
- 5.1.1.7: TokenStorage already returns null (httpOnly cookies not readable)
- 5.1.1.8: tokenRefresh already works with cookies
- 5.1.1.9: All token access goes through TokenStorage
No localStorage.getItem/setItem calls for tokens remain (only removeItem for cleanup)
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
- Updated apps/web/src/services/api/index.ts to export all API services
- Exports apiClient and utilities from './client'
- Exports authApi and types from './auth'
- Exports tracksApi and types from './tracks'
- Exports usersApi and types from './users'
- Exports playlistsApi and types from './playlists'
- Removed duplicate apiClient export from './auth'
- Added documentation comments for each service section
- All services properly exported and accessible via barrel export
- No TypeScript errors
- Action 6.1.1.9 complete
- Replaced imports in UserProfilePage.tsx (listPlaylists → playlistsApi.list)
- Replaced imports in PlaylistDetailPage.tsx (getCollaborators → playlistsApi.getCollaborators)
- Replaced imports in CreatePlaylistDialog.tsx (createPlaylist → playlistsApi.create)
- Replaced imports in PlaylistList.tsx (searchPlaylists → playlistsApi.search)
- Replaced imports in CollaboratorManagement.tsx (getCollaborators → playlistsApi.getCollaborators)
- Replaced imports in PlaylistSearch.tsx (searchPlaylists → playlistsApi.search)
- Replaced imports in unifiedSearchService.ts (searchPlaylists → playlistsApi.search)
- Replaced imports in GlobalSearchBar.tsx (searchPlaylists → playlistsApi.search)
- Fixed type imports in services/api/playlists.ts (types from types.ts, not playlistService.ts)
- All function calls updated to use playlistsApi methods
- Test files and hooks still use direct imports (acceptable - tests can use implementation details, hooks will be updated in Action 6.1.1.10)
- No TypeScript errors related to playlistsApi
- Action 6.1.1.7 complete
- Created apps/web/src/services/api/tracks.ts with tracksApi object
- Exports: list, get, create, update, delete, getStats, getHistory, download, like, unlike, getLikes, createShare
- Includes chunked upload methods: initiateChunkedUpload, uploadChunk, completeChunkedUpload
- Includes batch operations: batchDelete, batchUpdate
- Wraps existing track API functions from features/tracks/api/trackApi.ts
- Includes getTrack from features/tracks/services/trackService.ts for single track retrieval
- Re-exports all related types for convenience
- Added to services/api/index.ts for barrel export
- No TypeScript errors
- Follows existing service layer pattern (similar to auth.ts)
- Action 6.1.1.1 complete
- 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
- Added comprehensive tests for wrapped format handling
- Test wrapped format with success: true and data unwrapping
- Test wrapped format with success: false and error handling
- Test wrapped format with null data
- Test safety check for non-wrapped responses (warning log)
- Test non-object response data handling
- Test verification that no direct format handling remains
- All 30 tests pass successfully
- Tests verify wrapped format only, no direct format handling
- Action 1.3.2.3 complete - response format consistency verified
- 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