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