@aifabrix/miso-client 3.2.5 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +624 -0
  2. package/dist/api/auth-cache.api.d.ts +52 -0
  3. package/dist/api/auth-cache.api.d.ts.map +1 -0
  4. package/dist/api/auth-cache.api.js +125 -0
  5. package/dist/api/auth-cache.api.js.map +1 -0
  6. package/dist/api/auth-login.api.d.ts +52 -0
  7. package/dist/api/auth-login.api.d.ts.map +1 -0
  8. package/dist/api/auth-login.api.js +102 -0
  9. package/dist/api/auth-login.api.js.map +1 -0
  10. package/dist/api/auth-token.api.d.ts +46 -0
  11. package/dist/api/auth-token.api.d.ts.map +1 -0
  12. package/dist/api/auth-token.api.js +90 -0
  13. package/dist/api/auth-token.api.js.map +1 -0
  14. package/dist/api/auth-user.api.d.ts +43 -0
  15. package/dist/api/auth-user.api.d.ts.map +1 -0
  16. package/dist/api/auth-user.api.js +87 -0
  17. package/dist/api/auth-user.api.js.map +1 -0
  18. package/dist/api/auth.api.d.ts +48 -0
  19. package/dist/api/auth.api.d.ts.map +1 -0
  20. package/dist/api/auth.api.js +152 -0
  21. package/dist/api/auth.api.js.map +1 -0
  22. package/dist/api/index.d.ts +39 -0
  23. package/dist/api/index.d.ts.map +1 -0
  24. package/dist/api/index.js +31 -0
  25. package/dist/api/index.js.map +1 -0
  26. package/dist/api/logs-create.api.d.ts +32 -0
  27. package/dist/api/logs-create.api.d.ts.map +1 -0
  28. package/dist/api/logs-create.api.js +63 -0
  29. package/dist/api/logs-create.api.js.map +1 -0
  30. package/dist/api/logs-export.api.d.ts +24 -0
  31. package/dist/api/logs-export.api.d.ts.map +1 -0
  32. package/dist/api/logs-export.api.js +43 -0
  33. package/dist/api/logs-export.api.js.map +1 -0
  34. package/dist/api/logs-list.api.d.ts +63 -0
  35. package/dist/api/logs-list.api.d.ts.map +1 -0
  36. package/dist/api/logs-list.api.js +155 -0
  37. package/dist/api/logs-list.api.js.map +1 -0
  38. package/dist/api/logs-stats.api.d.ts +48 -0
  39. package/dist/api/logs-stats.api.d.ts.map +1 -0
  40. package/dist/api/logs-stats.api.js +107 -0
  41. package/dist/api/logs-stats.api.js.map +1 -0
  42. package/dist/api/logs.api.d.ts +35 -0
  43. package/dist/api/logs.api.d.ts.map +1 -0
  44. package/dist/api/logs.api.js +71 -0
  45. package/dist/api/logs.api.js.map +1 -0
  46. package/dist/api/permissions.api.d.ts +31 -0
  47. package/dist/api/permissions.api.d.ts.map +1 -0
  48. package/dist/api/permissions.api.js +62 -0
  49. package/dist/api/permissions.api.js.map +1 -0
  50. package/dist/api/roles.api.d.ts +31 -0
  51. package/dist/api/roles.api.d.ts.map +1 -0
  52. package/dist/api/roles.api.js +62 -0
  53. package/dist/api/roles.api.js.map +1 -0
  54. package/dist/api/types/auth.types.d.ts +293 -0
  55. package/dist/api/types/auth.types.d.ts.map +1 -0
  56. package/dist/api/types/auth.types.js +7 -0
  57. package/dist/api/types/auth.types.js.map +1 -0
  58. package/dist/api/types/logs.types.d.ts +266 -0
  59. package/dist/api/types/logs.types.d.ts.map +1 -0
  60. package/dist/api/types/logs.types.js +7 -0
  61. package/dist/api/types/logs.types.js.map +1 -0
  62. package/dist/api/types/permissions.types.d.ts +32 -0
  63. package/dist/api/types/permissions.types.d.ts.map +1 -0
  64. package/dist/api/types/permissions.types.js +7 -0
  65. package/dist/api/types/permissions.types.js.map +1 -0
  66. package/dist/api/types/roles.types.d.ts +32 -0
  67. package/dist/api/types/roles.types.d.ts.map +1 -0
  68. package/dist/api/types/roles.types.js +7 -0
  69. package/dist/api/types/roles.types.js.map +1 -0
  70. package/dist/index.d.ts +31 -0
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +52 -5
  73. package/dist/index.js.map +1 -1
  74. package/dist/services/auth.service.d.ts +3 -1
  75. package/dist/services/auth.service.d.ts.map +1 -1
  76. package/dist/services/auth.service.js +62 -23
  77. package/dist/services/auth.service.js.map +1 -1
  78. package/dist/services/browser-permission.service.d.ts +3 -1
  79. package/dist/services/browser-permission.service.d.ts.map +1 -1
  80. package/dist/services/browser-permission.service.js +32 -16
  81. package/dist/services/browser-permission.service.js.map +1 -1
  82. package/dist/services/browser-role.service.d.ts +3 -1
  83. package/dist/services/browser-role.service.d.ts.map +1 -1
  84. package/dist/services/browser-role.service.js +32 -16
  85. package/dist/services/browser-role.service.js.map +1 -1
  86. package/dist/services/logger.service.d.ts +7 -0
  87. package/dist/services/logger.service.d.ts.map +1 -1
  88. package/dist/services/logger.service.js +72 -7
  89. package/dist/services/logger.service.js.map +1 -1
  90. package/dist/services/permission.service.d.ts +3 -1
  91. package/dist/services/permission.service.d.ts.map +1 -1
  92. package/dist/services/permission.service.js +32 -16
  93. package/dist/services/permission.service.js.map +1 -1
  94. package/dist/services/role.service.d.ts +3 -1
  95. package/dist/services/role.service.d.ts.map +1 -1
  96. package/dist/services/role.service.js +25 -13
  97. package/dist/services/role.service.js.map +1 -1
  98. package/dist/services/token-validation.service.d.ts +49 -0
  99. package/dist/services/token-validation.service.d.ts.map +1 -0
  100. package/dist/services/token-validation.service.js +258 -0
  101. package/dist/services/token-validation.service.js.map +1 -0
  102. package/dist/types/config.types.d.ts +7 -0
  103. package/dist/types/config.types.d.ts.map +1 -1
  104. package/dist/types/config.types.js.map +1 -1
  105. package/dist/types/token-validation.types.d.ts +88 -0
  106. package/dist/types/token-validation.types.d.ts.map +1 -0
  107. package/dist/types/token-validation.types.js +7 -0
  108. package/dist/types/token-validation.types.js.map +1 -0
  109. package/dist/utils/audit-log-queue.d.ts +7 -0
  110. package/dist/utils/audit-log-queue.d.ts.map +1 -1
  111. package/dist/utils/audit-log-queue.js +29 -8
  112. package/dist/utils/audit-log-queue.js.map +1 -1
  113. package/dist/utils/data-client.d.ts.map +1 -1
  114. package/dist/utils/data-client.js +8 -3
  115. package/dist/utils/data-client.js.map +1 -1
  116. package/package.json +4 -2
package/CHANGELOG.md ADDED
@@ -0,0 +1,624 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [3.4.0] - 2025-12-24
9
+
10
+ ### Added
11
+
12
+ - **Local Token Validation** - JWKS-based JWT validation without API calls
13
+ - New `validateTokenLocal()` method for local JWT signature verification
14
+ - Supports Keycloak tokens and delegated OAuth provider tokens
15
+ - Dual-layer caching: JWKS keys (1 hour) + validation results (1 minute)
16
+ - `skipResultCache` option for high-security scenarios
17
+ - Auto-detection of token type based on issuer claim
18
+ - New `TokenValidationService` exported for advanced usage
19
+
20
+ - **Keycloak Configuration** - Native Keycloak integration
21
+ - New `keycloak` config option in `MisoClientConfig`
22
+ - `setKeycloakConfig()` method for runtime configuration
23
+ - Audience validation support (opt-in via `verifyAudience`)
24
+
25
+ - **Cache Management** - Fine-grained cache control
26
+ - `clearJwksCache(uri?)` - Clear JWKS key cache
27
+ - `clearValidationCache()` - Clear validation result cache
28
+ - `clearAllTokenCaches()` - Clear all caches
29
+
30
+ ### Changed
31
+
32
+ - **Package Distribution** - Added CHANGELOG.md to npm package files
33
+
34
+ ### Dependencies
35
+
36
+ - Added `jose` ^5.9.6 for JWT/JWKS operations
37
+
38
+ ## [3.3.0] - 2025-12-23
39
+
40
+ ### Added
41
+
42
+ - **Centralized API layer** - Typed interfaces for all controller API calls
43
+ - New API layer in `src/api/` with domain-specific API classes (`AuthApi`, `RolesApi`, `PermissionsApi`, `LogsApi`)
44
+ - `ApiClient` class wraps `HttpClient` and organizes APIs by domain
45
+ - Centralized endpoint URLs as constants in each API class for maintainability
46
+ - All API request/response types use interfaces (not types) with camelCase naming convention
47
+ - Services can optionally use `ApiClient` instead of direct `HttpClient` calls (gradual migration pattern)
48
+ - Improved type safety and code organization for controller API interactions
49
+ - API classes are composed from specialized sub-modules to keep file sizes manageable
50
+
51
+ ### Changed
52
+
53
+ - **Token validation enhancements** - Improved token acceptance criteria
54
+ - Updated token validation logic to accept both JWT and non-JWT token formats
55
+ - Enhanced validation to ensure tokens are non-empty and of reasonable length
56
+ - Improved error handling for token validation failures
57
+ - Updated unit tests to reflect changes in token acceptance criteria
58
+
59
+ - **OAuth callback handling** - Enhanced error feedback
60
+ - Updated error handling in `handleOAuthCallback()` to provide clearer feedback on token validation failures
61
+ - Improved documentation for token validation and OAuth handling
62
+
63
+ - **Service dependencies** - Optional API client support
64
+ - Services can now optionally include `ApiClient` for typed API access
65
+ - Allows for gradual migration from direct `HttpClient` usage to typed API layer
66
+ - Maintains backward compatibility with existing service implementations
67
+
68
+ ### Technical
69
+
70
+ - **New API layer structure**:
71
+ - `src/api/index.ts` - Main `ApiClient` class
72
+ - `src/api/auth.api.ts` - Authentication API (composed from sub-modules)
73
+ - `src/api/roles.api.ts` - Roles API
74
+ - `src/api/permissions.api.ts` - Permissions API
75
+ - `src/api/logs.api.ts` - Logs API
76
+ - `src/api/types/` - API request/response type definitions
77
+
78
+ - **Test coverage**:
79
+ - Updated mock patterns to include `ApiClient` for testing purposes
80
+ - Enhanced unit tests for token validation with new acceptance criteria
81
+
82
+ - **Documentation**:
83
+ - Added API layer pattern documentation to project rules
84
+ - Updated usage examples to demonstrate API layer pattern
85
+ - Enhanced documentation for token validation and OAuth handling
86
+
87
+ ## [3.2.5] - 2025-12-22
88
+
89
+ ### Added
90
+
91
+ - **Indexed logging fields** - Standardized indexed fields for improved query performance and observability
92
+ - New `extractLoggingContext()` utility function in `src/utils/logging-helpers.ts`
93
+ - Added indexed context fields to `LogEntry` interface: `sourceKey`, `sourceDisplayName`, `externalSystemKey`, `externalSystemDisplayName`, `recordKey`, `recordDisplayName`
94
+ - Added credential context fields: `credentialId`, `credentialType`
95
+ - Added request/response metrics: `requestSize`, `responseSize`, `durationMs`
96
+ - Added error classification fields: `errorCategory`, `httpStatusCategory`
97
+ - New `LoggerChain` methods: `withIndexedContext()`, `withCredentialContext()`, `withRequestMetrics()`
98
+ - Exported types: `IndexedLoggingContext`, `HasKey`, `HasExternalSystem`
99
+ - Improves query performance and root-cause analysis for audit logs
100
+
101
+ - **Request context auto-extraction** - Automatic extraction of logging context from Express Request objects
102
+ - New `extractRequestContext()` utility function in `src/utils/request-context.ts`
103
+ - New `withRequest()` method on `LoggerChain` for automatic context extraction
104
+ - New `forRequest()` method on `LoggerService` for request-based logging
105
+ - Automatically extracts: IP address, HTTP method, path, user-agent, correlation ID, user from JWT, session ID, request ID
106
+ - Handles proxy IPs via `x-forwarded-for` header
107
+ - Reduces logging code from 10-15 lines to 2-3 lines per log call
108
+ - Exported `RequestContext` interface and `extractRequestContext` function
109
+
110
+ - **Token validation caching** - Caching for token validation to reduce API calls
111
+ - Cache validation results by userId with 15-minute TTL (configurable via `config.cache?.tokenValidationTTL`)
112
+ - Cache key format: `token:${userId}` (consistent with roles/permissions caching)
113
+ - Automatic cache invalidation on logout (clears cache even if logout returns 400)
114
+ - New `clearTokenCache()` method in `AuthService` for manual cache clearing
115
+ - Extracts userId from JWT token before API call (avoids unnecessary validate API call)
116
+ - Graceful fallback to API call on cache failures
117
+ - Uses `CacheService` instead of `RedisService` for consistency
118
+
119
+ - **User token refresh** - Token refresh functionality for secure token renewal
120
+ - New `refreshToken()` method in `AuthService` for backend applications
121
+ - New `onTokenRefresh` callback support in `DataClient` for frontend applications
122
+ - Automatic token refresh on 401 errors in DataClient with retry logic
123
+ - New `RefreshTokenResponse` interface with `accessToken`, `refreshToken`, `expiresIn`, `expiresAt`
124
+ - Exposed `refreshToken()` method in `MisoClient` class
125
+ - Prevents infinite retry loops with `tokenRefreshAttempted` flag
126
+ - Refresh tokens never stored in browser localStorage (security requirement)
127
+
128
+ - **OAuth callback handler** - ISO 27001 compliant OAuth callback handling with hash fragments
129
+ - New `handleOAuthCallback()` function in `src/utils/data-client-auth.ts`
130
+ - New `handleOAuthCallback()` method in `DataClient` class
131
+ - Extracts tokens from URL hash fragments (`#token=...`) instead of query parameters
132
+ - Immediate hash cleanup (< 100ms) to prevent token exposure
133
+ - Token format validation (JWT format check)
134
+ - HTTPS enforcement in production environments
135
+ - Supports multiple parameter names: `token`, `access_token`, `accessToken`
136
+ - Auto-calls on DataClient initialization in browser environments
137
+ - Secure error handling without exposing tokens
138
+
139
+ ### Changed
140
+
141
+ - **LoggerService enhancements** - Enhanced logging capabilities with indexed fields
142
+ - Updated `ClientLoggingOptions` interface with indexed context fields
143
+ - Updated `LogEntry` interface with indexed fields for fast queries
144
+ - Enhanced `LoggerChain` fluent API with new context methods
145
+ - Improved developer experience with automatic request context extraction
146
+
147
+ - **AuthService improvements** - Enhanced authentication service with caching
148
+ - Updated constructor to accept `CacheService` instead of `RedisService`
149
+ - Added `extractUserIdFromToken()` private method for JWT extraction
150
+ - Enhanced `validateToken()` method with caching logic
151
+ - Updated `logout()` method to clear token cache on logout
152
+
153
+ - **DataClient enhancements** - Improved token refresh and OAuth handling
154
+ - Added `refreshUserToken()` private method for token refresh
155
+ - Enhanced 401 error handling with automatic token refresh and retry
156
+ - Updated `redirectToLogin()` documentation for hash fragment flow
157
+ - Improved OAuth callback handling with security measures
158
+
159
+ ### Fixed
160
+
161
+ - **Token validation performance** - Reduced API calls through caching
162
+ - Token validation now uses cache to avoid unnecessary controller API calls
163
+ - Cache hit significantly improves performance for repeated validations
164
+
165
+ - **OAuth security** - Improved security for OAuth callback flow
166
+ - Tokens extracted from hash fragments (not sent to server, not in logs)
167
+ - Immediate cleanup prevents token exposure in address bar
168
+ - HTTPS enforcement prevents token transmission over HTTP in production
169
+
170
+ ### Technical
171
+
172
+ - **New utility files**:
173
+ - `src/utils/logging-helpers.ts` - Logging context extraction utility (91 lines)
174
+ - `src/utils/request-context.ts` - Request context extraction utility (102 lines)
175
+
176
+ - **Test coverage**:
177
+ - Comprehensive tests for logging helpers (15 tests)
178
+ - Comprehensive tests for request context extraction (33 tests)
179
+ - Enhanced tests for token caching (80 tests total in auth.service.test.ts)
180
+ - Comprehensive tests for token refresh (17 AuthService + 15 DataClient tests)
181
+ - Comprehensive tests for OAuth callback handler (34 tests)
182
+
183
+ - **Type definitions**:
184
+ - Added `RefreshTokenResponse` interface to `src/types/config.types.ts`
185
+ - Added `tokenValidationTTL?: number` to cache config type
186
+ - Added `onTokenRefresh` callback to `DataClientConfig` interface
187
+
188
+ - **Exports updated**:
189
+ - `src/index.ts` - Exports `extractLoggingContext`, `IndexedLoggingContext`, `HasKey`, `HasExternalSystem`
190
+ - `src/index.ts` - Exports `extractRequestContext`, `RequestContext`
191
+ - `src/index.ts` - Exports `refreshToken()` method in `MisoClient`
192
+
193
+ ## [3.2.0] - 2025-12-22
194
+
195
+ ### Added
196
+
197
+ - **Circuit breaker for HTTP logging** - Prevents infinite retry loops when logging service is unavailable
198
+ - Added circuit breaker pattern to `LoggerService` and `AuditLogQueue`
199
+ - Automatically disables HTTP logging after 3 consecutive failures
200
+ - Circuit breaker opens for 60 seconds after failures, then resets
201
+ - Prevents performance degradation when controller logging endpoint is unavailable
202
+ - Gracefully handles network errors and server unavailability
203
+
204
+ - **DataClient redirect utilities** - Comprehensive redirect handling for login flows
205
+ - New `data-client-redirect.ts` utility module with robust redirect logic
206
+ - Enhanced `redirectToLogin()` with comprehensive error handling
207
+ - URL validation prevents dangerous redirects (javascript:, data:, etc.)
208
+ - User-friendly error messages for network, CORS, and authentication errors
209
+ - Proper timeout handling (30 seconds) to prevent hanging requests
210
+ - Only redirects when controller returns valid login URL (no fallback redirects on error)
211
+ - Supports both nested (`data.loginUrl`) and flat (`loginUrl`) response formats
212
+
213
+ - **Client token expiration checking** - Enhanced token validation with JWT expiration support
214
+ - Improved `getClientToken()` to check JWT expiration claims when expiration timestamp is missing
215
+ - Decodes JWT tokens to extract `exp` claim for expiration validation
216
+ - Better logging for debugging token expiration issues
217
+ - Handles missing expiration timestamps gracefully
218
+ - Automatically removes expired tokens from cache
219
+
220
+ - **Auto-initialization improvements** - New utility for accessing cached configuration
221
+ - New `getCachedDataClientConfig()` function exported from `src/index.ts`
222
+ - Allows reading cached DataClient configuration without re-initializing
223
+ - Useful for accessing configuration values in application code
224
+ - Returns cached config or null if not found or expired
225
+
226
+ - **Controller URL validation utility** - Exported URL validation function
227
+ - `validateUrl()` function now exported from `controller-url-resolver.ts`
228
+ - Validates HTTP/HTTPS URLs with comprehensive JSDoc documentation
229
+ - Useful for validating URLs before use in application code
230
+ - Exported from `src/index.ts` for public use
231
+
232
+ ### Changed
233
+
234
+ - **Documentation restructure** - Improved documentation organization and clarity
235
+ - New reference documentation structure with dedicated files for each major component
236
+ - Added `docs/reference-authentication.md` - Comprehensive authentication guide
237
+ - Added `docs/reference-authorization.md` - RBAC and permissions documentation
238
+ - Added `docs/reference-dataclient.md` - Complete DataClient API reference
239
+ - Added `docs/reference-errors.md` - Error handling and troubleshooting guide
240
+ - Added `docs/reference-misoclient.md` - MisoClient API reference
241
+ - Added `docs/reference-services.md` - Service layer documentation
242
+ - Added `docs/reference-types.md` - TypeScript type definitions reference
243
+ - Added `docs/reference-utilities.md` - Utility functions documentation
244
+ - Enhanced examples with improved clarity and error handling
245
+ - Updated all example files with corrected import paths
246
+
247
+ - **DataClient enhancements** - Improved robustness and developer experience
248
+ - Enhanced DataClient configuration and performance optimizations
249
+ - Improved authorization examples and documentation
250
+ - Better error handling in example code
251
+
252
+ - **Audit logging error handling** - Improved handling of network errors in audit logging
253
+ - Enhanced error detection for network errors (ECONNREFUSED, ENOTFOUND, ERR_CONNECTION_REFUSED)
254
+ - Silently skips audit logging for expected network errors (server unavailable, misconfigured)
255
+ - Prevents error noise in development and demo environments
256
+ - Better error classification and handling
257
+
258
+ ### Fixed
259
+
260
+ - **DataClient metrics** - Fixed handling of missing response times in metrics
261
+ - Modified `getMetrics()` method to handle cases where `responseTimes` may be undefined
262
+ - Ensures robust performance metrics retrieval without errors
263
+
264
+ - **Example imports** - Fixed import paths in all example files
265
+ - Updated example imports for clarity and proper error handling
266
+ - Corrected script source references in demo applications
267
+
268
+ - **Cache service test handling** - Fixed cleanup interval keeping process alive in tests
269
+ - Added `unref()` to cleanup interval in `CacheService` to prevent tests from hanging
270
+ - Ensures Node.js process can exit cleanly after tests complete
271
+ - Important for CI/CD environments and test suites
272
+
273
+ ### Removed
274
+
275
+ - **Performance logging** - Removed deprecated performance logging functionality
276
+ - Eliminated all performance logging code from the codebase
277
+ - Removed PerformanceMetrics interface and related methods
278
+ - Removed performance tracking logic from logger service
279
+ - Functionality replaced by OpenTelemetry integration
280
+
281
+ ### Technical
282
+
283
+ - **Code quality improvements** - Enhanced development workflow and configuration
284
+ - Updated ESLint and Jest configurations for improved testing and code quality
285
+ - Enhanced configuration files and scripts for better development workflow
286
+ - Improved .gitignore patterns
287
+ - Updated package.json for testing enhancements
288
+
289
+ - **New utility file**: `src/utils/data-client-redirect.ts` - Comprehensive redirect handling
290
+ - Extracted redirect logic from DataClient into dedicated utility module
291
+ - 424 lines of robust redirect handling with comprehensive error handling
292
+ - URL validation, timeout handling, and user-friendly error messages
293
+ - Proper separation of concerns for better maintainability
294
+
295
+ ## [3.1.2] - 2025-12-15
296
+
297
+ ### Changed
298
+
299
+ - **DataClient refactoring** - Improved code organization and maintainability
300
+ - Extracted request execution logic into separate utility modules
301
+ - Split DataClient into focused utility files: `data-client-request.ts`, `data-client-auth.ts`, `data-client-cache.ts`, `data-client-utils.ts`
302
+ - Improved code organization and separation of concerns
303
+ - Reduced code complexity in main DataClient class
304
+
305
+ ### Fixed
306
+
307
+ - **TypeScript error handling** - Fixed TypeScript error in retry logic
308
+ - Fixed type checking for error constructor name in authentication error detection
309
+ - Improved error type safety in retry logic
310
+
311
+ ### Technical
312
+
313
+ - **Code quality improvements** - Significant refactoring for better maintainability
314
+ - Reduced DataClient.ts from ~1600 lines to ~500 lines through modularization
315
+ - Improved test coverage and organization
316
+ - Better separation of concerns between authentication, caching, and request execution
317
+
318
+ ## [3.1.1] - 2025-12-15
319
+
320
+ ### Fixed
321
+
322
+ - **DataClient retry logic** - Improved handling of 401 authentication errors in retry logic
323
+ - Enhanced error type detection to prevent retries on authentication errors
324
+ - Added explicit checks for AuthenticationError instances to ensure 401/403 errors are not retried
325
+ - Improved statusCode extraction from error objects for more reliable retry decisions
326
+
327
+ ## [3.1.0] - 2025-12-15
328
+
329
+ ### Added
330
+
331
+ - **Public and Private Controller URL Support** - Separate URLs for browser and server environments
332
+ - New `controllerPublicUrl` configuration option for browser/Vite environments (accessible from internet)
333
+ - New `controllerPrivateUrl` configuration option for server environments (internal network access)
334
+ - New `resolveControllerUrl()` utility function that automatically detects environment and selects appropriate URL
335
+ - New `isBrowser()` utility function for environment detection (checks for window, localStorage, fetch globals)
336
+ - Environment variable support: `MISO_WEB_SERVER_URL` (maps to `controllerPublicUrl` for browser)
337
+ - Environment variable support: `MISO_CONTROLLER_URL` (maps to `controllerPrivateUrl` for server, maintains backward compatibility)
338
+ - Automatic URL resolution based on environment:
339
+ - Browser environment: Uses `controllerPublicUrl` → falls back to `controllerUrl`
340
+ - Server environment: Uses `controllerPrivateUrl` → falls back to `controllerUrl`
341
+ - URL validation ensures resolved URLs are valid HTTP/HTTPS URLs
342
+ - Clear error messages when no URL is configured
343
+
344
+ ### Changed
345
+
346
+ - **InternalHttpClient** - Now uses `resolveControllerUrl()` for automatic URL resolution
347
+ - Constructor uses resolved URL instead of hardcoded `config.controllerUrl`
348
+ - Client token fetch uses resolved URL for temporary axios instance
349
+ - Maintains backward compatibility with existing `controllerUrl` configuration
350
+
351
+ - **AuthService** - Now uses `resolveControllerUrl()` for axios instance creation
352
+ - Automatically selects appropriate URL based on environment
353
+ - Maintains backward compatibility with existing configurations
354
+
355
+ - **Config Loader** - Enhanced environment variable parsing
356
+ - `MISO_WEB_SERVER_URL` loads into `controllerPublicUrl` (browser/public)
357
+ - `MISO_CONTROLLER_URL` loads into `controllerPrivateUrl` (server/private) and `controllerUrl` (backward compatibility)
358
+ - Maintains existing behavior for applications using `MISO_CONTROLLER_URL`
359
+
360
+ - **Documentation** - Updated configuration documentation
361
+ - Added sections for public/private URL configuration in `docs/configuration.md`
362
+ - Added examples for browser and server setup patterns
363
+ - Updated `docs/api-reference.md` with new utility functions and configuration options
364
+ - Includes migration guide and usage examples
365
+
366
+ ### Technical
367
+
368
+ - **New utility file**: `src/utils/controller-url-resolver.ts` - URL resolution with environment detection
369
+ - `resolveControllerUrl()` function (35 lines, comprehensive JSDoc)
370
+ - `isBrowser()` helper function (7 lines)
371
+ - `validateUrl()` private helper function (7 lines)
372
+ - 100% test coverage (28 tests in `tests/unit/controller-url-resolver.test.ts`)
373
+
374
+ - **Test coverage** - Comprehensive tests for URL resolution
375
+ - Browser environment detection tests (mocked window, localStorage, fetch)
376
+ - Server environment detection tests (no browser globals)
377
+ - URL resolution priority tests (public → private → controllerUrl → error)
378
+ - Backward compatibility tests (existing `controllerUrl` still works)
379
+ - Environment variable parsing tests (`MISO_WEB_SERVER_URL`, `MISO_CONTROLLER_URL`)
380
+ - URL validation tests (invalid URLs throw errors)
381
+ - Updated `tests/unit/config-loader.test.ts` with 52 new test lines
382
+ - Updated `tests/unit/http-client.test.ts` and `tests/unit/client.test.ts` with URL resolution tests
383
+
384
+ - **Exports updated**:
385
+ - `src/index.ts` - Exports `resolveControllerUrl` and `isBrowser` utilities
386
+ - Public API maintains camelCase naming convention
387
+
388
+ ## [3.0.1] - 2025-12-14
389
+
390
+ ### Fixed
391
+
392
+ - **DataClient audit logging bug** - Fixed 401 Unauthorized errors when audit logging unauthenticated requests
393
+ - Added `hasClientToken()` and `hasAnyToken()` helper methods to check authentication status
394
+ - `logAuditEvent()` now skips audit logging when no authentication token is available (user token OR client token)
395
+ - Prevents circular dependency where login requests trigger audit logging that requires authentication
396
+ - Gracefully handles audit logging errors without breaking main requests
397
+ - Improved error handling for 401 errors in audit logging (silently skipped for unauthenticated requests)
398
+
399
+ ### Changed
400
+
401
+ - **Documentation improvements** - Updated documentation files to match project style and improve clarity
402
+ - `docs/api-reference.md` - Streamlined API documentation
403
+ - `docs/configuration.md` - Reduced verbosity, focused on practical examples (reduced from ~1522 to ~785 lines)
404
+ - `docs/data-client.md` - Improved clarity and consistency (reduced from ~1497 to ~926 lines)
405
+ - `docs/examples.md` - Consolidated examples, removed redundancy (reduced from ~1014 to ~991 lines)
406
+ - `docs/troubleshooting.md` - More action-oriented format, clearer solutions (reduced from ~965 to ~707 lines)
407
+ - All documentation now follows consistent "You need to:" / "Here's how:" patterns
408
+ - Removed jargon and technical verbosity
409
+ - Added consistent "✅ Use standard .env parameters" patterns throughout
410
+
411
+ ### Technical
412
+
413
+ - **Test coverage** - Added tests for audit logging skip behavior
414
+ - Updated `tests/unit/data-client.test.ts` with 69 new lines of test coverage
415
+ - Tests verify audit logging is skipped for unauthenticated requests
416
+ - Tests verify audit logging still works for authenticated requests
417
+
418
+ ## [3.0.0] - 2025-12-14
419
+
420
+ ### Added
421
+
422
+ - **Configurable client token endpoint** - Customizable client token URI for authentication
423
+ - New `clientTokenUri` configuration option in `MisoClientConfig` (defaults to `/api/v1/auth/token`)
424
+ - Environment variable support: `MISO_CLIENT_TOKEN_URI`
425
+ - Backward compatible with existing implementations
426
+ - Used by `AuthService.getEnvironmentToken()` method
427
+
428
+ - **Origin validation for security** - CORS origin validation with wildcard port support
429
+ - New `allowedOrigins` configuration option in `MisoClientConfig`
430
+ - Environment variable support: `MISO_ALLOWED_ORIGINS` (comma-separated list)
431
+ - Supports wildcard ports: `http://localhost:*` (matches any port)
432
+ - New `validateOrigin()` utility function exported for use in miso-controller backend
433
+ - Checks `origin` header first, falls back to `referer` header
434
+ - Security-first approach: validates origin before calling controller
435
+
436
+ - **Server-side environment token wrapper** - Secure token fetching with origin validation
437
+ - New `getEnvironmentToken()` server-side wrapper function
438
+ - Validates request origin before calling controller
439
+ - ISO 27001 compliant audit logging with masked client credentials
440
+ - Logs error and audit events on validation failures
441
+ - Exported from `src/index.ts` and `src/express/index.ts`
442
+
443
+ - **Client token decoding utility** - Extract application and environment info from tokens
444
+ - New `extractClientTokenInfo()` utility function
445
+ - Decodes JWT client tokens without verification (no secret available)
446
+ - Supports multiple field name variations:
447
+ - `application` or `app`
448
+ - `environment` or `env`
449
+ - `applicationId` or `app_id`
450
+ - `clientId` or `client_id`
451
+ - Returns `ClientTokenInfo` interface with optional fields
452
+ - Exported from `src/index.ts` and `src/express/index.ts`
453
+
454
+ - **DataClient `getEnvironmentToken()` method** - Browser-side token fetching with caching
455
+ - New public method for browser applications
456
+ - Checks localStorage cache first (`miso:client-token` and `miso:client-token-expires-at`)
457
+ - Fetches from backend endpoint if cache miss or expired
458
+ - Uses `clientTokenUri` from config or defaults to `/api/v1/auth/client-token`
459
+ - Supports absolute URLs and relative paths
460
+ - Handles nested and flat response formats
461
+ - ISO 27001 audit logging integration
462
+ - Automatic cache expiration handling
463
+
464
+ - **DataClient `getClientTokenInfo()` method** - Extract token metadata in browser
465
+ - New public method to extract application/environment info from client token
466
+ - Checks cached token first, then config token
467
+ - Returns `ClientTokenInfo` object or `null` if no token available
468
+ - Useful for displaying current application/environment in UI
469
+ - Handles decode errors gracefully
470
+
471
+ - **DataClient `logout()` method** - Logout functionality for browser applications
472
+ - Calls controller logout API to invalidate server-side session
473
+ - Clears authentication tokens from localStorage (all configured token keys)
474
+ - Clears HTTP response cache
475
+ - Redirects to logout URL or login page
476
+ - Supports optional `redirectUrl` parameter for custom redirect after logout
477
+ - Gracefully handles API failures (always clears local state)
478
+ - SSR compatible (no-op in non-browser environments)
479
+
480
+ - **DataClient `logoutUrl` configuration** - Custom logout redirect URL
481
+ - Optional `logoutUrl` property in `DataClientConfig`
482
+ - Falls back to `loginUrl` config if not provided
483
+ - Supports both relative paths and absolute URLs
484
+ - Defaults to `/login` if neither `logoutUrl` nor `loginUrl` is configured
485
+
486
+ ### Changed
487
+
488
+ - **AuthService `getEnvironmentToken()`** - Now uses configurable `clientTokenUri`
489
+ - Changed from hardcoded `/api/v1/auth/token` to `this.config.clientTokenUri || '/api/v1/auth/token'`
490
+ - Maintains backward compatibility (defaults to existing endpoint)
491
+ - Existing error handling and correlation ID generation preserved
492
+
493
+ - **MisoClientConfig interface** - Added new configuration options
494
+ - New optional property: `clientTokenUri?: string`
495
+ - New optional property: `allowedOrigins?: string[]`
496
+
497
+ - **DataClient configuration** - Added `logoutUrl` option to `DataClientConfig` interface
498
+ - New optional property: `logoutUrl?: string`
499
+ - Follows same pattern as `loginUrl` configuration
500
+
501
+ ### Technical
502
+
503
+ - **New utility files**:
504
+ - `src/utils/origin-validator.ts` - Origin validation with wildcard port support
505
+ - `src/utils/environment-token.ts` - Server-side wrapper with audit logging
506
+ - `src/utils/token-utils.ts` - Client token decoding utility
507
+
508
+ - **New test files**:
509
+ - `tests/unit/origin-validator.test.ts` - 22 tests covering origin validation
510
+ - `tests/unit/token-utils.test.ts` - 20 tests covering token decoding
511
+ - `tests/unit/environment-token.test.ts` - 10 tests covering server-side wrapper
512
+ - Updated `tests/unit/data-client.test.ts` - Added 22 new tests
513
+ - Updated `tests/unit/config-loader.test.ts` - Added 7 new tests
514
+ - Updated `tests/unit/auth.service.test.ts` - Added 4 new tests
515
+
516
+ - **Exports updated**:
517
+ - `src/index.ts` - Exports `validateOrigin`, `getEnvironmentToken`, `extractClientTokenInfo`, and types
518
+ - `src/express/index.ts` - Exports same utilities for Express applications
519
+
520
+ - **Documentation updated**:
521
+ - `docs/data-client.md` - Added sections for `getEnvironmentToken()` and `getClientTokenInfo()`
522
+ - Includes browser usage examples, server-side route examples, configuration examples, and security best practices
523
+
524
+ ## [2.2.1] - 2025-12-13
525
+
526
+ ### Fixed
527
+
528
+ - **DataClient `redirectToLogin()`** - Fixed redirect to use controller login endpoint
529
+ - Now calls controller's `/api/v1/auth/login` endpoint with redirect parameter
530
+ - Properly constructs full redirect URL instead of relative path
531
+ - Falls back to static loginUrl when misoClient is unavailable or controller call fails
532
+
533
+ ### Changed
534
+
535
+ - **DataClient `redirectToLogin()`** - Enhanced with optional redirect URL parameter
536
+ - Made method async to support controller API calls
537
+ - Added optional `redirectUrl` parameter (defaults to current page URL)
538
+ - Returns controller's login URL for proper OAuth flow handling
539
+
540
+ ## [2.2.0] - 2025-12-13
541
+
542
+ ### Added
543
+
544
+ - **DataClient Browser Wrapper** - Browser-compatible HTTP client wrapper around MisoClient
545
+ - Enhanced HTTP client capabilities for React/front-end applications
546
+ - ISO 27001 compliant audit logging with configurable levels (minimal, standard, detailed, full)
547
+ - Automatic sensitive data masking using DataMasker before audit logging
548
+ - Request/response interceptors for custom request/response transformation
549
+ - Response caching with configurable TTL and cache size limits
550
+ - Automatic retry logic with exponential backoff for retryable errors
551
+ - Request deduplication for concurrent duplicate requests
552
+ - Request metrics tracking (response times, error rates, cache hit rates)
553
+ - Custom error types (NetworkError, TimeoutError, AuthenticationError)
554
+ - Browser compatibility checks with SSR support
555
+ - Token management from localStorage with multiple key support
556
+ - Automatic login redirect on authentication errors
557
+ - Support for all HTTP methods (GET, POST, PUT, PATCH, DELETE)
558
+ - Request cancellation via AbortController
559
+ - Per-request timeout support
560
+ - Integration with MisoClient for authentication and audit logging
561
+ - **Client Token Pattern** - Secure browser usage without exposing clientSecret
562
+ - Support for server-provided client tokens (`clientToken`, `clientTokenExpiresAt`)
563
+ - Token refresh callback pattern (`onClientTokenRefresh`) for browser applications
564
+ - Automatic token refresh with proactive expiration handling (60s buffer)
565
+ - Memory-only token storage (never persisted to localStorage)
566
+
567
+ ### Changed
568
+
569
+ - **MisoClientConfig** - `clientSecret` is now optional when using client token pattern
570
+ - Added `clientToken?: string` - Pre-obtained client token for browser usage
571
+ - Added `clientTokenExpiresAt?: Date | string` - Token expiration tracking
572
+ - Added `onClientTokenRefresh?: () => Promise<{ token: string; expiresIn: number }>` - Refresh callback
573
+ - `InternalHttpClient` now supports both clientSecret (server-side) and clientToken (browser) patterns
574
+
575
+ ## [2.1.2] - 2025-12-11
576
+
577
+ ### Added
578
+
579
+ - **Express.js Utilities** - Complete set of utilities for building Express.js REST APIs
580
+ - `ResponseHelper` - Standardized API response formatting (success, created, paginated, noContent, accepted)
581
+ - `injectResponseHelpers` - Middleware to inject response helpers into Express Response
582
+ - `asyncHandler` and `asyncHandlerNamed` - Automatic error handling for async route handlers
583
+ - `ValidationHelper` - Common validation patterns (findOrFail, ensureNotExists, ensureOwnershipOrAdmin, etc.)
584
+ - `AppError` - Application error class with RFC 7807 support
585
+ - `handleRouteError` - Centralized error handling for Express routes
586
+ - `setErrorLogger` - Injectable error logger for custom logging
587
+ - `EncryptionUtil` - AES-256-GCM encryption utility (replaces EncryptionService)
588
+ - Express Response type augmentation for TypeScript
589
+
590
+ - **Sort Utilities** - Client-side sorting helpers
591
+ - `applySorting()` - Apply sorting to in-memory data arrays
592
+ - `parseSortParams()` - Parse sort query parameters (already existed)
593
+
594
+ - **GitHub Workflows** - Manual release management
595
+ - Manual Version Bump workflow - Bump version, create git tags, and GitHub Releases
596
+ - Manual Publish to NPM workflow - Publish to npm with validation and verification
597
+
598
+ - **Package Configuration**
599
+ - Express as optional peer dependency (^4.18.0 || ^5.0.0)
600
+ - @types/express as dev dependency
601
+
602
+ - **Authentication API Updates**
603
+ - `LoginResponse` and `LogoutResponse` types for standardized authentication responses
604
+ - Updated `login()` method to make API call to `/api/v1/auth/login` with query parameters (redirect, state)
605
+ - Updated `logout()` method to accept token parameter and make API call to `/api/v1/auth/logout`
606
+ - Comprehensive test coverage for `response-middleware.ts` (100% coverage)
607
+
608
+ ### Changed
609
+
610
+ - **Package Description** - Updated to include Express.js utilities
611
+ - **EncryptionService** - Replaced instance-based EncryptionService with static EncryptionUtil class
612
+ - **Workflow Strategy** - Removed automatic publish on push, added manual workflows for better control
613
+ - **Authentication Methods** - Breaking changes:
614
+ - `login()` - Changed from synchronous method returning URL string to async method returning `LoginResponse` object
615
+ - `logout()` - Now requires `{ token: string }` parameter and returns `LogoutResponse` object
616
+
617
+ ### Removed
618
+
619
+ - Old automatic npm-publish workflow (replaced by manual workflows)
620
+ - EncryptionService class (replaced by EncryptionUtil)
621
+
622
+ ## [2.0.0] - Previous Release
623
+
624
+ See git history for previous changes.
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Auth Cache API client
3
+ * Handles cache statistics and management
4
+ */
5
+ import { HttpClient } from '../utils/http-client';
6
+ import { AuthStrategy } from '../types/config.types';
7
+ import { CacheStatsResponse, CachePerformanceResponse, CacheEfficiencyResponse, ClearCacheResponse, InvalidateCacheRequest, InvalidateCacheResponse } from './types/auth.types';
8
+ /**
9
+ * Auth Cache API class
10
+ * Handles cache-related endpoints
11
+ */
12
+ export declare class AuthCacheApi {
13
+ private httpClient;
14
+ private static readonly CACHE_STATS_ENDPOINT;
15
+ private static readonly CACHE_PERFORMANCE_ENDPOINT;
16
+ private static readonly CACHE_EFFICIENCY_ENDPOINT;
17
+ private static readonly CACHE_CLEAR_ENDPOINT;
18
+ private static readonly CACHE_INVALIDATE_ENDPOINT;
19
+ constructor(httpClient: HttpClient);
20
+ /**
21
+ * Get cache statistics
22
+ * @param authStrategy - Optional authentication strategy override
23
+ * @returns Cache stats response with hits, misses, and size
24
+ */
25
+ getCacheStats(authStrategy?: AuthStrategy): Promise<CacheStatsResponse>;
26
+ /**
27
+ * Get cache performance metrics
28
+ * @param authStrategy - Optional authentication strategy override
29
+ * @returns Cache performance response with hitRate and avgResponseTime
30
+ */
31
+ getCachePerformance(authStrategy?: AuthStrategy): Promise<CachePerformanceResponse>;
32
+ /**
33
+ * Get cache efficiency metrics
34
+ * @param authStrategy - Optional authentication strategy override
35
+ * @returns Cache efficiency response with efficiency score
36
+ */
37
+ getCacheEfficiency(authStrategy?: AuthStrategy): Promise<CacheEfficiencyResponse>;
38
+ /**
39
+ * Clear authentication cache
40
+ * @param authStrategy - Optional authentication strategy override
41
+ * @returns Clear cache response with success message
42
+ */
43
+ clearCache(authStrategy?: AuthStrategy): Promise<ClearCacheResponse>;
44
+ /**
45
+ * Invalidate cache entries by pattern
46
+ * @param params - Invalidate cache request parameters
47
+ * @param authStrategy - Optional authentication strategy override
48
+ * @returns Invalidate cache response with number of invalidated entries
49
+ */
50
+ invalidateCache(params: InvalidateCacheRequest, authStrategy?: AuthStrategy): Promise<InvalidateCacheResponse>;
51
+ }
52
+ //# sourceMappingURL=auth-cache.api.d.ts.map