@aifabrix/miso-client 4.3.1 → 4.4.1

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