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