@aifabrix/miso-client 4.4.0 → 4.4.1

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