@nibssplc/cams-sdk 0.0.1-beta.3 โ†’ 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
@@ -5,63 +5,66 @@ Central Authentication Management Service (CAMS) SDK for popup-based authenticat
5
5
  ## Features
6
6
 
7
7
  - ๐Ÿ” Secure popup-based authentication
8
- - ๐Ÿ›ก๏ธ URL validation and domain allowlisting
9
- - โฑ๏ธ Configurable timeouts and retry logic
10
- - ๐Ÿ”„ Automatic token management with expiration checking
8
+ - ๐Ÿ›ก๏ธ Origin validation and security controls
9
+ - โฑ๏ธ Configurable auth and idle timeouts with retry logic
10
+ - ๐Ÿ”„ Automatic token management with JWT expiration checking
11
11
  - ๐Ÿ“ฑ Session management with event callbacks
12
- - ๐Ÿงช Comprehensive TypeScript support
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
- import { openCAMSLogin, CAMSConfig } from '@nibssplc/cams-sdk';
36
+ import { openCAMSPopUpLogin, CAMSConfig } from '@nibssplc/cams-sdk';
27
37
 
28
38
  const config: CAMSConfig = {
29
39
  camsUrl: 'https://your-cams-instance.com/auth',
30
- allowedOrigin: 'https://your-cams-instance.com',
40
+ messageOrigin: 'your-cams-instance.com',
31
41
  windowWidth: 500,
32
42
  windowHeight: 600,
33
- timeout: 300000, // 5 minutes
34
- allowedDomains: ['your-cams-instance.com'], // Security allowlist
43
+ authTimeout: 300000, // 5 minutes auth timeout
44
+ idleTimeout: 120000, // 2 minutes idle timeout
45
+ debug: true, // Enable debug logging
35
46
  };
36
47
 
37
48
  try {
38
- const response = await openCAMSPopUpLogin(config);
39
- console.log('Authentication successful:', response.token);
49
+ const profile = await openCAMSPopUpLogin(config);
50
+ console.log('Authentication successful:', profile);
40
51
  } catch (error) {
41
52
  console.error('Authentication failed:', error);
42
53
  }
43
54
  ```
44
55
 
45
- ### Session Management (Recommended)
56
+ #### Session Management
46
57
 
47
58
  ```typescript
48
- import { CAMSSession, CAMSEvents } from '@nibssplc/cams-sdk';
59
+ import { CAMSSessionManager } from '@nibssplc/cams-sdk';
49
60
 
50
- const events: CAMSEvents = {
51
- onAuthStart: () => console.log('Authentication started'),
52
- onAuthSuccess: (token) => console.log('Login successful'),
61
+ const session = new CAMSSessionManager(localStorage, 'my_app', {
62
+ onAuthSuccess: (response) => console.log('Login successful'),
53
63
  onAuthError: (error) => console.error('Login failed:', error),
54
64
  onTokenExpired: () => console.log('Token expired'),
55
- };
56
-
57
- const session = new CAMSSession(sessionStorage, 'my_app_token', events);
58
-
59
- // Login with retry logic
60
- const config = {
61
- // ... your config
62
- retryAttempts: 2, // Retry twice on failure
63
- };
65
+ });
64
66
 
67
+ // Login
65
68
  try {
66
69
  await session.login(config);
67
70
 
@@ -78,18 +81,174 @@ try {
78
81
  await session.logout();
79
82
  ```
80
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
+
81
214
  ## Configuration Options
82
215
 
216
+ ### Core SDK Configuration
217
+
83
218
  ```typescript
84
219
  interface CAMSConfig {
85
220
  camsUrl: string; // CAMS authentication URL
86
- allowedOrigin: string; // Expected message origin
221
+ messageOrigin: string; // Expected message origin (hostname)
87
222
  windowWidth: number; // Popup window width
88
223
  windowHeight: number; // Popup window height
89
- timeout?: number; // Auth timeout in ms (default: 300000)
90
- allowedDomains?: string[]; // URL allowlist for security
224
+ authTimeout?: number; // Auth timeout in ms (default: 300000)
225
+ idleTimeout?: number; // Idle timeout in ms (default: 120000)
91
226
  storageKey?: string; // Custom storage key
92
227
  retryAttempts?: number; // Auto-retry on failure (default: 0)
228
+ debug?: boolean; // Enable debug logging (default: false)
229
+ }
230
+ ```
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
93
252
  }
94
253
  ```
95
254
 
@@ -114,9 +273,18 @@ try {
114
273
  case CAMSErrorType.INVALID_URL:
115
274
  // Handle invalid URL
116
275
  break;
276
+ case CAMSErrorType.INVALID_ORIGIN:
277
+ // Handle invalid message origin
278
+ break;
117
279
  case CAMSErrorType.USER_CANCELLED:
118
280
  // Handle user cancellation
119
281
  break;
282
+ case CAMSErrorType.MAX_RETRIES_EXCEEDED:
283
+ // Handle retry limit exceeded
284
+ break;
285
+ case CAMSErrorType.API_VALIDATION_ERROR:
286
+ // Handle API validation errors
287
+ break;
120
288
  }
121
289
  }
122
290
  }
@@ -124,11 +292,164 @@ try {
124
292
 
125
293
  ## Security Features
126
294
 
127
- - **URL Validation**: Prevents open redirect attacks
128
- - **Domain Allowlisting**: Restricts authentication to approved domains
129
- - **Origin Validation**: Validates message origins
130
- - **Token Validation**: Uses Zod schemas for runtime validation
295
+ - **URL Validation**: Prevents open redirect attacks using Zod schemas
296
+ - **Origin Validation**: Validates message origins with subdomain support
297
+ - **Token Validation**: JWT parsing with expiration checking
131
298
  - **Secure Storage**: Configurable storage with automatic cleanup
299
+ - **Input Sanitization**: Log injection prevention
300
+
301
+ ## API Reference
302
+
303
+ ### Core SDK
304
+
305
+ #### Session Manager
306
+
307
+ ```typescript
308
+ new CAMSSessionManager(
309
+ storage?: StorageLike | null, // Storage implementation (default: localStorage)
310
+ keyPrefix?: string, // Storage key prefix (default: "CAMS-SDK")
311
+ events?: CAMSEvents // Event callbacks
312
+ )
313
+ ```
314
+
315
+ **Methods:**
316
+ - `login(config: CAMSConfig): Promise<CAMSTokenResponse>` - Authenticate user
317
+ - `logout(): Promise<void>` - Clear session
318
+ - `isAuthenticated(): boolean` - Check if user is authenticated
319
+ - `getAccessToken(): string | null` - Get current token
320
+ - `getProfile(): Promise<Profile | null>` - Extract user profile from JWT
321
+ - `setToken(token: string): void` - Store token
322
+ - `clearToken(): void` - Clear stored token
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
+
390
+ ## Debugging
391
+
392
+ The SDK includes comprehensive logging to aid in debugging:
393
+
394
+ ```typescript
395
+ import { Logger, LogLevel } from '@nibssplc/cams-sdk';
396
+
397
+ // Set global log level
398
+ Logger.setLevel(LogLevel.DEBUG);
399
+
400
+ // Or enable debug mode in config
401
+ const config = {
402
+ // ... other config
403
+ debug: true // Automatically sets debug level
404
+ };
405
+ ```
406
+
407
+ **Log Levels:**
408
+ - `ERROR`: Critical errors only
409
+ - `WARN`: Warnings and errors (default)
410
+ - `INFO`: General information, warnings, and errors
411
+ - `DEBUG`: All logs including detailed flow information
412
+
413
+ ## Message Protocol
414
+
415
+ The SDK expects specific message formats from the authentication window:
416
+
417
+ ### Success Message (Profile)
418
+ ```typescript
419
+ {
420
+ userProfile: {
421
+ name: string,
422
+ image?: string | null,
423
+ tokens: {
424
+ Bearer: string
425
+ }
426
+ }
427
+ }
428
+ ```
429
+
430
+ ### Failure Message
431
+ ```typescript
432
+ {
433
+ type: "AUTH_FAILURE",
434
+ error: string,
435
+ errorCode?: string,
436
+ errorDetails?: any
437
+ }
438
+ ```
439
+
440
+ ### Error Message
441
+ ```typescript
442
+ {
443
+ error: string
444
+ }
445
+ ```
446
+
447
+ ### Heartbeat (Optional)
448
+ ```typescript
449
+ {
450
+ type: "heartbeat"
451
+ }
452
+ ```
132
453
 
133
454
  ## Development
134
455
 
@@ -136,14 +457,41 @@ try {
136
457
  # Install dependencies
137
458
  npm install
138
459
 
139
- # 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)
140
467
  npm test
141
468
 
142
- # Build
143
- npm run build
469
+ # Run tests (React)
470
+ npm run test:react
144
471
 
145
472
  # Lint
146
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
147
495
  ```
148
496
 
149
497
  ## License
package/dist/auth.d.ts CHANGED
@@ -1,3 +1,5 @@
1
- import { CAMSConfig, CAMSTokenResponse } from "./types";
2
- export declare function validateConfig(config: CAMSConfig): void;
3
- export declare function openCAMSPopUpLogin(config: CAMSConfig): Promise<CAMSTokenResponse>;
1
+ import { CAMSConfig } from "./types";
2
+ import { Profile } from "./validators";
3
+ export declare const generateSecureWindowName: () => string;
4
+ export declare function validateConfig(config: CAMSConfig): URL;
5
+ export declare function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile>;