@aifabrix/miso-client 3.9.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +1148 -1052
  2. package/dist/api/encryption.api.d.ts +31 -0
  3. package/dist/api/encryption.api.d.ts.map +1 -0
  4. package/dist/api/encryption.api.js +61 -0
  5. package/dist/api/encryption.api.js.map +1 -0
  6. package/dist/api/index.d.ts +5 -0
  7. package/dist/api/index.d.ts.map +1 -1
  8. package/dist/api/index.js +2 -0
  9. package/dist/api/index.js.map +1 -1
  10. package/dist/api/types/encryption.types.d.ts +47 -0
  11. package/dist/api/types/encryption.types.d.ts.map +1 -0
  12. package/dist/api/types/encryption.types.js +7 -0
  13. package/dist/api/types/encryption.types.js.map +1 -0
  14. package/dist/express/index.d.ts +0 -1
  15. package/dist/express/index.d.ts.map +1 -1
  16. package/dist/express/index.js +1 -4
  17. package/dist/express/index.js.map +1 -1
  18. package/dist/index.d.ts +13 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +17 -4
  21. package/dist/index.js.map +1 -1
  22. package/dist/services/encryption.service.d.ts +59 -0
  23. package/dist/services/encryption.service.d.ts.map +1 -0
  24. package/dist/services/encryption.service.js +83 -0
  25. package/dist/services/encryption.service.js.map +1 -0
  26. package/dist/services/permission.service.d.ts +0 -4
  27. package/dist/services/permission.service.d.ts.map +1 -1
  28. package/dist/services/permission.service.js +2 -23
  29. package/dist/services/permission.service.js.map +1 -1
  30. package/dist/services/role.service.d.ts +0 -4
  31. package/dist/services/role.service.d.ts.map +1 -1
  32. package/dist/services/role.service.js +2 -23
  33. package/dist/services/role.service.js.map +1 -1
  34. package/dist/types/config.types.d.ts +1 -1
  35. package/dist/types/config.types.d.ts.map +1 -1
  36. package/dist/types/config.types.js.map +1 -1
  37. package/dist/utils/config-loader.js +4 -4
  38. package/dist/utils/config-loader.js.map +1 -1
  39. package/dist/utils/data-client-request.d.ts.map +1 -1
  40. package/dist/utils/data-client-request.js +8 -0
  41. package/dist/utils/data-client-request.js.map +1 -1
  42. package/dist/utils/encryption-error.d.ts +24 -0
  43. package/dist/utils/encryption-error.d.ts.map +1 -0
  44. package/dist/utils/encryption-error.js +31 -0
  45. package/dist/utils/encryption-error.js.map +1 -0
  46. package/package.json +84 -84
  47. package/dist/express/encryption.d.ts +0 -29
  48. package/dist/express/encryption.d.ts.map +0 -1
  49. package/dist/express/encryption.js +0 -95
  50. package/dist/express/encryption.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,1052 +1,1148 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file.
4
-
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
-
8
- ## [3.9.0] - 2026-01-14
9
-
10
- ### Added
11
-
12
- - **Enhanced Filter System** - Comprehensive filter parsing, validation, and SQL compilation
13
- - **Dual format parsing**: Support for both colon format (`status:eq:active`) and JSON format (`{"status":{"eq":"active"}}`)
14
- - **Schema-based validation**: Define filterable fields, allowed operators, and value types per resource
15
- - **Type coercion**: Automatic value validation and conversion for string, number, boolean, uuid, timestamp, and enum types
16
- - **SQL compilation**: Generate PostgreSQL-safe parameterized WHERE clauses with `compileFilter()`
17
- - **Human-readable errors**: RFC 7807 compliant structured error responses with error codes (UNKNOWN_FIELD, INVALID_OPERATOR, INVALID_TYPE, etc.)
18
- - New `ilike` operator for case-insensitive pattern matching
19
- - New types: `FilterSchema`, `FilterFieldDefinition`, `FilterError`, `CompiledFilter`
20
- - New utilities: `validateFilter()`, `coerceValue()`, `compileFilter()`, `createFilterSchema()`
21
- - Filter meta-schema for validating custom filter schemas (`src/schemas/filter.schema.json`)
22
-
23
- ### Changed
24
-
25
- - **Code Size Compliance** - Refactored large files to comply with 500-line guideline
26
- - `data-client.ts`: 995 416 lines (extracted to helper modules)
27
- - `data-client-request.ts`: 683 280 lines
28
- - `data-client-auth.ts`: 654 → 290 lines
29
- - `internal-http-client.ts`: 741 → 496 lines
30
- - `auth.service.ts`: 825 → 462 lines
31
- - `index.ts`: 681 → 472 lines
32
- - `logger.service.ts`: 597 → 480 lines
33
-
34
- - **Console Logging Audit** - Cleaned up debug logging
35
- - Removed 10 debug `console.log` statements from `token-utils.ts` that could expose sensitive token data
36
- - All remaining console calls are appropriate error/warning logs or guarded by debug checks
37
-
38
- ### Technical
39
-
40
- - **New filter utilities**: `src/utils/filter-schema.utils.ts` (497 lines), `src/utils/filter-colon.utils.ts` (119 lines)
41
- - **New filter types**: `src/types/filter-schema.types.ts` (148 lines)
42
- - **New helper modules** for DataClient refactoring:
43
- - `data-client-init.ts` - Initialization logic
44
- - `data-client-permissions.ts` - Permission helpers
45
- - `data-client-roles.ts` - Role helpers
46
- - `data-client-response.ts` - Response processing
47
- - `data-client-oauth.ts` - OAuth callback handling
48
- - **New HTTP helpers**: `http-error-handler.ts`, `http-response-validator.ts`
49
- - **New auth helper**: `auth-error-handler.ts` - Centralized auth error formatting
50
- - **New tests**: `filter-colon-format.test.ts` (178 lines), `filter-schema.utils.test.ts` (545 lines)
51
- - **Documentation**: Updated `docs/reference-utilities.md` with filter system examples
52
-
53
- ## [3.8.2] - 2026-01-12
54
-
55
- ### Added
56
-
57
- - **Keycloak Separate Private/Public URL Support** - Separate URLs for JWKS fetching and issuer validation
58
- - New `authServerPrivateUrl` configuration option for server-side JWKS fetching (internal network)
59
- - New `authServerPublicUrl` configuration option for browser-side and issuer validation (public network)
60
- - New `resolveKeycloakUrl()` utility function that automatically detects environment and selects appropriate URL
61
- - `validateTokenLocal()` now uses private URL for JWKS fetching on server, public URL for issuer validation
62
- - Environment variable support: `KEYCLOAK_SERVER_URL` (maps to `authServerPrivateUrl`), `KEYCLOAK_PUBLIC_SERVER_URL` (maps to `authServerPublicUrl`)
63
- - Maintains backward compatibility with existing `authServerUrl` configuration
64
-
65
- ### Technical
66
-
67
- - **TokenValidationService** - Now uses `resolveKeycloakUrl()` for automatic URL resolution
68
- - JWKS URI construction uses resolved URL (private on server, public on browser)
69
- - Issuer validation always uses public URL (matches token's `iss` claim)
70
- - `determineTokenType()` updated to use public URL for issuer matching
71
- - **controller-url-resolver.ts** - Added `resolveKeycloakUrl()` function (mirrors `resolveControllerUrl()` pattern)
72
- - **config-loader.ts** - Added Keycloak environment variable support
73
- - **Tests**: Comprehensive tests for `resolveKeycloakUrl()` and updated TokenValidationService tests
74
-
75
- ## [3.8.1] - 2026-01-10
76
-
77
- ### Changed
78
-
79
- - **Unified Application Context Service** - Centralized application and environment extraction
80
- - New `ApplicationContextService` class to extract `application`, `applicationId`, and `environment` with consistent fallback logic
81
- - Extracts from client token first (if available), then falls back to parsing `miso-controller-{environment}-{application}` format from clientId
82
- - RoleService, PermissionService, LoggerService, and UnifiedLoggerService now use the unified service
83
- - Reduces code duplication and ensures consistent behavior across all services
84
- - Caches parsed results to avoid repeated extraction
85
-
86
- ### Fixed
87
-
88
- - **Logger Context Application Fallback** - Fixed application fallback to use clientId when parsing fails
89
- - Logger getter methods (`getLogWithRequest`, `getWithContext`, `getWithToken`) now properly fall back to `clientId` when `application` cannot be extracted from client token or parsed from clientId format
90
- - Ensures application field is always populated in log entries, even when clientId format doesn't match expected pattern
91
-
92
- ### Technical
93
-
94
- - **New service**: `src/services/application-context.service.ts` - Unified application context extraction (175 lines)
95
- - **Test coverage**: Comprehensive tests in `tests/unit/application-context.service.test.ts` (323 lines, 100% coverage)
96
- - **Code quality**: All services updated to use ApplicationContextService, reducing code duplication by ~50 lines
97
-
98
- ## [3.8.0] - 2026-01-10
99
-
100
- ### Added
101
-
102
- - **Unified Logging Interface**: New minimal API with automatic context extraction
103
- - `getLogger()` factory function for automatic context detection from AsyncLocalStorage
104
- - `setLoggerContext()` and `clearLoggerContext()` for manual context management
105
- - `loggerContextMiddleware` Express middleware helper for automatic request context extraction
106
- - AsyncLocalStorage-based context propagation across async boundaries
107
- - Simplified API: `logger.info(message)`, `logger.error(message, error?)`, `logger.audit(action, resource, entityId?, oldValues?, newValues?)`
108
- - Automatic context extraction from AsyncLocalStorage (set by Express middleware or manually)
109
- - Works seamlessly in Express routes, service layers, and background jobs
110
- - Zero configuration required when middleware is used
111
-
112
- ### Documentation
113
-
114
- - Added unified logging examples and guides (`docs/examples/unified-logging.md`)
115
- - Updated Express middleware examples with unified logging pattern
116
- - Added background job logging examples with unified interface
117
- - Comprehensive API reference for UnifiedLogger interface in `docs/reference-services.md`
118
-
119
- ## [3.7.2] - 2026-01-10
120
-
121
- ### Added
122
-
123
- - **Comprehensive Integration Tests** - Full end-to-end integration tests for Auth and Logs API endpoints
124
- - New `tests/integration/api-endpoints.integration.test.ts` with comprehensive endpoint coverage
125
- - Tests all Auth and Logs endpoints against real controller using credentials from `.env`
126
- - Validates endpoint paths, HTTP methods, request bodies, and response structures against OpenAPI specs
127
- - Tests error cases (invalid tokens, missing params, etc.) with proper status code verification
128
- - Gracefully skips tests if controller is unavailable (CI/CD friendly)
129
- - New npm script `test:integration:api` for running integration tests
130
-
131
- ### Changed
132
-
133
- - **Logger Service Refactoring** - Improved code organization and maintainability
134
- - Moved logger service to modular structure in `src/services/logger/` directory
135
- - Split `LoggerService` into focused modules: `logger-chain.ts`, `logger-context.ts`, `logger.service.ts`
136
- - New barrel export `src/services/logger/index.ts` for cleaner imports
137
- - Maintains backward compatibility (no breaking changes to public API)
138
-
139
- - **Error Handling Improvements** - Enhanced error handling across API layer
140
- - Updated error handling in integration tests to gracefully skip unavailable controllers
141
- - Improved error reporting and logging throughout API files
142
- - Enhanced user information retrieval functionality
143
-
144
- - **Code Quality Improvements** - Refactoring for better readability and maintainability
145
- - Updated various components for improved logging and error reporting
146
- - Enhanced API response handling and validation
147
- - Improved code organization and structure
148
-
149
- ### Fixed
150
-
151
- - **Linting Issues** - Fixed ESLint errors in internal HTTP client
152
- - Converted `require()` statements to use ESLint disable comments for Node.js-only code
153
- - Fixed `@typescript-eslint/no-var-requires` errors in `src/utils/internal-http-client.ts`
154
-
155
- ### Technical
156
-
157
- - **New test infrastructure**:
158
- - Comprehensive integration test suite (`tests/integration/api-endpoints.integration.test.ts` - 554 lines)
159
- - New npm script: `test:integration:api` for running integration tests
160
- - Enhanced validation plans and summaries for API calls
161
-
162
- - **Code organization**:
163
- - Logger service modularized into `src/services/logger/` directory structure
164
- - Improved separation of concerns with focused modules
165
- - Better code maintainability and testability
166
-
167
- - **Documentation**:
168
- - Added endpoint validation summary documentation
169
- - Updated validation plans for API calls
170
-
171
- ## [3.7.1] - 2026-01-09
172
-
173
- ### Added
174
-
175
- - **Enhanced Error Logging with Correlation IDs** - Comprehensive error logging system with structured error extraction
176
- - New `extractErrorInfo()` utility in `src/utils/error-extractor.ts` for structured error information extraction
177
- - New `logErrorWithContext()` utility in `src/utils/console-logger.ts` for enhanced console logging with correlation ID prefixes
178
- - Supports all error types: `MisoClientError`, `ApiError`, `AuthenticationError`, `NetworkError`, `TimeoutError`, and generic `Error`
179
- - Automatic correlation ID extraction from error responses or auto-generation when missing
180
- - Enhanced error context includes endpoint, method, status codes, response bodies, and stack traces
181
- - All API files updated with structured error logging (11 API files enhanced)
182
- - DataClient and Express error handlers updated with enhanced logging
183
-
184
- - **Logger Service Getter Methods** - Public methods for external logger integration
185
- - New `getLogWithRequest()` method - Extracts IP, method, path, userAgent, correlationId, userId from Express Request
186
- - New `getWithContext()` method - Returns LogEntry with provided context and auto-generated correlation ID
187
- - New `getWithToken()` method - Extracts userId, sessionId, applicationId from JWT token
188
- - New `getForRequest()` method - Alias for `getLogWithRequest()` for consistency
189
- - All methods return complete `LogEntry` objects for integration with external logger tables
190
- - `generateCorrelationId()` method made public for consistent correlation ID generation
191
-
192
- - **Unified JSON Filter Model** - Standardized JSON format for all filter representations
193
- - New filter operators: `isNull` and `isNotNull` for null/undefined checks
194
- - JSON format parser supports multiple input formats: direct object, JSON string, URL-encoded JSON, array of filters
195
- - Operator normalization (e.g., `equals` → `eq`, `>` → `gt`)
196
- - Comprehensive validation with clear error messages and examples
197
- - Filter conversion utilities: `filterQueryToJson()` and `jsonToFilterQuery()`
198
- - Query string builder outputs URL-encoded JSON format
199
- - Local filtering supports null checks with `isNull` and `isNotNull` operators
200
-
201
- - **Server Code Improvements** - Enhanced Express server error handling and logging
202
- - Replaced all `console.log/error/warn` with MisoClient logger service
203
- - All route handlers wrapped with `asyncHandler()` wrapper for automatic error handling
204
- - Error middleware uses `handleRouteError()` from SDK for RFC 7807 compliance
205
- - Error logger configured with MisoClient logger via `setErrorLogger()`
206
- - All business logic errors use `AppError` for consistent error formatting
207
- - Automatic correlation ID extraction and error logging with full context
208
-
209
- - **Frontend Code Improvements** - Enhanced React application error handling and code quality
210
- - Centralized error handling utilities (`src/utils/error-handler.ts`)
211
- - Centralized type definitions (`src/types/errors.ts`, `src/types/api.ts`)
212
- - Input validation utilities (`src/utils/validation.ts`) for role names, permission names, endpoints
213
- - Component refactoring: ApiTestingPage reduced from 589 to 79 lines (87% reduction)
214
- - New custom hooks: `useApiTesting` for API testing logic, `useLoadingState` for loading state management
215
- - Improved DataClientContext with retry logic and exponential backoff
216
- - Simplified ErrorDetailsDialog component (115 lines, reduced from 193)
217
-
218
- - **Comprehensive Integration Tests** - Real integration tests for all auth and logs endpoints
219
- - New `tests/integration/api-endpoints.integration.test.ts` with comprehensive endpoint coverage
220
- - Tests all 24 auth endpoints against real controller using credentials from `.env`
221
- - Tests all 15 logs endpoints with proper request/response validation
222
- - Validates endpoint paths, HTTP methods, request bodies, and response structures against OpenAPI specs
223
- - Tests error cases (invalid tokens, missing params, etc.) with proper status code verification
224
- - Gracefully skips tests if controller is unavailable (CI/CD friendly)
225
- - New npm script `test:integration:api` for running integration tests
226
-
227
- - **Logger Service Refactoring** - Improved code organization and maintainability
228
- - Split `LoggerService` into modular structure following API layer pattern
229
- - New `src/services/logger/logger-chain.ts` - LoggerChain class for method chaining
230
- - New `src/services/logger/logger-context.ts` - Context extraction utilities (JWT, metadata, request)
231
- - New `src/services/logger/index.ts` - Barrel export for logger modules
232
- - Reduced main `logger.service.ts` from 866 lines to under 500 lines (code size compliance)
233
- - Maintains backward compatibility (no breaking changes to public API)
234
-
235
- ### Changed
236
-
237
- - **Error Logging** - Enhanced error logging across all API layer files
238
- - All API files now use `extractErrorInfo()` and `logErrorWithContext()` for structured error logging
239
- - Error logs include correlation ID prefixes: `[MisoClient] [correlation-id] Error details`
240
- - Authentication errors have special handling with detailed context (authFlow: 'token_validation_failed')
241
- - Enhanced audit logs include structured error info (errorType, errorCategory, httpStatusCategory)
242
-
243
- - **Filter Parsing** - Unified JSON format replaces colon-separated format
244
- - Filter parser now accepts JSON format only: `{"field": {"op": value}}`
245
- - Supports 12 operators: `eq`, `neq`, `in`, `nin`, `gt`, `lt`, `gte`, `lte`, `contains`, `like`, `isNull`, `isNotNull`
246
- - FilterBuilder outputs JSON format (URL-encoded) in query strings
247
- - Comprehensive validation with helpful error messages including examples
248
-
249
- - **Server Error Handling** - Standardized error handling patterns
250
- - All route handlers use `asyncHandler()` wrapper (no manual try-catch needed)
251
- - All errors automatically formatted as RFC 7807 Problem Details
252
- - Error logger uses MisoClient logger with `forRequest()` for automatic context extraction
253
- - Consistent error responses across all routes with correlation IDs
254
-
255
- - **Frontend Error Handling** - Centralized error handling patterns
256
- - All components use shared error handling utilities
257
- - RFC 7807 compliant error parsing with `parseError()` utility
258
- - Consistent error message extraction with `getErrorMessage()` and `getErrorStatus()`
259
- - Input validation integrated into authorization testing hooks
260
-
261
- - **API Layer Cleanup** - Removed duplicate code and improved code quality
262
- - Removed duplicate roles/permissions methods from `AuthApi` class
263
- - Removed `getRoles()`, `refreshRoles()`, `getPermissions()`, `refreshPermissions()` from `AuthApi`
264
- - Services now use dedicated `RolesApi` and `PermissionsApi` classes (DRY principle)
265
- - Removed unused endpoint constants and type imports from `AuthApi`
266
- - Updated class JSDoc to reflect removed methods
267
-
268
- - **Error Handling Improvements** - Fixed duplicate throw statements across API layer
269
- - Removed duplicate `throw error;` statements from `auth.api.ts`, `roles.api.ts`, `permissions.api.ts`
270
- - Fixed duplicate throws in `logs-create.api.ts` and `logs-list.api.ts`
271
- - Improved error handling consistency across all API files
272
-
273
- ### Fixed
274
-
275
- - **Server Error Handling** - Fixed logic bug in server.ts (dead code removed)
276
- - **Server Logging** - Fixed inconsistent logging format (now uses MisoClient logger)
277
- - **Server Error Responses** - Fixed non-RFC 7807 error responses (now uses `handleRouteError()`)
278
- - **Frontend Component Size** - Fixed large component files exceeding 500-line limit
279
- - ApiTestingPage: 589 → 79 lines (87% reduction)
280
- - ConfigurationPage: 382 283 lines (26% reduction)
281
- - **Frontend Error Handling** - Fixed duplicate error handling logic across components
282
- - **Frontend Type Safety** - Fixed loose error typing with centralized type definitions
283
- - **Code Size Compliance** - Fixed logger service file size violation
284
- - Refactored `LoggerService` from 866 lines to under 500 lines
285
- - Split into focused modules: logger-chain.ts, logger-context.ts, index.ts
286
- - Maintains all functionality while improving maintainability
287
- - **API Endpoint Validation** - Validated all endpoints against OpenAPI specifications
288
- - Verified all 24 auth endpoints match OpenAPI spec paths and HTTP methods
289
- - Verified all 15 logs endpoints match OpenAPI spec with proper request/response structures
290
- - Confirmed audit logs include required fields (entityType, entityId, action) in data object
291
- - Validated client token endpoints use correct paths (`/api/v1/auth/token` for legacy, `/api/v1/auth/client-token` for frontend)
292
-
293
- ### Technical
294
-
295
- - **New utility files**:
296
- - `src/utils/error-extractor.ts` - Error extraction utility (172 lines)
297
- - `src/utils/console-logger.ts` - Enhanced console logger (72 lines)
298
- - `src/utils/error-handler.ts` - Frontend error handling utilities (175 lines)
299
- - `src/utils/validation.ts` - Frontend input validation utilities (139 lines)
300
- - `src/types/errors.ts` - Frontend error type definitions (25 lines)
301
- - `src/types/api.ts` - Frontend API type definitions (63 lines)
302
-
303
- - **Test coverage**:
304
- - Error extraction utility: 18 tests (`tests/unit/utils/error-extractor.test.ts`)
305
- - Console logger utility: 12 tests (`tests/unit/utils/console-logger.test.ts`)
306
- - Logger getter methods: 31 tests (`tests/unit/services/logger-getter-methods.test.ts`)
307
- - Filter utilities: 68 tests (`tests/unit/filter.utils.test.ts`)
308
- - Frontend error handler: 21 tests (`server/frontend/src/utils/__tests__/error-handler.test.ts`)
309
- - Frontend validation: 43 tests (`server/frontend/src/utils/__tests__/validation.test.ts`)
310
- - Integration tests: Comprehensive tests for all 39 endpoints (`tests/integration/api-endpoints.integration.test.ts`)
311
- - Total: 193+ new tests added, all passing
312
-
313
- - **New logger module structure**:
314
- - `src/services/logger/logger-chain.ts` - LoggerChain class (method chaining support)
315
- - `src/services/logger/logger-context.ts` - Context extraction utilities
316
- - `src/services/logger/index.ts` - Barrel export
317
- - `src/services/logger.service.ts` - Core LoggerService class (reduced to <500 lines)
318
-
319
- - **Code quality**:
320
- - All new utilities follow camelCase naming convention
321
- - All public methods have JSDoc comments with parameter types, return types, and examples
322
- - File sizes within limits (all files ≤500 lines)
323
- - Method sizes within limits (all methods ≤30 lines)
324
- - Zero linting errors or warnings
325
- - Proper error handling with try-catch for all async operations
326
- - Removed duplicate code (roles/permissions methods from AuthApi)
327
- - Fixed duplicate throw statements across API layer
328
- - All endpoints validated against OpenAPI specs
329
-
330
- - **Documentation**:
331
- - Updated `docs/reference-services.md` with logger getter methods documentation
332
- - Updated `docs/reference-utilities.md` with filter JSON format examples
333
- - Updated `server/README.md` with factory function pattern and error logger configuration
334
- - Updated `docs/examples/express-middleware.md` with error logger configuration examples
335
- - Updated `AuthApi` class JSDoc to remove references to removed methods
336
- - Added integration test documentation explaining test structure and requirements
337
-
338
- ## [3.6.0] - 2024-12-31
339
-
340
- ### Added
341
-
342
- - **API Response Validation** - Runtime validation for API response structures
343
- - New `validateSuccessResponse<T>()` type guard for standard success responses
344
- - New `validatePaginatedResponse<T>()` type guard for paginated responses
345
- - New `validateErrorResponse()` type guard for error responses (re-exports existing validation)
346
- - New `getResponseType()` utility to determine response type (success, paginated, error)
347
- - Response validation utilities in `src/utils/response-validator.ts` with comprehensive type guards
348
- - All validation functions use TypeScript type guards for proper type narrowing
349
- - Detailed validation error messages for debugging response structure mismatches
350
-
351
- - **Response Validation Configuration** - Configurable validation control
352
- - New `validateResponses?: boolean` configuration option in `MisoClientConfig`
353
- - Environment variable support: `MISO_VALIDATE_RESPONSES` (defaults to `true` in development, `false` in production)
354
- - Validation is opt-in and backward compatible (doesn't break existing code)
355
- - Non-breaking validation failures (logs warnings instead of throwing errors)
356
-
357
- ### Changed
358
-
359
- - **HTTP Client Response Validation** - Enhanced HTTP client with response structure validation
360
- - `InternalHttpClient` now validates all API responses when `validateResponses` is enabled
361
- - All HTTP methods (`get`, `post`, `put`, `delete`, `request`, `authenticatedRequest`) validate responses
362
- - Validation checks for standard success response format: `{ success: boolean, data?: T, message?: string, timestamp: string }`
363
- - Validation checks for paginated response format: `{ data: T[], meta: {...}, links: {...} }`
364
- - Validation handles both nested and flat response formats (backward compatibility)
365
- - Validation failures log warnings with endpoint URL, expected structure, and actual response
366
- - Graceful error handling - validation failures don't break existing functionality
367
-
368
- ### Fixed
369
-
370
- - **Circuit breaker priority** - Fixed critical ordering issue where circuit breaker check now occurs before cache check
371
- - Circuit breaker check moved before cache and pending request checks to prevent requests to failing endpoints
372
- - Ensures failed endpoints are blocked even if cache is cleared, preventing unnecessary API calls during failures
373
- - Improved error consistency by using `throw` instead of `Promise.reject()` for circuit breaker errors
374
-
375
- - **Cache key generation** - Fixed cache key generation to ensure HTTP method is always included
376
- - Cache key now explicitly includes HTTP method from method parameter to ensure consistency
377
- - Prevents potential cache key collisions when method might be undefined in options
378
- - Ensures proper cache key generation for all HTTP methods (GET, POST, PUT, DELETE, etc.)
379
-
380
- ### Technical
381
-
382
- - **New utility file**: `src/utils/response-validator.ts` - Response validation utilities (174 lines)
383
- - Type guard functions for runtime type checking
384
- - Support for success, paginated, and error response formats
385
- - Comprehensive JSDoc documentation for all public functions
386
- - Proper TypeScript type narrowing with type guards
387
-
388
- - **Test coverage**:
389
- - Comprehensive tests in `tests/unit/utils/response-validator.test.ts` (413 lines)
390
- - 36 test cases covering valid/invalid responses, edge cases, and backward compatibility
391
- - Test coverage: **96.53%** (exceeds ≥80% requirement)
392
- - Statements: 96.53% (167/173)
393
- - Branches: 91.83% (45/49)
394
- - Functions: 100% (4/4)
395
- - Lines: 96.53% (167/173)
396
- - All tests passing with execution time < 0.5 seconds
397
-
398
- - **Configuration updates**:
399
- - Added `validateResponses?: boolean` to `MisoClientConfig` interface
400
- - Added `MISO_VALIDATE_RESPONSES` environment variable support in config loader
401
- - Defaults to `true` in development, `false` in production for performance
402
-
403
- - **Code quality**:
404
- - All validation functions follow camelCase naming convention
405
- - All public functions have JSDoc comments with parameter types and return types
406
- - File size: 174 lines (≤500 lines requirement met)
407
- - Method sizes: ≤30 lines (≤20-30 lines requirement met)
408
- - Zero linting errors or warnings
409
- - Proper error handling with try-catch for all async operations
410
-
411
- ## [3.4.1] - 2025-12-30
412
-
413
- ### Fixed
414
-
415
- - **Token validation caching** - Improved caching strategy for token validation
416
- - Enhanced cache key generation using SHA-256 hash of token for security
417
- - Smart TTL calculation based on token expiration with safety buffer
418
- - Minimum TTL enforcement to prevent excessive API calls
419
- - Better cache invalidation handling
420
-
421
- ### Changed
422
-
423
- - **Error handling** - Enhanced error handling and logging for token retrieval
424
- - Added detailed error responses for timeout scenarios in client token endpoint
425
- - Updated AuthService to use shorter timeout for axios requests (aligns with handler timeout)
426
- - Improved logging for token retrieval processes with controller URL details
427
- - Integrated controller URL resolution in environment token utility for consistent URL handling
428
-
429
- ### Technical
430
-
431
- - **Dependencies** - Updated dependencies and improved linting configuration
432
- - Removed unnecessary "peer" flags from package-lock.json
433
- - Updated linting scripts to ignore declaration files for better efficiency
434
- - Updated package dependencies for improved functionality and performance
435
-
436
- ## [3.4.0] - 2025-12-24
437
-
438
- ### Added
439
-
440
- - **Local Token Validation** - JWKS-based JWT validation without API calls
441
- - New `validateTokenLocal()` method for local JWT signature verification
442
- - Supports Keycloak tokens and delegated OAuth provider tokens
443
- - Dual-layer caching: JWKS keys (1 hour) + validation results (1 minute)
444
- - `skipResultCache` option for high-security scenarios
445
- - Auto-detection of token type based on issuer claim
446
- - New `TokenValidationService` exported for advanced usage
447
-
448
- - **Keycloak Configuration** - Native Keycloak integration
449
- - New `keycloak` config option in `MisoClientConfig`
450
- - `setKeycloakConfig()` method for runtime configuration
451
- - Audience validation support (opt-in via `verifyAudience`)
452
-
453
- - **Cache Management** - Fine-grained cache control
454
- - `clearJwksCache(uri?)` - Clear JWKS key cache
455
- - `clearValidationCache()` - Clear validation result cache
456
- - `clearAllTokenCaches()` - Clear all caches
457
-
458
- ### Changed
459
-
460
- - **Package Distribution** - Added CHANGELOG.md to npm package files
461
-
462
- ### Dependencies
463
-
464
- - Added `jose` ^5.9.6 for JWT/JWKS operations
465
-
466
- ## [3.3.0] - 2025-12-23
467
-
468
- ### Added
469
-
470
- - **Centralized API layer** - Typed interfaces for all controller API calls
471
- - New API layer in `src/api/` with domain-specific API classes (`AuthApi`, `RolesApi`, `PermissionsApi`, `LogsApi`)
472
- - `ApiClient` class wraps `HttpClient` and organizes APIs by domain
473
- - Centralized endpoint URLs as constants in each API class for maintainability
474
- - All API request/response types use interfaces (not types) with camelCase naming convention
475
- - Services can optionally use `ApiClient` instead of direct `HttpClient` calls (gradual migration pattern)
476
- - Improved type safety and code organization for controller API interactions
477
- - API classes are composed from specialized sub-modules to keep file sizes manageable
478
-
479
- ### Changed
480
-
481
- - **Token validation enhancements** - Improved token acceptance criteria
482
- - Updated token validation logic to accept both JWT and non-JWT token formats
483
- - Enhanced validation to ensure tokens are non-empty and of reasonable length
484
- - Improved error handling for token validation failures
485
- - Updated unit tests to reflect changes in token acceptance criteria
486
-
487
- - **OAuth callback handling** - Enhanced error feedback
488
- - Updated error handling in `handleOAuthCallback()` to provide clearer feedback on token validation failures
489
- - Improved documentation for token validation and OAuth handling
490
-
491
- - **Service dependencies** - Optional API client support
492
- - Services can now optionally include `ApiClient` for typed API access
493
- - Allows for gradual migration from direct `HttpClient` usage to typed API layer
494
- - Maintains backward compatibility with existing service implementations
495
-
496
- ### Technical
497
-
498
- - **New API layer structure**:
499
- - `src/api/index.ts` - Main `ApiClient` class
500
- - `src/api/auth.api.ts` - Authentication API (composed from sub-modules)
501
- - `src/api/roles.api.ts` - Roles API
502
- - `src/api/permissions.api.ts` - Permissions API
503
- - `src/api/logs.api.ts` - Logs API
504
- - `src/api/types/` - API request/response type definitions
505
-
506
- - **Test coverage**:
507
- - Updated mock patterns to include `ApiClient` for testing purposes
508
- - Enhanced unit tests for token validation with new acceptance criteria
509
-
510
- - **Documentation**:
511
- - Added API layer pattern documentation to project rules
512
- - Updated usage examples to demonstrate API layer pattern
513
- - Enhanced documentation for token validation and OAuth handling
514
-
515
- ## [3.2.5] - 2025-12-22
516
-
517
- ### Added
518
-
519
- - **Indexed logging fields** - Standardized indexed fields for improved query performance and observability
520
- - New `extractLoggingContext()` utility function in `src/utils/logging-helpers.ts`
521
- - Added indexed context fields to `LogEntry` interface: `sourceKey`, `sourceDisplayName`, `externalSystemKey`, `externalSystemDisplayName`, `recordKey`, `recordDisplayName`
522
- - Added credential context fields: `credentialId`, `credentialType`
523
- - Added request/response metrics: `requestSize`, `responseSize`, `durationMs`
524
- - Added error classification fields: `errorCategory`, `httpStatusCategory`
525
- - New `LoggerChain` methods: `withIndexedContext()`, `withCredentialContext()`, `withRequestMetrics()`
526
- - Exported types: `IndexedLoggingContext`, `HasKey`, `HasExternalSystem`
527
- - Improves query performance and root-cause analysis for audit logs
528
-
529
- - **Request context auto-extraction** - Automatic extraction of logging context from Express Request objects
530
- - New `extractRequestContext()` utility function in `src/utils/request-context.ts`
531
- - New `withRequest()` method on `LoggerChain` for automatic context extraction
532
- - New `forRequest()` method on `LoggerService` for request-based logging
533
- - Automatically extracts: IP address, HTTP method, path, user-agent, correlation ID, user from JWT, session ID, request ID
534
- - Handles proxy IPs via `x-forwarded-for` header
535
- - Reduces logging code from 10-15 lines to 2-3 lines per log call
536
- - Exported `RequestContext` interface and `extractRequestContext` function
537
-
538
- - **Token validation caching** - Caching for token validation to reduce API calls
539
- - Cache validation results by userId with 15-minute TTL (configurable via `config.cache?.tokenValidationTTL`)
540
- - Cache key format: `token:${userId}` (consistent with roles/permissions caching)
541
- - Automatic cache invalidation on logout (clears cache even if logout returns 400)
542
- - New `clearTokenCache()` method in `AuthService` for manual cache clearing
543
- - Extracts userId from JWT token before API call (avoids unnecessary validate API call)
544
- - Graceful fallback to API call on cache failures
545
- - Uses `CacheService` instead of `RedisService` for consistency
546
-
547
- - **User token refresh** - Token refresh functionality for secure token renewal
548
- - New `refreshToken()` method in `AuthService` for backend applications
549
- - New `onTokenRefresh` callback support in `DataClient` for frontend applications
550
- - Automatic token refresh on 401 errors in DataClient with retry logic
551
- - New `RefreshTokenResponse` interface with `accessToken`, `refreshToken`, `expiresIn`, `expiresAt`
552
- - Exposed `refreshToken()` method in `MisoClient` class
553
- - Prevents infinite retry loops with `tokenRefreshAttempted` flag
554
- - Refresh tokens never stored in browser localStorage (security requirement)
555
-
556
- - **OAuth callback handler** - ISO 27001 compliant OAuth callback handling with hash fragments
557
- - New `handleOAuthCallback()` function in `src/utils/data-client-auth.ts`
558
- - New `handleOAuthCallback()` method in `DataClient` class
559
- - Extracts tokens from URL hash fragments (`#token=...`) instead of query parameters
560
- - Immediate hash cleanup (< 100ms) to prevent token exposure
561
- - Token format validation (JWT format check)
562
- - HTTPS enforcement in production environments
563
- - Supports multiple parameter names: `token`, `access_token`, `accessToken`
564
- - Auto-calls on DataClient initialization in browser environments
565
- - Secure error handling without exposing tokens
566
-
567
- ### Changed
568
-
569
- - **LoggerService enhancements** - Enhanced logging capabilities with indexed fields
570
- - Updated `ClientLoggingOptions` interface with indexed context fields
571
- - Updated `LogEntry` interface with indexed fields for fast queries
572
- - Enhanced `LoggerChain` fluent API with new context methods
573
- - Improved developer experience with automatic request context extraction
574
-
575
- - **AuthService improvements** - Enhanced authentication service with caching
576
- - Updated constructor to accept `CacheService` instead of `RedisService`
577
- - Added `extractUserIdFromToken()` private method for JWT extraction
578
- - Enhanced `validateToken()` method with caching logic
579
- - Updated `logout()` method to clear token cache on logout
580
-
581
- - **DataClient enhancements** - Improved token refresh and OAuth handling
582
- - Added `refreshUserToken()` private method for token refresh
583
- - Enhanced 401 error handling with automatic token refresh and retry
584
- - Updated `redirectToLogin()` documentation for hash fragment flow
585
- - Improved OAuth callback handling with security measures
586
-
587
- ### Fixed
588
-
589
- - **Token validation performance** - Reduced API calls through caching
590
- - Token validation now uses cache to avoid unnecessary controller API calls
591
- - Cache hit significantly improves performance for repeated validations
592
-
593
- - **OAuth security** - Improved security for OAuth callback flow
594
- - Tokens extracted from hash fragments (not sent to server, not in logs)
595
- - Immediate cleanup prevents token exposure in address bar
596
- - HTTPS enforcement prevents token transmission over HTTP in production
597
-
598
- ### Technical
599
-
600
- - **New utility files**:
601
- - `src/utils/logging-helpers.ts` - Logging context extraction utility (91 lines)
602
- - `src/utils/request-context.ts` - Request context extraction utility (102 lines)
603
-
604
- - **Test coverage**:
605
- - Comprehensive tests for logging helpers (15 tests)
606
- - Comprehensive tests for request context extraction (33 tests)
607
- - Enhanced tests for token caching (80 tests total in auth.service.test.ts)
608
- - Comprehensive tests for token refresh (17 AuthService + 15 DataClient tests)
609
- - Comprehensive tests for OAuth callback handler (34 tests)
610
-
611
- - **Type definitions**:
612
- - Added `RefreshTokenResponse` interface to `src/types/config.types.ts`
613
- - Added `tokenValidationTTL?: number` to cache config type
614
- - Added `onTokenRefresh` callback to `DataClientConfig` interface
615
-
616
- - **Exports updated**:
617
- - `src/index.ts` - Exports `extractLoggingContext`, `IndexedLoggingContext`, `HasKey`, `HasExternalSystem`
618
- - `src/index.ts` - Exports `extractRequestContext`, `RequestContext`
619
- - `src/index.ts` - Exports `refreshToken()` method in `MisoClient`
620
-
621
- ## [3.2.0] - 2025-12-22
622
-
623
- ### Added
624
-
625
- - **Circuit breaker for HTTP logging** - Prevents infinite retry loops when logging service is unavailable
626
- - Added circuit breaker pattern to `LoggerService` and `AuditLogQueue`
627
- - Automatically disables HTTP logging after 3 consecutive failures
628
- - Circuit breaker opens for 60 seconds after failures, then resets
629
- - Prevents performance degradation when controller logging endpoint is unavailable
630
- - Gracefully handles network errors and server unavailability
631
-
632
- - **DataClient redirect utilities** - Comprehensive redirect handling for login flows
633
- - New `data-client-redirect.ts` utility module with robust redirect logic
634
- - Enhanced `redirectToLogin()` with comprehensive error handling
635
- - URL validation prevents dangerous redirects (javascript:, data:, etc.)
636
- - User-friendly error messages for network, CORS, and authentication errors
637
- - Proper timeout handling (30 seconds) to prevent hanging requests
638
- - Only redirects when controller returns valid login URL (no fallback redirects on error)
639
- - Supports both nested (`data.loginUrl`) and flat (`loginUrl`) response formats
640
-
641
- - **Client token expiration checking** - Enhanced token validation with JWT expiration support
642
- - Improved `getClientToken()` to check JWT expiration claims when expiration timestamp is missing
643
- - Decodes JWT tokens to extract `exp` claim for expiration validation
644
- - Better logging for debugging token expiration issues
645
- - Handles missing expiration timestamps gracefully
646
- - Automatically removes expired tokens from cache
647
-
648
- - **Auto-initialization improvements** - New utility for accessing cached configuration
649
- - New `getCachedDataClientConfig()` function exported from `src/index.ts`
650
- - Allows reading cached DataClient configuration without re-initializing
651
- - Useful for accessing configuration values in application code
652
- - Returns cached config or null if not found or expired
653
-
654
- - **Controller URL validation utility** - Exported URL validation function
655
- - `validateUrl()` function now exported from `controller-url-resolver.ts`
656
- - Validates HTTP/HTTPS URLs with comprehensive JSDoc documentation
657
- - Useful for validating URLs before use in application code
658
- - Exported from `src/index.ts` for public use
659
-
660
- ### Changed
661
-
662
- - **Documentation restructure** - Improved documentation organization and clarity
663
- - New reference documentation structure with dedicated files for each major component
664
- - Added `docs/reference-authentication.md` - Comprehensive authentication guide
665
- - Added `docs/reference-authorization.md` - RBAC and permissions documentation
666
- - Added `docs/reference-dataclient.md` - Complete DataClient API reference
667
- - Added `docs/reference-errors.md` - Error handling and troubleshooting guide
668
- - Added `docs/reference-misoclient.md` - MisoClient API reference
669
- - Added `docs/reference-services.md` - Service layer documentation
670
- - Added `docs/reference-types.md` - TypeScript type definitions reference
671
- - Added `docs/reference-utilities.md` - Utility functions documentation
672
- - Enhanced examples with improved clarity and error handling
673
- - Updated all example files with corrected import paths
674
-
675
- - **DataClient enhancements** - Improved robustness and developer experience
676
- - Enhanced DataClient configuration and performance optimizations
677
- - Improved authorization examples and documentation
678
- - Better error handling in example code
679
-
680
- - **Audit logging error handling** - Improved handling of network errors in audit logging
681
- - Enhanced error detection for network errors (ECONNREFUSED, ENOTFOUND, ERR_CONNECTION_REFUSED)
682
- - Silently skips audit logging for expected network errors (server unavailable, misconfigured)
683
- - Prevents error noise in development and demo environments
684
- - Better error classification and handling
685
-
686
- ### Fixed
687
-
688
- - **DataClient metrics** - Fixed handling of missing response times in metrics
689
- - Modified `getMetrics()` method to handle cases where `responseTimes` may be undefined
690
- - Ensures robust performance metrics retrieval without errors
691
-
692
- - **Example imports** - Fixed import paths in all example files
693
- - Updated example imports for clarity and proper error handling
694
- - Corrected script source references in demo applications
695
-
696
- - **Cache service test handling** - Fixed cleanup interval keeping process alive in tests
697
- - Added `unref()` to cleanup interval in `CacheService` to prevent tests from hanging
698
- - Ensures Node.js process can exit cleanly after tests complete
699
- - Important for CI/CD environments and test suites
700
-
701
- ### Removed
702
-
703
- - **Performance logging** - Removed deprecated performance logging functionality
704
- - Eliminated all performance logging code from the codebase
705
- - Removed PerformanceMetrics interface and related methods
706
- - Removed performance tracking logic from logger service
707
- - Functionality replaced by OpenTelemetry integration
708
-
709
- ### Technical
710
-
711
- - **Code quality improvements** - Enhanced development workflow and configuration
712
- - Updated ESLint and Jest configurations for improved testing and code quality
713
- - Enhanced configuration files and scripts for better development workflow
714
- - Improved .gitignore patterns
715
- - Updated package.json for testing enhancements
716
-
717
- - **New utility file**: `src/utils/data-client-redirect.ts` - Comprehensive redirect handling
718
- - Extracted redirect logic from DataClient into dedicated utility module
719
- - 424 lines of robust redirect handling with comprehensive error handling
720
- - URL validation, timeout handling, and user-friendly error messages
721
- - Proper separation of concerns for better maintainability
722
-
723
- ## [3.1.2] - 2025-12-15
724
-
725
- ### Changed
726
-
727
- - **DataClient refactoring** - Improved code organization and maintainability
728
- - Extracted request execution logic into separate utility modules
729
- - Split DataClient into focused utility files: `data-client-request.ts`, `data-client-auth.ts`, `data-client-cache.ts`, `data-client-utils.ts`
730
- - Improved code organization and separation of concerns
731
- - Reduced code complexity in main DataClient class
732
-
733
- ### Fixed
734
-
735
- - **TypeScript error handling** - Fixed TypeScript error in retry logic
736
- - Fixed type checking for error constructor name in authentication error detection
737
- - Improved error type safety in retry logic
738
-
739
- ### Technical
740
-
741
- - **Code quality improvements** - Significant refactoring for better maintainability
742
- - Reduced DataClient.ts from ~1600 lines to ~500 lines through modularization
743
- - Improved test coverage and organization
744
- - Better separation of concerns between authentication, caching, and request execution
745
-
746
- ## [3.1.1] - 2025-12-15
747
-
748
- ### Fixed
749
-
750
- - **DataClient retry logic** - Improved handling of 401 authentication errors in retry logic
751
- - Enhanced error type detection to prevent retries on authentication errors
752
- - Added explicit checks for AuthenticationError instances to ensure 401/403 errors are not retried
753
- - Improved statusCode extraction from error objects for more reliable retry decisions
754
-
755
- ## [3.1.0] - 2025-12-15
756
-
757
- ### Added
758
-
759
- - **Public and Private Controller URL Support** - Separate URLs for browser and server environments
760
- - New `controllerPublicUrl` configuration option for browser/Vite environments (accessible from internet)
761
- - New `controllerPrivateUrl` configuration option for server environments (internal network access)
762
- - New `resolveControllerUrl()` utility function that automatically detects environment and selects appropriate URL
763
- - New `isBrowser()` utility function for environment detection (checks for window, localStorage, fetch globals)
764
- - Environment variable support: `MISO_WEB_SERVER_URL` (maps to `controllerPublicUrl` for browser)
765
- - Environment variable support: `MISO_CONTROLLER_URL` (maps to `controllerPrivateUrl` for server, maintains backward compatibility)
766
- - Automatic URL resolution based on environment:
767
- - Browser environment: Uses `controllerPublicUrl` falls back to `controllerUrl`
768
- - Server environment: Uses `controllerPrivateUrl` falls back to `controllerUrl`
769
- - URL validation ensures resolved URLs are valid HTTP/HTTPS URLs
770
- - Clear error messages when no URL is configured
771
-
772
- ### Changed
773
-
774
- - **InternalHttpClient** - Now uses `resolveControllerUrl()` for automatic URL resolution
775
- - Constructor uses resolved URL instead of hardcoded `config.controllerUrl`
776
- - Client token fetch uses resolved URL for temporary axios instance
777
- - Maintains backward compatibility with existing `controllerUrl` configuration
778
-
779
- - **AuthService** - Now uses `resolveControllerUrl()` for axios instance creation
780
- - Automatically selects appropriate URL based on environment
781
- - Maintains backward compatibility with existing configurations
782
-
783
- - **Config Loader** - Enhanced environment variable parsing
784
- - `MISO_WEB_SERVER_URL` loads into `controllerPublicUrl` (browser/public)
785
- - `MISO_CONTROLLER_URL` loads into `controllerPrivateUrl` (server/private) and `controllerUrl` (backward compatibility)
786
- - Maintains existing behavior for applications using `MISO_CONTROLLER_URL`
787
-
788
- - **Documentation** - Updated configuration documentation
789
- - Added sections for public/private URL configuration in `docs/configuration.md`
790
- - Added examples for browser and server setup patterns
791
- - Updated `docs/api-reference.md` with new utility functions and configuration options
792
- - Includes migration guide and usage examples
793
-
794
- ### Technical
795
-
796
- - **New utility file**: `src/utils/controller-url-resolver.ts` - URL resolution with environment detection
797
- - `resolveControllerUrl()` function (35 lines, comprehensive JSDoc)
798
- - `isBrowser()` helper function (7 lines)
799
- - `validateUrl()` private helper function (7 lines)
800
- - 100% test coverage (28 tests in `tests/unit/controller-url-resolver.test.ts`)
801
-
802
- - **Test coverage** - Comprehensive tests for URL resolution
803
- - Browser environment detection tests (mocked window, localStorage, fetch)
804
- - Server environment detection tests (no browser globals)
805
- - URL resolution priority tests (public → private → controllerUrl → error)
806
- - Backward compatibility tests (existing `controllerUrl` still works)
807
- - Environment variable parsing tests (`MISO_WEB_SERVER_URL`, `MISO_CONTROLLER_URL`)
808
- - URL validation tests (invalid URLs throw errors)
809
- - Updated `tests/unit/config-loader.test.ts` with 52 new test lines
810
- - Updated `tests/unit/http-client.test.ts` and `tests/unit/client.test.ts` with URL resolution tests
811
-
812
- - **Exports updated**:
813
- - `src/index.ts` - Exports `resolveControllerUrl` and `isBrowser` utilities
814
- - Public API maintains camelCase naming convention
815
-
816
- ## [3.0.1] - 2025-12-14
817
-
818
- ### Fixed
819
-
820
- - **DataClient audit logging bug** - Fixed 401 Unauthorized errors when audit logging unauthenticated requests
821
- - Added `hasClientToken()` and `hasAnyToken()` helper methods to check authentication status
822
- - `logAuditEvent()` now skips audit logging when no authentication token is available (user token OR client token)
823
- - Prevents circular dependency where login requests trigger audit logging that requires authentication
824
- - Gracefully handles audit logging errors without breaking main requests
825
- - Improved error handling for 401 errors in audit logging (silently skipped for unauthenticated requests)
826
-
827
- ### Changed
828
-
829
- - **Documentation improvements** - Updated documentation files to match project style and improve clarity
830
- - `docs/api-reference.md` - Streamlined API documentation
831
- - `docs/configuration.md` - Reduced verbosity, focused on practical examples (reduced from ~1522 to ~785 lines)
832
- - `docs/data-client.md` - Improved clarity and consistency (reduced from ~1497 to ~926 lines)
833
- - `docs/examples.md` - Consolidated examples, removed redundancy (reduced from ~1014 to ~991 lines)
834
- - `docs/troubleshooting.md` - More action-oriented format, clearer solutions (reduced from ~965 to ~707 lines)
835
- - All documentation now follows consistent "You need to:" / "Here's how:" patterns
836
- - Removed jargon and technical verbosity
837
- - Added consistent "✅ Use standard .env parameters" patterns throughout
838
-
839
- ### Technical
840
-
841
- - **Test coverage** - Added tests for audit logging skip behavior
842
- - Updated `tests/unit/data-client.test.ts` with 69 new lines of test coverage
843
- - Tests verify audit logging is skipped for unauthenticated requests
844
- - Tests verify audit logging still works for authenticated requests
845
-
846
- ## [3.0.0] - 2025-12-14
847
-
848
- ### Added
849
-
850
- - **Configurable client token endpoint** - Customizable client token URI for authentication
851
- - New `clientTokenUri` configuration option in `MisoClientConfig` (defaults to `/api/v1/auth/token`)
852
- - Environment variable support: `MISO_CLIENT_TOKEN_URI`
853
- - Backward compatible with existing implementations
854
- - Used by `AuthService.getEnvironmentToken()` method
855
-
856
- - **Origin validation for security** - CORS origin validation with wildcard port support
857
- - New `allowedOrigins` configuration option in `MisoClientConfig`
858
- - Environment variable support: `MISO_ALLOWED_ORIGINS` (comma-separated list)
859
- - Supports wildcard ports: `http://localhost:*` (matches any port)
860
- - New `validateOrigin()` utility function exported for use in miso-controller backend
861
- - Checks `origin` header first, falls back to `referer` header
862
- - Security-first approach: validates origin before calling controller
863
-
864
- - **Server-side environment token wrapper** - Secure token fetching with origin validation
865
- - New `getEnvironmentToken()` server-side wrapper function
866
- - Validates request origin before calling controller
867
- - ISO 27001 compliant audit logging with masked client credentials
868
- - Logs error and audit events on validation failures
869
- - Exported from `src/index.ts` and `src/express/index.ts`
870
-
871
- - **Client token decoding utility** - Extract application and environment info from tokens
872
- - New `extractClientTokenInfo()` utility function
873
- - Decodes JWT client tokens without verification (no secret available)
874
- - Supports multiple field name variations:
875
- - `application` or `app`
876
- - `environment` or `env`
877
- - `applicationId` or `app_id`
878
- - `clientId` or `client_id`
879
- - Returns `ClientTokenInfo` interface with optional fields
880
- - Exported from `src/index.ts` and `src/express/index.ts`
881
-
882
- - **DataClient `getEnvironmentToken()` method** - Browser-side token fetching with caching
883
- - New public method for browser applications
884
- - Checks localStorage cache first (`miso:client-token` and `miso:client-token-expires-at`)
885
- - Fetches from backend endpoint if cache miss or expired
886
- - Uses `clientTokenUri` from config or defaults to `/api/v1/auth/client-token`
887
- - Supports absolute URLs and relative paths
888
- - Handles nested and flat response formats
889
- - ISO 27001 audit logging integration
890
- - Automatic cache expiration handling
891
-
892
- - **DataClient `getClientTokenInfo()` method** - Extract token metadata in browser
893
- - New public method to extract application/environment info from client token
894
- - Checks cached token first, then config token
895
- - Returns `ClientTokenInfo` object or `null` if no token available
896
- - Useful for displaying current application/environment in UI
897
- - Handles decode errors gracefully
898
-
899
- - **DataClient `logout()` method** - Logout functionality for browser applications
900
- - Calls controller logout API to invalidate server-side session
901
- - Clears authentication tokens from localStorage (all configured token keys)
902
- - Clears HTTP response cache
903
- - Redirects to logout URL or login page
904
- - Supports optional `redirectUrl` parameter for custom redirect after logout
905
- - Gracefully handles API failures (always clears local state)
906
- - SSR compatible (no-op in non-browser environments)
907
-
908
- - **DataClient `logoutUrl` configuration** - Custom logout redirect URL
909
- - Optional `logoutUrl` property in `DataClientConfig`
910
- - Falls back to `loginUrl` config if not provided
911
- - Supports both relative paths and absolute URLs
912
- - Defaults to `/login` if neither `logoutUrl` nor `loginUrl` is configured
913
-
914
- ### Changed
915
-
916
- - **AuthService `getEnvironmentToken()`** - Now uses configurable `clientTokenUri`
917
- - Changed from hardcoded `/api/v1/auth/token` to `this.config.clientTokenUri || '/api/v1/auth/token'`
918
- - Maintains backward compatibility (defaults to existing endpoint)
919
- - Existing error handling and correlation ID generation preserved
920
-
921
- - **MisoClientConfig interface** - Added new configuration options
922
- - New optional property: `clientTokenUri?: string`
923
- - New optional property: `allowedOrigins?: string[]`
924
-
925
- - **DataClient configuration** - Added `logoutUrl` option to `DataClientConfig` interface
926
- - New optional property: `logoutUrl?: string`
927
- - Follows same pattern as `loginUrl` configuration
928
-
929
- ### Technical
930
-
931
- - **New utility files**:
932
- - `src/utils/origin-validator.ts` - Origin validation with wildcard port support
933
- - `src/utils/environment-token.ts` - Server-side wrapper with audit logging
934
- - `src/utils/token-utils.ts` - Client token decoding utility
935
-
936
- - **New test files**:
937
- - `tests/unit/origin-validator.test.ts` - 22 tests covering origin validation
938
- - `tests/unit/token-utils.test.ts` - 20 tests covering token decoding
939
- - `tests/unit/environment-token.test.ts` - 10 tests covering server-side wrapper
940
- - Updated `tests/unit/data-client.test.ts` - Added 22 new tests
941
- - Updated `tests/unit/config-loader.test.ts` - Added 7 new tests
942
- - Updated `tests/unit/auth.service.test.ts` - Added 4 new tests
943
-
944
- - **Exports updated**:
945
- - `src/index.ts` - Exports `validateOrigin`, `getEnvironmentToken`, `extractClientTokenInfo`, and types
946
- - `src/express/index.ts` - Exports same utilities for Express applications
947
-
948
- - **Documentation updated**:
949
- - `docs/data-client.md` - Added sections for `getEnvironmentToken()` and `getClientTokenInfo()`
950
- - Includes browser usage examples, server-side route examples, configuration examples, and security best practices
951
-
952
- ## [2.2.1] - 2025-12-13
953
-
954
- ### Fixed
955
-
956
- - **DataClient `redirectToLogin()`** - Fixed redirect to use controller login endpoint
957
- - Now calls controller's `/api/v1/auth/login` endpoint with redirect parameter
958
- - Properly constructs full redirect URL instead of relative path
959
- - Falls back to static loginUrl when misoClient is unavailable or controller call fails
960
-
961
- ### Changed
962
-
963
- - **DataClient `redirectToLogin()`** - Enhanced with optional redirect URL parameter
964
- - Made method async to support controller API calls
965
- - Added optional `redirectUrl` parameter (defaults to current page URL)
966
- - Returns controller's login URL for proper OAuth flow handling
967
-
968
- ## [2.2.0] - 2025-12-13
969
-
970
- ### Added
971
-
972
- - **DataClient Browser Wrapper** - Browser-compatible HTTP client wrapper around MisoClient
973
- - Enhanced HTTP client capabilities for React/front-end applications
974
- - ISO 27001 compliant audit logging with configurable levels (minimal, standard, detailed, full)
975
- - Automatic sensitive data masking using DataMasker before audit logging
976
- - Request/response interceptors for custom request/response transformation
977
- - Response caching with configurable TTL and cache size limits
978
- - Automatic retry logic with exponential backoff for retryable errors
979
- - Request deduplication for concurrent duplicate requests
980
- - Request metrics tracking (response times, error rates, cache hit rates)
981
- - Custom error types (NetworkError, TimeoutError, AuthenticationError)
982
- - Browser compatibility checks with SSR support
983
- - Token management from localStorage with multiple key support
984
- - Automatic login redirect on authentication errors
985
- - Support for all HTTP methods (GET, POST, PUT, PATCH, DELETE)
986
- - Request cancellation via AbortController
987
- - Per-request timeout support
988
- - Integration with MisoClient for authentication and audit logging
989
- - **Client Token Pattern** - Secure browser usage without exposing clientSecret
990
- - Support for server-provided client tokens (`clientToken`, `clientTokenExpiresAt`)
991
- - Token refresh callback pattern (`onClientTokenRefresh`) for browser applications
992
- - Automatic token refresh with proactive expiration handling (60s buffer)
993
- - Memory-only token storage (never persisted to localStorage)
994
-
995
- ### Changed
996
-
997
- - **MisoClientConfig** - `clientSecret` is now optional when using client token pattern
998
- - Added `clientToken?: string` - Pre-obtained client token for browser usage
999
- - Added `clientTokenExpiresAt?: Date | string` - Token expiration tracking
1000
- - Added `onClientTokenRefresh?: () => Promise<{ token: string; expiresIn: number }>` - Refresh callback
1001
- - `InternalHttpClient` now supports both clientSecret (server-side) and clientToken (browser) patterns
1002
-
1003
- ## [2.1.2] - 2025-12-11
1004
-
1005
- ### Added
1006
-
1007
- - **Express.js Utilities** - Complete set of utilities for building Express.js REST APIs
1008
- - `ResponseHelper` - Standardized API response formatting (success, created, paginated, noContent, accepted)
1009
- - `injectResponseHelpers` - Middleware to inject response helpers into Express Response
1010
- - `asyncHandler` and `asyncHandlerNamed` - Automatic error handling for async route handlers
1011
- - `ValidationHelper` - Common validation patterns (findOrFail, ensureNotExists, ensureOwnershipOrAdmin, etc.)
1012
- - `AppError` - Application error class with RFC 7807 support
1013
- - `handleRouteError` - Centralized error handling for Express routes
1014
- - `setErrorLogger` - Injectable error logger for custom logging
1015
- - `EncryptionUtil` - AES-256-GCM encryption utility (replaces EncryptionService)
1016
- - Express Response type augmentation for TypeScript
1017
-
1018
- - **Sort Utilities** - Client-side sorting helpers
1019
- - `applySorting()` - Apply sorting to in-memory data arrays
1020
- - `parseSortParams()` - Parse sort query parameters (already existed)
1021
-
1022
- - **GitHub Workflows** - Manual release management
1023
- - Manual Version Bump workflow - Bump version, create git tags, and GitHub Releases
1024
- - Manual Publish to NPM workflow - Publish to npm with validation and verification
1025
-
1026
- - **Package Configuration**
1027
- - Express as optional peer dependency (^4.18.0 || ^5.0.0)
1028
- - @types/express as dev dependency
1029
-
1030
- - **Authentication API Updates**
1031
- - `LoginResponse` and `LogoutResponse` types for standardized authentication responses
1032
- - Updated `login()` method to make API call to `/api/v1/auth/login` with query parameters (redirect, state)
1033
- - Updated `logout()` method to accept token parameter and make API call to `/api/v1/auth/logout`
1034
- - Comprehensive test coverage for `response-middleware.ts` (100% coverage)
1035
-
1036
- ### Changed
1037
-
1038
- - **Package Description** - Updated to include Express.js utilities
1039
- - **EncryptionService** - Replaced instance-based EncryptionService with static EncryptionUtil class
1040
- - **Workflow Strategy** - Removed automatic publish on push, added manual workflows for better control
1041
- - **Authentication Methods** - Breaking changes:
1042
- - `login()` - Changed from synchronous method returning URL string to async method returning `LoginResponse` object
1043
- - `logout()` - Now requires `{ token: string }` parameter and returns `LogoutResponse` object
1044
-
1045
- ### Removed
1046
-
1047
- - Old automatic npm-publish workflow (replaced by manual workflows)
1048
- - EncryptionService class (replaced by EncryptionUtil)
1049
-
1050
- ## [2.0.0] - Previous Release
1051
-
1052
- See git history for previous changes.
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [4.1.0] - 2026-01-21
9
+
10
+ ### Changed
11
+
12
+ - **Encryption Key Parameter** - `encryptionKey` is now sent to the controller for server-side validation
13
+ - Added `encryptionKey` field to `EncryptRequest` and `DecryptRequest` interfaces
14
+ - `EncryptionService` validates encryption key is configured before API calls
15
+ - Throws `ENCRYPTION_KEY_REQUIRED` error with helpful message if key is missing
16
+
17
+ ### Added
18
+
19
+ - `ENCRYPTION_KEY_REQUIRED` error code in `EncryptionError` class
20
+ - Tests for encryption key validation in `EncryptionService`
21
+ - Tests for `MISO_ENCRYPTION_KEY` environment variable loading in `config-loader`
22
+
23
+ ### Technical
24
+
25
+ - `EncryptionError.parameterName` is now optional (not applicable for `ENCRYPTION_KEY_REQUIRED` errors)
26
+ - `EncryptionService` constructor accepts optional `encryptionKey` parameter
27
+ - `MisoClient` passes `config.encryptionKey` to `EncryptionService`
28
+
29
+ ## [4.0.0] - 2026-01-20
30
+
31
+ ### Breaking Changes
32
+
33
+ - **Removed `EncryptionUtil` class** - Local encryption via `EncryptionUtil.encrypt()`/`decrypt()` is no longer supported. Use the new controller-based `client.encryption` service instead.
34
+ - **Encryption Key Required** - The `encryptionKey` config option is now required for encryption operations
35
+ - Load from `MISO_ENCRYPTION_KEY` environment variable
36
+ - Or provide `encryptionKey` in `MisoClientConfig`
37
+ - Throws `ENCRYPTION_KEY_REQUIRED` error if not configured when using encrypt/decrypt
38
+
39
+ ### Migration Guide
40
+
41
+ **Before (v3.x) - Local encryption:**
42
+
43
+ ```typescript
44
+ import { EncryptionUtil } from '@aifabrix/miso-client';
45
+
46
+ EncryptionUtil.initialize(); // Required ENCRYPTION_KEY env var
47
+ const encrypted = EncryptionUtil.encrypt('my-secret');
48
+ const decrypted = EncryptionUtil.decrypt(encrypted);
49
+ ```
50
+
51
+ **After (v4.0) - Controller-based encryption:**
52
+
53
+ ```typescript
54
+ import { MisoClient, loadConfig } from '@aifabrix/miso-client';
55
+
56
+ // Option 1: Use environment variable (recommended)
57
+ // Set MISO_ENCRYPTION_KEY in your .env file
58
+ const client = new MisoClient(loadConfig());
59
+
60
+ // Option 2: Provide in config
61
+ const client = new MisoClient({
62
+ controllerUrl: 'https://miso-controller.example.com',
63
+ clientId: 'my-app',
64
+ clientSecret: 'secret',
65
+ encryptionKey: 'your-encryption-key', // Required for encryption operations
66
+ });
67
+
68
+ const result = await client.encryption.encrypt('my-secret', 'param-name');
69
+ // result.value: 'kv://param-name' (Key Vault) or 'enc://v1:...' (local)
70
+ // result.storage: 'keyvault' or 'local'
71
+
72
+ const decrypted = await client.encryption.decrypt(result.value, 'param-name');
73
+ ```
74
+
75
+ ### Why This Change?
76
+
77
+ - **Centralized key management** - Encryption keys are managed by the controller, validated server-side
78
+ - **Azure Key Vault support** - Production environments can use Azure Key Vault for secure secret storage
79
+ - **Application isolation** - Each application can only access its own encrypted parameters
80
+ - **Audit logging** - All encryption/decryption operations are logged by the controller
81
+ - **Security** - Encryption key prevents misuse of rotated or leaked application credentials
82
+
83
+ ### Added
84
+
85
+ - `client.encryption.encrypt(plaintext, parameterName)` - Encrypt a value via controller
86
+ - `client.encryption.decrypt(value, parameterName)` - Decrypt a value via controller
87
+ - `EncryptionService` class - Service layer with parameter and encryption key validation
88
+ - `EncryptionError` class - Error class with codes: `ENCRYPTION_FAILED`, `DECRYPTION_FAILED`, `INVALID_PARAMETER_NAME`, `ACCESS_DENIED`, `PARAMETER_NOT_FOUND`, `ENCRYPTION_KEY_REQUIRED`
89
+ - `EncryptResult` type - Return type for encrypt operations
90
+ - `EncryptionApi` class - API layer for controller communication
91
+ - `encryptionKey` config option - For server-side encryption key validation
92
+ - `MISO_ENCRYPTION_KEY` environment variable support in `loadConfig()`
93
+
94
+ ### Removed
95
+
96
+ - `EncryptionUtil` class - Use `client.encryption` instead
97
+
98
+ ### Technical
99
+
100
+ - **New files**: `src/api/encryption.api.ts`, `src/api/types/encryption.types.ts`, `src/services/encryption.service.ts`, `src/utils/encryption-error.ts`
101
+ - **Deleted files**: `src/express/encryption.ts`
102
+ - **Tests**: `tests/unit/api/encryption.api.test.ts`, `tests/unit/services/encryption.service.test.ts`
103
+
104
+ ## [3.9.0] - 2026-01-14
105
+
106
+ ### Added
107
+
108
+ - **Enhanced Filter System** - Comprehensive filter parsing, validation, and SQL compilation
109
+ - **Dual format parsing**: Support for both colon format (`status:eq:active`) and JSON format (`{"status":{"eq":"active"}}`)
110
+ - **Schema-based validation**: Define filterable fields, allowed operators, and value types per resource
111
+ - **Type coercion**: Automatic value validation and conversion for string, number, boolean, uuid, timestamp, and enum types
112
+ - **SQL compilation**: Generate PostgreSQL-safe parameterized WHERE clauses with `compileFilter()`
113
+ - **Human-readable errors**: RFC 7807 compliant structured error responses with error codes (UNKNOWN_FIELD, INVALID_OPERATOR, INVALID_TYPE, etc.)
114
+ - New `ilike` operator for case-insensitive pattern matching
115
+ - New types: `FilterSchema`, `FilterFieldDefinition`, `FilterError`, `CompiledFilter`
116
+ - New utilities: `validateFilter()`, `coerceValue()`, `compileFilter()`, `createFilterSchema()`
117
+ - Filter meta-schema for validating custom filter schemas (`src/schemas/filter.schema.json`)
118
+
119
+ ### Changed
120
+
121
+ - **Code Size Compliance** - Refactored large files to comply with 500-line guideline
122
+ - `data-client.ts`: 995 → 416 lines (extracted to helper modules)
123
+ - `data-client-request.ts`: 683 280 lines
124
+ - `data-client-auth.ts`: 654 290 lines
125
+ - `internal-http-client.ts`: 741 496 lines
126
+ - `auth.service.ts`: 825 462 lines
127
+ - `index.ts`: 681 472 lines
128
+ - `logger.service.ts`: 597 480 lines
129
+
130
+ - **Console Logging Audit** - Cleaned up debug logging
131
+ - Removed 10 debug `console.log` statements from `token-utils.ts` that could expose sensitive token data
132
+ - All remaining console calls are appropriate error/warning logs or guarded by debug checks
133
+
134
+ ### Technical
135
+
136
+ - **New filter utilities**: `src/utils/filter-schema.utils.ts` (497 lines), `src/utils/filter-colon.utils.ts` (119 lines)
137
+ - **New filter types**: `src/types/filter-schema.types.ts` (148 lines)
138
+ - **New helper modules** for DataClient refactoring:
139
+ - `data-client-init.ts` - Initialization logic
140
+ - `data-client-permissions.ts` - Permission helpers
141
+ - `data-client-roles.ts` - Role helpers
142
+ - `data-client-response.ts` - Response processing
143
+ - `data-client-oauth.ts` - OAuth callback handling
144
+ - **New HTTP helpers**: `http-error-handler.ts`, `http-response-validator.ts`
145
+ - **New auth helper**: `auth-error-handler.ts` - Centralized auth error formatting
146
+ - **New tests**: `filter-colon-format.test.ts` (178 lines), `filter-schema.utils.test.ts` (545 lines)
147
+ - **Documentation**: Updated `docs/reference-utilities.md` with filter system examples
148
+
149
+ ## [3.8.2] - 2026-01-12
150
+
151
+ ### Added
152
+
153
+ - **Keycloak Separate Private/Public URL Support** - Separate URLs for JWKS fetching and issuer validation
154
+ - New `authServerPrivateUrl` configuration option for server-side JWKS fetching (internal network)
155
+ - New `authServerPublicUrl` configuration option for browser-side and issuer validation (public network)
156
+ - New `resolveKeycloakUrl()` utility function that automatically detects environment and selects appropriate URL
157
+ - `validateTokenLocal()` now uses private URL for JWKS fetching on server, public URL for issuer validation
158
+ - Environment variable support: `KEYCLOAK_SERVER_URL` (maps to `authServerPrivateUrl`), `KEYCLOAK_PUBLIC_SERVER_URL` (maps to `authServerPublicUrl`)
159
+ - Maintains backward compatibility with existing `authServerUrl` configuration
160
+
161
+ ### Technical
162
+
163
+ - **TokenValidationService** - Now uses `resolveKeycloakUrl()` for automatic URL resolution
164
+ - JWKS URI construction uses resolved URL (private on server, public on browser)
165
+ - Issuer validation always uses public URL (matches token's `iss` claim)
166
+ - `determineTokenType()` updated to use public URL for issuer matching
167
+ - **controller-url-resolver.ts** - Added `resolveKeycloakUrl()` function (mirrors `resolveControllerUrl()` pattern)
168
+ - **config-loader.ts** - Added Keycloak environment variable support
169
+ - **Tests**: Comprehensive tests for `resolveKeycloakUrl()` and updated TokenValidationService tests
170
+
171
+ ## [3.8.1] - 2026-01-10
172
+
173
+ ### Changed
174
+
175
+ - **Unified Application Context Service** - Centralized application and environment extraction
176
+ - New `ApplicationContextService` class to extract `application`, `applicationId`, and `environment` with consistent fallback logic
177
+ - Extracts from client token first (if available), then falls back to parsing `miso-controller-{environment}-{application}` format from clientId
178
+ - RoleService, PermissionService, LoggerService, and UnifiedLoggerService now use the unified service
179
+ - Reduces code duplication and ensures consistent behavior across all services
180
+ - Caches parsed results to avoid repeated extraction
181
+
182
+ ### Fixed
183
+
184
+ - **Logger Context Application Fallback** - Fixed application fallback to use clientId when parsing fails
185
+ - Logger getter methods (`getLogWithRequest`, `getWithContext`, `getWithToken`) now properly fall back to `clientId` when `application` cannot be extracted from client token or parsed from clientId format
186
+ - Ensures application field is always populated in log entries, even when clientId format doesn't match expected pattern
187
+
188
+ ### Technical
189
+
190
+ - **New service**: `src/services/application-context.service.ts` - Unified application context extraction (175 lines)
191
+ - **Test coverage**: Comprehensive tests in `tests/unit/application-context.service.test.ts` (323 lines, 100% coverage)
192
+ - **Code quality**: All services updated to use ApplicationContextService, reducing code duplication by ~50 lines
193
+
194
+ ## [3.8.0] - 2026-01-10
195
+
196
+ ### Added
197
+
198
+ - **Unified Logging Interface**: New minimal API with automatic context extraction
199
+ - `getLogger()` factory function for automatic context detection from AsyncLocalStorage
200
+ - `setLoggerContext()` and `clearLoggerContext()` for manual context management
201
+ - `loggerContextMiddleware` Express middleware helper for automatic request context extraction
202
+ - AsyncLocalStorage-based context propagation across async boundaries
203
+ - Simplified API: `logger.info(message)`, `logger.error(message, error?)`, `logger.audit(action, resource, entityId?, oldValues?, newValues?)`
204
+ - Automatic context extraction from AsyncLocalStorage (set by Express middleware or manually)
205
+ - Works seamlessly in Express routes, service layers, and background jobs
206
+ - Zero configuration required when middleware is used
207
+
208
+ ### Documentation
209
+
210
+ - Added unified logging examples and guides (`docs/examples/unified-logging.md`)
211
+ - Updated Express middleware examples with unified logging pattern
212
+ - Added background job logging examples with unified interface
213
+ - Comprehensive API reference for UnifiedLogger interface in `docs/reference-services.md`
214
+
215
+ ## [3.7.2] - 2026-01-10
216
+
217
+ ### Added
218
+
219
+ - **Comprehensive Integration Tests** - Full end-to-end integration tests for Auth and Logs API endpoints
220
+ - New `tests/integration/api-endpoints.integration.test.ts` with comprehensive endpoint coverage
221
+ - Tests all Auth and Logs endpoints against real controller using credentials from `.env`
222
+ - Validates endpoint paths, HTTP methods, request bodies, and response structures against OpenAPI specs
223
+ - Tests error cases (invalid tokens, missing params, etc.) with proper status code verification
224
+ - Gracefully skips tests if controller is unavailable (CI/CD friendly)
225
+ - New npm script `test:integration:api` for running integration tests
226
+
227
+ ### Changed
228
+
229
+ - **Logger Service Refactoring** - Improved code organization and maintainability
230
+ - Moved logger service to modular structure in `src/services/logger/` directory
231
+ - Split `LoggerService` into focused modules: `logger-chain.ts`, `logger-context.ts`, `logger.service.ts`
232
+ - New barrel export `src/services/logger/index.ts` for cleaner imports
233
+ - Maintains backward compatibility (no breaking changes to public API)
234
+
235
+ - **Error Handling Improvements** - Enhanced error handling across API layer
236
+ - Updated error handling in integration tests to gracefully skip unavailable controllers
237
+ - Improved error reporting and logging throughout API files
238
+ - Enhanced user information retrieval functionality
239
+
240
+ - **Code Quality Improvements** - Refactoring for better readability and maintainability
241
+ - Updated various components for improved logging and error reporting
242
+ - Enhanced API response handling and validation
243
+ - Improved code organization and structure
244
+
245
+ ### Fixed
246
+
247
+ - **Linting Issues** - Fixed ESLint errors in internal HTTP client
248
+ - Converted `require()` statements to use ESLint disable comments for Node.js-only code
249
+ - Fixed `@typescript-eslint/no-var-requires` errors in `src/utils/internal-http-client.ts`
250
+
251
+ ### Technical
252
+
253
+ - **New test infrastructure**:
254
+ - Comprehensive integration test suite (`tests/integration/api-endpoints.integration.test.ts` - 554 lines)
255
+ - New npm script: `test:integration:api` for running integration tests
256
+ - Enhanced validation plans and summaries for API calls
257
+
258
+ - **Code organization**:
259
+ - Logger service modularized into `src/services/logger/` directory structure
260
+ - Improved separation of concerns with focused modules
261
+ - Better code maintainability and testability
262
+
263
+ - **Documentation**:
264
+ - Added endpoint validation summary documentation
265
+ - Updated validation plans for API calls
266
+
267
+ ## [3.7.1] - 2026-01-09
268
+
269
+ ### Added
270
+
271
+ - **Enhanced Error Logging with Correlation IDs** - Comprehensive error logging system with structured error extraction
272
+ - New `extractErrorInfo()` utility in `src/utils/error-extractor.ts` for structured error information extraction
273
+ - New `logErrorWithContext()` utility in `src/utils/console-logger.ts` for enhanced console logging with correlation ID prefixes
274
+ - Supports all error types: `MisoClientError`, `ApiError`, `AuthenticationError`, `NetworkError`, `TimeoutError`, and generic `Error`
275
+ - Automatic correlation ID extraction from error responses or auto-generation when missing
276
+ - Enhanced error context includes endpoint, method, status codes, response bodies, and stack traces
277
+ - All API files updated with structured error logging (11 API files enhanced)
278
+ - DataClient and Express error handlers updated with enhanced logging
279
+
280
+ - **Logger Service Getter Methods** - Public methods for external logger integration
281
+ - New `getLogWithRequest()` method - Extracts IP, method, path, userAgent, correlationId, userId from Express Request
282
+ - New `getWithContext()` method - Returns LogEntry with provided context and auto-generated correlation ID
283
+ - New `getWithToken()` method - Extracts userId, sessionId, applicationId from JWT token
284
+ - New `getForRequest()` method - Alias for `getLogWithRequest()` for consistency
285
+ - All methods return complete `LogEntry` objects for integration with external logger tables
286
+ - `generateCorrelationId()` method made public for consistent correlation ID generation
287
+
288
+ - **Unified JSON Filter Model** - Standardized JSON format for all filter representations
289
+ - New filter operators: `isNull` and `isNotNull` for null/undefined checks
290
+ - JSON format parser supports multiple input formats: direct object, JSON string, URL-encoded JSON, array of filters
291
+ - Operator normalization (e.g., `equals` `eq`, `>` `gt`)
292
+ - Comprehensive validation with clear error messages and examples
293
+ - Filter conversion utilities: `filterQueryToJson()` and `jsonToFilterQuery()`
294
+ - Query string builder outputs URL-encoded JSON format
295
+ - Local filtering supports null checks with `isNull` and `isNotNull` operators
296
+
297
+ - **Server Code Improvements** - Enhanced Express server error handling and logging
298
+ - Replaced all `console.log/error/warn` with MisoClient logger service
299
+ - All route handlers wrapped with `asyncHandler()` wrapper for automatic error handling
300
+ - Error middleware uses `handleRouteError()` from SDK for RFC 7807 compliance
301
+ - Error logger configured with MisoClient logger via `setErrorLogger()`
302
+ - All business logic errors use `AppError` for consistent error formatting
303
+ - Automatic correlation ID extraction and error logging with full context
304
+
305
+ - **Frontend Code Improvements** - Enhanced React application error handling and code quality
306
+ - Centralized error handling utilities (`src/utils/error-handler.ts`)
307
+ - Centralized type definitions (`src/types/errors.ts`, `src/types/api.ts`)
308
+ - Input validation utilities (`src/utils/validation.ts`) for role names, permission names, endpoints
309
+ - Component refactoring: ApiTestingPage reduced from 589 to 79 lines (87% reduction)
310
+ - New custom hooks: `useApiTesting` for API testing logic, `useLoadingState` for loading state management
311
+ - Improved DataClientContext with retry logic and exponential backoff
312
+ - Simplified ErrorDetailsDialog component (115 lines, reduced from 193)
313
+
314
+ - **Comprehensive Integration Tests** - Real integration tests for all auth and logs endpoints
315
+ - New `tests/integration/api-endpoints.integration.test.ts` with comprehensive endpoint coverage
316
+ - Tests all 24 auth endpoints against real controller using credentials from `.env`
317
+ - Tests all 15 logs endpoints with proper request/response validation
318
+ - Validates endpoint paths, HTTP methods, request bodies, and response structures against OpenAPI specs
319
+ - Tests error cases (invalid tokens, missing params, etc.) with proper status code verification
320
+ - Gracefully skips tests if controller is unavailable (CI/CD friendly)
321
+ - New npm script `test:integration:api` for running integration tests
322
+
323
+ - **Logger Service Refactoring** - Improved code organization and maintainability
324
+ - Split `LoggerService` into modular structure following API layer pattern
325
+ - New `src/services/logger/logger-chain.ts` - LoggerChain class for method chaining
326
+ - New `src/services/logger/logger-context.ts` - Context extraction utilities (JWT, metadata, request)
327
+ - New `src/services/logger/index.ts` - Barrel export for logger modules
328
+ - Reduced main `logger.service.ts` from 866 lines to under 500 lines (code size compliance)
329
+ - Maintains backward compatibility (no breaking changes to public API)
330
+
331
+ ### Changed
332
+
333
+ - **Error Logging** - Enhanced error logging across all API layer files
334
+ - All API files now use `extractErrorInfo()` and `logErrorWithContext()` for structured error logging
335
+ - Error logs include correlation ID prefixes: `[MisoClient] [correlation-id] Error details`
336
+ - Authentication errors have special handling with detailed context (authFlow: 'token_validation_failed')
337
+ - Enhanced audit logs include structured error info (errorType, errorCategory, httpStatusCategory)
338
+
339
+ - **Filter Parsing** - Unified JSON format replaces colon-separated format
340
+ - Filter parser now accepts JSON format only: `{"field": {"op": value}}`
341
+ - Supports 12 operators: `eq`, `neq`, `in`, `nin`, `gt`, `lt`, `gte`, `lte`, `contains`, `like`, `isNull`, `isNotNull`
342
+ - FilterBuilder outputs JSON format (URL-encoded) in query strings
343
+ - Comprehensive validation with helpful error messages including examples
344
+
345
+ - **Server Error Handling** - Standardized error handling patterns
346
+ - All route handlers use `asyncHandler()` wrapper (no manual try-catch needed)
347
+ - All errors automatically formatted as RFC 7807 Problem Details
348
+ - Error logger uses MisoClient logger with `forRequest()` for automatic context extraction
349
+ - Consistent error responses across all routes with correlation IDs
350
+
351
+ - **Frontend Error Handling** - Centralized error handling patterns
352
+ - All components use shared error handling utilities
353
+ - RFC 7807 compliant error parsing with `parseError()` utility
354
+ - Consistent error message extraction with `getErrorMessage()` and `getErrorStatus()`
355
+ - Input validation integrated into authorization testing hooks
356
+
357
+ - **API Layer Cleanup** - Removed duplicate code and improved code quality
358
+ - Removed duplicate roles/permissions methods from `AuthApi` class
359
+ - Removed `getRoles()`, `refreshRoles()`, `getPermissions()`, `refreshPermissions()` from `AuthApi`
360
+ - Services now use dedicated `RolesApi` and `PermissionsApi` classes (DRY principle)
361
+ - Removed unused endpoint constants and type imports from `AuthApi`
362
+ - Updated class JSDoc to reflect removed methods
363
+
364
+ - **Error Handling Improvements** - Fixed duplicate throw statements across API layer
365
+ - Removed duplicate `throw error;` statements from `auth.api.ts`, `roles.api.ts`, `permissions.api.ts`
366
+ - Fixed duplicate throws in `logs-create.api.ts` and `logs-list.api.ts`
367
+ - Improved error handling consistency across all API files
368
+
369
+ ### Fixed
370
+
371
+ - **Server Error Handling** - Fixed logic bug in server.ts (dead code removed)
372
+ - **Server Logging** - Fixed inconsistent logging format (now uses MisoClient logger)
373
+ - **Server Error Responses** - Fixed non-RFC 7807 error responses (now uses `handleRouteError()`)
374
+ - **Frontend Component Size** - Fixed large component files exceeding 500-line limit
375
+ - ApiTestingPage: 589 79 lines (87% reduction)
376
+ - ConfigurationPage: 382 283 lines (26% reduction)
377
+ - **Frontend Error Handling** - Fixed duplicate error handling logic across components
378
+ - **Frontend Type Safety** - Fixed loose error typing with centralized type definitions
379
+ - **Code Size Compliance** - Fixed logger service file size violation
380
+ - Refactored `LoggerService` from 866 lines to under 500 lines
381
+ - Split into focused modules: logger-chain.ts, logger-context.ts, index.ts
382
+ - Maintains all functionality while improving maintainability
383
+ - **API Endpoint Validation** - Validated all endpoints against OpenAPI specifications
384
+ - Verified all 24 auth endpoints match OpenAPI spec paths and HTTP methods
385
+ - Verified all 15 logs endpoints match OpenAPI spec with proper request/response structures
386
+ - Confirmed audit logs include required fields (entityType, entityId, action) in data object
387
+ - Validated client token endpoints use correct paths (`/api/v1/auth/token` for legacy, `/api/v1/auth/client-token` for frontend)
388
+
389
+ ### Technical
390
+
391
+ - **New utility files**:
392
+ - `src/utils/error-extractor.ts` - Error extraction utility (172 lines)
393
+ - `src/utils/console-logger.ts` - Enhanced console logger (72 lines)
394
+ - `src/utils/error-handler.ts` - Frontend error handling utilities (175 lines)
395
+ - `src/utils/validation.ts` - Frontend input validation utilities (139 lines)
396
+ - `src/types/errors.ts` - Frontend error type definitions (25 lines)
397
+ - `src/types/api.ts` - Frontend API type definitions (63 lines)
398
+
399
+ - **Test coverage**:
400
+ - Error extraction utility: 18 tests (`tests/unit/utils/error-extractor.test.ts`)
401
+ - Console logger utility: 12 tests (`tests/unit/utils/console-logger.test.ts`)
402
+ - Logger getter methods: 31 tests (`tests/unit/services/logger-getter-methods.test.ts`)
403
+ - Filter utilities: 68 tests (`tests/unit/filter.utils.test.ts`)
404
+ - Frontend error handler: 21 tests (`server/frontend/src/utils/__tests__/error-handler.test.ts`)
405
+ - Frontend validation: 43 tests (`server/frontend/src/utils/__tests__/validation.test.ts`)
406
+ - Integration tests: Comprehensive tests for all 39 endpoints (`tests/integration/api-endpoints.integration.test.ts`)
407
+ - Total: 193+ new tests added, all passing
408
+
409
+ - **New logger module structure**:
410
+ - `src/services/logger/logger-chain.ts` - LoggerChain class (method chaining support)
411
+ - `src/services/logger/logger-context.ts` - Context extraction utilities
412
+ - `src/services/logger/index.ts` - Barrel export
413
+ - `src/services/logger.service.ts` - Core LoggerService class (reduced to <500 lines)
414
+
415
+ - **Code quality**:
416
+ - All new utilities follow camelCase naming convention
417
+ - All public methods have JSDoc comments with parameter types, return types, and examples
418
+ - File sizes within limits (all files ≤500 lines)
419
+ - Method sizes within limits (all methods ≤30 lines)
420
+ - Zero linting errors or warnings
421
+ - Proper error handling with try-catch for all async operations
422
+ - Removed duplicate code (roles/permissions methods from AuthApi)
423
+ - Fixed duplicate throw statements across API layer
424
+ - All endpoints validated against OpenAPI specs
425
+
426
+ - **Documentation**:
427
+ - Updated `docs/reference-services.md` with logger getter methods documentation
428
+ - Updated `docs/reference-utilities.md` with filter JSON format examples
429
+ - Updated `server/README.md` with factory function pattern and error logger configuration
430
+ - Updated `docs/examples/express-middleware.md` with error logger configuration examples
431
+ - Updated `AuthApi` class JSDoc to remove references to removed methods
432
+ - Added integration test documentation explaining test structure and requirements
433
+
434
+ ## [3.6.0] - 2024-12-31
435
+
436
+ ### Added
437
+
438
+ - **API Response Validation** - Runtime validation for API response structures
439
+ - New `validateSuccessResponse<T>()` type guard for standard success responses
440
+ - New `validatePaginatedResponse<T>()` type guard for paginated responses
441
+ - New `validateErrorResponse()` type guard for error responses (re-exports existing validation)
442
+ - New `getResponseType()` utility to determine response type (success, paginated, error)
443
+ - Response validation utilities in `src/utils/response-validator.ts` with comprehensive type guards
444
+ - All validation functions use TypeScript type guards for proper type narrowing
445
+ - Detailed validation error messages for debugging response structure mismatches
446
+
447
+ - **Response Validation Configuration** - Configurable validation control
448
+ - New `validateResponses?: boolean` configuration option in `MisoClientConfig`
449
+ - Environment variable support: `MISO_VALIDATE_RESPONSES` (defaults to `true` in development, `false` in production)
450
+ - Validation is opt-in and backward compatible (doesn't break existing code)
451
+ - Non-breaking validation failures (logs warnings instead of throwing errors)
452
+
453
+ ### Changed
454
+
455
+ - **HTTP Client Response Validation** - Enhanced HTTP client with response structure validation
456
+ - `InternalHttpClient` now validates all API responses when `validateResponses` is enabled
457
+ - All HTTP methods (`get`, `post`, `put`, `delete`, `request`, `authenticatedRequest`) validate responses
458
+ - Validation checks for standard success response format: `{ success: boolean, data?: T, message?: string, timestamp: string }`
459
+ - Validation checks for paginated response format: `{ data: T[], meta: {...}, links: {...} }`
460
+ - Validation handles both nested and flat response formats (backward compatibility)
461
+ - Validation failures log warnings with endpoint URL, expected structure, and actual response
462
+ - Graceful error handling - validation failures don't break existing functionality
463
+
464
+ ### Fixed
465
+
466
+ - **Circuit breaker priority** - Fixed critical ordering issue where circuit breaker check now occurs before cache check
467
+ - Circuit breaker check moved before cache and pending request checks to prevent requests to failing endpoints
468
+ - Ensures failed endpoints are blocked even if cache is cleared, preventing unnecessary API calls during failures
469
+ - Improved error consistency by using `throw` instead of `Promise.reject()` for circuit breaker errors
470
+
471
+ - **Cache key generation** - Fixed cache key generation to ensure HTTP method is always included
472
+ - Cache key now explicitly includes HTTP method from method parameter to ensure consistency
473
+ - Prevents potential cache key collisions when method might be undefined in options
474
+ - Ensures proper cache key generation for all HTTP methods (GET, POST, PUT, DELETE, etc.)
475
+
476
+ ### Technical
477
+
478
+ - **New utility file**: `src/utils/response-validator.ts` - Response validation utilities (174 lines)
479
+ - Type guard functions for runtime type checking
480
+ - Support for success, paginated, and error response formats
481
+ - Comprehensive JSDoc documentation for all public functions
482
+ - Proper TypeScript type narrowing with type guards
483
+
484
+ - **Test coverage**:
485
+ - Comprehensive tests in `tests/unit/utils/response-validator.test.ts` (413 lines)
486
+ - 36 test cases covering valid/invalid responses, edge cases, and backward compatibility
487
+ - Test coverage: **96.53%** (exceeds ≥80% requirement)
488
+ - Statements: 96.53% (167/173)
489
+ - Branches: 91.83% (45/49)
490
+ - Functions: 100% (4/4)
491
+ - Lines: 96.53% (167/173)
492
+ - All tests passing with execution time < 0.5 seconds
493
+
494
+ - **Configuration updates**:
495
+ - Added `validateResponses?: boolean` to `MisoClientConfig` interface
496
+ - Added `MISO_VALIDATE_RESPONSES` environment variable support in config loader
497
+ - Defaults to `true` in development, `false` in production for performance
498
+
499
+ - **Code quality**:
500
+ - All validation functions follow camelCase naming convention
501
+ - All public functions have JSDoc comments with parameter types and return types
502
+ - File size: 174 lines (≤500 lines requirement met)
503
+ - Method sizes: ≤30 lines (≤20-30 lines requirement met)
504
+ - Zero linting errors or warnings
505
+ - Proper error handling with try-catch for all async operations
506
+
507
+ ## [3.4.1] - 2025-12-30
508
+
509
+ ### Fixed
510
+
511
+ - **Token validation caching** - Improved caching strategy for token validation
512
+ - Enhanced cache key generation using SHA-256 hash of token for security
513
+ - Smart TTL calculation based on token expiration with safety buffer
514
+ - Minimum TTL enforcement to prevent excessive API calls
515
+ - Better cache invalidation handling
516
+
517
+ ### Changed
518
+
519
+ - **Error handling** - Enhanced error handling and logging for token retrieval
520
+ - Added detailed error responses for timeout scenarios in client token endpoint
521
+ - Updated AuthService to use shorter timeout for axios requests (aligns with handler timeout)
522
+ - Improved logging for token retrieval processes with controller URL details
523
+ - Integrated controller URL resolution in environment token utility for consistent URL handling
524
+
525
+ ### Technical
526
+
527
+ - **Dependencies** - Updated dependencies and improved linting configuration
528
+ - Removed unnecessary "peer" flags from package-lock.json
529
+ - Updated linting scripts to ignore declaration files for better efficiency
530
+ - Updated package dependencies for improved functionality and performance
531
+
532
+ ## [3.4.0] - 2025-12-24
533
+
534
+ ### Added
535
+
536
+ - **Local Token Validation** - JWKS-based JWT validation without API calls
537
+ - New `validateTokenLocal()` method for local JWT signature verification
538
+ - Supports Keycloak tokens and delegated OAuth provider tokens
539
+ - Dual-layer caching: JWKS keys (1 hour) + validation results (1 minute)
540
+ - `skipResultCache` option for high-security scenarios
541
+ - Auto-detection of token type based on issuer claim
542
+ - New `TokenValidationService` exported for advanced usage
543
+
544
+ - **Keycloak Configuration** - Native Keycloak integration
545
+ - New `keycloak` config option in `MisoClientConfig`
546
+ - `setKeycloakConfig()` method for runtime configuration
547
+ - Audience validation support (opt-in via `verifyAudience`)
548
+
549
+ - **Cache Management** - Fine-grained cache control
550
+ - `clearJwksCache(uri?)` - Clear JWKS key cache
551
+ - `clearValidationCache()` - Clear validation result cache
552
+ - `clearAllTokenCaches()` - Clear all caches
553
+
554
+ ### Changed
555
+
556
+ - **Package Distribution** - Added CHANGELOG.md to npm package files
557
+
558
+ ### Dependencies
559
+
560
+ - Added `jose` ^5.9.6 for JWT/JWKS operations
561
+
562
+ ## [3.3.0] - 2025-12-23
563
+
564
+ ### Added
565
+
566
+ - **Centralized API layer** - Typed interfaces for all controller API calls
567
+ - New API layer in `src/api/` with domain-specific API classes (`AuthApi`, `RolesApi`, `PermissionsApi`, `LogsApi`)
568
+ - `ApiClient` class wraps `HttpClient` and organizes APIs by domain
569
+ - Centralized endpoint URLs as constants in each API class for maintainability
570
+ - All API request/response types use interfaces (not types) with camelCase naming convention
571
+ - Services can optionally use `ApiClient` instead of direct `HttpClient` calls (gradual migration pattern)
572
+ - Improved type safety and code organization for controller API interactions
573
+ - API classes are composed from specialized sub-modules to keep file sizes manageable
574
+
575
+ ### Changed
576
+
577
+ - **Token validation enhancements** - Improved token acceptance criteria
578
+ - Updated token validation logic to accept both JWT and non-JWT token formats
579
+ - Enhanced validation to ensure tokens are non-empty and of reasonable length
580
+ - Improved error handling for token validation failures
581
+ - Updated unit tests to reflect changes in token acceptance criteria
582
+
583
+ - **OAuth callback handling** - Enhanced error feedback
584
+ - Updated error handling in `handleOAuthCallback()` to provide clearer feedback on token validation failures
585
+ - Improved documentation for token validation and OAuth handling
586
+
587
+ - **Service dependencies** - Optional API client support
588
+ - Services can now optionally include `ApiClient` for typed API access
589
+ - Allows for gradual migration from direct `HttpClient` usage to typed API layer
590
+ - Maintains backward compatibility with existing service implementations
591
+
592
+ ### Technical
593
+
594
+ - **New API layer structure**:
595
+ - `src/api/index.ts` - Main `ApiClient` class
596
+ - `src/api/auth.api.ts` - Authentication API (composed from sub-modules)
597
+ - `src/api/roles.api.ts` - Roles API
598
+ - `src/api/permissions.api.ts` - Permissions API
599
+ - `src/api/logs.api.ts` - Logs API
600
+ - `src/api/types/` - API request/response type definitions
601
+
602
+ - **Test coverage**:
603
+ - Updated mock patterns to include `ApiClient` for testing purposes
604
+ - Enhanced unit tests for token validation with new acceptance criteria
605
+
606
+ - **Documentation**:
607
+ - Added API layer pattern documentation to project rules
608
+ - Updated usage examples to demonstrate API layer pattern
609
+ - Enhanced documentation for token validation and OAuth handling
610
+
611
+ ## [3.2.5] - 2025-12-22
612
+
613
+ ### Added
614
+
615
+ - **Indexed logging fields** - Standardized indexed fields for improved query performance and observability
616
+ - New `extractLoggingContext()` utility function in `src/utils/logging-helpers.ts`
617
+ - Added indexed context fields to `LogEntry` interface: `sourceKey`, `sourceDisplayName`, `externalSystemKey`, `externalSystemDisplayName`, `recordKey`, `recordDisplayName`
618
+ - Added credential context fields: `credentialId`, `credentialType`
619
+ - Added request/response metrics: `requestSize`, `responseSize`, `durationMs`
620
+ - Added error classification fields: `errorCategory`, `httpStatusCategory`
621
+ - New `LoggerChain` methods: `withIndexedContext()`, `withCredentialContext()`, `withRequestMetrics()`
622
+ - Exported types: `IndexedLoggingContext`, `HasKey`, `HasExternalSystem`
623
+ - Improves query performance and root-cause analysis for audit logs
624
+
625
+ - **Request context auto-extraction** - Automatic extraction of logging context from Express Request objects
626
+ - New `extractRequestContext()` utility function in `src/utils/request-context.ts`
627
+ - New `withRequest()` method on `LoggerChain` for automatic context extraction
628
+ - New `forRequest()` method on `LoggerService` for request-based logging
629
+ - Automatically extracts: IP address, HTTP method, path, user-agent, correlation ID, user from JWT, session ID, request ID
630
+ - Handles proxy IPs via `x-forwarded-for` header
631
+ - Reduces logging code from 10-15 lines to 2-3 lines per log call
632
+ - Exported `RequestContext` interface and `extractRequestContext` function
633
+
634
+ - **Token validation caching** - Caching for token validation to reduce API calls
635
+ - Cache validation results by userId with 15-minute TTL (configurable via `config.cache?.tokenValidationTTL`)
636
+ - Cache key format: `token:${userId}` (consistent with roles/permissions caching)
637
+ - Automatic cache invalidation on logout (clears cache even if logout returns 400)
638
+ - New `clearTokenCache()` method in `AuthService` for manual cache clearing
639
+ - Extracts userId from JWT token before API call (avoids unnecessary validate API call)
640
+ - Graceful fallback to API call on cache failures
641
+ - Uses `CacheService` instead of `RedisService` for consistency
642
+
643
+ - **User token refresh** - Token refresh functionality for secure token renewal
644
+ - New `refreshToken()` method in `AuthService` for backend applications
645
+ - New `onTokenRefresh` callback support in `DataClient` for frontend applications
646
+ - Automatic token refresh on 401 errors in DataClient with retry logic
647
+ - New `RefreshTokenResponse` interface with `accessToken`, `refreshToken`, `expiresIn`, `expiresAt`
648
+ - Exposed `refreshToken()` method in `MisoClient` class
649
+ - Prevents infinite retry loops with `tokenRefreshAttempted` flag
650
+ - Refresh tokens never stored in browser localStorage (security requirement)
651
+
652
+ - **OAuth callback handler** - ISO 27001 compliant OAuth callback handling with hash fragments
653
+ - New `handleOAuthCallback()` function in `src/utils/data-client-auth.ts`
654
+ - New `handleOAuthCallback()` method in `DataClient` class
655
+ - Extracts tokens from URL hash fragments (`#token=...`) instead of query parameters
656
+ - Immediate hash cleanup (< 100ms) to prevent token exposure
657
+ - Token format validation (JWT format check)
658
+ - HTTPS enforcement in production environments
659
+ - Supports multiple parameter names: `token`, `access_token`, `accessToken`
660
+ - Auto-calls on DataClient initialization in browser environments
661
+ - Secure error handling without exposing tokens
662
+
663
+ ### Changed
664
+
665
+ - **LoggerService enhancements** - Enhanced logging capabilities with indexed fields
666
+ - Updated `ClientLoggingOptions` interface with indexed context fields
667
+ - Updated `LogEntry` interface with indexed fields for fast queries
668
+ - Enhanced `LoggerChain` fluent API with new context methods
669
+ - Improved developer experience with automatic request context extraction
670
+
671
+ - **AuthService improvements** - Enhanced authentication service with caching
672
+ - Updated constructor to accept `CacheService` instead of `RedisService`
673
+ - Added `extractUserIdFromToken()` private method for JWT extraction
674
+ - Enhanced `validateToken()` method with caching logic
675
+ - Updated `logout()` method to clear token cache on logout
676
+
677
+ - **DataClient enhancements** - Improved token refresh and OAuth handling
678
+ - Added `refreshUserToken()` private method for token refresh
679
+ - Enhanced 401 error handling with automatic token refresh and retry
680
+ - Updated `redirectToLogin()` documentation for hash fragment flow
681
+ - Improved OAuth callback handling with security measures
682
+
683
+ ### Fixed
684
+
685
+ - **Token validation performance** - Reduced API calls through caching
686
+ - Token validation now uses cache to avoid unnecessary controller API calls
687
+ - Cache hit significantly improves performance for repeated validations
688
+
689
+ - **OAuth security** - Improved security for OAuth callback flow
690
+ - Tokens extracted from hash fragments (not sent to server, not in logs)
691
+ - Immediate cleanup prevents token exposure in address bar
692
+ - HTTPS enforcement prevents token transmission over HTTP in production
693
+
694
+ ### Technical
695
+
696
+ - **New utility files**:
697
+ - `src/utils/logging-helpers.ts` - Logging context extraction utility (91 lines)
698
+ - `src/utils/request-context.ts` - Request context extraction utility (102 lines)
699
+
700
+ - **Test coverage**:
701
+ - Comprehensive tests for logging helpers (15 tests)
702
+ - Comprehensive tests for request context extraction (33 tests)
703
+ - Enhanced tests for token caching (80 tests total in auth.service.test.ts)
704
+ - Comprehensive tests for token refresh (17 AuthService + 15 DataClient tests)
705
+ - Comprehensive tests for OAuth callback handler (34 tests)
706
+
707
+ - **Type definitions**:
708
+ - Added `RefreshTokenResponse` interface to `src/types/config.types.ts`
709
+ - Added `tokenValidationTTL?: number` to cache config type
710
+ - Added `onTokenRefresh` callback to `DataClientConfig` interface
711
+
712
+ - **Exports updated**:
713
+ - `src/index.ts` - Exports `extractLoggingContext`, `IndexedLoggingContext`, `HasKey`, `HasExternalSystem`
714
+ - `src/index.ts` - Exports `extractRequestContext`, `RequestContext`
715
+ - `src/index.ts` - Exports `refreshToken()` method in `MisoClient`
716
+
717
+ ## [3.2.0] - 2025-12-22
718
+
719
+ ### Added
720
+
721
+ - **Circuit breaker for HTTP logging** - Prevents infinite retry loops when logging service is unavailable
722
+ - Added circuit breaker pattern to `LoggerService` and `AuditLogQueue`
723
+ - Automatically disables HTTP logging after 3 consecutive failures
724
+ - Circuit breaker opens for 60 seconds after failures, then resets
725
+ - Prevents performance degradation when controller logging endpoint is unavailable
726
+ - Gracefully handles network errors and server unavailability
727
+
728
+ - **DataClient redirect utilities** - Comprehensive redirect handling for login flows
729
+ - New `data-client-redirect.ts` utility module with robust redirect logic
730
+ - Enhanced `redirectToLogin()` with comprehensive error handling
731
+ - URL validation prevents dangerous redirects (javascript:, data:, etc.)
732
+ - User-friendly error messages for network, CORS, and authentication errors
733
+ - Proper timeout handling (30 seconds) to prevent hanging requests
734
+ - Only redirects when controller returns valid login URL (no fallback redirects on error)
735
+ - Supports both nested (`data.loginUrl`) and flat (`loginUrl`) response formats
736
+
737
+ - **Client token expiration checking** - Enhanced token validation with JWT expiration support
738
+ - Improved `getClientToken()` to check JWT expiration claims when expiration timestamp is missing
739
+ - Decodes JWT tokens to extract `exp` claim for expiration validation
740
+ - Better logging for debugging token expiration issues
741
+ - Handles missing expiration timestamps gracefully
742
+ - Automatically removes expired tokens from cache
743
+
744
+ - **Auto-initialization improvements** - New utility for accessing cached configuration
745
+ - New `getCachedDataClientConfig()` function exported from `src/index.ts`
746
+ - Allows reading cached DataClient configuration without re-initializing
747
+ - Useful for accessing configuration values in application code
748
+ - Returns cached config or null if not found or expired
749
+
750
+ - **Controller URL validation utility** - Exported URL validation function
751
+ - `validateUrl()` function now exported from `controller-url-resolver.ts`
752
+ - Validates HTTP/HTTPS URLs with comprehensive JSDoc documentation
753
+ - Useful for validating URLs before use in application code
754
+ - Exported from `src/index.ts` for public use
755
+
756
+ ### Changed
757
+
758
+ - **Documentation restructure** - Improved documentation organization and clarity
759
+ - New reference documentation structure with dedicated files for each major component
760
+ - Added `docs/reference-authentication.md` - Comprehensive authentication guide
761
+ - Added `docs/reference-authorization.md` - RBAC and permissions documentation
762
+ - Added `docs/reference-dataclient.md` - Complete DataClient API reference
763
+ - Added `docs/reference-errors.md` - Error handling and troubleshooting guide
764
+ - Added `docs/reference-misoclient.md` - MisoClient API reference
765
+ - Added `docs/reference-services.md` - Service layer documentation
766
+ - Added `docs/reference-types.md` - TypeScript type definitions reference
767
+ - Added `docs/reference-utilities.md` - Utility functions documentation
768
+ - Enhanced examples with improved clarity and error handling
769
+ - Updated all example files with corrected import paths
770
+
771
+ - **DataClient enhancements** - Improved robustness and developer experience
772
+ - Enhanced DataClient configuration and performance optimizations
773
+ - Improved authorization examples and documentation
774
+ - Better error handling in example code
775
+
776
+ - **Audit logging error handling** - Improved handling of network errors in audit logging
777
+ - Enhanced error detection for network errors (ECONNREFUSED, ENOTFOUND, ERR_CONNECTION_REFUSED)
778
+ - Silently skips audit logging for expected network errors (server unavailable, misconfigured)
779
+ - Prevents error noise in development and demo environments
780
+ - Better error classification and handling
781
+
782
+ ### Fixed
783
+
784
+ - **DataClient metrics** - Fixed handling of missing response times in metrics
785
+ - Modified `getMetrics()` method to handle cases where `responseTimes` may be undefined
786
+ - Ensures robust performance metrics retrieval without errors
787
+
788
+ - **Example imports** - Fixed import paths in all example files
789
+ - Updated example imports for clarity and proper error handling
790
+ - Corrected script source references in demo applications
791
+
792
+ - **Cache service test handling** - Fixed cleanup interval keeping process alive in tests
793
+ - Added `unref()` to cleanup interval in `CacheService` to prevent tests from hanging
794
+ - Ensures Node.js process can exit cleanly after tests complete
795
+ - Important for CI/CD environments and test suites
796
+
797
+ ### Removed
798
+
799
+ - **Performance logging** - Removed deprecated performance logging functionality
800
+ - Eliminated all performance logging code from the codebase
801
+ - Removed PerformanceMetrics interface and related methods
802
+ - Removed performance tracking logic from logger service
803
+ - Functionality replaced by OpenTelemetry integration
804
+
805
+ ### Technical
806
+
807
+ - **Code quality improvements** - Enhanced development workflow and configuration
808
+ - Updated ESLint and Jest configurations for improved testing and code quality
809
+ - Enhanced configuration files and scripts for better development workflow
810
+ - Improved .gitignore patterns
811
+ - Updated package.json for testing enhancements
812
+
813
+ - **New utility file**: `src/utils/data-client-redirect.ts` - Comprehensive redirect handling
814
+ - Extracted redirect logic from DataClient into dedicated utility module
815
+ - 424 lines of robust redirect handling with comprehensive error handling
816
+ - URL validation, timeout handling, and user-friendly error messages
817
+ - Proper separation of concerns for better maintainability
818
+
819
+ ## [3.1.2] - 2025-12-15
820
+
821
+ ### Changed
822
+
823
+ - **DataClient refactoring** - Improved code organization and maintainability
824
+ - Extracted request execution logic into separate utility modules
825
+ - Split DataClient into focused utility files: `data-client-request.ts`, `data-client-auth.ts`, `data-client-cache.ts`, `data-client-utils.ts`
826
+ - Improved code organization and separation of concerns
827
+ - Reduced code complexity in main DataClient class
828
+
829
+ ### Fixed
830
+
831
+ - **TypeScript error handling** - Fixed TypeScript error in retry logic
832
+ - Fixed type checking for error constructor name in authentication error detection
833
+ - Improved error type safety in retry logic
834
+
835
+ ### Technical
836
+
837
+ - **Code quality improvements** - Significant refactoring for better maintainability
838
+ - Reduced DataClient.ts from ~1600 lines to ~500 lines through modularization
839
+ - Improved test coverage and organization
840
+ - Better separation of concerns between authentication, caching, and request execution
841
+
842
+ ## [3.1.1] - 2025-12-15
843
+
844
+ ### Fixed
845
+
846
+ - **DataClient retry logic** - Improved handling of 401 authentication errors in retry logic
847
+ - Enhanced error type detection to prevent retries on authentication errors
848
+ - Added explicit checks for AuthenticationError instances to ensure 401/403 errors are not retried
849
+ - Improved statusCode extraction from error objects for more reliable retry decisions
850
+
851
+ ## [3.1.0] - 2025-12-15
852
+
853
+ ### Added
854
+
855
+ - **Public and Private Controller URL Support** - Separate URLs for browser and server environments
856
+ - New `controllerPublicUrl` configuration option for browser/Vite environments (accessible from internet)
857
+ - New `controllerPrivateUrl` configuration option for server environments (internal network access)
858
+ - New `resolveControllerUrl()` utility function that automatically detects environment and selects appropriate URL
859
+ - New `isBrowser()` utility function for environment detection (checks for window, localStorage, fetch globals)
860
+ - Environment variable support: `MISO_WEB_SERVER_URL` (maps to `controllerPublicUrl` for browser)
861
+ - Environment variable support: `MISO_CONTROLLER_URL` (maps to `controllerPrivateUrl` for server, maintains backward compatibility)
862
+ - Automatic URL resolution based on environment:
863
+ - Browser environment: Uses `controllerPublicUrl` → falls back to `controllerUrl`
864
+ - Server environment: Uses `controllerPrivateUrl` falls back to `controllerUrl`
865
+ - URL validation ensures resolved URLs are valid HTTP/HTTPS URLs
866
+ - Clear error messages when no URL is configured
867
+
868
+ ### Changed
869
+
870
+ - **InternalHttpClient** - Now uses `resolveControllerUrl()` for automatic URL resolution
871
+ - Constructor uses resolved URL instead of hardcoded `config.controllerUrl`
872
+ - Client token fetch uses resolved URL for temporary axios instance
873
+ - Maintains backward compatibility with existing `controllerUrl` configuration
874
+
875
+ - **AuthService** - Now uses `resolveControllerUrl()` for axios instance creation
876
+ - Automatically selects appropriate URL based on environment
877
+ - Maintains backward compatibility with existing configurations
878
+
879
+ - **Config Loader** - Enhanced environment variable parsing
880
+ - `MISO_WEB_SERVER_URL` loads into `controllerPublicUrl` (browser/public)
881
+ - `MISO_CONTROLLER_URL` loads into `controllerPrivateUrl` (server/private) and `controllerUrl` (backward compatibility)
882
+ - Maintains existing behavior for applications using `MISO_CONTROLLER_URL`
883
+
884
+ - **Documentation** - Updated configuration documentation
885
+ - Added sections for public/private URL configuration in `docs/configuration.md`
886
+ - Added examples for browser and server setup patterns
887
+ - Updated `docs/api-reference.md` with new utility functions and configuration options
888
+ - Includes migration guide and usage examples
889
+
890
+ ### Technical
891
+
892
+ - **New utility file**: `src/utils/controller-url-resolver.ts` - URL resolution with environment detection
893
+ - `resolveControllerUrl()` function (35 lines, comprehensive JSDoc)
894
+ - `isBrowser()` helper function (7 lines)
895
+ - `validateUrl()` private helper function (7 lines)
896
+ - 100% test coverage (28 tests in `tests/unit/controller-url-resolver.test.ts`)
897
+
898
+ - **Test coverage** - Comprehensive tests for URL resolution
899
+ - Browser environment detection tests (mocked window, localStorage, fetch)
900
+ - Server environment detection tests (no browser globals)
901
+ - URL resolution priority tests (public private → controllerUrl → error)
902
+ - Backward compatibility tests (existing `controllerUrl` still works)
903
+ - Environment variable parsing tests (`MISO_WEB_SERVER_URL`, `MISO_CONTROLLER_URL`)
904
+ - URL validation tests (invalid URLs throw errors)
905
+ - Updated `tests/unit/config-loader.test.ts` with 52 new test lines
906
+ - Updated `tests/unit/http-client.test.ts` and `tests/unit/client.test.ts` with URL resolution tests
907
+
908
+ - **Exports updated**:
909
+ - `src/index.ts` - Exports `resolveControllerUrl` and `isBrowser` utilities
910
+ - Public API maintains camelCase naming convention
911
+
912
+ ## [3.0.1] - 2025-12-14
913
+
914
+ ### Fixed
915
+
916
+ - **DataClient audit logging bug** - Fixed 401 Unauthorized errors when audit logging unauthenticated requests
917
+ - Added `hasClientToken()` and `hasAnyToken()` helper methods to check authentication status
918
+ - `logAuditEvent()` now skips audit logging when no authentication token is available (user token OR client token)
919
+ - Prevents circular dependency where login requests trigger audit logging that requires authentication
920
+ - Gracefully handles audit logging errors without breaking main requests
921
+ - Improved error handling for 401 errors in audit logging (silently skipped for unauthenticated requests)
922
+
923
+ ### Changed
924
+
925
+ - **Documentation improvements** - Updated documentation files to match project style and improve clarity
926
+ - `docs/api-reference.md` - Streamlined API documentation
927
+ - `docs/configuration.md` - Reduced verbosity, focused on practical examples (reduced from ~1522 to ~785 lines)
928
+ - `docs/data-client.md` - Improved clarity and consistency (reduced from ~1497 to ~926 lines)
929
+ - `docs/examples.md` - Consolidated examples, removed redundancy (reduced from ~1014 to ~991 lines)
930
+ - `docs/troubleshooting.md` - More action-oriented format, clearer solutions (reduced from ~965 to ~707 lines)
931
+ - All documentation now follows consistent "You need to:" / "Here's how:" patterns
932
+ - Removed jargon and technical verbosity
933
+ - Added consistent "✅ Use standard .env parameters" patterns throughout
934
+
935
+ ### Technical
936
+
937
+ - **Test coverage** - Added tests for audit logging skip behavior
938
+ - Updated `tests/unit/data-client.test.ts` with 69 new lines of test coverage
939
+ - Tests verify audit logging is skipped for unauthenticated requests
940
+ - Tests verify audit logging still works for authenticated requests
941
+
942
+ ## [3.0.0] - 2025-12-14
943
+
944
+ ### Added
945
+
946
+ - **Configurable client token endpoint** - Customizable client token URI for authentication
947
+ - New `clientTokenUri` configuration option in `MisoClientConfig` (defaults to `/api/v1/auth/token`)
948
+ - Environment variable support: `MISO_CLIENT_TOKEN_URI`
949
+ - Backward compatible with existing implementations
950
+ - Used by `AuthService.getEnvironmentToken()` method
951
+
952
+ - **Origin validation for security** - CORS origin validation with wildcard port support
953
+ - New `allowedOrigins` configuration option in `MisoClientConfig`
954
+ - Environment variable support: `MISO_ALLOWED_ORIGINS` (comma-separated list)
955
+ - Supports wildcard ports: `http://localhost:*` (matches any port)
956
+ - New `validateOrigin()` utility function exported for use in miso-controller backend
957
+ - Checks `origin` header first, falls back to `referer` header
958
+ - Security-first approach: validates origin before calling controller
959
+
960
+ - **Server-side environment token wrapper** - Secure token fetching with origin validation
961
+ - New `getEnvironmentToken()` server-side wrapper function
962
+ - Validates request origin before calling controller
963
+ - ISO 27001 compliant audit logging with masked client credentials
964
+ - Logs error and audit events on validation failures
965
+ - Exported from `src/index.ts` and `src/express/index.ts`
966
+
967
+ - **Client token decoding utility** - Extract application and environment info from tokens
968
+ - New `extractClientTokenInfo()` utility function
969
+ - Decodes JWT client tokens without verification (no secret available)
970
+ - Supports multiple field name variations:
971
+ - `application` or `app`
972
+ - `environment` or `env`
973
+ - `applicationId` or `app_id`
974
+ - `clientId` or `client_id`
975
+ - Returns `ClientTokenInfo` interface with optional fields
976
+ - Exported from `src/index.ts` and `src/express/index.ts`
977
+
978
+ - **DataClient `getEnvironmentToken()` method** - Browser-side token fetching with caching
979
+ - New public method for browser applications
980
+ - Checks localStorage cache first (`miso:client-token` and `miso:client-token-expires-at`)
981
+ - Fetches from backend endpoint if cache miss or expired
982
+ - Uses `clientTokenUri` from config or defaults to `/api/v1/auth/client-token`
983
+ - Supports absolute URLs and relative paths
984
+ - Handles nested and flat response formats
985
+ - ISO 27001 audit logging integration
986
+ - Automatic cache expiration handling
987
+
988
+ - **DataClient `getClientTokenInfo()` method** - Extract token metadata in browser
989
+ - New public method to extract application/environment info from client token
990
+ - Checks cached token first, then config token
991
+ - Returns `ClientTokenInfo` object or `null` if no token available
992
+ - Useful for displaying current application/environment in UI
993
+ - Handles decode errors gracefully
994
+
995
+ - **DataClient `logout()` method** - Logout functionality for browser applications
996
+ - Calls controller logout API to invalidate server-side session
997
+ - Clears authentication tokens from localStorage (all configured token keys)
998
+ - Clears HTTP response cache
999
+ - Redirects to logout URL or login page
1000
+ - Supports optional `redirectUrl` parameter for custom redirect after logout
1001
+ - Gracefully handles API failures (always clears local state)
1002
+ - SSR compatible (no-op in non-browser environments)
1003
+
1004
+ - **DataClient `logoutUrl` configuration** - Custom logout redirect URL
1005
+ - Optional `logoutUrl` property in `DataClientConfig`
1006
+ - Falls back to `loginUrl` config if not provided
1007
+ - Supports both relative paths and absolute URLs
1008
+ - Defaults to `/login` if neither `logoutUrl` nor `loginUrl` is configured
1009
+
1010
+ ### Changed
1011
+
1012
+ - **AuthService `getEnvironmentToken()`** - Now uses configurable `clientTokenUri`
1013
+ - Changed from hardcoded `/api/v1/auth/token` to `this.config.clientTokenUri || '/api/v1/auth/token'`
1014
+ - Maintains backward compatibility (defaults to existing endpoint)
1015
+ - Existing error handling and correlation ID generation preserved
1016
+
1017
+ - **MisoClientConfig interface** - Added new configuration options
1018
+ - New optional property: `clientTokenUri?: string`
1019
+ - New optional property: `allowedOrigins?: string[]`
1020
+
1021
+ - **DataClient configuration** - Added `logoutUrl` option to `DataClientConfig` interface
1022
+ - New optional property: `logoutUrl?: string`
1023
+ - Follows same pattern as `loginUrl` configuration
1024
+
1025
+ ### Technical
1026
+
1027
+ - **New utility files**:
1028
+ - `src/utils/origin-validator.ts` - Origin validation with wildcard port support
1029
+ - `src/utils/environment-token.ts` - Server-side wrapper with audit logging
1030
+ - `src/utils/token-utils.ts` - Client token decoding utility
1031
+
1032
+ - **New test files**:
1033
+ - `tests/unit/origin-validator.test.ts` - 22 tests covering origin validation
1034
+ - `tests/unit/token-utils.test.ts` - 20 tests covering token decoding
1035
+ - `tests/unit/environment-token.test.ts` - 10 tests covering server-side wrapper
1036
+ - Updated `tests/unit/data-client.test.ts` - Added 22 new tests
1037
+ - Updated `tests/unit/config-loader.test.ts` - Added 7 new tests
1038
+ - Updated `tests/unit/auth.service.test.ts` - Added 4 new tests
1039
+
1040
+ - **Exports updated**:
1041
+ - `src/index.ts` - Exports `validateOrigin`, `getEnvironmentToken`, `extractClientTokenInfo`, and types
1042
+ - `src/express/index.ts` - Exports same utilities for Express applications
1043
+
1044
+ - **Documentation updated**:
1045
+ - `docs/data-client.md` - Added sections for `getEnvironmentToken()` and `getClientTokenInfo()`
1046
+ - Includes browser usage examples, server-side route examples, configuration examples, and security best practices
1047
+
1048
+ ## [2.2.1] - 2025-12-13
1049
+
1050
+ ### Fixed
1051
+
1052
+ - **DataClient `redirectToLogin()`** - Fixed redirect to use controller login endpoint
1053
+ - Now calls controller's `/api/v1/auth/login` endpoint with redirect parameter
1054
+ - Properly constructs full redirect URL instead of relative path
1055
+ - Falls back to static loginUrl when misoClient is unavailable or controller call fails
1056
+
1057
+ ### Changed
1058
+
1059
+ - **DataClient `redirectToLogin()`** - Enhanced with optional redirect URL parameter
1060
+ - Made method async to support controller API calls
1061
+ - Added optional `redirectUrl` parameter (defaults to current page URL)
1062
+ - Returns controller's login URL for proper OAuth flow handling
1063
+
1064
+ ## [2.2.0] - 2025-12-13
1065
+
1066
+ ### Added
1067
+
1068
+ - **DataClient Browser Wrapper** - Browser-compatible HTTP client wrapper around MisoClient
1069
+ - Enhanced HTTP client capabilities for React/front-end applications
1070
+ - ISO 27001 compliant audit logging with configurable levels (minimal, standard, detailed, full)
1071
+ - Automatic sensitive data masking using DataMasker before audit logging
1072
+ - Request/response interceptors for custom request/response transformation
1073
+ - Response caching with configurable TTL and cache size limits
1074
+ - Automatic retry logic with exponential backoff for retryable errors
1075
+ - Request deduplication for concurrent duplicate requests
1076
+ - Request metrics tracking (response times, error rates, cache hit rates)
1077
+ - Custom error types (NetworkError, TimeoutError, AuthenticationError)
1078
+ - Browser compatibility checks with SSR support
1079
+ - Token management from localStorage with multiple key support
1080
+ - Automatic login redirect on authentication errors
1081
+ - Support for all HTTP methods (GET, POST, PUT, PATCH, DELETE)
1082
+ - Request cancellation via AbortController
1083
+ - Per-request timeout support
1084
+ - Integration with MisoClient for authentication and audit logging
1085
+ - **Client Token Pattern** - Secure browser usage without exposing clientSecret
1086
+ - Support for server-provided client tokens (`clientToken`, `clientTokenExpiresAt`)
1087
+ - Token refresh callback pattern (`onClientTokenRefresh`) for browser applications
1088
+ - Automatic token refresh with proactive expiration handling (60s buffer)
1089
+ - Memory-only token storage (never persisted to localStorage)
1090
+
1091
+ ### Changed
1092
+
1093
+ - **MisoClientConfig** - `clientSecret` is now optional when using client token pattern
1094
+ - Added `clientToken?: string` - Pre-obtained client token for browser usage
1095
+ - Added `clientTokenExpiresAt?: Date | string` - Token expiration tracking
1096
+ - Added `onClientTokenRefresh?: () => Promise<{ token: string; expiresIn: number }>` - Refresh callback
1097
+ - `InternalHttpClient` now supports both clientSecret (server-side) and clientToken (browser) patterns
1098
+
1099
+ ## [2.1.2] - 2025-12-11
1100
+
1101
+ ### Added
1102
+
1103
+ - **Express.js Utilities** - Complete set of utilities for building Express.js REST APIs
1104
+ - `ResponseHelper` - Standardized API response formatting (success, created, paginated, noContent, accepted)
1105
+ - `injectResponseHelpers` - Middleware to inject response helpers into Express Response
1106
+ - `asyncHandler` and `asyncHandlerNamed` - Automatic error handling for async route handlers
1107
+ - `ValidationHelper` - Common validation patterns (findOrFail, ensureNotExists, ensureOwnershipOrAdmin, etc.)
1108
+ - `AppError` - Application error class with RFC 7807 support
1109
+ - `handleRouteError` - Centralized error handling for Express routes
1110
+ - `setErrorLogger` - Injectable error logger for custom logging
1111
+ - `EncryptionUtil` - AES-256-GCM encryption utility (replaces EncryptionService)
1112
+ - Express Response type augmentation for TypeScript
1113
+
1114
+ - **Sort Utilities** - Client-side sorting helpers
1115
+ - `applySorting()` - Apply sorting to in-memory data arrays
1116
+ - `parseSortParams()` - Parse sort query parameters (already existed)
1117
+
1118
+ - **GitHub Workflows** - Manual release management
1119
+ - Manual Version Bump workflow - Bump version, create git tags, and GitHub Releases
1120
+ - Manual Publish to NPM workflow - Publish to npm with validation and verification
1121
+
1122
+ - **Package Configuration**
1123
+ - Express as optional peer dependency (^4.18.0 || ^5.0.0)
1124
+ - @types/express as dev dependency
1125
+
1126
+ - **Authentication API Updates**
1127
+ - `LoginResponse` and `LogoutResponse` types for standardized authentication responses
1128
+ - Updated `login()` method to make API call to `/api/v1/auth/login` with query parameters (redirect, state)
1129
+ - Updated `logout()` method to accept token parameter and make API call to `/api/v1/auth/logout`
1130
+ - Comprehensive test coverage for `response-middleware.ts` (100% coverage)
1131
+
1132
+ ### Changed
1133
+
1134
+ - **Package Description** - Updated to include Express.js utilities
1135
+ - **EncryptionService** - Replaced instance-based EncryptionService with static EncryptionUtil class
1136
+ - **Workflow Strategy** - Removed automatic publish on push, added manual workflows for better control
1137
+ - **Authentication Methods** - Breaking changes:
1138
+ - `login()` - Changed from synchronous method returning URL string to async method returning `LoginResponse` object
1139
+ - `logout()` - Now requires `{ token: string }` parameter and returns `LogoutResponse` object
1140
+
1141
+ ### Removed
1142
+
1143
+ - Old automatic npm-publish workflow (replaced by manual workflows)
1144
+ - EncryptionService class (replaced by EncryptionUtil)
1145
+
1146
+ ## [2.0.0] - Previous Release
1147
+
1148
+ See git history for previous changes.