@nibssplc/cams-sdk 0.0.1-beta.30 โ†’ 0.0.1-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,17 +10,27 @@ Central Authentication Management Service (CAMS) SDK for popup-based authenticat
10
10
  - ๐Ÿ”„ Automatic token management with JWT expiration checking
11
11
  - ๐Ÿ“ฑ Session management with event callbacks
12
12
  - ๐Ÿงช Comprehensive TypeScript support with Zod validation
13
+ - โš›๏ธ React hooks and components for seamless integration
14
+ - ๐Ÿ”ต Azure AD MSAL integration support
13
15
  - โœ… Full test coverage
14
16
 
15
- ## Installation
17
+ ## Packages
16
18
 
19
+ ### Core SDK
17
20
  ```bash
18
21
  npm install @nibssplc/cams-sdk
19
22
  ```
20
23
 
24
+ ### React Integration
25
+ ```bash
26
+ npm install @nibssplc/cams-sdk-react
27
+ ```
28
+
21
29
  ## Quick Start
22
30
 
23
- ### Basic Usage
31
+ ### Core SDK Usage
32
+
33
+ #### Basic Popup Authentication
24
34
 
25
35
  ```typescript
26
36
  import { openCAMSPopUpLogin, CAMSConfig } from '@nibssplc/cams-sdk';
@@ -36,36 +46,25 @@ const config: CAMSConfig = {
36
46
  };
37
47
 
38
48
  try {
39
- const response = await openCAMSPopUpLogin(config);
40
- console.log('Authentication successful:', response.token);
49
+ const profile = await openCAMSPopUpLogin(config);
50
+ console.log('Authentication successful:', profile);
41
51
  } catch (error) {
42
52
  console.error('Authentication failed:', error);
43
53
  }
44
54
  ```
45
55
 
46
- ### Session Management (Recommended)
56
+ #### Session Management
47
57
 
48
58
  ```typescript
49
- import { CAMSSessionManager, CAMSEvents } from '@nibssplc/cams-sdk';
59
+ import { CAMSSessionManager } from '@nibssplc/cams-sdk';
50
60
 
51
- const events: CAMSEvents = {
52
- onAuthStart: () => console.log('Authentication started'),
53
- onAuthSuccess: (token) => console.log('Login successful'),
61
+ const session = new CAMSSessionManager(localStorage, 'my_app', {
62
+ onAuthSuccess: (response) => console.log('Login successful'),
54
63
  onAuthError: (error) => console.error('Login failed:', error),
55
64
  onTokenExpired: () => console.log('Token expired'),
56
- };
57
-
58
- const session = new CAMSSessionManager(localStorage, 'my_app', events);
59
-
60
- // Login with retry logic
61
- const config = {
62
- camsUrl: 'https://your-cams-instance.com/auth',
63
- messageOrigin: 'your-cams-instance.com',
64
- windowWidth: 500,
65
- windowHeight: 600,
66
- retryAttempts: 2, // Retry twice on failure
67
- };
65
+ });
68
66
 
67
+ // Login
69
68
  try {
70
69
  await session.login(config);
71
70
 
@@ -82,8 +81,140 @@ try {
82
81
  await session.logout();
83
82
  ```
84
83
 
84
+ ### React Integration
85
+
86
+ #### Basic React Hook
87
+
88
+ ```typescript
89
+ import { useCAMSAuth } from '@nibssplc/cams-sdk-react';
90
+
91
+ function LoginComponent() {
92
+ const { login, logout, isAuthenticated, isLoading, error, profile } = useCAMSAuth({
93
+ appCode: 'your-app-code',
94
+ storageKey: 'CAMS-AUTH-SDK',
95
+ });
96
+
97
+ const handleLogin = async () => {
98
+ await login({
99
+ camsUrl: 'https://your-cams-instance.com/auth',
100
+ messageOrigin: 'your-cams-instance.com',
101
+ windowWidth: 500,
102
+ windowHeight: 600,
103
+ });
104
+ };
105
+
106
+ if (isLoading) return <div>Loading...</div>;
107
+ if (error) return <div>Error: {error.message}</div>;
108
+
109
+ return (
110
+ <div>
111
+ {isAuthenticated ? (
112
+ <div>
113
+ <p>Welcome, {profile?.name}!</p>
114
+ <button onClick={logout}>Logout</button>
115
+ </div>
116
+ ) : (
117
+ <button onClick={handleLogin}>Login</button>
118
+ )}
119
+ </div>
120
+ );
121
+ }
122
+ ```
123
+
124
+ #### React Provider Pattern
125
+
126
+ ```typescript
127
+ import { CAMSProvider, useCAMSContext } from '@nibssplc/cams-sdk-react';
128
+
129
+ // App.tsx
130
+ function App() {
131
+ return (
132
+ <CAMSProvider appCode="your-app-code" storageKey="CAMS-AUTH-SDK">
133
+ <LoginComponent />
134
+ </CAMSProvider>
135
+ );
136
+ }
137
+
138
+ // LoginComponent.tsx
139
+ function LoginComponent() {
140
+ const { login, logout, isAuthenticated, userProfile } = useCAMSContext();
141
+
142
+ const handleLogin = async () => {
143
+ await login({
144
+ camsUrl: 'https://your-cams-instance.com/auth',
145
+ messageOrigin: 'your-cams-instance.com',
146
+ windowWidth: 500,
147
+ windowHeight: 600,
148
+ });
149
+ };
150
+
151
+ return (
152
+ <div>
153
+ {isAuthenticated ? (
154
+ <div>
155
+ <p>Welcome, {userProfile?.name}!</p>
156
+ <button onClick={logout}>Logout</button>
157
+ </div>
158
+ ) : (
159
+ <button onClick={handleLogin}>Login</button>
160
+ )}
161
+ </div>
162
+ );
163
+ }
164
+ ```
165
+
166
+ #### Azure AD MSAL Integration
167
+
168
+ ```typescript
169
+ import { CAMSMSALProvider, useCAMSMSALContext } from '@nibssplc/cams-sdk-react';
170
+ import { Configuration } from '@azure/msal-browser';
171
+
172
+ const msalConfig: Configuration = {
173
+ auth: {
174
+ clientId: 'your-azure-client-id',
175
+ authority: 'https://login.microsoftonline.com/your-tenant-id',
176
+ redirectUri: window.location.origin,
177
+ },
178
+ };
179
+
180
+ // App.tsx
181
+ function App() {
182
+ return (
183
+ <CAMSMSALProvider
184
+ msalConfig={msalConfig}
185
+ mfaUrl="/auth/multi-factor"
186
+ storageKey="CAMS-MSAL-AUTH-SDK"
187
+ >
188
+ <LoginComponent />
189
+ </CAMSMSALProvider>
190
+ );
191
+ }
192
+
193
+ // LoginComponent.tsx
194
+ function LoginComponent() {
195
+ const { login, logout, isAuthenticated, isLoading, userProfile } = useCAMSMSALContext();
196
+
197
+ if (isLoading) return <div>Loading...</div>;
198
+
199
+ return (
200
+ <div>
201
+ {isAuthenticated ? (
202
+ <div>
203
+ <p>Welcome, {userProfile?.name}!</p>
204
+ <button onClick={logout}>Logout</button>
205
+ </div>
206
+ ) : (
207
+ <button onClick={login}>Login with Azure AD</button>
208
+ )}
209
+ </div>
210
+ );
211
+ }
212
+ ```
213
+
85
214
  ## Configuration Options
86
215
 
216
+ ### Core SDK Configuration
217
+
87
218
  ```typescript
88
219
  interface CAMSConfig {
89
220
  camsUrl: string; // CAMS authentication URL
@@ -98,6 +229,29 @@ interface CAMSConfig {
98
229
  }
99
230
  ```
100
231
 
232
+ ### React Hook Options
233
+
234
+ ```typescript
235
+ interface UseCAMSAuthOptions {
236
+ appCode: string; // Application code
237
+ storageKey?: string; // Storage key (default: "CAMS-AUTH-SDK")
238
+ onAuthSuccess?: (token: string) => void; // Success callback
239
+ onAuthError?: (error: CAMSError) => void; // Error callback
240
+ onTokenExpired?: () => void; // Token expiry callback
241
+ }
242
+
243
+ interface UseCAMSMSALAuthOptions {
244
+ mfaUrl?: string; // MFA URL (default: "/auth/multi-factor")
245
+ storageKey?: string; // Storage key (default: "CAMS-MSAL-AUTH-SDK")
246
+ scopes?: string[]; // MSAL scopes (default: ["openid", "profile", "email"])
247
+ prompt?: string; // MSAL prompt (default: "login")
248
+ allowedOrigins?: string[]; // Allowed message origins
249
+ messageOrigin?: string; // Expected message origin
250
+ onAuthSuccess?: (token: string) => void; // Success callback
251
+ onAuthError?: (error: CAMSError) => void; // Error callback
252
+ }
253
+ ```
254
+
101
255
  ## Error Handling
102
256
 
103
257
  The SDK provides typed errors for better error handling:
@@ -144,9 +298,12 @@ try {
144
298
  - **Secure Storage**: Configurable storage with automatic cleanup
145
299
  - **Input Sanitization**: Log injection prevention
146
300
 
147
- ## Session Manager API
301
+ ## API Reference
302
+
303
+ ### Core SDK
304
+
305
+ #### Session Manager
148
306
 
149
- ### Constructor
150
307
  ```typescript
151
308
  new CAMSSessionManager(
152
309
  storage?: StorageLike | null, // Storage implementation (default: localStorage)
@@ -155,7 +312,7 @@ new CAMSSessionManager(
155
312
  )
156
313
  ```
157
314
 
158
- ### Methods
315
+ **Methods:**
159
316
  - `login(config: CAMSConfig): Promise<CAMSTokenResponse>` - Authenticate user
160
317
  - `logout(): Promise<void>` - Clear session
161
318
  - `isAuthenticated(): boolean` - Check if user is authenticated
@@ -164,6 +321,72 @@ new CAMSSessionManager(
164
321
  - `setToken(token: string): void` - Store token
165
322
  - `clearToken(): void` - Clear stored token
166
323
 
324
+ ### React Hooks
325
+
326
+ #### useCAMSAuth
327
+
328
+ ```typescript
329
+ const {
330
+ login, // (config: CAMSConfig) => Promise<void>
331
+ logout, // () => Promise<void>
332
+ isAuthenticated, // boolean
333
+ isLoading, // boolean
334
+ error, // CAMSError | null
335
+ token, // string | null
336
+ profile, // Profile | null
337
+ appCode, // string
338
+ storageKey, // string
339
+ } = useCAMSAuth(options);
340
+ ```
341
+
342
+ #### useCAMSMSALAuth
343
+
344
+ ```typescript
345
+ const {
346
+ login, // () => Promise<void>
347
+ logout, // () => Promise<void>
348
+ isAuthenticated, // boolean
349
+ isLoading, // boolean
350
+ error, // CAMSError | null
351
+ idToken, // string
352
+ accessToken, // string
353
+ appCode, // string
354
+ storageKey, // string
355
+ } = useCAMSMSALAuth(options);
356
+ ```
357
+
358
+ ### React Components
359
+
360
+ #### CAMSProvider
361
+
362
+ Provides CAMS authentication context to child components.
363
+
364
+ ```typescript
365
+ <CAMSProvider appCode="your-app" storageKey="CAMS-AUTH">
366
+ {children}
367
+ </CAMSProvider>
368
+ ```
369
+
370
+ #### CAMSMSALProvider
371
+
372
+ Provides CAMS + Azure AD MSAL authentication context.
373
+
374
+ ```typescript
375
+ <CAMSMSALProvider msalConfig={config} mfaUrl="/auth/mfa">
376
+ {children}
377
+ </CAMSMSALProvider>
378
+ ```
379
+
380
+ #### ProtectedRoute
381
+
382
+ Route component that requires authentication.
383
+
384
+ ```typescript
385
+ <ProtectedRoute fallback={<LoginPage />}>
386
+ <Dashboard />
387
+ </ProtectedRoute>
388
+ ```
389
+
167
390
  ## Debugging
168
391
 
169
392
  The SDK includes comprehensive logging to aid in debugging:
@@ -191,14 +414,15 @@ const config = {
191
414
 
192
415
  The SDK expects specific message formats from the authentication window:
193
416
 
194
- ### Success Message
417
+ ### Success Message (Profile)
195
418
  ```typescript
196
419
  {
197
- type: "AUTH_SUCCESS",
198
- accessToken: string,
199
- user?: {
420
+ userProfile: {
200
421
  name: string,
201
- image: string | null
422
+ image?: string | null,
423
+ tokens: {
424
+ Bearer: string
425
+ }
202
426
  }
203
427
  }
204
428
  ```
@@ -208,7 +432,15 @@ The SDK expects specific message formats from the authentication window:
208
432
  {
209
433
  type: "AUTH_FAILURE",
210
434
  error: string,
211
- errorCode?: string
435
+ errorCode?: string,
436
+ errorDetails?: any
437
+ }
438
+ ```
439
+
440
+ ### Error Message
441
+ ```typescript
442
+ {
443
+ error: string
212
444
  }
213
445
  ```
214
446
 
@@ -225,14 +457,41 @@ The SDK expects specific message formats from the authentication window:
225
457
  # Install dependencies
226
458
  npm install
227
459
 
228
- # Run tests
460
+ # Build core SDK
461
+ npm run build
462
+
463
+ # Build React package
464
+ npm run build:react
465
+
466
+ # Run tests (core)
229
467
  npm test
230
468
 
231
- # Build
232
- npm run build
469
+ # Run tests (React)
470
+ npm run test:react
233
471
 
234
472
  # Lint
235
473
  npm run lint
474
+
475
+ # Publish all packages
476
+ npm run publish:all
477
+ ```
478
+
479
+ ## Project Structure
480
+
481
+ ```
482
+ NIBSS-CAMS-SDK/
483
+ โ”œโ”€โ”€ src/ # Core SDK source
484
+ โ”‚ โ”œโ”€โ”€ auth.ts # Main authentication logic
485
+ โ”‚ โ”œโ”€โ”€ sessionManager.ts # Session management
486
+ โ”‚ โ”œโ”€โ”€ types.ts # TypeScript definitions
487
+ โ”‚ โ”œโ”€โ”€ validators.ts # Zod schemas
488
+ โ”‚ โ””โ”€โ”€ logger.ts # Logging utilities
489
+ โ”œโ”€โ”€ packages/
490
+ โ”‚ โ””โ”€โ”€ react/ # React integration package
491
+ โ”‚ โ””โ”€โ”€ src/
492
+ โ”‚ โ”œโ”€โ”€ hooks/ # React hooks
493
+ โ”‚ โ””โ”€โ”€ components/ # React components
494
+ โ””โ”€โ”€ dist/ # Built packages
236
495
  ```
237
496
 
238
497
  ## License
package/dist/auth.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { CAMSConfig } from "./types";
2
2
  import { Profile } from "./validators";
3
+ export declare const generateSecureWindowName: () => string;
3
4
  export declare function validateConfig(config: CAMSConfig): URL;
4
5
  export declare function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile>;
package/dist/index.cjs.js CHANGED
@@ -64,38 +64,24 @@ class Logger {
64
64
  static setLevel(level) {
65
65
  Logger.level = level;
66
66
  }
67
- static sanitizeForLog(input) {
68
- if (typeof input === 'string') {
69
- // Remove newlines and control characters to prevent log injection
70
- return input.replace(/[\r\n\t]/g, ' ').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
71
- }
72
- if (typeof input === 'object' && input !== null) {
73
- const sanitized = {};
74
- for (const [key, value] of Object.entries(input)) {
75
- sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);
76
- }
77
- return sanitized;
78
- }
79
- return input;
80
- }
81
67
  static error(message, context) {
82
68
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
83
- console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
69
+ console.error(`${Logger.prefix} ERROR:`, message, context || '');
84
70
  }
85
71
  }
86
72
  static warn(message, context) {
87
73
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
88
- console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
74
+ console.warn(`${Logger.prefix} WARN:`, message, context || '');
89
75
  }
90
76
  }
91
77
  static info(message, context) {
92
78
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
93
- console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
79
+ console.info(`${Logger.prefix} INFO:`, message, context || '');
94
80
  }
95
81
  }
96
82
  static debug(message, context) {
97
83
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
98
- console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
84
+ console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
99
85
  }
100
86
  }
101
87
  }
@@ -572,6 +558,7 @@ exports.ErrorMessageSchema = ErrorMessageSchema;
572
558
  exports.Logger = Logger;
573
559
  exports.ProfileSchema = ProfileSchema;
574
560
  exports.URLSchema = URLSchema;
561
+ exports.generateSecureWindowName = generateSecureWindowName;
575
562
  exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
576
563
  exports.validateConfig = validateConfig;
577
564
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\"),\n userProfile: z\n .object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n redirectURL: z.url().optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n private static sanitizeForLog(input: any): any {\n if (typeof input === 'string') {\n // Remove newlines and control characters to prevent log injection\n return input.replace(/[\\r\\n\\t]/g, ' ').replace(/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]/g, '');\n }\n if (typeof input === 'object' && input !== null) {\n const sanitized: any = {};\n for (const [key, value] of Object.entries(input)) {\n sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);\n }\n return sanitized;\n }\n return input;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Capture original functions to prevent tampering\nconst originalWindowOpen = window.open;\nconst originalAddEventListener = window.addEventListener;\nconst originalRemoveEventListener = window.removeEventListener;\nconst originalSetTimeout = window.setTimeout;\nconst originalClearTimeout = window.clearTimeout;\n\n// Generate random window name to prevent targeting\nconst generateSecureWindowName = () =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n // Domain validation is mandatory for security\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 120000, // 2 minutes of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: number | null = null;\n let idleTimeoutId: number | null = null;\n let checkClosedInterval: number | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n const secureWindowName = generateSecureWindowName();\n authWindow = originalWindowOpen.call(\n window,\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Only check for immediate closure (true popup blocking)\n if (authWindow.closed) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n originalRemoveEventListener.call(window, \"message\", listener);\n\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n if (authTimeoutId) originalClearTimeout(authTimeoutId);\n if (checkClosedInterval) originalClearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: Event) => {\n const messageEvent = event as MessageEvent;\n Logger.debug(\"Received message\", {\n origin: messageEvent.origin,\n expectedOrigin: messageOrigin,\n data: messageEvent.data,\n });\n\n const originUrl = new URL(messageEvent.origin);\n const expectedHostname = messageOrigin.startsWith(\"http\")\n ? new URL(messageOrigin).hostname\n : messageOrigin;\n\n // Allow Microsoft redirect domains for Azure AD authentication\n const isMicrosoftDomain =\n originUrl.hostname.endsWith(\".microsoft.com\") ||\n originUrl.hostname.endsWith(\".microsoftonline.com\") ||\n originUrl.hostname.endsWith(\".live.com\");\n\n const isAllowedOrigin =\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain;\n\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Ignore heartbeat messages\n if (messageEvent.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // โœ… Validate payload\n const tokenMsg = ProfileSchema.safeParse(messageEvent.data);\n if (tokenMsg.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(tokenMsg.data);\n return;\n }\n\n const authFailureMsg = AuthFailureMessageSchema.safeParse(\n messageEvent.data\n );\n if (authFailureMsg.success) {\n Logger.warn(\"Authentication failure received\", {\n errorDetails: authFailureMsg.data.errorDetails,\n error: authFailureMsg.data.error,\n errorCode: authFailureMsg.data.errorCode,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n \"Authentication failed: \" + authFailureMsg.data.error\n )\n );\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);\n if (errorMsg.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: messageEvent.data,\n dataType: typeof messageEvent.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n\n try {\n originalAddEventListener.call(window, \"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\n }\n });\n}\n","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n // Add padding if needed\n while (result.length % 4) {\n result += \"=\";\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// ๐Ÿ”น Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;AAYYA;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,I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AAE;AACzC,QAAA,IAAI,CAAC,WAAW;AAAE,YAAA,OAAO,IAAI;;AAG7B,QAAA,IAAI,IAAI,CAAC,oBAAoB,EAAE,EAAE;AAC/B,YAAA,OAAO,IAAI;QACb;QAEA,OAAO,IAAI,CAAC,OAAO;IACrB;IAEA,eAAe,GAAA;AACb,QAAA,OAAO,IAAI;IACb;AACD;AASD;AACA,SAAS,iBAAiB,GAAA;IACxB,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,YAAY,EAAE;QACxD,OAAO,MAAM,CAAC,YAAY;IAC5B;IAEA,MAAM,WAAW,GAA2B,EAAE;IAC9C,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,MAAM,GAAG,IAAI,WAAW,GAAG,WAAW,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AAChE,QAAA,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,KAAI;AACtB,YAAA,WAAW,CAAC,GAAG,CAAC,GAAG,KAAK;QAC1B,CAAC;AACD,QAAA,UAAU,EAAE,CAAC,GAAG,KAAI;AAClB,YAAA,OAAO,WAAW,CAAC,GAAG,CAAC;QACzB,CAAC;AACD,QAAA,GAAG,EAAE,CAAC,CAAS,KAAK,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI;AACvD,QAAA,IAAI,MAAM,GAAA;YACR,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM;QACxC,CAAC;KACF;AACH;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\"),\n userProfile: z\n .object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n redirectURL: z.url().optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Capture original functions to prevent tampering\nconst originalWindowOpen = window.open;\nconst originalAddEventListener = window.addEventListener;\nconst originalRemoveEventListener = window.removeEventListener;\nconst originalSetTimeout = window.setTimeout;\nconst originalClearTimeout = window.clearTimeout;\n\n// Generate random window name to prevent targeting\nexport const generateSecureWindowName = () =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n // Domain validation is mandatory for security\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 120000, // 2 minutes of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: number | null = null;\n let idleTimeoutId: number | null = null;\n let checkClosedInterval: number | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n const secureWindowName = generateSecureWindowName();\n authWindow = originalWindowOpen.call(\n window,\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Only check for immediate closure (true popup blocking)\n if (authWindow.closed) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n originalRemoveEventListener.call(window, \"message\", listener);\n\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n if (authTimeoutId) originalClearTimeout(authTimeoutId);\n if (checkClosedInterval) originalClearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: Event) => {\n const messageEvent = event as MessageEvent;\n Logger.debug(\"Received message\", {\n origin: messageEvent.origin,\n expectedOrigin: messageOrigin,\n data: messageEvent.data,\n });\n\n const originUrl = new URL(messageEvent.origin);\n const expectedHostname = messageOrigin.startsWith(\"http\")\n ? new URL(messageOrigin).hostname\n : messageOrigin;\n\n // Allow Microsoft redirect domains for Azure AD authentication\n const isMicrosoftDomain =\n originUrl.hostname.endsWith(\".microsoft.com\") ||\n originUrl.hostname.endsWith(\".microsoftonline.com\") ||\n originUrl.hostname.endsWith(\".live.com\");\n\n const isAllowedOrigin =\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain;\n\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Ignore heartbeat messages\n if (messageEvent.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // โœ… Validate payload\n const tokenMsg = ProfileSchema.safeParse(messageEvent.data);\n if (tokenMsg.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(tokenMsg.data);\n return;\n }\n\n const authFailureMsg = AuthFailureMessageSchema.safeParse(\n messageEvent.data\n );\n if (authFailureMsg.success) {\n Logger.warn(\"Authentication failure received\", {\n errorDetails: authFailureMsg.data.errorDetails,\n error: authFailureMsg.data.error,\n errorCode: authFailureMsg.data.errorCode,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n \"Authentication failed: \" + authFailureMsg.data.error\n )\n );\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);\n if (errorMsg.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: messageEvent.data,\n dataType: typeof messageEvent.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n\n try {\n originalAddEventListener.call(window, \"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\n }\n });\n}\n","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n // Add padding if needed\n while (result.length % 4) {\n result += \"=\";\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// ๐Ÿ”น Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;AAYYA;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC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CAAC;QACzB,CAAC;AACD,QAAA,GAAG,EAAE,CAAC,CAAS,KAAK,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI;AACvD,QAAA,IAAI,MAAM,GAAA;YACR,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM;QACxC,CAAC;KACF;AACH;;;;;;;;;;;;;"}
package/dist/index.esm.js CHANGED
@@ -62,38 +62,24 @@ class Logger {
62
62
  static setLevel(level) {
63
63
  Logger.level = level;
64
64
  }
65
- static sanitizeForLog(input) {
66
- if (typeof input === 'string') {
67
- // Remove newlines and control characters to prevent log injection
68
- return input.replace(/[\r\n\t]/g, ' ').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
69
- }
70
- if (typeof input === 'object' && input !== null) {
71
- const sanitized = {};
72
- for (const [key, value] of Object.entries(input)) {
73
- sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);
74
- }
75
- return sanitized;
76
- }
77
- return input;
78
- }
79
65
  static error(message, context) {
80
66
  if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {
81
- console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
67
+ console.error(`${Logger.prefix} ERROR:`, message, context || '');
82
68
  }
83
69
  }
84
70
  static warn(message, context) {
85
71
  if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {
86
- console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
72
+ console.warn(`${Logger.prefix} WARN:`, message, context || '');
87
73
  }
88
74
  }
89
75
  static info(message, context) {
90
76
  if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {
91
- console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
77
+ console.info(`${Logger.prefix} INFO:`, message, context || '');
92
78
  }
93
79
  }
94
80
  static debug(message, context) {
95
81
  if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {
96
- console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
82
+ console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
97
83
  }
98
84
  }
99
85
  }
@@ -563,5 +549,5 @@ function getDefaultStorage() {
563
549
  };
564
550
  }
565
551
 
566
- export { AuthFailureMessageSchema, CAMSError, CAMSErrorType, CAMSSessionManager, ErrorMessageSchema, LogLevel, Logger, ProfileSchema, URLSchema, openCAMSPopUpLogin, validateConfig };
552
+ export { AuthFailureMessageSchema, CAMSError, CAMSErrorType, CAMSSessionManager, ErrorMessageSchema, LogLevel, Logger, ProfileSchema, URLSchema, generateSecureWindowName, openCAMSPopUpLogin, validateConfig };
567
553
  //# sourceMappingURL=index.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\"),\n userProfile: z\n .object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n redirectURL: z.url().optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n private static sanitizeForLog(input: any): any {\n if (typeof input === 'string') {\n // Remove newlines and control characters to prevent log injection\n return input.replace(/[\\r\\n\\t]/g, ' ').replace(/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]/g, '');\n }\n if (typeof input === 'object' && input !== null) {\n const sanitized: any = {};\n for (const [key, value] of Object.entries(input)) {\n sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);\n }\n return sanitized;\n }\n return input;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Capture original functions to prevent tampering\nconst originalWindowOpen = window.open;\nconst originalAddEventListener = window.addEventListener;\nconst originalRemoveEventListener = window.removeEventListener;\nconst originalSetTimeout = window.setTimeout;\nconst originalClearTimeout = window.clearTimeout;\n\n// Generate random window name to prevent targeting\nconst generateSecureWindowName = () =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n // Domain validation is mandatory for security\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 120000, // 2 minutes of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: number | null = null;\n let idleTimeoutId: number | null = null;\n let checkClosedInterval: number | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n const secureWindowName = generateSecureWindowName();\n authWindow = originalWindowOpen.call(\n window,\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Only check for immediate closure (true popup blocking)\n if (authWindow.closed) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n originalRemoveEventListener.call(window, \"message\", listener);\n\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n if (authTimeoutId) originalClearTimeout(authTimeoutId);\n if (checkClosedInterval) originalClearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: Event) => {\n const messageEvent = event as MessageEvent;\n Logger.debug(\"Received message\", {\n origin: messageEvent.origin,\n expectedOrigin: messageOrigin,\n data: messageEvent.data,\n });\n\n const originUrl = new URL(messageEvent.origin);\n const expectedHostname = messageOrigin.startsWith(\"http\")\n ? new URL(messageOrigin).hostname\n : messageOrigin;\n\n // Allow Microsoft redirect domains for Azure AD authentication\n const isMicrosoftDomain =\n originUrl.hostname.endsWith(\".microsoft.com\") ||\n originUrl.hostname.endsWith(\".microsoftonline.com\") ||\n originUrl.hostname.endsWith(\".live.com\");\n\n const isAllowedOrigin =\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain;\n\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Ignore heartbeat messages\n if (messageEvent.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // โœ… Validate payload\n const tokenMsg = ProfileSchema.safeParse(messageEvent.data);\n if (tokenMsg.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(tokenMsg.data);\n return;\n }\n\n const authFailureMsg = AuthFailureMessageSchema.safeParse(\n messageEvent.data\n );\n if (authFailureMsg.success) {\n Logger.warn(\"Authentication failure received\", {\n errorDetails: authFailureMsg.data.errorDetails,\n error: authFailureMsg.data.error,\n errorCode: authFailureMsg.data.errorCode,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n \"Authentication failed: \" + authFailureMsg.data.error\n )\n );\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);\n if (errorMsg.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: messageEvent.data,\n dataType: typeof messageEvent.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n\n try {\n originalAddEventListener.call(window, \"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\n }\n });\n}\n","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n // Add padding if needed\n while (result.length % 4) {\n result += \"=\";\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// ๐Ÿ”น Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n"],"names":[],"mappings":";;IAYY;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA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AAC,cAAc,EAAE;AACzC,QAAA,IAAI,CAAC,WAAW;AAAE,YAAA,OAAO,IAAI;;AAG7B,QAAA,IAAI,IAAI,CAAC,oBAAoB,EAAE,EAAE;AAC/B,YAAA,OAAO,IAAI;QACb;QAEA,OAAO,IAAI,CAAC,OAAO;IACrB;IAEA,eAAe,GAAA;AACb,QAAA,OAAO,IAAI;IACb;AACD;AASD;AACA,SAAS,iBAAiB,GAAA;IACxB,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,YAAY,EAAE;QACxD,OAAO,MAAM,CAAC,YAAY;IAC5B;IAEA,MAAM,WAAW,GAA2B,EAAE;IAC9C,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,MAAM,GAAG,IAAI,WAAW,GAAG,WAAW,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AAChE,QAAA,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,KAAI;AACtB,YAAA,WAAW,CAAC,GAAG,CAAC,GAAG,KAAK;QAC1B,CAAC;AACD,QAAA,UAAU,EAAE,CAAC,GAAG,KAAI;AAClB,YAAA,OAAO,WAAW,CAAC,GAAG,CAAC;QACzB,CAAC;AACD,QAAA,GAAG,EAAE,CAAC,CAAS,KAAK,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI;AACvD,QAAA,IAAI,MAAM,GAAA;YACR,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM;QACxC,CAAC;KACF;AACH;;;;"}
1
+ {"version":3,"file":"index.esm.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\"),\n userProfile: z\n .object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n redirectURL: z.url().optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Capture original functions to prevent tampering\nconst originalWindowOpen = window.open;\nconst originalAddEventListener = window.addEventListener;\nconst originalRemoveEventListener = window.removeEventListener;\nconst originalSetTimeout = window.setTimeout;\nconst originalClearTimeout = window.clearTimeout;\n\n// Generate random window name to prevent targeting\nexport const generateSecureWindowName = () =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n // Domain validation is mandatory for security\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 120000, // 2 minutes of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: number | null = null;\n let idleTimeoutId: number | null = null;\n let checkClosedInterval: number | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n const secureWindowName = generateSecureWindowName();\n authWindow = originalWindowOpen.call(\n window,\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Only check for immediate closure (true popup blocking)\n if (authWindow.closed) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n originalRemoveEventListener.call(window, \"message\", listener);\n\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n if (authTimeoutId) originalClearTimeout(authTimeoutId);\n if (checkClosedInterval) originalClearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: Event) => {\n const messageEvent = event as MessageEvent;\n Logger.debug(\"Received message\", {\n origin: messageEvent.origin,\n expectedOrigin: messageOrigin,\n data: messageEvent.data,\n });\n\n const originUrl = new URL(messageEvent.origin);\n const expectedHostname = messageOrigin.startsWith(\"http\")\n ? new URL(messageOrigin).hostname\n : messageOrigin;\n\n // Allow Microsoft redirect domains for Azure AD authentication\n const isMicrosoftDomain =\n originUrl.hostname.endsWith(\".microsoft.com\") ||\n originUrl.hostname.endsWith(\".microsoftonline.com\") ||\n originUrl.hostname.endsWith(\".live.com\");\n\n const isAllowedOrigin =\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain;\n\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Ignore heartbeat messages\n if (messageEvent.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // โœ… Validate payload\n const tokenMsg = ProfileSchema.safeParse(messageEvent.data);\n if (tokenMsg.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(tokenMsg.data);\n return;\n }\n\n const authFailureMsg = AuthFailureMessageSchema.safeParse(\n messageEvent.data\n );\n if (authFailureMsg.success) {\n Logger.warn(\"Authentication failure received\", {\n errorDetails: authFailureMsg.data.errorDetails,\n error: authFailureMsg.data.error,\n errorCode: authFailureMsg.data.errorCode,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n \"Authentication failed: \" + authFailureMsg.data.error\n )\n );\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);\n if (errorMsg.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: messageEvent.data,\n dataType: typeof messageEvent.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n\n try {\n originalAddEventListener.call(window, \"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\n }\n });\n}\n","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n // Add padding if needed\n while (result.length % 4) {\n result += \"=\";\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// ๐Ÿ”น Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n"],"names":[],"mappings":";;IAYY;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAA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C,CAAC,IAAI,IAAI;AACvD,QAAA,IAAI,MAAM,GAAA;YACR,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM;QACxC,CAAC;KACF;AACH;;;;"}
package/dist/index.umd.js CHANGED
@@ -66,38 +66,24 @@
66
66
  static setLevel(level) {
67
67
  Logger.level = level;
68
68
  }
69
- static sanitizeForLog(input) {
70
- if (typeof input === 'string') {
71
- // Remove newlines and control characters to prevent log injection
72
- return input.replace(/[\r\n\t]/g, ' ').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
73
- }
74
- if (typeof input === 'object' && input !== null) {
75
- const sanitized = {};
76
- for (const [key, value] of Object.entries(input)) {
77
- sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);
78
- }
79
- return sanitized;
80
- }
81
- return input;
82
- }
83
69
  static error(message, context) {
84
70
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
85
- console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
71
+ console.error(`${Logger.prefix} ERROR:`, message, context || '');
86
72
  }
87
73
  }
88
74
  static warn(message, context) {
89
75
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
90
- console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
76
+ console.warn(`${Logger.prefix} WARN:`, message, context || '');
91
77
  }
92
78
  }
93
79
  static info(message, context) {
94
80
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
95
- console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
81
+ console.info(`${Logger.prefix} INFO:`, message, context || '');
96
82
  }
97
83
  }
98
84
  static debug(message, context) {
99
85
  if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
100
- console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));
86
+ console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
101
87
  }
102
88
  }
103
89
  }
@@ -574,6 +560,7 @@
574
560
  exports.Logger = Logger;
575
561
  exports.ProfileSchema = ProfileSchema;
576
562
  exports.URLSchema = URLSchema;
563
+ exports.generateSecureWindowName = generateSecureWindowName;
577
564
  exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
578
565
  exports.validateConfig = validateConfig;
579
566
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\"),\n userProfile: z\n .object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n redirectURL: z.url().optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n private static sanitizeForLog(input: any): any {\n if (typeof input === 'string') {\n // Remove newlines and control characters to prevent log injection\n return input.replace(/[\\r\\n\\t]/g, ' ').replace(/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]/g, '');\n }\n if (typeof input === 'object' && input !== null) {\n const sanitized: any = {};\n for (const [key, value] of Object.entries(input)) {\n sanitized[Logger.sanitizeForLog(key)] = Logger.sanitizeForLog(value);\n }\n return sanitized;\n }\n return input;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, Logger.sanitizeForLog(message), Logger.sanitizeForLog(context || ''));\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Capture original functions to prevent tampering\nconst originalWindowOpen = window.open;\nconst originalAddEventListener = window.addEventListener;\nconst originalRemoveEventListener = window.removeEventListener;\nconst originalSetTimeout = window.setTimeout;\nconst originalClearTimeout = window.clearTimeout;\n\n// Generate random window name to prevent targeting\nconst generateSecureWindowName = () =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n // Domain validation is mandatory for security\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 120000, // 2 minutes of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: number | null = null;\n let idleTimeoutId: number | null = null;\n let checkClosedInterval: number | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n const secureWindowName = generateSecureWindowName();\n authWindow = originalWindowOpen.call(\n window,\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Only check for immediate closure (true popup blocking)\n if (authWindow.closed) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n originalRemoveEventListener.call(window, \"message\", listener);\n\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n if (authTimeoutId) originalClearTimeout(authTimeoutId);\n if (checkClosedInterval) originalClearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: Event) => {\n const messageEvent = event as MessageEvent;\n Logger.debug(\"Received message\", {\n origin: messageEvent.origin,\n expectedOrigin: messageOrigin,\n data: messageEvent.data,\n });\n\n const originUrl = new URL(messageEvent.origin);\n const expectedHostname = messageOrigin.startsWith(\"http\")\n ? new URL(messageOrigin).hostname\n : messageOrigin;\n\n // Allow Microsoft redirect domains for Azure AD authentication\n const isMicrosoftDomain =\n originUrl.hostname.endsWith(\".microsoft.com\") ||\n originUrl.hostname.endsWith(\".microsoftonline.com\") ||\n originUrl.hostname.endsWith(\".live.com\");\n\n const isAllowedOrigin =\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain;\n\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Ignore heartbeat messages\n if (messageEvent.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // โœ… Validate payload\n const tokenMsg = ProfileSchema.safeParse(messageEvent.data);\n if (tokenMsg.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(tokenMsg.data);\n return;\n }\n\n const authFailureMsg = AuthFailureMessageSchema.safeParse(\n messageEvent.data\n );\n if (authFailureMsg.success) {\n Logger.warn(\"Authentication failure received\", {\n errorDetails: authFailureMsg.data.errorDetails,\n error: authFailureMsg.data.error,\n errorCode: authFailureMsg.data.errorCode,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n \"Authentication failed: \" + authFailureMsg.data.error\n )\n );\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);\n if (errorMsg.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: messageEvent.data,\n dataType: typeof messageEvent.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n\n try {\n originalAddEventListener.call(window, \"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\n }\n });\n}\n","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n // Add padding if needed\n while (result.length % 4) {\n result += \"=\";\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// ๐Ÿ”น Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;;;AAYYA;IAAZ,CAAA,UAAY,aAAa,EAAA;IACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;IAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;IACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;IAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;IAC7C,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,kBAAyC;IAC3C,CAAC,EARWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;IAUnB,MAAO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O,IAAI;;IAG7B,QAAA,IAAI,IAAI,CAAC,oBAAoB,EAAE,EAAE;IAC/B,YAAA,OAAO,IAAI;YACb;YAEA,OAAO,IAAI,CAAC,OAAO;QACrB;QAEA,eAAe,GAAA;IACb,QAAA,OAAO,IAAI;QACb;IACD;IASD;IACA,SAAS,iBAAiB,GAAA;QACxB,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,YAAY,EAAE;YACxD,OAAO,MAAM,CAAC,YAAY;QAC5B;QAEA,MAAM,WAAW,GAA2B,EAAE;QAC9C,OAAO;YACL,OAAO,EAAE,CAAC,GAAG,MAAM,GAAG,IAAI,WAAW,GAAG,WAAW,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;IAChE,QAAA,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,KAAI;IACtB,YAAA,WAAW,CAAC,GAAG,CAAC,GAAG,KAAK;YAC1B,CAAC;IACD,QAAA,UAAU,EAAE,CAAC,GAAG,KAAI;IAClB,YAAA,OAAO,WAAW,CAAC,GAAG,CAAC;YACzB,CAAC;IACD,QAAA,GAAG,EAAE,CAAC,CAAS,KAAK,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI;IACvD,QAAA,IAAI,MAAM,GAAA;gBACR,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM;YACxC,CAAC;SACF;IACH;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\"),\n userProfile: z\n .object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n redirectURL: z.url().optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.WARN;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Capture original functions to prevent tampering\nconst originalWindowOpen = window.open;\nconst originalAddEventListener = window.addEventListener;\nconst originalRemoveEventListener = window.removeEventListener;\nconst originalSetTimeout = window.setTimeout;\nconst originalClearTimeout = window.clearTimeout;\n\n// Generate random window name to prevent targeting\nexport const generateSecureWindowName = () =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\nexport function validateConfig(config: CAMSConfig): URL {\n // Validate URL format and parse once\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n // Domain validation is mandatory for security\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n const url = new URL(config.camsUrl);\n\n return url;\n}\n\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Config validation passed\");\n } catch (error) {\n Logger.error(\"Config validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(error as Error);\n return;\n }\n\n const {\n messageOrigin,\n windowHeight,\n windowWidth,\n authTimeout = 300000, // 5 minutes as a final failsafe\n idleTimeout = 120000, // 2 minutes of inactivity\n } = config;\n let authWindow: Window | null;\n let authTimeoutId: number | null = null;\n let idleTimeoutId: number | null = null;\n let checkClosedInterval: number | null = null;\n\n try {\n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n });\n\n // Center the popup window\n const left = (window.screen.width - windowWidth) / 2;\n const top = (window.screen.height - windowHeight) / 2;\n\n const secureWindowName = generateSecureWindowName();\n authWindow = originalWindowOpen.call(\n window,\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`\n );\n } catch (error) {\n Logger.error(\"Failed to open popup window\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n if (!authWindow) {\n Logger.error(\"Popup window blocked\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Only check for immediate closure (true popup blocking)\n if (authWindow.closed) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n const cleanup = () => {\n originalRemoveEventListener.call(window, \"message\", listener);\n\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n if (authTimeoutId) originalClearTimeout(authTimeoutId);\n if (checkClosedInterval) originalClearTimeout(checkClosedInterval);\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n const listener = (event: Event) => {\n const messageEvent = event as MessageEvent;\n Logger.debug(\"Received message\", {\n origin: messageEvent.origin,\n expectedOrigin: messageOrigin,\n data: messageEvent.data,\n });\n\n const originUrl = new URL(messageEvent.origin);\n const expectedHostname = messageOrigin.startsWith(\"http\")\n ? new URL(messageOrigin).hostname\n : messageOrigin;\n\n // Allow Microsoft redirect domains for Azure AD authentication\n const isMicrosoftDomain =\n originUrl.hostname.endsWith(\".microsoft.com\") ||\n originUrl.hostname.endsWith(\".microsoftonline.com\") ||\n originUrl.hostname.endsWith(\".live.com\");\n\n const isAllowedOrigin =\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain;\n\n if (!isAllowedOrigin) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Validate event source\n if (messageEvent.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: messageEvent.source,\n origin: messageEvent.origin,\n expected: messageOrigin,\n data: messageEvent.data,\n });\n return;\n }\n\n // Ignore heartbeat messages\n if (messageEvent.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // โœ… Validate payload\n const tokenMsg = ProfileSchema.safeParse(messageEvent.data);\n if (tokenMsg.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(tokenMsg.data);\n return;\n }\n\n const authFailureMsg = AuthFailureMessageSchema.safeParse(\n messageEvent.data\n );\n if (authFailureMsg.success) {\n Logger.warn(\"Authentication failure received\", {\n errorDetails: authFailureMsg.data.errorDetails,\n error: authFailureMsg.data.error,\n errorCode: authFailureMsg.data.errorCode,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n \"Authentication failed: \" + authFailureMsg.data.error\n )\n );\n return;\n }\n\n const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);\n if (errorMsg.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorMsg.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication failed: \" + errorMsg.data.error\n )\n );\n return;\n }\n\n Logger.error(\"Invalid message format received\", {\n messageData: messageEvent.data,\n dataType: typeof messageEvent.data,\n tokenValidationError: tokenMsg.error\n ? tokenMsg.error.issues\n : undefined,\n errorValidationError: errorMsg.error\n ? errorMsg.error.issues\n : undefined,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n const cleanupAndClose = (error?: CAMSError) => {\n cleanup();\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.close();\n }\n } catch {\n // Ignore close errors\n }\n if (error) reject(error);\n };\n\n const resetIdleTimeout = () => {\n // Timeout handler\n if (idleTimeoutId) originalClearTimeout(idleTimeoutId);\n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n Logger.debug(\"Setting auth timeout\", { authTimeout });\n authTimeoutId = originalSetTimeout(() => {\n Logger.warn(\"Authentication auth timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded auth time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n\n // Use exponential backoff for popup closure checking\n let pollInterval = 1000; // Start with 1 second\n const maxPollInterval = 5000; // Max 5 seconds\n\n const checkClosed = () => {\n if (authWindow?.closed) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n // Exponential backoff: increase interval up to max\n pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);\n\n try {\n originalAddEventListener.call(window, \"message\", listener);\n Logger.debug(\"Message listener attached\");\n } catch (error) {\n Logger.error(\"Failed to attach message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to set up message listener: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n return;\n }\n\n // Add focus to the popup for better UX\n try {\n if (authWindow && !authWindow.closed) {\n authWindow.focus();\n }\n } catch {\n // Ignore focus errors (cross-origin restrictions)\n }\n });\n}\n","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n private decodeBase64Url(str: string): string {\n // Work with a copy to avoid mutating input\n let result = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n // Add padding if needed\n while (result.length % 4) {\n result += \"=\";\n }\n return atob(result);\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// ๐Ÿ”น Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;;;AAYYA;IAAZ,CAAA,UAAY,aAAa,EAAA;IACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;IAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;IACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,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O,WAAW,CAAC,GAAG,CAAC;YACzB,CAAC;IACD,QAAA,GAAG,EAAE,CAAC,CAAS,KAAK,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI;IACvD,QAAA,IAAI,MAAM,GAAA;gBACR,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM;YACxC,CAAC;SACF;IACH;;;;;;;;;;;;;;;;;"}
package/dist/logger.d.ts CHANGED
@@ -12,7 +12,6 @@ export declare class Logger {
12
12
  private static readonly prefix;
13
13
  private static readonly isTestEnv;
14
14
  static setLevel(level: LogLevel): void;
15
- private static sanitizeForLog;
16
15
  static error(message: string, context?: LogContext): void;
17
16
  static warn(message: string, context?: LogContext): void;
18
17
  static info(message: string, context?: LogContext): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nibssplc/cams-sdk",
3
- "version": "0.0.1-beta.30",
3
+ "version": "0.0.1-beta.31",
4
4
  "workspaces": [
5
5
  "packages/*"
6
6
  ],
@@ -39,6 +39,8 @@
39
39
  "author": "NIBSS PLC, Caleb Boluwade",
40
40
  "license": "MIT",
41
41
  "dependencies": {
42
+ "@types/react": "^19.1.13",
43
+ "react": "^19.1.1",
42
44
  "tslib": "^2.6.0",
43
45
  "zod": "^4.0.17"
44
46
  },