@aifabrix/miso-client 4.4.0 → 4.4.2

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