Commit graph

65 commits

Author SHA1 Message Date
senke
0f25d3c551 fix(webhooks): add DB migration and avoid 500 toast on developer portal
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>
2026-02-10 21:11:32 +01:00
senke
ae4e184fad fix(web): silence console for expected failures (CSRF, webhooks 5xx)
- 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>
2026-02-10 19:51:20 +01:00
senke
d744715f38 fix(web): rename duplicate status variable in api client error handler
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-10 19:38:54 +01:00
senke
8f3b562edb fix(web): reduce developer portal console errors
- 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>
2026-02-10 19:38:13 +01:00
senke
f979c6fa8f fix(web): reduce console noise when backend unavailable
- 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>
2026-02-10 19:29:10 +01:00
senke
a7209770bf fix(web): detect wrong server (HTML instead of JSON) and reduce console noise
- 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>
2026-02-10 13:52:23 +01:00
senke
b1ed46b142 small fixes : cors + login loop 2026-02-07 20:36:48 +01:00
senke
75f61c05b2 fix(csrf): add retry mechanism for 403 CSRF errors
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
2026-01-29 23:18:08 +01:00
senke
2edf37557d fix(auth): limit refresh token attempts to prevent infinite loops
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
2026-01-29 23:16:37 +01:00
senke
34241ae0bb fix: Corriger layout, sidebar et gestion erreurs marketplace
- 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
2026-01-18 12:30:56 +01:00
senke
dbb9fe58ff edge-cases: implement Edge 2.1 - handle partial network failures
- Created NetworkFailureTracker to track success/failure patterns
- Detects partial failures: HTTP 206, timeout after partial transfer, intermittent connectivity
- Detects complete failures: connection refused, network unreachable, all requests fail
- Enhanced error messages to distinguish partial vs complete failures
- Partial failures: show intermittent connectivity message
- Complete failures: show no connection message
- Retry logic: partial failures more retryable (if idempotent)
- Logs partial/complete failures for monitoring
- Tracks request patterns in 30-second window (last 10 requests)
- Improves user experience with clearer error messages
2026-01-16 13:08:14 +01:00
senke
e187fff64a edge-cases: implement Edge 2.3 - handle slow network connections
- 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
2026-01-16 12:51:14 +01:00
senke
94136141d6 edge-cases: implement Edge 2.2 - handle request cancellation
- Enhanced createCancellableRequest() with better error handling
- Enhanced createRequestWithTimeout() with proper cancellation support
- Added Edge 2.2 documentation comments
- Cancelled requests are handled gracefully:
  - Don't trigger retries
  - Don't show error toasts
  - Properly rejected with cancellation errors
- AbortController signals fully supported
- Helper functions prevent aborting already-aborted signals
2026-01-16 12:49:40 +01:00
senke
d74549bcef cleanup: remove unused imports (Cleanup 15 - batch 1)
- ESLint --fix automatically removed unused imports:
  - services/api/client.ts: Removed unused import
  - utils/formValidation.ts: Removed unused import
  - e2e/global-setup.ts: Fixed unused imports
- Cleanup 15: In progress - automated fixes applied
2026-01-16 12:19:06 +01:00
senke
d9b6510802 security: migrate access token to httpOnly cookie (Actions 5.1.1.1-5.1.1.3)
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
2026-01-16 01:03:23 +01:00
senke
ae603e77a0 security: parse rate limit headers and create rate limit store
- 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
2026-01-15 19:54:49 +01:00
senke
f67d7044c4 api-contracts: remove dual-format handling from frontend
- 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
2026-01-15 17:33:28 +01:00
senke
40cae3532d api-contracts: add validation error recovery mechanism
- 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
2026-01-15 17:25:44 +01:00
senke
d4e9cd7175 api-contracts: add validation error alerting for high failure rates
- 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
2026-01-15 17:23:01 +01:00
senke
41bbcff116 api-contracts: add validation error metrics tracking
- 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
2026-01-15 17:21:41 +01:00
senke
94e369797d api-contracts: add production error logging for validation failures
- 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
2026-01-15 17:19:17 +01:00
senke
efa2a90a50 api-contracts: enhance response validation for all responses with schemas
- 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
2026-01-15 17:18:02 +01:00
senke
64f62635a5 api-versioning: add X-API-Deprecated header and frontend deprecation warning
- 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
2026-01-15 16:56:21 +01:00
senke
76d95ecfb4 incus deployement fully implemented, Makefile updated and make fmt ran 2026-01-13 19:47:57 +01:00
senke
9f5b5dc415 error-propagation: redirect to login on auth errors 2026-01-11 17:29:55 +01:00
senke
6c848eeaf4 error-propagation: show offline indicator on network errors 2026-01-11 17:16:49 +01:00
senke
df0fff3e10 api-contracts: enhance request validation in API client
- 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
2026-01-11 16:39:51 +01:00
senke
75498c5c65 api-contracts: add API version header and config
- 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
2026-01-11 16:33:18 +01:00
senke
f74b020d4b api-contracts: install openapi-generator-cli and create type generation script
- Completed Action 1.1.2.1: Installed @openapitools/openapi-generator-cli
- Completed Action 1.1.2.2: Created generate-types.sh script
- Added swagger annotations to cmd/modern-server/main.go
- Regenerated swagger.yaml with proper info section
- Successfully generated TypeScript types to src/types/generated/

The script generates types from veza-backend-api/openapi.yaml using
typescript-axios generator and creates barrel exports.
2026-01-11 16:30:43 +01:00
senke
cc2ebae4dc feat: Visual masterpiece - true light mode & premium UI
🎨 **True Light/Dark Mode**
- Implemented proper light mode with inverted color scheme
- Smooth theme transitions (0.3s ease)
- Light mode colors: white backgrounds, dark text, vibrant accents
- System theme detection with proper class application

🌈 **Enhanced Theme System**
- 4 color themes work in both light and dark modes
- Cyber (cyan/magenta), Ocean (blue/teal), Forest (green/lime), Sunset (orange/purple)
- Theme-specific glassmorphism effects
- Proper contrast in light mode

 **Premium Animations**
- Float, glow-pulse, slide-in, scale-in, rotate-in animations
- Smooth page transitions
- Hover effects with depth (lift, glow, scale)
- Micro-interactions on all interactive elements

🎯 **Visual Polish**
- Enhanced glassmorphism for light/dark modes
- Custom scrollbar with theme colors
- Beautiful text selection
- Focus indicators for accessibility
- Premium utility classes

🔧 **Technical Improvements**
- Updated UIStore to properly apply light/dark classes
- Added data-theme attribute for CSS targeting
- Smooth scroll behavior
- Optimized transitions

The app is now a visual masterpiece with perfect light/dark mode support!
2026-01-11 02:32:21 +01:00
senke
8efbb97e6f stabilisation commit A 2026-01-07 19:39:21 +01:00
senke
99d5f1b61e chore: resolve property mismatches and type conflicts for snake_case alignment 2026-01-07 11:15:48 +01:00
senke
4315e3008d chore: remove production logs in services 2026-01-07 10:33:52 +01:00
senke
9e16672953 [T0-006] test(backend): Amélioration couverture tests Go - Scripts et tests RBAC
- Scripts créés pour exécuter tests par groupes/packages (évite crashes RAM)
- Tests complets pour handlers RBAC (16 tests, tous passent)
- Interface RBACServiceInterface créée pour permettre mock dans tests
- Couverture actuelle: 29.8% (objectif: 80%)

Files:
- veza-backend-api/scripts/test_coverage_by_groups.sh (créé)
- veza-backend-api/scripts/test_coverage_one_by_one.sh (créé)
- veza-backend-api/internal/api/handlers/rbac_handlers.go (modifié)
- veza-backend-api/internal/api/handlers/rbac_handlers_test.go (créé)
- VEZA_ROADMAP.json (mis à jour)

Hours: 16 estimated, 4 actual (travail en cours)
2026-01-04 01:44:21 +01:00
senke
5bdb224970 [T0-003] fix(frontend): Corriger erreurs TypeScript/React
- Variables non utilisées préfixées avec _
- Badge variants corrigés (outline -> default/secondary)
- Types ApiError corrigés (rate_limit supprimé)
- Logger errors corrigés (LogContext au lieu de Error)
- Types PaginatedResponse corrigés (items au lieu de data)
- Types génériques complexes corrigés (stateCleanup, undoRedo)
- Fichiers .example.ts exclus du typecheck
- Status undefined vérifié dans client.ts

Résultats:
- npm run build  (réussit)
- npm run typecheck  (0 erreurs)
- npm run lint ⚠️ (1521 erreurs restantes - style/variables non utilisées)

Files: 35 fichiers modifiés
Hours: 6 estimated, 6 actual
2026-01-04 01:44:20 +01:00
senke
5068305513 [FIX] PROD-007: Corriger erreurs TypeScript critiques - imports et exports manquants 2026-01-04 01:44:18 +01:00
senke
c5910c98c5 [LOGGING] Fix #22: Amélioration extraction request_id depuis réponses API d'erreur - Corrélation complète frontend/backend 2026-01-04 01:44:16 +01:00
senke
9cd76a512f [LOGGING] Fix #10: Erreurs silencieuses - Ajout de logs avec contexte pour toutes les erreurs dans core/auth et core/track 2026-01-04 01:44:15 +01:00
senke
9b33a184fe [FIX] Add cooldown for proactive token refresh to prevent rate limiting
- Add 5-second cooldown between proactive token refreshes
- Prevents multiple refresh requests when multiple API calls happen simultaneously
- Reduces rate limit errors from excessive refresh requests
2026-01-04 01:44:13 +01:00
senke
3f30ccec42 [FIX] Fix rate limit retry loop and Swagger /docs route
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
2026-01-04 01:44:13 +01:00
senke
c171d66b0c [INT-AUTH-004] Add token expiration pre-check 2025-12-26 09:15:13 +01:00
senke
25c38d10b7 [INT-AUTH-003] Verify refresh token flow handles edge cases 2025-12-26 09:13:36 +01:00
senke
55f357803a [INT-API-005] Add retry logic for 429 rate limit responses 2025-12-26 09:10:26 +01:00
senke
8d35484e14 [INT-API-004] Add request timeout configuration per endpoint type 2025-12-25 22:42:56 +01:00
senke
4c98715877 [INT-API-002] Verify response unwrapping in interceptor 2025-12-25 22:40:59 +01:00
senke
0441c2adf6 [INT-AUTH-001] Ensure CSRF protection active in production 2025-12-25 22:28:46 +01:00
senke
1311c095e3 [FE-TYPE-003] fe-type: Add Zod schemas for all API requests
- 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
2025-12-25 14:36:32 +01:00
senke
3b4b36bd72 [FE-TYPE-002] fe-type: Add Zod schemas for all API responses
- 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
2025-12-25 14:30:55 +01:00
senke
e43a20b122 [FE-STATE-004] fe-state: Add state invalidation 2025-12-25 13:45:49 +01:00
senke
c3d1d53787 [FE-API-017] fe-api: Add request caching 2025-12-25 13:29:43 +01:00